diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..4487d47 Binary files /dev/null and b/.DS_Store differ diff --git a/._.DS_Store b/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/._.DS_Store differ diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..b0bd27d --- /dev/null +++ b/.travis.yml @@ -0,0 +1,5 @@ +language: java +sudo: false +jdk: + - oraclejdk8 +script: mvn clean install \ No newline at end of file diff --git a/DEVELOPERS.md b/DEVELOPERS.md new file mode 100644 index 0000000..503fa1d --- /dev/null +++ b/DEVELOPERS.md @@ -0,0 +1 @@ +#TODO \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..8f71f43 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/app.icns b/app.icns new file mode 100644 index 0000000..0d0e87f Binary files /dev/null and b/app.icns differ diff --git a/hs_err_pid19552.log b/hs_err_pid19552.log new file mode 100644 index 0000000..b141869 --- /dev/null +++ b/hs_err_pid19552.log @@ -0,0 +1,627 @@ +# +# A fatal error has been detected by the Java Runtime Environment: +# +# SIGSEGV (0xb) at pc=0x00007fff942284dd, pid=19552, tid=2571 +# +# JRE version: Java(TM) SE Runtime Environment (8.0_66-b17) (build 1.8.0_66-b17) +# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.66-b17 mixed mode bsd-amd64 compressed oops) +# Problematic frame: +# C [libobjc.A.dylib+0x14dd] objc_msgSend+0x1d +# +# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again +# +# If you would like to submit a bug report, please visit: +# http://bugreport.java.com/bugreport/crash.jsp +# The crash happened outside the Java Virtual Machine in native code. +# See problematic frame for where to report the bug. +# + +--------------- T H R E A D --------------- + +Current thread (0x00007f80b3acf000): JavaThread "AWT-AppKit" daemon [_thread_in_native, id=2571, stack(0x00007fff56e88000,0x00007fff57688000)] + +siginfo: si_signo: 11 (SIGSEGV), si_code: 1 (SEGV_MAPERR), si_addr: 0x0000000000000018 + +Registers: +RAX=0x00007f80ba20c2c0, RBX=0x000000012a991450, RCX=0x0000000198b76480, RDX=0x0000000198b763c0 +RSP=0x00007fff57680738, RBP=0x00007fff576807f0, RSI=0x00007fff887e5cbe, RDI=0x00007f80b9d4dcc0 +R8 =0x0000000000000000, R9 =0x00000000000008b0, R10=0x00007fff887e5cbe, R11=0x0000000000000000 +R12=0x0000000000000000, R13=0x000000012e29c888, R14=0x000000012a991440, R15=0x00007f80b3acf000 +RIP=0x00007fff942284dd, EFLAGS=0x0000000000010246, ERR=0x0000000000000004 + TRAPNO=0x000000000000000e + +Top of Stack: (sp=0x00007fff57680738) +0x00007fff57680738: 000000012a98f157 0000000000000000 +0x00007fff57680748: 00007f80b9fcbd40 00007fff927ac7a0 +0x00007fff57680758: 0000000000000000 00007f80b5035db0 +0x00007fff57680768: 00007f80b2f3d430 00007f80ba20c2c0 +0x00007fff57680778: 000000012a9916a0 000000012a991710 +0x00007fff57680788: 00007fff78e48770 00007fff7877f500 +0x00007fff57680798: 000000012a991450 000000012a991690 +0x00007fff576807a8: 00007f80ba20c2c0 00007f80b9d4dcc0 +0x00007fff576807b8: 00007f80b5029fa0 00007f80ba20c2c0 +0x00007fff576807c8: 00007f80b9d4dcc0 00007fff57680870 +0x00007fff576807d8: 00007f80b3acf1f8 000000012e29c888 +0x00007fff576807e8: 00007fff57680898 00007fff57680860 +0x00007fff576807f8: 000000010b19b954 0000000108e27600 +0x00007fff57680808: 000000000000002f 00007f80ba2fc080 +0x00007fff57680818: 00007f80ba20e5c0 00007fff57680820 +0x00007fff57680828: 0000000000000000 00007fff57680898 +0x00007fff57680838: 000000012e2e5498 0000000000000000 +0x00007fff57680848: 000000012e29c888 0000000000000000 +0x00007fff57680858: 00007fff57680880 00007fff576808e0 +0x00007fff57680868: 000000010b18dc4d 00000006c0130108 +0x00007fff57680878: 000000010b195578 00007f80ba20c2c0 +0x00007fff57680888: 0000000000000000 00007f80b9d4dcc0 +0x00007fff57680898: 00007fff9ae7efe2 00007fff576808a0 +0x00007fff576808a8: 000000012e29ca52 00007fff57680908 +0x00007fff576808b8: 000000012e2e5498 0000000000000000 +0x00007fff576808c8: 000000012e29ca60 00007fff57680880 +0x00007fff576808d8: 00007fff576808f0 00007fff57680950 +0x00007fff576808e8: 000000010b18dc4d 00007f80ba20c2c0 +0x00007fff576808f8: 000000076bb8cdc0 00007f80b9d4dcc0 +0x00007fff57680908: 000000076bb8cdc0 00007fff57680910 +0x00007fff57680918: 000000012e3195f6 00007fff57680960 +0x00007fff57680928: 000000012e3196b0 0000000000000000 + +Instructions: (pc=0x00007fff942284dd) +0x00007fff942284bd: 44 00 00 48 85 ff 2e 74 62 40 f6 c7 01 2e 75 66 +0x00007fff942284cd: 49 bb f8 ff ff ff ff 7f 00 00 4c 23 1f 49 89 f2 +0x00007fff942284dd: 45 23 53 18 49 c1 e2 04 4d 03 53 10 49 3b 32 75 +0x00007fff942284ed: 04 41 ff 62 08 49 83 3a 01 76 0d 49 83 c2 10 49 + +Register to memory mapping: + +RAX=0x00007f80ba20c2c0 is an unknown value +RBX=0x000000012a991450: Java_jogamp_nativewindow_macosx_OSXUtil_GetScreenRefreshRate0+0x1cf0 in /private/var/folders/td/djw6lgtj5tx3f27yqjn1qk240000gp/T/jogamp_0000/file_cache/jln6271106923964908699/jln8600969762585133251/libnativewindow_macosx.jnilib at 0x000000012a98a000 +RCX=0x0000000198b76480 is an unknown value +RDX=0x0000000198b763c0 is an unknown value +RSP=0x00007fff57680738 is pointing into the stack for thread: 0x00007f80b3acf000 +RBP=0x00007fff576807f0 is pointing into the stack for thread: 0x00007f80b3acf000 +RSI=0x00007fff887e5cbe is an unknown value +RDI=0x00007f80b9d4dcc0 is an unknown value +R8 =0x0000000000000000 is an unknown value +R9 =0x00000000000008b0 is an unknown value +R10=0x00007fff887e5cbe is an unknown value +R11=0x0000000000000000 is an unknown value +R12=0x0000000000000000 is an unknown value +R13={method} {0x000000012e29c888} 'UnsetJAWTRootSurfaceLayer0' '(JJ)V' in 'jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow' +R14=0x000000012a991440: Java_jogamp_nativewindow_macosx_OSXUtil_GetScreenRefreshRate0+0x1ce0 in /private/var/folders/td/djw6lgtj5tx3f27yqjn1qk240000gp/T/jogamp_0000/file_cache/jln6271106923964908699/jln8600969762585133251/libnativewindow_macosx.jnilib at 0x000000012a98a000 +R15=0x00007f80b3acf000 is a thread + + +Stack: [0x00007fff56e88000,0x00007fff57688000], sp=0x00007fff57680738, free space=8161k +Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code) +C [libobjc.A.dylib+0x14dd] objc_msgSend+0x1d +j jogamp.nativewindow.jawt.macosx.MacOSXJAWTWindow.UnsetJAWTRootSurfaceLayer0(JJ)V+0 +j jogamp.nativewindow.jawt.macosx.MacOSXJAWTWindow.access$200(JJ)V+2 +j jogamp.nativewindow.jawt.macosx.MacOSXJAWTWindow$1.run()V+38 +j com.jogamp.common.util.RunnableTask.run()V+24 +v ~StubRoutines::call_stub +V [libjvm.dylib+0x2ea35e] +V [libjvm.dylib+0x321467] +V [libjvm.dylib+0x313c3b] +C [libnativewindow_macosx.jnilib+0x5326] Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_UnsetJAWTRootSurfaceLayer0+0x2b6 +C [Foundation+0x76fde] __NSThreadPerformPerform+0x117 +C [CoreFoundation+0xaa7e1] __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__+0x11 +C [CoreFoundation+0x89f1c] __CFRunLoopDoSources0+0x22c +C [CoreFoundation+0x8943f] __CFRunLoopRun+0x39f +C [CoreFoundation+0x88e38] CFRunLoopRunSpecific+0x128 +C [HIToolbox+0x30935] RunCurrentEventLoopInMode+0xeb +C [HIToolbox+0x30677] ReceiveNextEventCommon+0xb8 +C [HIToolbox+0x305af] _BlockUntilNextEventMatchingListInModeWithFilter+0x47 +C [AppKit+0x48df6] _DPSNextEvent+0x42b +C [AppKit+0x48226] -[NSApplication _nextEventMatchingEventMask:untilDate:inMode:dequeue:]+0x1c6 +C [libosxapp.dylib+0x23aa] -[NSApplicationAWT nextEventMatchingMask:untilDate:inMode:dequeue:]+0x7c +C [AppKit+0x3cd80] -[NSApplication run]+0x2aa +C [libosxapp.dylib+0x214d] +[NSApplicationAWT runAWTLoopWithApp:]+0x9c +C [libawt_lwawt.dylib+0x4455b] -[AWTStarter starter:]+0x389 +C [Foundation+0x76fde] __NSThreadPerformPerform+0x117 +C [CoreFoundation+0xaa7e1] __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__+0x11 +C [CoreFoundation+0x89f1c] __CFRunLoopDoSources0+0x22c +C [CoreFoundation+0x8943f] __CFRunLoopRun+0x39f +C [CoreFoundation+0x88e38] CFRunLoopRunSpecific+0x128 +C [java+0x6463] CreateExecutionEnvironment+0x367 +C [java+0x21ac] JLI_Launch+0x7a0 +C [java+0x84c0] main+0x65 +C [java+0x1a04] start+0x34 +C 0x0000000000000009 + +Java frames: (J=compiled Java code, j=interpreted, Vv=VM code) +j jogamp.nativewindow.jawt.macosx.MacOSXJAWTWindow.UnsetJAWTRootSurfaceLayer0(JJ)V+0 +j jogamp.nativewindow.jawt.macosx.MacOSXJAWTWindow.access$200(JJ)V+2 +j jogamp.nativewindow.jawt.macosx.MacOSXJAWTWindow$1.run()V+38 +j com.jogamp.common.util.RunnableTask.run()V+24 +v ~StubRoutines::call_stub + +--------------- P R O C E S S --------------- + +Java Threads: ( => current thread ) + 0x00007f80b4c94000 JavaThread "TimerQueue" daemon [_thread_blocked, id=78851, stack(0x0000700002f30000,0x0000700003030000)] + 0x00007f80b4b3b000 JavaThread "J3D-InputDeviceScheduler-1" [_thread_blocked, id=78339, stack(0x0000700002e2d000,0x0000700002f2d000)] + 0x00007f80b6cb1800 JavaThread "J3D-SoundSchedulerUpdateThread-1" [_thread_blocked, id=77827, stack(0x0000700002d2a000,0x0000700002e2a000)] + 0x00007f80b3003800 JavaThread "J3D-RenderStructureUpdateThread-1" [_thread_blocked, id=77315, stack(0x0000700002c27000,0x0000700002d27000)] + 0x00007f80b4a3b000 JavaThread "J3D-BehaviorScheduler-1" [_thread_blocked, id=76803, stack(0x0000700002b24000,0x0000700002c24000)] + 0x00007f80b3f5b800 JavaThread "J3D-TransformStructureUpdateThread-1" [_thread_blocked, id=76291, stack(0x0000700002a21000,0x0000700002b21000)] + 0x00007f80b3cf2800 JavaThread "J3D-RenderingEnvironmentStructureUpdateThread-1" [_thread_blocked, id=75779, stack(0x000070000291e000,0x0000700002a1e000)] + 0x00007f80b3cf2000 JavaThread "J3D-SoundStructureUpdateThread-1" [_thread_blocked, id=75275, stack(0x000070000281b000,0x000070000291b000)] + 0x00007f80b40c3000 JavaThread "J3D-GeometryStructureUpdateThread-1" [_thread_blocked, id=74771, stack(0x0000700002718000,0x0000700002818000)] + 0x00007f80b4b53000 JavaThread "J3D-BehaviorStructureUpdateThread-1" [_thread_blocked, id=74535, stack(0x0000700002615000,0x0000700002715000)] + 0x00007f80b6c71000 JavaThread "J3D-Renderer-1" [_thread_blocked, id=66307, stack(0x000070000248f000,0x000070000258f000)] + 0x00007f80b4b0d000 JavaThread "J3D-MasterControl-1" [_thread_blocked, id=65795, stack(0x000070000238c000,0x000070000248c000)] + 0x00007f80b4af3800 JavaThread "J3D-NotificationThread" [_thread_blocked, id=65283, stack(0x0000700002289000,0x0000700002389000)] + 0x00007f80b488b000 JavaThread "J3D-TimerThread" [_thread_blocked, id=64771, stack(0x0000700002186000,0x0000700002286000)] + 0x00007f80b4aae800 JavaThread "J3D-RenderingAttributesStructureUpdateThread" [_thread_blocked, id=64263, stack(0x0000700002083000,0x0000700002183000)] + 0x00007f80b4a29000 JavaThread "Timer-0" daemon [_thread_blocked, id=62991, stack(0x0000700001f80000,0x0000700002080000)] + 0x00007f80b4967800 JavaThread "Java2D Disposer" daemon [_thread_blocked, id=61443, stack(0x0000700001e7d000,0x0000700001f7d000)] + 0x00007f80b6a4e000 JavaThread "Java2D Queue Flusher" daemon [_thread_blocked, id=57095, stack(0x0000700001d7a000,0x0000700001e7a000)] + 0x00007f80b30e4000 JavaThread "Image Fetcher 3" daemon [_thread_blocked, id=55043, stack(0x0000700001c77000,0x0000700001d77000)] + 0x00007f80b300a000 JavaThread "DestroyJavaVM" [_thread_blocked, id=5891, stack(0x000070000011a000,0x000070000021a000)] + 0x00007f80b69c1800 JavaThread "AWT-EventQueue-0" [_thread_in_native, id=47419, stack(0x0000700001b74000,0x0000700001c74000)] + 0x00007f80b5861800 JavaThread "AWT-Shutdown" [_thread_blocked, id=34067, stack(0x0000700001865000,0x0000700001965000)] +=>0x00007f80b3acf000 JavaThread "AWT-AppKit" daemon [_thread_in_native, id=2571, stack(0x00007fff56e88000,0x00007fff57688000)] + 0x00007f80b7000800 JavaThread "snapshooter" daemon [_thread_in_native, id=22531, stack(0x00007000015d9000,0x00007000016d9000)] + 0x00007f80b5802800 JavaThread "Service Thread" daemon [_thread_blocked, id=21507, stack(0x00007000013d3000,0x00007000014d3000)] + 0x00007f80b4006800 JavaThread "C1 CompilerThread3" daemon [_thread_blocked, id=20995, stack(0x00007000012d0000,0x00007000013d0000)] + 0x00007f80b4004000 JavaThread "C2 CompilerThread2" daemon [_thread_blocked, id=20483, stack(0x00007000011cd000,0x00007000012cd000)] + 0x00007f80b4003800 JavaThread "C2 CompilerThread1" daemon [_thread_blocked, id=19971, stack(0x00007000010ca000,0x00007000011ca000)] + 0x00007f80b6011800 JavaThread "C2 CompilerThread0" daemon [_thread_blocked, id=19459, stack(0x0000700000fc7000,0x00007000010c7000)] + 0x00007f80b686b800 JavaThread "Monitor Ctrl-Break" daemon [_thread_in_native, id=18947, stack(0x0000700000ec4000,0x0000700000fc4000)] + 0x00007f80b6856000 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=15887, stack(0x0000700000dc1000,0x0000700000ec1000)] + 0x00007f80b680e800 JavaThread "Finalizer" daemon [_thread_blocked, id=14339, stack(0x0000700000c3b000,0x0000700000d3b000)] + 0x00007f80b680d800 JavaThread "Reference Handler" daemon [_thread_blocked, id=13827, stack(0x0000700000b38000,0x0000700000c38000)] + +Other Threads: + 0x00007f80b3045000 VMThread [stack: 0x0000700000a35000,0x0000700000b35000] [id=13315] + 0x00007f80b604d000 WatcherThread [stack: 0x00007000014d6000,0x00007000015d6000] [id=22019] + +VM state:not at safepoint (normal execution) + +VM Mutex/Monitor currently owned by a thread: None + +Heap: + PSYoungGen total 76288K, used 31910K [0x000000076ab00000, 0x0000000770000000, 0x00000007c0000000) + eden space 65536K, 48% used [0x000000076ab00000,0x000000076ca29b78,0x000000076eb00000) + from space 10752K, 0% used [0x000000076f580000,0x000000076f580000,0x0000000770000000) + to space 10752K, 0% used [0x000000076eb00000,0x000000076eb00000,0x000000076f580000) + ParOldGen total 114176K, used 9154K [0x00000006c0000000, 0x00000006c6f80000, 0x000000076ab00000) + object space 114176K, 8% used [0x00000006c0000000,0x00000006c08f0980,0x00000006c6f80000) + Metaspace used 29817K, capacity 30143K, committed 30256K, reserved 1075200K + class space used 3546K, capacity 3619K, committed 3632K, reserved 1048576K + +Card table byte_map: [0x000000011a546000,0x000000011ad47000] byte_map_base: 0x0000000116f46000 + +Marking Bits: (ParMarkBitMap*) 0x000000010aadde20 + Begin Bits: [0x000000011b29d000, 0x000000011f29d000) + End Bits: [0x000000011f29d000, 0x000000012329d000) + +Polling page: 0x00000001090c7000 + +CodeCache: size=245760Kb used=8438Kb max_used=8438Kb free=237322Kb + bounds [0x000000010b186000, 0x000000010b9d6000, 0x000000011a186000] + total_blobs=3292 nmethods=2352 adapters=853 + compilation: enabled + +Compilation events (10 events): +Event: 8.574 Thread 0x00007f80b4006800 nmethod 2348 0x000000010b9b6e50 code [0x000000010b9b7100, 0x000000010b9b8a28] +Event: 8.577 Thread 0x00007f80b4006800 2349 3 java.awt.Point:: (13 bytes) +Event: 8.577 Thread 0x00007f80b4006800 nmethod 2349 0x000000010b9b8d50 code [0x000000010b9b8ec0, 0x000000010b9b9130] +Event: 8.577 Thread 0x00007f80b4006800 2350 3 java.util.LinkedList$ListItr::hasNext (20 bytes) +Event: 8.578 Thread 0x00007f80b4006800 nmethod 2350 0x000000010b9b9290 code [0x000000010b9b9400, 0x000000010b9b95d0] +Event: 8.578 Thread 0x00007f80b4006800 2351 s 3 javax.media.j3d.UnorderList::toArray (99 bytes) +Event: 8.578 Thread 0x00007f80b4006800 nmethod 2351 0x000000010b9b9690 code [0x000000010b9b9840, 0x000000010b9b9f98] +Event: 8.579 Thread 0x00007f80b4006800 2352 1 com.jogamp.common.nio.StructAccessor::getBuffer (5 bytes) +Event: 8.580 Thread 0x00007f80b4006800 nmethod 2352 0x000000010b9ba110 code [0x000000010b9ba260, 0x000000010b9ba370] +Event: 8.580 Thread 0x00007f80b4006800 2353 s! 3 javax.media.j3d.MasterControl::runMonitor (1532 bytes) + +GC Heap History (6 events): +Event: 1.045 GC heap before +{Heap before GC invocations=1 (full 0): + PSYoungGen total 76288K, used 65536K [0x000000076ab00000, 0x0000000770000000, 0x00000007c0000000) + eden space 65536K, 100% used [0x000000076ab00000,0x000000076eb00000,0x000000076eb00000) + from space 10752K, 0% used [0x000000076f580000,0x000000076f580000,0x0000000770000000) + to space 10752K, 0% used [0x000000076eb00000,0x000000076eb00000,0x000000076f580000) + ParOldGen total 175104K, used 0K [0x00000006c0000000, 0x00000006cab00000, 0x000000076ab00000) + object space 175104K, 0% used [0x00000006c0000000,0x00000006c0000000,0x00000006cab00000) + Metaspace used 13743K, capacity 13965K, committed 14336K, reserved 1062912K + class space used 1369K, capacity 1423K, committed 1536K, reserved 1048576K +Event: 1.055 GC heap after +Heap after GC invocations=1 (full 0): + PSYoungGen total 76288K, used 10739K [0x000000076ab00000, 0x0000000770000000, 0x00000007c0000000) + eden space 65536K, 0% used [0x000000076ab00000,0x000000076ab00000,0x000000076eb00000) + from space 10752K, 99% used [0x000000076eb00000,0x000000076f57cfd0,0x000000076f580000) + to space 10752K, 0% used [0x000000076f580000,0x000000076f580000,0x0000000770000000) + ParOldGen total 175104K, used 3560K [0x00000006c0000000, 0x00000006cab00000, 0x000000076ab00000) + object space 175104K, 2% used [0x00000006c0000000,0x00000006c037a338,0x00000006cab00000) + Metaspace used 13743K, capacity 13965K, committed 14336K, reserved 1062912K + class space used 1369K, capacity 1423K, committed 1536K, reserved 1048576K +} +Event: 3.397 GC heap before +{Heap before GC invocations=2 (full 0): + PSYoungGen total 76288K, used 39191K [0x000000076ab00000, 0x0000000770000000, 0x00000007c0000000) + eden space 65536K, 43% used [0x000000076ab00000,0x000000076c6c8e18,0x000000076eb00000) + from space 10752K, 99% used [0x000000076eb00000,0x000000076f57cfd0,0x000000076f580000) + to space 10752K, 0% used [0x000000076f580000,0x000000076f580000,0x0000000770000000) + ParOldGen total 175104K, used 3560K [0x00000006c0000000, 0x00000006cab00000, 0x000000076ab00000) + object space 175104K, 2% used [0x00000006c0000000,0x00000006c037a338,0x00000006cab00000) + Metaspace used 20920K, capacity 21169K, committed 21296K, reserved 1069056K + class space used 2214K, capacity 2306K, committed 2352K, reserved 1048576K +Event: 3.403 GC heap after +Heap after GC invocations=2 (full 0): + PSYoungGen total 76288K, used 8877K [0x000000076ab00000, 0x0000000770000000, 0x00000007c0000000) + eden space 65536K, 0% used [0x000000076ab00000,0x000000076ab00000,0x000000076eb00000) + from space 10752K, 82% used [0x000000076f580000,0x000000076fe2b700,0x0000000770000000) + to space 10752K, 0% used [0x000000076eb00000,0x000000076eb00000,0x000000076f580000) + ParOldGen total 175104K, used 3568K [0x00000006c0000000, 0x00000006cab00000, 0x000000076ab00000) + object space 175104K, 2% used [0x00000006c0000000,0x00000006c037c338,0x00000006cab00000) + Metaspace used 20920K, capacity 21169K, committed 21296K, reserved 1069056K + class space used 2214K, capacity 2306K, committed 2352K, reserved 1048576K +} +Event: 3.403 GC heap before +{Heap before GC invocations=3 (full 1): + PSYoungGen total 76288K, used 8877K [0x000000076ab00000, 0x0000000770000000, 0x00000007c0000000) + eden space 65536K, 0% used [0x000000076ab00000,0x000000076ab00000,0x000000076eb00000) + from space 10752K, 82% used [0x000000076f580000,0x000000076fe2b700,0x0000000770000000) + to space 10752K, 0% used [0x000000076eb00000,0x000000076eb00000,0x000000076f580000) + ParOldGen total 175104K, used 3568K [0x00000006c0000000, 0x00000006cab00000, 0x000000076ab00000) + object space 175104K, 2% used [0x00000006c0000000,0x00000006c037c338,0x00000006cab00000) + Metaspace used 20920K, capacity 21169K, committed 21296K, reserved 1069056K + class space used 2214K, capacity 2306K, committed 2352K, reserved 1048576K +Event: 3.425 GC heap after +Heap after GC invocations=3 (full 1): + PSYoungGen total 76288K, used 0K [0x000000076ab00000, 0x0000000770000000, 0x00000007c0000000) + eden space 65536K, 0% used [0x000000076ab00000,0x000000076ab00000,0x000000076eb00000) + from space 10752K, 0% used [0x000000076f580000,0x000000076f580000,0x0000000770000000) + to space 10752K, 0% used [0x000000076eb00000,0x000000076eb00000,0x000000076f580000) + ParOldGen total 114176K, used 9154K [0x00000006c0000000, 0x00000006c6f80000, 0x000000076ab00000) + object space 114176K, 8% used [0x00000006c0000000,0x00000006c08f0980,0x00000006c6f80000) + Metaspace used 20920K, capacity 21169K, committed 21296K, reserved 1069056K + class space used 2214K, capacity 2306K, committed 2352K, reserved 1048576K +} + +Deoptimization events (10 events): +Event: 4.084 Thread 0x00007f80b69c1800 Uncommon trap: reason=unstable_if action=reinterpret pc=0x000000010b74deac method=sun.awt.SunToolkit.getAppContext(Ljava/lang/Object;)Lsun/awt/AppContext; @ 4 +Event: 4.111 Thread 0x00007f80b69c1800 Uncommon trap: reason=unstable_if action=reinterpret pc=0x000000010b3878e0 method=java.lang.CharacterData.of(I)Ljava/lang/CharacterData; @ 4 +Event: 4.174 Thread 0x00007f80b69c1800 Uncommon trap: reason=unstable_if action=reinterpret pc=0x000000010b8312f0 method=javax.swing.RepaintManager.addDirtyRegion0(Ljava/awt/Container;IIII)V @ 78 +Event: 5.681 Thread 0x00007f80b69c1800 Uncommon trap: reason=class_check action=maybe_recompile pc=0x000000010b6aafec method=java.util.Hashtable.put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; @ 60 +Event: 5.681 Thread 0x00007f80b69c1800 Uncommon trap: reason=class_check action=maybe_recompile pc=0x000000010b6aafec method=java.util.Hashtable.put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; @ 60 +Event: 6.221 Thread 0x00007f80b69c1800 Uncommon trap: reason=unstable_if action=reinterpret pc=0x000000010b91bd10 method=java.awt.image.DirectColorModel.getsRGBComponentFromsRGB(II)I @ 20 +Event: 6.221 Thread 0x00007f80b69c1800 Uncommon trap: reason=unstable_if action=reinterpret pc=0x000000010b91d2e8 method=java.awt.image.DirectColorModel.getsRGBComponentFromsRGB(II)I @ 20 +Event: 6.221 Thread 0x00007f80b69c1800 Uncommon trap: reason=unstable_if action=reinterpret pc=0x000000010b91d868 method=java.awt.image.DirectColorModel.getsRGBComponentFromsRGB(II)I @ 20 +Event: 6.221 Thread 0x00007f80b69c1800 Uncommon trap: reason=unstable_if action=reinterpret pc=0x000000010b91c328 method=java.awt.image.DirectColorModel.getsRGBComponentFromsRGB(II)I @ 20 +Event: 6.221 Thread 0x00007f80b69c1800 Uncommon trap: reason=unstable_if action=reinterpret pc=0x000000010b911118 method=java.awt.image.DirectColorModel.getsRGBComponentFromsRGB(II)I @ 20 + +Internal exceptions (10 events): +Event: 3.933 Thread 0x00007f80b69c1800 Exception (0x000000076c02c8d0) thrown at [/HUDSON3/workspace/8-2-build-macosx-x86_64/jdk8u66/4988/hotspot/src/share/vm/prims/jni.cpp, line 709] +Event: 3.934 Thread 0x00007f80b69c1800 Exception (0x000000076c033478) thrown at [/HUDSON3/workspace/8-2-build-macosx-x86_64/jdk8u66/4988/hotspot/src/share/vm/prims/jni.cpp, line 709] +Event: 3.934 Thread 0x00007f80b69c1800 Exception (0x000000076c037548) thrown at [/HUDSON3/workspace/8-2-build-macosx-x86_64/jdk8u66/4988/hotspot/src/share/vm/prims/jni.cpp, line 709] +Event: 3.950 Thread 0x00007f80b69c1800 Exception (0x000000076c229b40) thrown at [/HUDSON3/workspace/8-2-build-macosx-x86_64/jdk8u66/4988/hotspot/src/share/vm/prims/jni.cpp, line 709] +Event: 3.960 Thread 0x00007f80b69c1800 Implicit null exception at 0x000000010b79b813 to 0x000000010b79c365 +Event: 3.960 Thread 0x00007f80b69c1800 Implicit null exception at 0x000000010b7c32fe to 0x000000010b7c4281 +Event: 3.963 Thread 0x00007f80b69c1800 Exception (0x000000076c32a980) thrown at [/HUDSON3/workspace/8-2-build-macosx-x86_64/jdk8u66/4988/hotspot/src/share/vm/prims/jni.cpp, line 709] +Event: 3.964 Thread 0x00007f80b69c1800 Exception (0x000000076c333d08) thrown at [/HUDSON3/workspace/8-2-build-macosx-x86_64/jdk8u66/4988/hotspot/src/share/vm/prims/jni.cpp, line 709] +Event: 3.987 Thread 0x00007f80b69c1800 Exception (0x000000076c37cc68) thrown at [/HUDSON3/workspace/8-2-build-macosx-x86_64/jdk8u66/4988/hotspot/src/share/vm/prims/jni.cpp, line 709] +Event: 3.989 Thread 0x00007f80b69c1800 Exception (0x000000076c3854d8) thrown at [/HUDSON3/workspace/8-2-build-macosx-x86_64/jdk8u66/4988/hotspot/src/share/vm/prims/jni.cpp, line 709] + +Events (10 events): +Event: 8.456 loading class com/apple/laf/AquaUtils$Selectable done +Event: 8.456 loading class com/apple/laf/AquaMenuItemUI$1 done +Event: 8.565 loading class sun/swing/MenuItemLayoutHelper$LayoutResult +Event: 8.565 loading class sun/swing/MenuItemLayoutHelper$LayoutResult done +Event: 8.565 loading class javax/swing/plaf/basic/BasicMenuItemUI$Actions +Event: 8.565 loading class javax/swing/plaf/basic/BasicMenuItemUI$Actions done +Event: 8.570 loading class javax/swing/Popup$DefaultFrame +Event: 8.571 loading class javax/swing/Popup$DefaultFrame done +Event: 8.571 loading class javax/swing/PopupFactory$HeavyWeightPopup$1 +Event: 8.571 loading class javax/swing/PopupFactory$HeavyWeightPopup$1 done + + +Dynamic libraries: +0x00000000072f5000 /System/Library/Frameworks/Cocoa.framework/Versions/A/Cocoa +0x0000000108593000 /System/Library/Frameworks/Security.framework/Versions/A/Security +0x00000000072f5000 /System/Library/Frameworks/ApplicationServices.framework/Versions/A/ApplicationServices +0x00000000072f5000 /usr/lib/libz.1.dylib +0x00000000072f5000 /usr/lib/libSystem.B.dylib +0x00000000072f5000 /usr/lib/libobjc.A.dylib +0x00000000072f5000 /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation +0x00000000072f5000 /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation +0x00000000072f5000 /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit +0x00000000072f5000 /System/Library/Frameworks/CoreData.framework/Versions/A/CoreData +0x00000000072f5000 /System/Library/PrivateFrameworks/RemoteViewServices.framework/Versions/A/RemoteViewServices +0x00000000072f5000 /System/Library/PrivateFrameworks/UIFoundation.framework/Versions/A/UIFoundation +0x00000000072f5000 /usr/lib/libScreenReader.dylib +0x00000000072f5000 /System/Library/Frameworks/Accelerate.framework/Versions/A/Accelerate +0x00000000072f5000 /System/Library/Frameworks/IOSurface.framework/Versions/A/IOSurface +0x00000000072f5000 /System/Library/Frameworks/AudioToolbox.framework/Versions/A/AudioToolbox +0x00000000072f5000 /System/Library/Frameworks/AudioUnit.framework/Versions/A/AudioUnit +0x00000000072f5000 /System/Library/PrivateFrameworks/DataDetectorsCore.framework/Versions/A/DataDetectorsCore +0x00000000072f5000 /System/Library/PrivateFrameworks/DesktopServicesPriv.framework/Versions/A/DesktopServicesPriv +0x00000000072f5000 /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox +0x00000000072f5000 /System/Library/Frameworks/QuartzCore.framework/Versions/A/QuartzCore +0x00000000072f5000 /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/SpeechRecognition.framework/Versions/A/SpeechRecognition +0x00000000072f5000 /usr/lib/libauto.dylib +0x00000000072f5000 /usr/lib/libicucore.A.dylib +0x00000000072f5000 /usr/lib/libxml2.2.dylib +0x00000000072f5000 /System/Library/PrivateFrameworks/CoreUI.framework/Versions/A/CoreUI +0x00000000072f5000 /System/Library/Frameworks/CoreAudio.framework/Versions/A/CoreAudio +0x00000000072f5000 /System/Library/Frameworks/DiskArbitration.framework/Versions/A/DiskArbitration +0x00000000072f5000 /usr/lib/liblangid.dylib +0x00000000072f5000 /System/Library/PrivateFrameworks/MultitouchSupport.framework/Versions/A/MultitouchSupport +0x00000000072f5000 /System/Library/Frameworks/IOKit.framework/Versions/A/IOKit +0x00000000072f5000 /usr/lib/libDiagnosticMessagesClient.dylib +0x00000000072f5000 /System/Library/Frameworks/CoreServices.framework/Versions/A/CoreServices +0x00000000072f5000 /System/Library/PrivateFrameworks/PerformanceAnalysis.framework/Versions/A/PerformanceAnalysis +0x00000000072f5000 /System/Library/PrivateFrameworks/GenerationalStorage.framework/Versions/A/GenerationalStorage +0x00000000072f5000 /System/Library/Frameworks/OpenGL.framework/Versions/A/OpenGL +0x00000000072f5000 /System/Library/PrivateFrameworks/Sharing.framework/Versions/A/Sharing +0x00000000072f5000 /System/Library/Frameworks/CoreGraphics.framework/Versions/A/CoreGraphics +0x00000000072f5000 /System/Library/Frameworks/CoreImage.framework/Versions/A/CoreImage +0x00000000072f5000 /System/Library/Frameworks/CoreText.framework/Versions/A/CoreText +0x00000000072f5000 /System/Library/Frameworks/ImageIO.framework/Versions/A/ImageIO +0x00000000072f5000 /System/Library/PrivateFrameworks/Backup.framework/Versions/A/Backup +0x00000000072f5000 /usr/lib/libextension.dylib +0x00000000072f5000 /usr/lib/libarchive.2.dylib +0x00000001089ae000 /System/Library/Frameworks/CFNetwork.framework/Versions/A/CFNetwork +0x00000000072f5000 /System/Library/Frameworks/SystemConfiguration.framework/Versions/A/SystemConfiguration +0x00000000072f5000 /usr/lib/libCRFSuite.dylib +0x00000000072f5000 /usr/lib/libc++.1.dylib +0x00000000072f5000 /usr/lib/libc++abi.dylib +0x00000000072f5000 /usr/lib/system/libcache.dylib +0x00000000072f5000 /usr/lib/system/libcommonCrypto.dylib +0x00000000072f5000 /usr/lib/system/libcompiler_rt.dylib +0x00000000072f5000 /usr/lib/system/libcopyfile.dylib +0x00000000072f5000 /usr/lib/system/libcorecrypto.dylib +0x00000000072f5000 /usr/lib/system/libdispatch.dylib +0x00000000072f5000 /usr/lib/system/libdyld.dylib +0x00000000072f5000 /usr/lib/system/libkeymgr.dylib +0x00000000072f5000 /usr/lib/system/liblaunch.dylib +0x00000000072f5000 /usr/lib/system/libmacho.dylib +0x00000000072f5000 /usr/lib/system/libquarantine.dylib +0x00000000072f5000 /usr/lib/system/libremovefile.dylib +0x00000000072f5000 /usr/lib/system/libsystem_asl.dylib +0x00000000072f5000 /usr/lib/system/libsystem_blocks.dylib +0x00000000072f5000 /usr/lib/system/libsystem_c.dylib +0x00000000072f5000 /usr/lib/system/libsystem_configuration.dylib +0x00000000072f5000 /usr/lib/system/libsystem_coreservices.dylib +0x00000000072f5000 /usr/lib/system/libsystem_coretls.dylib +0x00000000072f5000 /usr/lib/system/libsystem_dnssd.dylib +0x00000000072f5000 /usr/lib/system/libsystem_info.dylib +0x00000000072f5000 /usr/lib/system/libsystem_kernel.dylib +0x00000000072f5000 /usr/lib/system/libsystem_m.dylib +0x00000000072f5000 /usr/lib/system/libsystem_malloc.dylib +0x00000000072f5000 /usr/lib/system/libsystem_network.dylib +0x00000000072f5000 /usr/lib/system/libsystem_networkextension.dylib +0x00000000072f5000 /usr/lib/system/libsystem_notify.dylib +0x00000000072f5000 /usr/lib/system/libsystem_platform.dylib +0x00000000072f5000 /usr/lib/system/libsystem_pthread.dylib +0x00000000072f5000 /usr/lib/system/libsystem_sandbox.dylib +0x00000000072f5000 /usr/lib/system/libsystem_secinit.dylib +0x00000000072f5000 /usr/lib/system/libsystem_trace.dylib +0x00000000072f5000 /usr/lib/system/libunc.dylib +0x00000000072f5000 /usr/lib/system/libunwind.dylib +0x00000000072f5000 /usr/lib/system/libxpc.dylib +0x00000000072f5000 /usr/lib/libenergytrace.dylib +0x00000000072f5000 /usr/lib/libbsm.0.dylib +0x00000000072f5000 /usr/lib/system/libkxld.dylib +0x00000000072f5000 /usr/lib/libxar.1.dylib +0x00000000072f5000 /usr/lib/libsqlite3.dylib +0x00000000072f5000 /usr/lib/libpam.2.dylib +0x00000000072f5000 /usr/lib/libOpenScriptingUtil.dylib +0x00000000072f5000 /usr/lib/libbz2.1.0.dylib +0x00000000072f5000 /usr/lib/liblzma.5.dylib +0x00000000072f5000 /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/FSEvents.framework/Versions/A/FSEvents +0x00000000072f5000 /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/CarbonCore.framework/Versions/A/CarbonCore +0x00000000072f5000 /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/Metadata.framework/Versions/A/Metadata +0x00000000072f5000 /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/OSServices.framework/Versions/A/OSServices +0x00000000072f5000 /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/SearchKit.framework/Versions/A/SearchKit +0x00000000072f5000 /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/AE.framework/Versions/A/AE +0x00000000072f5000 /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/LaunchServices +0x00000000072f5000 /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/DictionaryServices.framework/Versions/A/DictionaryServices +0x00000000072f5000 /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/SharedFileList.framework/Versions/A/SharedFileList +0x00000000072f5000 /System/Library/Frameworks/NetFS.framework/Versions/A/NetFS +0x00000000072f5000 /System/Library/PrivateFrameworks/NetAuth.framework/Versions/A/NetAuth +0x00000000072f5000 /System/Library/PrivateFrameworks/login.framework/Versions/A/Frameworks/loginsupport.framework/Versions/A/loginsupport +0x00000000072f5000 /System/Library/PrivateFrameworks/TCC.framework/Versions/A/TCC +0x00000000072f5000 /usr/lib/libmecabra.dylib +0x00000000072f5000 /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/ATS.framework/Versions/A/ATS +0x00000000072f5000 /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/ColorSync.framework/Versions/A/ColorSync +0x00000000072f5000 /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/HIServices.framework/Versions/A/HIServices +0x00000000072f5000 /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/LangAnalysis.framework/Versions/A/LangAnalysis +0x00000000072f5000 /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/PrintCore.framework/Versions/A/PrintCore +0x00000000072f5000 /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/QD.framework/Versions/A/QD +0x00000000072f5000 /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/SpeechSynthesis.framework/Versions/A/SpeechSynthesis +0x00000000072f5000 /System/Library/Frameworks/Metal.framework/Versions/A/Metal +0x00000000072f5000 /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vImage.framework/Versions/A/vImage +0x00000000072f5000 /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/vecLib +0x00000000072f5000 /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libvDSP.dylib +0x00000000072f5000 /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libvMisc.dylib +0x00000000072f5000 /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libLAPACK.dylib +0x00000000072f5000 /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib +0x00000000072f5000 /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libLinearAlgebra.dylib +0x00000000072f5000 /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libSparseBLAS.dylib +0x00000000072f5000 /System/Library/PrivateFrameworks/GPUCompiler.framework/libmetal_timestamp.dylib +0x00000000072f5000 /System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libCoreFSCache.dylib +0x00000000072f5000 /System/Library/PrivateFrameworks/IOAccelerator.framework/Versions/A/IOAccelerator +0x00000000072f5000 /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/ATS.framework/Versions/A/Resources/libFontParser.dylib +0x00000000072f5000 /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/ATS.framework/Versions/A/Resources/libFontRegistry.dylib +0x00000000072f5000 /System/Library/PrivateFrameworks/AppleVPA.framework/Versions/A/AppleVPA +0x00000000072f5000 /System/Library/PrivateFrameworks/AppleJPEG.framework/Versions/A/AppleJPEG +0x00000000072f5000 /System/Library/Frameworks/ImageIO.framework/Versions/A/Resources/libJPEG.dylib +0x00000000072f5000 /System/Library/Frameworks/ImageIO.framework/Versions/A/Resources/libTIFF.dylib +0x00000000072f5000 /System/Library/Frameworks/ImageIO.framework/Versions/A/Resources/libPng.dylib +0x00000000072f5000 /System/Library/Frameworks/ImageIO.framework/Versions/A/Resources/libGIF.dylib +0x00000000072f5000 /System/Library/Frameworks/ImageIO.framework/Versions/A/Resources/libJP2.dylib +0x00000000072f5000 /System/Library/Frameworks/ImageIO.framework/Versions/A/Resources/libRadiance.dylib +0x00000000072f5000 /System/Library/Frameworks/CoreVideo.framework/Versions/A/CoreVideo +0x00000000072f5000 /System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGLU.dylib +0x00000000072f5000 /System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGFXShared.dylib +0x00000000072f5000 /System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib +0x00000000072f5000 /System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGLImage.dylib +0x00000000072f5000 /System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libCVMSPluginSupport.dylib +0x00000000072f5000 /System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libCoreVMClient.dylib +0x00000000072f5000 /usr/lib/libcompression.dylib +0x00000000072f5000 /usr/lib/libcups.2.dylib +0x00000000072f5000 /System/Library/Frameworks/Kerberos.framework/Versions/A/Kerberos +0x00000000072f5000 /System/Library/Frameworks/GSS.framework/Versions/A/GSS +0x00000000072f5000 /usr/lib/libresolv.9.dylib +0x00000000072f5000 /usr/lib/libiconv.2.dylib +0x00000000072f5000 /System/Library/PrivateFrameworks/Heimdal.framework/Versions/A/Heimdal +0x00000000072f5000 /usr/lib/libheimdal-asn1.dylib +0x00000000072f5000 /System/Library/Frameworks/OpenDirectory.framework/Versions/A/OpenDirectory +0x00000000072f5000 /System/Library/PrivateFrameworks/CommonAuth.framework/Versions/A/CommonAuth +0x00000000072f5000 /System/Library/Frameworks/OpenDirectory.framework/Versions/A/Frameworks/CFOpenDirectory.framework/Versions/A/CFOpenDirectory +0x00000000072f5000 /System/Library/Frameworks/SecurityFoundation.framework/Versions/A/SecurityFoundation +0x00000000072f5000 /System/Library/PrivateFrameworks/LanguageModeling.framework/Versions/A/LanguageModeling +0x00000000072f5000 /usr/lib/libmarisa.dylib +0x00000000072f5000 /usr/lib/libChineseTokenizer.dylib +0x00000000072f5000 /usr/lib/libcmph.dylib +0x00000000072f5000 /System/Library/Frameworks/ServiceManagement.framework/Versions/A/ServiceManagement +0x00000000072f5000 /usr/lib/libxslt.1.dylib +0x00000000072f5000 /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/Ink.framework/Versions/A/Ink +0x00000000072f5000 /usr/lib/libFosl_dynamic.dylib +0x00000000072f5000 /System/Library/PrivateFrameworks/FaceCore.framework/Versions/A/FaceCore +0x00000000072f5000 /System/Library/Frameworks/OpenCL.framework/Versions/A/OpenCL +0x00000000072f5000 /System/Library/PrivateFrameworks/CrashReporterSupport.framework/Versions/A/CrashReporterSupport +0x00000000072f5000 /System/Library/PrivateFrameworks/IconServices.framework/Versions/A/IconServices +0x00000000072f5000 /System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Apple80211 +0x00000000072f5000 /System/Library/Frameworks/CoreWLAN.framework/Versions/A/CoreWLAN +0x00000000072f5000 /System/Library/Frameworks/IOBluetooth.framework/Versions/A/IOBluetooth +0x00000000072f5000 /System/Library/PrivateFrameworks/CoreWiFi.framework/Versions/A/CoreWiFi +0x00000000072f5000 /System/Library/Frameworks/CoreBluetooth.framework/Versions/A/CoreBluetooth +0x00000000072f5000 /System/Library/PrivateFrameworks/ChunkingLibrary.framework/Versions/A/ChunkingLibrary +0x00000000072f5000 /System/Library/PrivateFrameworks/DebugSymbols.framework/Versions/A/DebugSymbols +0x00000000072f5000 /System/Library/PrivateFrameworks/CoreSymbolication.framework/Versions/A/CoreSymbolication +0x00000000072f5000 /System/Library/PrivateFrameworks/Symbolication.framework/Versions/A/Symbolication +0x00000000072f5000 /System/Library/PrivateFrameworks/SpeechRecognitionCore.framework/Versions/A/SpeechRecognitionCore +0x000000010a200000 /Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/server/libjvm.dylib +0x00000000072f5000 /usr/lib/libstdc++.6.dylib +0x0000000109084000 /Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/libverify.dylib +0x0000000109092000 /Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/libjava.dylib +0x00000001090c8000 /Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/libinstrument.dylib +0x0000000109126000 /Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/libzip.dylib +0x0000000126148000 /System/Library/Frameworks/JavaVM.framework/Frameworks/JavaRuntimeSupport.framework/JavaRuntimeSupport +0x0000000126163000 /System/Library/Frameworks/JavaVM.framework/Versions/A/Frameworks/JavaNativeFoundation.framework/Versions/A/JavaNativeFoundation +0x0000000126178000 /System/Library/Frameworks/JavaVM.framework/Versions/A/JavaVM +0x00000000072f5000 /System/Library/Frameworks/Carbon.framework/Versions/A/Carbon +0x0000000126185000 /System/Library/PrivateFrameworks/JavaLaunching.framework/Versions/A/JavaLaunching +0x00000000072f5000 /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/CommonPanels.framework/Versions/A/CommonPanels +0x00000000072f5000 /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/Help.framework/Versions/A/Help +0x00000000072f5000 /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/ImageCapture.framework/Versions/A/ImageCapture +0x00000000072f5000 /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/OpenScripting.framework/Versions/A/OpenScripting +0x00000000072f5000 /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/Print.framework/Versions/A/Print +0x00000000072f5000 /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/SecurityHI.framework/Versions/A/SecurityHI +0x0000000128600000 /Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/libnet.dylib +0x0000000128661000 /Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/libawt.dylib +0x0000000128709000 /Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/./libmlib_image.dylib +0x00000001287d5000 /Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/libawt_lwawt.dylib +0x000000012888a000 /Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/./libosxapp.dylib +0x00000000072f5000 /System/Library/Frameworks/ExceptionHandling.framework/Versions/A/ExceptionHandling +0x00000000072f5000 /System/Library/PrivateFrameworks/CoreServicesInternal.framework/Versions/A/CoreServicesInternal +0x00000000072f5000 /System/Library/Frameworks/CoreGraphics.framework/Versions/A/Resources/libRIP.A.dylib +0x00000000072f5000 /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vImage.framework/Versions/A/Libraries/libCGInterfaces.dylib +0x00000000072f5000 /System/Library/Frameworks/CoreGraphics.framework/Versions/A/Resources/libCGXType.A.dylib +0x00000000072f5000 /System/Library/Frameworks/OpenCL.framework/Versions/A/Libraries/libcldcpuengine.dylib +0x00000000072f5000 /System/Library/PrivateFrameworks/DiskImages.framework/Versions/A/DiskImages +0x00000000072f5000 /System/Library/Frameworks/DiscRecording.framework/Versions/A/DiscRecording +0x00000000072f5000 /usr/lib/libcsfde.dylib +0x00000000072f5000 /usr/lib/libcurl.4.dylib +0x00000000072f5000 /System/Library/PrivateFrameworks/MediaKit.framework/Versions/A/MediaKit +0x00000000072f5000 /System/Library/PrivateFrameworks/ProtectedCloudStorage.framework/Versions/A/ProtectedCloudStorage +0x00000000072f5000 /usr/lib/libCoreStorage.dylib +0x00000000072f5000 /System/Library/PrivateFrameworks/EFILogin.framework/Versions/A/EFILogin +0x00000000072f5000 /usr/lib/libutil.dylib +0x00000000072f5000 /System/Library/PrivateFrameworks/FindMyDevice.framework/Versions/A/FindMyDevice +0x00000000072f5000 /System/Library/Frameworks/LDAP.framework/Versions/A/LDAP +0x00000000072f5000 /usr/lib/libsasl2.2.dylib +0x00000000072f5000 /System/Library/PrivateFrameworks/CoreDaemon.framework/Versions/B/CoreDaemon +0x00000000072f5000 /usr/lib/libcrypto.0.9.8.dylib +0x00000000072f5000 /System/Library/PrivateFrameworks/AppleSRP.framework/Versions/A/AppleSRP +0x00000000072f5000 /System/Library/PrivateFrameworks/TrustEvaluationAgent.framework/Versions/A/TrustEvaluationAgent +0x00000001297fd000 cl_kernels +0x00000000072f5000 /System/Library/Frameworks/OpenCL.framework/Versions/A/Libraries/ImageFormats/unorm8_bgra.dylib +0x00000000072f5000 /System/Library/Frameworks/OpenCL.framework/Versions/A/Libraries/ImageFormats/unorm8_rgba.dylib +0x00000000072f5000 /System/Library/PrivateFrameworks/FamilyControls.framework/Versions/A/FamilyControls +0x00000000072f5000 /System/Library/PrivateFrameworks/CommerceKit.framework/Versions/A/Frameworks/CommerceCore.framework/Versions/A/CommerceCore +0x00000000072f5000 /System/Library/PrivateFrameworks/SystemAdministration.framework/Versions/A/SystemAdministration +0x00000000072f5000 /System/Library/PrivateFrameworks/AppContainer.framework/Versions/A/AppContainer +0x00000000072f5000 /System/Library/PrivateFrameworks/SecCodeWrapper.framework/Versions/A/SecCodeWrapper +0x00000000072f5000 /System/Library/Frameworks/DirectoryService.framework/Versions/A/DirectoryService +0x00000000072f5000 /System/Library/PrivateFrameworks/LoginUIKit.framework/Versions/A/Frameworks/LoginUICore.framework/Versions/A/LoginUICore +0x00000000072f5000 /usr/lib/libodfde.dylib +0x00000001298f7000 /Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/libfontmanager.dylib +0x00000001299d6000 /Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/libnio.dylib +0x000000012954a000 /private/var/folders/td/djw6lgtj5tx3f27yqjn1qk240000gp/T/jogamp_0000/file_cache/jln6271106923964908699/jln8600969762585133251/libgluegen-rt.jnilib +0x0000000129420000 /private/var/folders/td/djw6lgtj5tx3f27yqjn1qk240000gp/T/jogamp_0000/file_cache/jln6271106923964908699/jln8600969762585133251/libnativewindow_awt.jnilib +0x0000000129423000 /Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/libjawt.dylib +0x000000012a7a2000 /System/Library/Frameworks/OpenGL.framework/Resources/GLEngine.bundle/GLEngine +0x00000000072f5000 /System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGLProgrammability.dylib +0x000000012bf2e000 /System/Library/Extensions/AppleIntelHD5000GraphicsGLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsGLDriver +0x00000000072f5000 /System/Library/PrivateFrameworks/GPUSupport.framework/Versions/A/Libraries/libGPUSupportMercury.dylib +0x000000012bbd8000 /System/Library/Extensions/AMDRadeonX4000GLDriver.bundle/Contents/MacOS/AMDRadeonX4000GLDriver +0x000000012c67d000 /System/Library/Extensions/AMDRadeonX4000GLDriver.bundle/Contents/MacOS/ATIRadeonX4000SCLib.dylib +0x00000001297a8000 /System/Library/Frameworks/OpenGL.framework/Resources//GLRendererFloat.bundle/GLRendererFloat +0x000000012a98a000 /private/var/folders/td/djw6lgtj5tx3f27yqjn1qk240000gp/T/jogamp_0000/file_cache/jln6271106923964908699/jln8600969762585133251/libnativewindow_macosx.jnilib +0x000000012d0a0000 /private/var/folders/td/djw6lgtj5tx3f27yqjn1qk240000gp/T/jogamp_0000/file_cache/jln6271106923964908699/jln8600969762585133251/libjogl_desktop.jnilib +0x000000012a6d0000 /Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/libosx.dylib +0x000000012a6de000 /Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/libosxui.dylib +0x00000000072f5000 /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/ATS.framework/Versions/A/Resources/libTrueTypeScaler.dylib +0x0000000194461000 /System/Library/Extensions/AMDMTLBronzeDriver.bundle/Contents/MacOS/AMDMTLBronzeDriver +0x00000000072f5000 /System/Library/PrivateFrameworks/IOAccelMemoryInfo.framework/Versions/A/IOAccelMemoryInfo +0x00000001945c0000 /System/Library/Extensions/AppleIntelHD5000GraphicsMTLDriver.bundle/Contents/MacOS/AppleIntelHD5000GraphicsMTLDriver +0x00000000072f5000 /System/Library/PrivateFrameworks/CloudDocs.framework/Versions/A/CloudDocs +0x00000000072f5000 /System/Library/PrivateFrameworks/CoreDuet.framework/Versions/A/CoreDuet +0x00000000072f5000 /System/Library/Frameworks/CloudKit.framework/Versions/A/CloudKit +0x00000000072f5000 /System/Library/PrivateFrameworks/ProtocolBuffer.framework/Versions/A/ProtocolBuffer +0x00000000072f5000 /System/Library/PrivateFrameworks/CoreDuetDaemonProtocol.framework/Versions/A/CoreDuetDaemonProtocol +0x00000000072f5000 /System/Library/PrivateFrameworks/CoreDuetDebugLogging.framework/Versions/A/CoreDuetDebugLogging +0x00000000072f5000 /System/Library/PrivateFrameworks/MMCS.framework/Versions/A/MMCS +0x00000000072f5000 /System/Library/Frameworks/CoreLocation.framework/Versions/A/CoreLocation +0x00000000072f5000 /System/Library/PrivateFrameworks/AssetCacheServices.framework/Versions/A/AssetCacheServices +0x00000000072f5000 /System/Library/PrivateFrameworks/GeoServices.framework/Versions/A/GeoServices +0x000000012e0f0000 /Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/libdcpr.dylib + +VM Arguments: +jvm_args: -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=51930:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 +java_command: com.intellij.uiDesigner.snapShooter.SnapShooter 121 51929 cct.JamberooMolecularEditor +java_class_path (initial): /Applications/IntelliJ IDEA.app/Contents/plugins/uiDesigner/lib/uiDesigner.jar:/Applications/IntelliJ IDEA.app/Contents/lib/xercesImpl.jar:/Applications/IntelliJ IDEA.app/Contents/lib/util.jar:/Applications/IntelliJ IDEA.app/Contents/lib/trove4j.jar:/Applications/IntelliJ IDEA.app/Contents/lib/snappy-in-java-0.5.1.jar:/Applications/IntelliJ IDEA.app/Contents/lib/resources_en.jar:/Applications/IntelliJ IDEA.app/Contents/lib/oromatcher.jar:/Applications/IntelliJ IDEA.app/Contents/lib/openapi.jar:/Applications/IntelliJ IDEA.app/Contents/lib/log4j.jar:/Applications/IntelliJ IDEA.app/Contents/lib/jna.jar:/Applications/IntelliJ IDEA.app/Contents/lib/jna-platform.jar:/Applications/IntelliJ IDEA.app/Contents/lib/jgoodies-forms.jar:/Applications/IntelliJ IDEA.app/Contents/lib/jdom.jar:/Applications/IntelliJ IDEA.app/Contents/lib/idea.jar:/Applications/IntelliJ IDEA.app/Contents/lib/forms_rt.jar:/Applications/IntelliJ IDEA.app/Contents/lib/extensions.jar:/Applications/IntelliJ IDEA.app/Contents/lib/batik-all.jar:/Applications/IntelliJ IDEA.app/Contents/lib/annotations.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/ +Launcher Type: SUN_STANDARD + +Environment Variables: +JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home +PATH=/Users/spamidig1/anaconda/bin:/Users/spamidig1/anaconda/bin://anaconda/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/Users/spamidig/Applications/apache-ant-1.9.4/bin:/Users/spamidig/Applications/apache-maven-3.2.3/bin +SHELL=/bin/bash +DISPLAY=/private/tmp/com.apple.launchd.zl7yJOdFoM/org.macosforge.xquartz:0 + +Signal Handlers: +SIGSEGV: [libjvm.dylib+0x5a65d5], sa_mask[0]=11111111011111110111111111111111, sa_flags=SA_ONSTACK|SA_RESTART|SA_SIGINFO +SIGBUS: [libjvm.dylib+0x5a65d5], sa_mask[0]=11111111011111110111111111111111, sa_flags=SA_RESTART|SA_SIGINFO +SIGFPE: [libjvm.dylib+0x4802e8], sa_mask[0]=11111111011111110111111111111111, sa_flags=SA_RESTART|SA_SIGINFO +SIGPIPE: [libjvm.dylib+0x4802e8], sa_mask[0]=11111111011111110111111111111111, sa_flags=SA_RESTART|SA_SIGINFO +SIGXFSZ: [libjvm.dylib+0x4802e8], sa_mask[0]=11111111011111110111111111111111, sa_flags=SA_RESTART|SA_SIGINFO +SIGILL: [libjvm.dylib+0x4802e8], sa_mask[0]=11111111011111110111111111111111, sa_flags=SA_RESTART|SA_SIGINFO +SIGUSR1: SIG_DFL, sa_mask[0]=00000000000000000000000000000000, sa_flags=none +SIGUSR2: [libjvm.dylib+0x47fe06], sa_mask[0]=00100000000000000000000000000000, sa_flags=SA_RESTART|SA_SIGINFO +SIGHUP: [libjvm.dylib+0x47e3dd], sa_mask[0]=11111111011111110111111111111111, sa_flags=SA_RESTART|SA_SIGINFO +SIGINT: [libjvm.dylib+0x47e3dd], sa_mask[0]=11111111011111110111111111111111, sa_flags=SA_RESTART|SA_SIGINFO +SIGTERM: [libjvm.dylib+0x47e3dd], sa_mask[0]=11111111011111110111111111111111, sa_flags=SA_RESTART|SA_SIGINFO +SIGQUIT: [libjvm.dylib+0x47e3dd], sa_mask[0]=11111111011111110111111111111111, sa_flags=SA_RESTART|SA_SIGINFO + + +--------------- S Y S T E M --------------- + +OS:Bsduname:Darwin 15.6.0 Darwin Kernel Version 15.6.0: Fri Feb 17 10:21:18 PST 2017; root:xnu-3248.60.11.4.1~1/RELEASE_X86_64 x86_64 +rlimit: STACK 8192k, CORE 0k, NPROC 709, NOFILE 10240, AS infinity +load average:2.34 3.30 3.36 + +CPU:total 8 (4 cores per cpu, 2 threads per core) family 6 model 70 stepping 1, cmov, cx8, fxsr, mmx, sse, sse2, sse3, ssse3, sse4.1, sse4.2, popcnt, avx, avx2, aes, clmul, erms, lzcnt, ht, tsc, tscinvbit, bmi1, bmi2 + +Memory: 4k page, physical 16777216k(599864k free) + +/proc/meminfo: + + +vm_info: Java HotSpot(TM) 64-Bit Server VM (25.66-b17) for bsd-amd64 JRE (1.8.0_66-b17), built on Oct 6 2015 16:09:13 by "java_re" with gcc 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00) + +time: Thu Apr 27 14:51:18 2017 +elapsed time: 8 seconds (0d 0h 0m 8s) + diff --git a/init-auto-update.sh b/init-auto-update.sh new file mode 100644 index 0000000..5041085 --- /dev/null +++ b/init-auto-update.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +java -jar updatefx-app-1.5.jar --url=https://seagrid.org/seagrid-rich-client/site ./ + +cp -R site /var/www/portals/seagrid/public/seagrid-rich-client \ No newline at end of file diff --git a/jamberoo-libs/Fragments.jar b/jamberoo-libs/Fragments.jar new file mode 100644 index 0000000..f107d41 Binary files /dev/null and b/jamberoo-libs/Fragments.jar differ diff --git a/jamberoo-libs/Jamberoo-help.jar b/jamberoo-libs/Jamberoo-help.jar new file mode 100644 index 0000000..59eb151 Binary files /dev/null and b/jamberoo-libs/Jamberoo-help.jar differ diff --git a/jamberoo-libs/Solvents.jar b/jamberoo-libs/Solvents.jar new file mode 100644 index 0000000..8454072 Binary files /dev/null and b/jamberoo-libs/Solvents.jar differ diff --git a/jamberoo-libs/bsh-2.0b4.jar b/jamberoo-libs/bsh-2.0b4.jar new file mode 100644 index 0000000..36fe03d Binary files /dev/null and b/jamberoo-libs/bsh-2.0b4.jar differ diff --git a/jamberoo-libs/cct-globus.jar b/jamberoo-libs/cct-globus.jar new file mode 100644 index 0000000..1f50a69 Binary files /dev/null and b/jamberoo-libs/cct-globus.jar differ diff --git a/jamberoo-libs/j2ssh-common.jar b/jamberoo-libs/j2ssh-common.jar new file mode 100644 index 0000000..2e44d41 Binary files /dev/null and b/jamberoo-libs/j2ssh-common.jar differ diff --git a/jamberoo-libs/j2ssh-core.jar b/jamberoo-libs/j2ssh-core.jar new file mode 100644 index 0000000..7ba5eda Binary files /dev/null and b/jamberoo-libs/j2ssh-core.jar differ diff --git a/jamberoo-libs/jbzip2-0.9.1.jar b/jamberoo-libs/jbzip2-0.9.1.jar new file mode 100644 index 0000000..138d342 Binary files /dev/null and b/jamberoo-libs/jbzip2-0.9.1.jar differ diff --git a/jamberoo-libs/jcommon-1.0.12.jar b/jamberoo-libs/jcommon-1.0.12.jar new file mode 100644 index 0000000..b46a2b6 Binary files /dev/null and b/jamberoo-libs/jcommon-1.0.12.jar differ diff --git a/jamberoo-libs/jfreechart-1.0.9.jar b/jamberoo-libs/jfreechart-1.0.9.jar new file mode 100644 index 0000000..d1e2b74 Binary files /dev/null and b/jamberoo-libs/jfreechart-1.0.9.jar differ diff --git a/jamberoo-libs/jhall.jar b/jamberoo-libs/jhall.jar new file mode 100644 index 0000000..80451a9 Binary files /dev/null and b/jamberoo-libs/jhall.jar differ diff --git a/jamberoo-libs/mvn_install_libs.bat b/jamberoo-libs/mvn_install_libs.bat new file mode 100644 index 0000000..b012d3d --- /dev/null +++ b/jamberoo-libs/mvn_install_libs.bat @@ -0,0 +1,12 @@ +mvn install:install-file -DgroupId=jamberoo -DartifactId=bsh-2.0b4 -Dversion=1.0 -Dpackaging=jar -Dfile=./bsh-2.0b4.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=cct-globus -Dversion=1.0 -Dpackaging=jar -Dfile=./cct-globus.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=Fragments -Dversion=1.0 -Dpackaging=jar -Dfile=./Fragments.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=j2ssh-common -Dversion=1.0 -Dpackaging=jar -Dfile=./j2ssh-common.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=j2ssh-core -Dversion=1.0 -Dpackaging=jar -Dfile=./j2ssh-core.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=Jamberoo-help -Dversion=1.0 -Dpackaging=jar -Dfile=./Jamberoo-help.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=jbzip2-0.9.1 -Dversion=1.0 -Dpackaging=jar -Dfile=./jbzip2-0.9.1.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=jcommon-1.0.12 -Dversion=1.0 -Dpackaging=jar -Dfile=./jcommon-1.0.12.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=jfreechart-1.0.9 -Dversion=1.0 -Dpackaging=jar -Dfile=./jfreechart-1.0.9.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=jhall -Dversion=1.0 -Dpackaging=jar -Dfile=./jhall.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=mysql-connector-java-5.1.33-bin -Dversion=1.0 -Dpackaging=jar -Dfile=./mysql-connector-java-5.1.33-bin.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=Solvents -Dversion=1.0 -Dpackaging=jar -Dfile=./Solvents.jar \ No newline at end of file diff --git a/jamberoo-libs/mvn_install_libs.sh b/jamberoo-libs/mvn_install_libs.sh new file mode 100644 index 0000000..6dc31c4 --- /dev/null +++ b/jamberoo-libs/mvn_install_libs.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash + +mvn install:install-file -DgroupId=jamberoo -DartifactId=bsh-2.0b4 -Dversion=1.0 -Dpackaging=jar -Dfile=./bsh-2.0b4.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=cct-globus -Dversion=1.0 -Dpackaging=jar -Dfile=./cct-globus.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=Fragments -Dversion=1.0 -Dpackaging=jar -Dfile=./Fragments.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=j2ssh-common -Dversion=1.0 -Dpackaging=jar -Dfile=./j2ssh-common.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=j2ssh-core -Dversion=1.0 -Dpackaging=jar -Dfile=./j2ssh-core.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=Jamberoo-help -Dversion=1.0 -Dpackaging=jar -Dfile=./Jamberoo-help.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=jbzip2-0.9.1 -Dversion=1.0 -Dpackaging=jar -Dfile=./jbzip2-0.9.1.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=jcommon-1.0.12 -Dversion=1.0 -Dpackaging=jar -Dfile=./jcommon-1.0.12.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=jfreechart-1.0.9 -Dversion=1.0 -Dpackaging=jar -Dfile=./jfreechart-1.0.9.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=jhall -Dversion=1.0 -Dpackaging=jar -Dfile=./jhall.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=mysql-connector-java-5.1.33-bin -Dversion=1.0 -Dpackaging=jar -Dfile=./mysql-connector-java-5.1.33-bin.jar +mvn install:install-file -DgroupId=jamberoo -DartifactId=Solvents -Dversion=1.0 -Dpackaging=jar -Dfile=./Solvents.jar \ No newline at end of file diff --git a/jamberoo-libs/mysql-connector-java-5.1.33-bin.jar b/jamberoo-libs/mysql-connector-java-5.1.33-bin.jar new file mode 100644 index 0000000..6f94c03 Binary files /dev/null and b/jamberoo-libs/mysql-connector-java-5.1.33-bin.jar differ diff --git a/javapackager.sh b/javapackager.sh new file mode 100644 index 0000000..3c6bffc --- /dev/null +++ b/javapackager.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +$JAVA_HOME/bin/javapackager -deploy -native -outdir distribution -outfile SEAGridDesktop -srcdir builds/processed -srcfiles 1.jar\ + -appclass org.seagrid.desktop.SEAGridDesktop -name "SEAGridDesktop" -title "SEAGridDesktop" \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..cb2a06c --- /dev/null +++ b/pom.xml @@ -0,0 +1,425 @@ + + + 4.0.0 + + org.seagrid + seagrid-app + SEAGrid Desktop Client + 1.0 + + + + 0.17-SNAPSHOT + + + + SEAGridDesktop + + + org.seagrid.desktop.SEAGridDesktop + + + + + + Indiana University + + + 1.0 + + + app.icns + + + + https://seagrid.org/seagrid-rich-client/ + + + + + root@gf4.ucs.indiana.edu:/var/www/portals/seagrid/public/seagrid-rich-client + + + + + + + + ${project.build.directory}/app + + + ${project.build.directory}/installer + + UTF-8 + + + + + default + + true + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 1.8 + 1.8 + + + + + + + update-deployment + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + ${app.dir} + + + + + + org.apache.maven.plugins + maven-dependency-plugin + 2.10 + + provided + ${app.dir} + true + + + + package + + copy-dependencies + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.4.0 + + + + create-manifest + package + + java + + + fxlauncher.CreateManifest + + ${app.url} + ${app.mainClass} + ${app.dir} + ${app.parameters} + + + + + + + embed-manifest-in-launcher + package + + exec + + + jar + ${app.dir} + + uf + fxlauncher.jar + app.xml + + + + + + + installer + install + + exec + + + ${env.JAVA_HOME}/bin/javapackager + + -deploy + -native + -outdir + ${app.installerdir} + -outfile + ${app.filename} + -srcdir + ${app.dir} + -srcfiles + fxlauncher.jar + -appclass + fxlauncher.Launcher + -name + ${project.name} + -title + ${project.name} + -vendor + ${app.vendor} + -BappVersion=${app.version} + -Bicon=${app.icon} + -Bmac.signing-key-user-name=${app.vendor} + + + + + + deploy-app + + exec + + + scp + + -r + ${app.dir}/. + ${app.deploy.target} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 1.8 + 1.8 + + + + + + + + + + + no.tornado + fxlauncher + 1.0.8 + + + + + org.apache.airavata + airavata-data-models + ${airavata.version} + + + org.apache.airavata + airavata-model-utils + ${airavata.version} + + + org.apache.airavata + airavata-api-stubs + ${airavata.version} + + + org.apache.airavata + airavata-client-configuration + ${airavata.version} + + + + + org.controlsfx + controlsfx + 8.40.10 + + + + + org.codehaus.jackson + jackson-mapper-asl + 1.8.5 + + + org.apache.oltu.oauth2 + org.apache.oltu.oauth2.client + 1.0.0 + + + + + + commons-lang + commons-lang + 2.6 + + + commons-collections + commons-collections + 3.2.2 + + + + + com.jcraft + jsch + 0.1.53 + + + + + + com.google.guava + guava + 18.0 + + + + + org.slf4j + slf4j-log4j12 + 1.7.12 + + + + + jamberoo + bsh-2.0b4 + 1.0 + + + jamberoo + cct-globus + 1.0 + + + jamberoo + Fragments + 1.0 + + + jamberoo + j2ssh-common + 1.0 + + + jamberoo + j2ssh-core + 1.0 + + + jamberoo + Jamberoo-help + 1.0 + + + jamberoo + jbzip2-0.9.1 + 1.0 + + + jamberoo + jcommon-1.0.12 + 1.0 + + + jamberoo + jfreechart-1.0.9 + 1.0 + + + jamberoo + jhall + 1.0 + + + jamberoo + mysql-connector-java-5.1.33-bin + 1.0 + + + jamberoo + Solvents + 1.0 + + + org.jogamp.jogl + jogl-all-main + 2.3.2 + + + org.jogamp.gluegen + gluegen-rt-main + 2.3.2 + + + + + org.scijava + j3dutils + 1.6.0-scijava-2 + + + org.scijava + j3dcore + 1.6.0-scijava-2 + + + org.scijava + vecmath + 1.6.0-scijava-2 + + + org.apache.httpcomponents + httpclient + 4.5.5 + + + org.json + json + 20180130 + + + com.github.lookfirst + sardine + 5.8 + + + + + + apache.snapshots + Apache Snapshot Repository + http://repository.apache.org/snapshots + + false + + + + Codehaus Mojo + Codehaus Mojo + https://nexus.codehaus.org/contents/repositories/releases + + + + + diff --git a/src/.DS_Store b/src/.DS_Store new file mode 100644 index 0000000..8ac1f29 Binary files /dev/null and b/src/.DS_Store differ diff --git a/src/main/.DS_Store b/src/main/.DS_Store new file mode 100644 index 0000000..d5d1348 Binary files /dev/null and b/src/main/.DS_Store differ diff --git a/src/main/client_truststore.jks b/src/main/client_truststore.jks new file mode 100644 index 0000000..21e4e62 Binary files /dev/null and b/src/main/client_truststore.jks differ diff --git a/src/main/deploy/.DS_Store b/src/main/deploy/.DS_Store new file mode 100644 index 0000000..7b3e43f Binary files /dev/null and b/src/main/deploy/.DS_Store differ diff --git a/src/main/deploy/._.DS_Store b/src/main/deploy/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/deploy/._.DS_Store differ diff --git a/src/main/deploy/package/.DS_Store b/src/main/deploy/package/.DS_Store new file mode 100644 index 0000000..1430251 Binary files /dev/null and b/src/main/deploy/package/.DS_Store differ diff --git a/src/main/deploy/package/._.DS_Store b/src/main/deploy/package/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/deploy/package/._.DS_Store differ diff --git a/src/main/deploy/package/macosx/seagrid-app-0.1-SNAPSHOT.icns b/src/main/deploy/package/macosx/seagrid-app-0.1-SNAPSHOT.icns new file mode 100644 index 0000000..8c5bc3c Binary files /dev/null and b/src/main/deploy/package/macosx/seagrid-app-0.1-SNAPSHOT.icns differ diff --git a/src/main/deploy/package/macosx/seagrid-app-0.1-SNAPSHOT.ico b/src/main/deploy/package/macosx/seagrid-app-0.1-SNAPSHOT.ico new file mode 100644 index 0000000..2f12686 Binary files /dev/null and b/src/main/deploy/package/macosx/seagrid-app-0.1-SNAPSHOT.ico differ diff --git a/src/main/java/.DS_Store b/src/main/java/.DS_Store new file mode 100644 index 0000000..e0ce407 Binary files /dev/null and b/src/main/java/.DS_Store differ diff --git a/src/main/java/cct/.DS_Store b/src/main/java/cct/.DS_Store new file mode 100644 index 0000000..3a5abcc Binary files /dev/null and b/src/main/java/cct/.DS_Store differ diff --git a/src/main/java/cct/._.DS_Store b/src/main/java/cct/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/cct/._.DS_Store differ diff --git a/src/main/java/cct/Constants.java b/src/main/java/cct/Constants.java new file mode 100644 index 0000000..730cc6c --- /dev/null +++ b/src/main/java/cct/Constants.java @@ -0,0 +1,63 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class Constants { + + public static final double ONE_BOHR = 0.529177249; // In Angstrom + public static final float ONE_BOHR_FLOAT = (float) ONE_BOHR; // In Angstrom + public static final double DEGREES_TO_RADIANS = Math.PI / 180.0; + public static final double RADIANS_TO_DEGREES = 180.0 / Math.PI; + public static final double FROM_CAL_TO_J = 4.1868; + + public static final double GAS_CONSTANT = 8.31436; // in J/(K*mol) + + private Constants() { + } +} diff --git a/src/main/java/cct/GlobalConstants.java b/src/main/java/cct/GlobalConstants.java new file mode 100644 index 0000000..9f6def5 --- /dev/null +++ b/src/main/java/cct/GlobalConstants.java @@ -0,0 +1,57 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct; + +/** + *

Title: Jamberoo - Java Molecular Editor

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2009

+ * + *

Company:

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ + +public interface GlobalConstants { + + double ONE_BOHR = Constants.ONE_BOHR; // In Angstrom + float ONE_BOHR_FLOAT = (float) ONE_BOHR; // In Angstrom + double RADIANS_TO_DEGREES = Constants.RADIANS_TO_DEGREES; +} diff --git a/src/main/java/cct/GlobalSettings.java b/src/main/java/cct/GlobalSettings.java new file mode 100644 index 0000000..72db23a --- /dev/null +++ b/src/main/java/cct/GlobalSettings.java @@ -0,0 +1,464 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct; + +import cct.config.FormatObject; +import org.w3c.dom.Document; + +import javax.swing.*; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import java.awt.*; +import java.io.File; +import java.io.InputStream; +import java.net.URI; +import java.net.URL; +import java.util.*; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class GlobalSettings { + + public enum ADD_MOLECULE_MODE { + + SET, APPEND + } + static final String MESSAGES_BUNDLE = "cct/MessagesBundle"; + static final boolean PublicRelease = false; + static final boolean New_Database = true; + public static final String CUSTOM_PROPERTIES_FILE = "cct/custom.properties"; + public static final String DIVIDER = "@"; + public static final String CWD_KEY = "cwd"; + public static final String URL_HOME_PAGE = "urlHomePage"; + public static final String HELP_EMAIL = "helpEMail"; + public static final String lastPWDKey = "lastPWD"; + static final String defaultFragmentDictionary = "defaultFragments.dic"; + static final String defaultSolventDictionary = "defaultSolvent.dic"; + public static final String CCT_PROPERTY_FILE = "cct/cct.properties"; + public static final String FORMATS_XML_FILE = "cct/formats.xml"; + public static final String CCT_CONFIG_XML_FILE = "cct/cct-config.xml"; + public static final String MOLECULE_INTERFACE_CLASS = "moleculeInterfaceClass"; + private static Properties customProperties = null; + private static boolean customPropsInitiated = false; + private static URL customPropsURL = null; + private static Properties cctProperties = null; + private static boolean cctPropsInitiated = false; + private static URL cctPropsURL = null; + private static Map sessionProps = new HashMap(); + private static Document cctConfig; + private static Map formats; + private static Map> extensionToParser; + private static Map registeredDialogs = new HashMap(); + // --- Icon images + public static final ImageIcon ICON_16x16_OPEN_FILE = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/openFile.png")); + public static final ImageIcon ICON_16x16_GAUSSIAN = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/gaussian-16x16.png")); + public static final ImageIcon ICON_16x16_MOPAC = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/mopac-16x16.png")); + public static final ImageIcon ICON_16x16_GAMESS = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/banned-by-gaussian-16x16.png")); + public static final ImageIcon ICON_16x16_ADF = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/adf-16x16.png")); + public static final ImageIcon ICON_16x16_SIESTA = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/siesta-16x16.png")); + public static final ImageIcon ICON_16x16_MDL = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/MDL-16x16.png")); + public static final ImageIcon ICON_16x16_GROMACS = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/gromacs-16x16.png")); + public static final ImageIcon ICON_16x16_VASP = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/vasp-16x16.png")); + public static final ImageIcon ICON_16x16_QCHEM = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/qchem-16x16.png")); + public static final ImageIcon ICON_16x16_GULP = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/gulp-16x16.png")); + public static final ImageIcon ICON_16x16_MOLECULE = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/mol-3.png")); + public static final ImageIcon ICON_16x16_LINE_CHART = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/line-chart.png")); + public static final ImageIcon ICON_16x16_ADD_COMPONENT = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/component_add.png")); + public static final ImageIcon ICON_16x16_POVRAY = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/povray-file.png")); + public static final ImageIcon ICON_16x16_REMOTE_DOWNLOAD = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/307-web_download.png")); + public static final ImageIcon ICON_16x16_IMAGE_FILE = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/image-file.png")); + public static final ImageIcon ICON_16x16_GEAR = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/gear.png")); + public static final ImageIcon ICON_16x16_SERVER_INTO = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/server_into.png")); + public static final ImageIcon ICON_16x16_DOCUMENT_WARNING = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/document_warning.png")); + public static final ImageIcon ICON_16x16_ERROR = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/error.png")); + public static final ImageIcon ICON_16x16_DOCUMENT_EDIT = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/document_edit.png")); + public static final ImageIcon ICON_16x16_DOCUMENT_INTO = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/document_into.png")); + public static final ImageIcon ICON_16x16_DOCUMENT_OUT = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/document_out.png")); + public static final ImageIcon ICON_16x16_ADD_ATOM = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/add-atom.gif")); + public static final ImageIcon ICON_16x16_ADD_FRAGMENT = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/add-fragment.png")); + public static final ImageIcon ICON_16x16_WRENCH = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/wrench.png")); + public static final ImageIcon ICON_16x16_ATOM = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/atom.png")); + public static final ImageIcon ICON_16x16_BOND = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/bond-16x16.gif")); + public static final ImageIcon ICON_16x16_ANGLE = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/angle-16x16.gif")); + public static final ImageIcon ICON_16x16_HUMMER = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/hummer-16x16.gif")); + public static final ImageIcon ICON_16x16_CUT = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/cut-16x16.gif")); + public static final ImageIcon ICON_16x16_CENTROID = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/centroid.png")); + public static final ImageIcon ICON_16x16_ADD_ENTRY = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/addEntry.png")); + public static final ImageIcon ICON_16x16_REMOVE_ENTRY = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/removeEntry.png")); + public static final ImageIcon ICON_16x16_DIHEDRAL = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/dihedral.png")); + public static final ImageIcon ICON_16x16_JAVA_FILE = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/java-file.png")); + public static final ImageIcon ICON_16x16_SERVER_CLIENT = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/server_client.png")); + public static final ImageIcon ICON_16x16_DOCUMENT_GEAR = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/document_gear.png")); + public static final ImageIcon ICON_16x16_DOCUMENT_INFO = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/document_info.png")); + public static final ImageIcon ICON_16x16_MEMORY_MONITOR = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/memory-monitor-16x16.png")); + public static final ImageIcon ICON_16x16_RECYCLE = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/recycle.png")); + public static final ImageIcon ICON_32x32_SERVER_FROM_CLIENT = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons32x32/server_from_client.png")); + // + static final Logger logger = Logger.getLogger(GlobalSettings.class.getCanonicalName()); + static private GlobalSettings mock = new GlobalSettings(); + + private static Locale currentLocale; + private static ResourceBundle messages; + + private GlobalSettings() { + getProperties(); + getCustomProperties(); + loadConfig(); + try { + //currentLocale = new Locale("ru", "RU"); + currentLocale = Locale.getDefault(); + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Current Locale: " + currentLocale.toString()); + } + messages = ResourceBundle.getBundle(MESSAGES_BUNDLE, currentLocale); + } catch (Exception ex) { + logger.warning("Cannot get resource : " + MESSAGES_BUNDLE + " : " + ex.getMessage()); + } + } + + static void loadConfig() { + loadConfig(CCT_CONFIG_XML_FILE); + } + + public static ResourceBundle getResourceBundle() { + return messages; + } + + public static Map getParsers() { + Map parsers = new HashMap(); + if (formats == null || formats.size() < 1) { + return parsers; + } + for (Map.Entry entry : formats.entrySet()) { + String key = entry.getKey(); + FormatObject fo = entry.getValue(); + if (fo.getParser() != null) { + parsers.put(key, fo); + } + } + return parsers; + } + + static void loadConfig(String fileName) { + InputStream is = null; + try { + ClassLoader cl = cct.modelling.FormatManager.class.getClassLoader(); + //logger.info("Class loader: " + cl.toString()); + //builderURL = cl.getResource(file_name); + is = cl.getResourceAsStream(fileName); + } catch (Exception ex) { + logger.warning("Cannot get resource : " + fileName + " : " + ex.getMessage()); + return; + } + + // --- Using DOM + try { + // Create a factory + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + // Use the factory to create a builder + DocumentBuilder builder = factory.newDocumentBuilder(); + cctConfig = builder.parse(is); + } catch (Exception ex) { + logger.warning("Error parsing file " + fileName + " : " + ex.getMessage()); + } + + // --- Get formats + try { + formats = FormatObject.getFormatObjects(cctConfig); + setupFormatsAndParsers(formats); + } catch (Exception ex) { + logger.severe("Cannot get formats: " + ex.getMessage()); + } + } + + public static List getParsersForFile(File file) { + return getParsersForFile(file.getName()); + } + + public static List getParsersForFile(String fileName) { + int ind = fileName.lastIndexOf("."); + if (ind == -1) { + logger.warning("Input file has no extension"); + return null; + } + String extension = fileName.substring(ind + 1); + return extensionToParser.get(extension); + } + + static private void setupFormatsAndParsers(Map formats) { + if (extensionToParser == null) { + extensionToParser = new HashMap>(); + } else { + extensionToParser.clear(); + } + + for (String key : formats.keySet()) { + FormatObject fo = formats.get(key); + String ext = fo.getExtensions(); + if (ext == null) { + System.err.println("Format " + key + " has no extension(s) information"); + continue; + } + String[] tokens = ext.split(";"); + for (String e : tokens) { + if (!extensionToParser.containsKey(e)) { + extensionToParser.put(e, new ArrayList()); + } + + List pl = extensionToParser.get(e); + pl.add(fo); + } + } + } + + static private Document getConfig() { + return cctConfig; + } + + static public boolean isPublicRelease() { + return PublicRelease; + } + + static public boolean isNewDatabase() { + return New_Database; + } + + static public String getDefaultFragmentDictionary() { + return defaultFragmentDictionary; + } + + static public String getDefaultSolventDictionary() { + return defaultSolventDictionary; + } + + public static Properties getCustomProperties(String propertiesFile) { + + String file = propertiesFile; + if (file == null || file.trim().length() < 1) { + file = CUSTOM_PROPERTIES_FILE; + } + customProperties = null; + customPropsURL = null; + try { + customPropsURL = GlobalSettings.class.getClassLoader().getResource(GlobalSettings.CUSTOM_PROPERTIES_FILE); + customProperties = new Properties(); + customProperties.load(customPropsURL.openStream()); + customPropsInitiated = true; + logger.info("Loaded custom properties file " + file); + } catch (Exception ex) { + logger.warning("Cannot open custom properties file " + file + ": " + ex.getMessage()); + } + return customProperties; + } + + public static Properties getCustomProperties() { + if (customPropsInitiated) { + return customProperties; + } + + customProperties = getCustomProperties(CUSTOM_PROPERTIES_FILE); + customPropsInitiated = true; + return customProperties; + } + + public static String getCustomPropertiesURL() { + if (customPropsURL == null) { + return ""; + } + return customPropsURL.getPath(); + } + + public static Properties getProperties() { + if (cctPropsInitiated) { + return cctProperties; + } + + cctProperties = getProperties(CCT_PROPERTY_FILE); + cctPropsInitiated = true; + return cctProperties; + } + + public static String getProperty(String key) { + if (cctPropsInitiated) { + return cctProperties.getProperty(key); + } + + cctProperties = getProperties(CCT_PROPERTY_FILE); + cctPropsInitiated = true; + return cctProperties.getProperty(key); + } + + public static String getProperty(String key, String defaultValue) { + String prop = cctProperties.getProperty(key); + if (prop == null) { + return defaultValue; + } + return prop; + } + + public static Properties getProperties(String propertiesFile) { + + String file = propertiesFile; + if (file == null || file.trim().length() < 1) { + file = CCT_PROPERTY_FILE; + } + cctProperties = null; + cctPropsURL = null; + try { + cctPropsURL = GlobalSettings.class.getClassLoader().getResource(GlobalSettings.CCT_PROPERTY_FILE); + cctProperties = new Properties(); + cctProperties.load(cctPropsURL.openStream()); + cctPropsInitiated = true; + logger.info("Loaded cct properties file " + file); + } catch (Exception ex) { + logger.warning("Cannot open cct properties file " + file + ": " + ex.getMessage()); + } + return cctProperties; + } + + public static String getPropertiesURL() { + if (cctPropsURL == null) { + return ""; + } + return cctPropsURL.getPath(); + } + + public static void setSessionProperty(String key, Object value) { + sessionProps.put(key, value); + } + + public static Object getSessionProperty(String key) { + return sessionProps.get(key); + } + + public static File getCurrentWorkingDirectory() { + Object obj = sessionProps.get(CWD_KEY); + if (obj == null) { + return null; + } + if (obj instanceof File) { + return (File) obj; + } + logger.warning("Current Working Directory should be a File, got: " + obj.getClass().getCanonicalName()); + return null; + } + + public static void setCurrentWorkingDirectory(File pwd) { + sessionProps.put(CWD_KEY, pwd); + } + + public static void showInDefaultBrowser(String url) throws Exception { + Desktop desktop = null; + if (Desktop.isDesktopSupported()) { + desktop = Desktop.getDesktop(); + if (desktop.isSupported(Desktop.Action.BROWSE)) { + URI uri = null; + try { + uri = new URI(url); + } catch (Exception ex) { + throw new Exception("Wrong Uniform Resource Identifier (URI) reference: " + url + " : " + ex.getMessage()); + } + try { + desktop.browse(uri); + } catch (Exception ex) { + throw new Exception("The default browser cannot display " + url + " : " + ex.getMessage()); + } + } else { + throw new Exception("Desktop does not support the BROWSE action"); + } + } else { + throw new Exception("The Native Desktop is not supported"); + } + } + + public static void mailUsingDefaultClient(String address, String subject, String body) throws Exception { + Desktop desktop = null; + if (Desktop.isDesktopSupported()) { + desktop = Desktop.getDesktop(); + if (desktop.isSupported(Desktop.Action.MAIL)) { + StringBuilder sb = new StringBuilder("mailto:"); + if (address != null && address.length() > 0) { + sb.append(address); + } + + if (subject != null) { + sb.append("?subject=" + subject.replaceAll("[&]", "&")); + } + + if (body != null && body.length() > 1) { + if (subject == null) { + sb.append("?"); + } else { + sb.append("&"); + } + sb.append("body=" + body.replaceAll("[&]", "&")); + } + + String uriString = sb.toString().replaceAll("[ ]", "%20").replaceAll("[\n]", "%0D%0A"); + System.out.println(uriString); + URI uri = null; + try { + uri = new URI(uriString); + } catch (Exception ex) { + throw new Exception("Wrong Uniform Resource Identifier (URI) reference: " + uriString + " : " + ex.getMessage()); + } + try { + desktop.mail(uri); + } catch (Exception ex) { + throw new Exception("The default mail client cannot parse " + uriString + " : " + ex.getMessage()); + } + } else { + throw new Exception("Desktop does not support the MAIL action"); + } + } else { + throw new Exception("The Native Desktop is not supported"); + } + } + + public static void registerDialog(String label, Component dialog) { + if (registeredDialogs.get(label) != null) { + logger.warning("Dialog with label " + label + " is already registered. Replacing..."); + } + registeredDialogs.put(label, dialog); + logger.info("Registered dialog: " + label); + } + + public static Component getRegisterDialog(String label) { + return registeredDialogs.get(label); + } +} diff --git a/src/main/java/cct/JMolEditor.java b/src/main/java/cct/JMolEditor.java new file mode 100644 index 0000000..39d5a68 --- /dev/null +++ b/src/main/java/cct/JMolEditor.java @@ -0,0 +1,285 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct; + +import java.awt.Dimension; +import java.awt.Toolkit; +import java.util.Locale; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.swing.ImageIcon; +import javax.swing.JFrame; +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +import cct.dialogs.JamberooFrame; +import cct.help.JavaHelp; +import cct.tools.SwingLookAndFeel; +import java.awt.Window; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.LinkedHashSet; +import java.util.Set; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE; + +/** + * + *

+ * Title: Computational Chemsitry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + * @deprecated Use JamberooMolecularEditor class instead + */ +@Deprecated +public class JMolEditor implements ActionListener { + + static String JAMBEROO_ICON = "cct/images/icons16x16/cube_molecule.png"; + static String JAMBEROO_NEW_EDITOR_ACTION_COMMAND = "New Editor"; + private static String Version = "07"; + private static String Build = "0703"; + private boolean packFrame = false; + private ImageIcon icon = null; + private Set windows = new LinkedHashSet(); + static final Logger logger = Logger.getLogger(JMolEditor.class.getCanonicalName()); + + /** + * Construct and show the application. + */ + public JMolEditor(String[] args) { + + System.err.println(JMolEditor.class.getCanonicalName()+" is a deprecated class & is not supported any more"); + + Logger.getLogger("").setLevel(Level.WARNING); + + try { + String javaVersion = System.getProperty("java.version"); + if (javaVersion != null) { + String version[] = javaVersion.split("\\."); + if (version.length > 1 && Integer.parseInt(version[1]) < 5) { + JOptionPane.showMessageDialog(null, "Java Virtual Machine version should be 1.5 and later\nYour JVM Version is " + + javaVersion, "Error", JOptionPane.ERROR_MESSAGE); + } + } + } catch (Exception ex) { + logger.warning("Cannot query Java VM version: " + ex.getMessage()); + } + + try { + icon = new ImageIcon(cct.resources.Resources.class.getResource(JAMBEROO_ICON)); + } catch (Exception ex) { + logger.severe("Cannot get Jamberoo icon: " + ex.getMessage() + " Ignored... Continued..."); + } + + try { + //logger.info("JMolEditor: checking for java3d..."); + Class.forName("org.scijava.java3d.VirtualUniverse"); + //logger.info("JMolEditor: java3d ok..."); + } catch (Exception ex) { + logger.severe("Cannot load " + ex.getMessage() + " Either java3d is not installed or it is not in the CLASSPATH"); + String variable = System.getenv("CLASSPATH"); + logger.info("CLASSPATH=" + variable); + JOptionPane.showMessageDialog(null, "Cannot load " + ex.getMessage() + "\nEither java3d is not installed or it is not in the CLASSPATH", "Error", JOptionPane.ERROR_MESSAGE); + System.exit(1); + } + + JFrame.setDefaultLookAndFeelDecorated(false); + Class frame_class = null; + try { + frame_class = this.getClass().getClassLoader().loadClass("cct.dialogs.JEditorFrame"); + } catch (Exception ex) { + logger.severe(ex.getMessage()); + System.exit(1); + } + + //String look = SwingLookAndFeel.retrieveLookAndFeelPrefs(cct.dialogs.JamberooFrame.class); + String look = SwingLookAndFeel.retrieveLookAndFeelPrefs(frame_class); + try { + if (look != null) { + SwingLookAndFeel.setLookAndFeel(look); + } else { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + // --- Create Jamberoo Window + JamberooFrame frame = createJamberooInstance("Jamberoo - Main Window", args); + windows.add(frame); + + frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); + addNewEditorMenuItem(frame); + // Center the window + centerOnScreen(frame); + frame.setVisible(true); + + } + + protected void addNewEditorMenuItem(JamberooFrame frame) { + try { + JMenu fileMenu = frame.getMenu("File"); + JMenuItem newEditorMenuItem = new JMenuItem("New Editor Window"); + newEditorMenuItem.setActionCommand(JAMBEROO_NEW_EDITOR_ACTION_COMMAND); + newEditorMenuItem.setIcon(icon); + newEditorMenuItem.addActionListener(this); + fileMenu.add(newEditorMenuItem, 0); + fileMenu.addSeparator(); + } catch (Exception ex) { + logger.severe("Cannot get File Menu: " + ex.getMessage() + " Ignored... Continued..."); + } + } + + public void centerOnScreen(JamberooFrame frame) { + try { + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension frameSize = frame.getSize(); + if (frameSize.height > screenSize.height) { + frameSize.height = screenSize.height; + } + if (frameSize.width > screenSize.width) { + frameSize.width = screenSize.width; + } + frame.setLocation((screenSize.width - frameSize.width) / 2, + (screenSize.height - frameSize.height) / 2); + } catch (Exception ex) { + logger.severe("Cannot center frame on a window: " + ex.getMessage() + " Ignored & continued..."); + } + } + + public JamberooFrame createJamberooInstance(String title, String[] args) { + JamberooFrame frame = new JamberooFrame(title, args); + frame.setIconImage(icon.getImage()); + //frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); + frame.setSize(new Dimension(800, 600)); + + String helpHS = "JMolEditorHelpSet.hs"; + JavaHelp javahelp = null; + try { + javahelp = new JavaHelp(helpHS); + frame.setHelper(javahelp); + } catch (Exception ex) { + logger.warning("Activating Help System: " + ex.getMessage()); + } + + // Validate frames that have preset sizes + // Pack frames that have useful preferred size info, e.g. from their layout + if (packFrame) { + frame.pack(); + } else { + frame.validate(); + } + + frame.addWindowListener(new WindowAdapter() { + + @Override + public void windowClosing(WindowEvent we) { + Window window = we.getWindow(); + windows.remove(window); + window.dispose(); + if (windows.size() < 1) { + System.exit(0); + } + } + }); + + return frame; + } + + /** + * Application entry point. + * + * @param args String[] + */ + public static void main(String[] args) { + + processArguments(args); + Locale.setDefault(Locale.ENGLISH); + final String[] Args = args; + SwingUtilities.invokeLater(new Runnable() { + + @Override + public void run() { + + new JMolEditor(Args); + + } + }); + } + + static void processArguments(String[] args) { + for (int i = 0; i < args.length; i++) { + if (args[i].equals("-v")) { + logger.info(Version + "." + Build); + System.exit(0); + } else if (args[i].equals("-V")) { + logger.info("Version " + Version + " build " + Build); + System.exit(0); + } + } + } + + public void actionPerformed(ActionEvent actionEvent) { + + Object source = actionEvent.getSource(); + String arg = actionEvent.getActionCommand(); + + if (arg.equals(JAMBEROO_NEW_EDITOR_ACTION_COMMAND)) { + JamberooFrame frame = createJamberooInstance("Jamberoo Molecular Editor", null); + windows.add(frame); + frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); + addNewEditorMenuItem(frame); + centerOnScreen(frame); + frame.setVisible(true); + } + } +} diff --git a/src/main/java/cct/JamberooMolecularEditor.java b/src/main/java/cct/JamberooMolecularEditor.java new file mode 100644 index 0000000..c5acb1b --- /dev/null +++ b/src/main/java/cct/JamberooMolecularEditor.java @@ -0,0 +1,304 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct; + +import cct.dialogs.JamberooFrame; +import cct.help.JavaHelp; +import cct.tools.SwingLookAndFeel; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.logging.Level; +import java.util.logging.Logger; + +import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE; + +/** + * + *

+ * Title: Computational Chemsitry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class JamberooMolecularEditor implements ActionListener { + + static String JAMBEROO_ICON = "/cct/images/icons16x16/cube_molecule.png"; + static String JAMBEROO_NEW_EDITOR_ACTION_COMMAND = "New Editor"; + private static String Version = "07"; + private static String Build = "0703"; + private boolean packFrame = false; + private ImageIcon icon = null; + private static List windows = null; + static final Logger logger = Logger.getLogger(JamberooMolecularEditor.class.getCanonicalName()); + private int Number_of_open_windows = 0; + + /** + * Construct and show the application. + */ + public JamberooMolecularEditor(String[] args) { + Logger.getLogger("").setLevel(Level.WARNING); + + try { + String javaVersion = System.getProperty("java.version"); + if (javaVersion != null) { + String version[] = javaVersion.split("\\."); + if (version.length > 1 && Integer.parseInt(version[1]) < 5) { + JOptionPane.showMessageDialog(null, "Java Virtual Machine version should be 1.5 and later\nYour JVM Version is " + + javaVersion, "Error", JOptionPane.ERROR_MESSAGE); + } + } + } catch (Exception ex) { + logger.warning("Cannot query Java VM version: " + ex.getMessage()); + } + + try { + icon = new ImageIcon(cct.resources.Resources.class.getResource(JAMBEROO_ICON)); + } catch (Exception ex) { + logger.severe("Cannot get Jamberoo icon: " + ex.getMessage() + " Ignored... Continued..."); + } + + try { + //logger.info("JMolEditor: checking for java3d..."); + Class.forName("org.scijava.java3d.VirtualUniverse"); + //logger.info("JMolEditor: java3d ok..."); + } catch (Exception ex) { + ex.printStackTrace(); + String variable = System.getenv("CLASSPATH"); + logger.info("CLASSPATH=" + variable); + System.out.println("CLASSPATH=" + variable); + logger.severe("Cannot load " + ex.getMessage() + " Either java3d is not installed or it is not in the CLASSPATH"); + + JOptionPane.showMessageDialog(null, "Cannot load " + ex.getMessage() + "\nEither java3d is not installed or it is not in the CLASSPATH", "Error", JOptionPane.ERROR_MESSAGE); +// System.exit(1); + } + + JFrame.setDefaultLookAndFeelDecorated(false); + Class frame_class = null; + try { + frame_class = this.getClass().getClassLoader().loadClass("cct.dialogs.JEditorFrame"); + } catch (Exception ex) { + logger.severe(ex.getMessage()); +// System.exit(1); + } + + //String look = SwingLookAndFeel.retrieveLookAndFeelPrefs(cct.dialogs.JamberooFrame.class); + String look = SwingLookAndFeel.retrieveLookAndFeelPrefs(frame_class); + try { + if (look != null) { + SwingLookAndFeel.setLookAndFeel(look); + } else { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + // --- Create Jamberoo Window + JamberooFrame frame = createJamberooInstance("Jamberoo - Main Window", args); + ++Number_of_open_windows; + windows.add(frame); + + frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); + addNewEditorMenuItem(frame); + // Center the window + centerOnScreen(frame); + frame.setVisible(true); + + } + + protected void addNewEditorMenuItem(JamberooFrame frame) { + try { + JMenu fileMenu = frame.getMenu("File"); + JMenuItem newEditorMenuItem = new JMenuItem("New Editor Window"); + newEditorMenuItem.setActionCommand(JAMBEROO_NEW_EDITOR_ACTION_COMMAND); + newEditorMenuItem.setIcon(icon); + newEditorMenuItem.addActionListener(this); + fileMenu.add(newEditorMenuItem, 0); + fileMenu.addSeparator(); + } catch (Exception ex) { + logger.severe("Cannot get File Menu: " + ex.getMessage() + " Ignored... Continued..."); + } + } + + public void centerOnScreen(JamberooFrame frame) { + try { + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension frameSize = frame.getSize(); + if (frameSize.height > screenSize.height) { + frameSize.height = screenSize.height; + } + if (frameSize.width > screenSize.width) { + frameSize.width = screenSize.width; + } + frame.setLocation((screenSize.width - frameSize.width) / 2, + (screenSize.height - frameSize.height) / 2); + } catch (Exception ex) { + logger.severe("Cannot center frame on a window: " + ex.getMessage() + " Ignored & continued..."); + } + } + + public JamberooFrame createJamberooInstance(String title, String[] args) { + JamberooFrame frame = new JamberooFrame(title, args); + frame.setIconImage(icon.getImage()); + //frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); + frame.setSize(new Dimension(800, 600)); + + String helpHS = "JMolEditorHelpSet.hs"; + JavaHelp javahelp = null; + try { + javahelp = new JavaHelp(helpHS); + frame.setHelper(javahelp); + } catch (Exception ex) { + logger.warning("Activating Help System: " + ex.getMessage()); + } + + // Validate frames that have preset sizes + // Pack frames that have useful preferred size info, e.g. from their layout + if (packFrame) { + frame.pack(); + } else { + frame.validate(); + } + + frame.addWindowListener(new WindowAdapter() { + + @Override + public void windowClosing(WindowEvent we) { + Window window = we.getWindow(); + windows.remove(window); + --Number_of_open_windows; + window.dispose(); + if(windows.size() == 0){ + JamberooFrame frame = createJamberooInstance("Jamberoo - Main Window", args); + windows.add(frame); + ++Number_of_open_windows; + + frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); + addNewEditorMenuItem(frame); + // Center the window + centerOnScreen(frame); + frame.setVisible(false); + } + + } + }); + + return frame; + } + + /** + * Application entry point. + * + * @param args String[] + */ + public static void main(String[] args) { + windows = new ArrayList<>(); + processArguments(args); + Locale.setDefault(Locale.ENGLISH); + final String[] Args = args; + SwingUtilities.invokeLater(new Runnable() { + + @Override + public void run() { + + new JamberooMolecularEditor(Args); + + } + }); + } + + static void processArguments(String[] args) { + for (int i = 0; i < args.length; i++) { + if (args[i].equals("-v")) { + logger.info(Version + "." + Build); +// System.exit(0); + } else if (args[i].equals("-V")) { + logger.info("Version " + Version + " build " + Build); +// System.exit(0); + } + } + } + + public List getJamberooFrames() { + return windows; + } + + public void actionPerformed(ActionEvent actionEvent) { + + Object source = actionEvent.getSource(); + String arg = actionEvent.getActionCommand(); + + if (arg.equals(JAMBEROO_NEW_EDITOR_ACTION_COMMAND)) { + JamberooFrame frame = createJamberooInstance(String.valueOf(Number_of_open_windows++) + ": Jamberoo Molecular Editor", null); + windows.add(frame); + frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); + addNewEditorMenuItem(frame); + centerOnScreen(frame); + frame.setVisible(true); + } + } + + public static void showJamberoo() { + if(windows == null){ + windows = new ArrayList<>(); + Locale.setDefault(Locale.ENGLISH); + new JamberooMolecularEditor(new String []{}); + }else{ + for(JamberooFrame w : windows){ + w.setVisible(true); + } + } + + } +} diff --git a/src/main/java/cct/adf/ADF.java b/src/main/java/cct/adf/ADF.java new file mode 100644 index 0000000..3996c07 --- /dev/null +++ b/src/main/java/cct/adf/ADF.java @@ -0,0 +1,1444 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.adf; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.math.MathExpressionParser; +import cct.modelling.CCTAtomTypes; +import cct.modelling.ChemicalElements; +import cct.modelling.GeneralMolecularDataParser; +import cct.modelling.Molecule; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.StringReader; +import java.util.*; +import java.util.logging.Logger; + +/** + *

+ * Title: Computational Chemistry Tookit + *

+ * + *

+ * Description: + *

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev + *

+ * + *

+ * Company: ANU + *

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +// KEY, , , +// +enum KEY_WORDS { + + A1FIT, ADDDIFFUSEFIT, ALLOW, ALLPOINTS, ANALYTICALFREQ, ATOMS, BASIS, BONDORDER, CHARGE, COLLINEAR, COMMENT, COMMTIMING, + CONSTRAINT, COREPOTENTIALS, CREATE, CURRENTRESPONSE, DEBUG, DEFINE, DENSPREP, DEPENDENCY, DIPOLEMAT, DISK, DRF, EFIELD, + ENERGYFRAG, EPRINT, EPSFIT, ESR, EXACTDENSITY, EXTERNALS, FDE, FILE, FITELSTAT, FORCEALDA, FRAGMENTS, FRAGOCCUPATIONS, + FULLFOCK, EXCITATIONS, FULLSCF, GEOSTEP, HARTREEFOCK, HESSTEST, HFEXCHANGE, INLINE, IRCSTART, LOCORB, METAGGA, MMDISPERSION, + EXTENDEDPOPAN, MODIFYEXCITATION, NONCOLLINEAR, NOPRINT, NOSAVE, OLDGRADIENTS, PRINT, QTENS, RADIALCOREGRID, + REMOVEFRAGORBITALS, GEOMETRY, GEOVAR, RELATIVISTIC, RESPONSE, RESTRAINT, SAVE, SFTDDFT, SICOEP, SINGULARFIT, SKIP, SOLVATION, + STCONTRIB, STOPAFTER, SYMMETRY, TAILS, TDA, THERMO, UNRESTRICTED, VECTORLENGTH, VIBRON, SCF, TITLE, UNITS, XC, QMMM, + INTEGRATION, HESSDIAG, LINEARSCALING, MODIFYSTARTPOTENTIAL, OCCUPATIONS, RESTART, SLATERDETERMINANTS +} + +public class ADF extends GeneralMolecularDataParser { + + static final double ONE_BOHR = 0.529177249; // In Angstrom + static final float DEGREES_TO_RADIANS = (float) (Math.PI / 180.0); + static final String FF_LABEL_PROP = "Adf FF Label"; + static final String MM_TYPE_PROP = "Adf MM Type"; + static Map keyWords = new HashMap(); + + static { + + keyWords.put("A1FIT", KEY_WORDS.A1FIT); + keyWords.put("ADDDIFFUSEFIT", KEY_WORDS.ADDDIFFUSEFIT); + keyWords.put("ALLOW", KEY_WORDS.ALLOW); + keyWords.put("ALLPOINTS", KEY_WORDS.ALLPOINTS); + keyWords.put("ANALYTICALFREQ", KEY_WORDS.ANALYTICALFREQ); + keyWords.put("ATOMS", KEY_WORDS.ATOMS); + keyWords.put("BONDORDER", KEY_WORDS.BONDORDER); + keyWords.put("CHARGE", KEY_WORDS.CHARGE); + keyWords.put("COMMENT", KEY_WORDS.COMMENT); + keyWords.put("COMMTIMING", KEY_WORDS.COMMTIMING); + keyWords.put("COLLINEAR", KEY_WORDS.COLLINEAR); + keyWords.put("CONSTRAINT", KEY_WORDS.CONSTRAINT); + keyWords.put("COREPOTENTIALS", KEY_WORDS.COREPOTENTIALS); + keyWords.put("CREATE", KEY_WORDS.CREATE); + keyWords.put("CURRENTRESPONSE", KEY_WORDS.CURRENTRESPONSE); + keyWords.put("DEBUG", KEY_WORDS.DEBUG); + keyWords.put("DEFINE", KEY_WORDS.DEFINE); + keyWords.put("DENSPREP", KEY_WORDS.DENSPREP); + keyWords.put("DEPENDENCY", KEY_WORDS.DEPENDENCY); + keyWords.put("DIPOLEMAT", KEY_WORDS.DIPOLEMAT); + keyWords.put("DISK", KEY_WORDS.DISK); + keyWords.put("DRF", KEY_WORDS.DRF); + keyWords.put("EFIELD", KEY_WORDS.EFIELD); + keyWords.put("EXTENDEDPOPAN", KEY_WORDS.EXTENDEDPOPAN); + keyWords.put("ENERGYFRAG", KEY_WORDS.ENERGYFRAG); + keyWords.put("EPRINT", KEY_WORDS.EPRINT); + keyWords.put("EPSFIT", KEY_WORDS.EPSFIT); + keyWords.put("ESR", KEY_WORDS.ESR); + keyWords.put("EXACTDENSITY", KEY_WORDS.EXACTDENSITY); + keyWords.put("EXCITATIONS", KEY_WORDS.EXCITATIONS); + keyWords.put("EXTERNALS", KEY_WORDS.EXTERNALS); + keyWords.put("FDE", KEY_WORDS.FDE); + keyWords.put("FILE", KEY_WORDS.FILE); + keyWords.put("FITELSTAT", KEY_WORDS.FITELSTAT); + keyWords.put("FORCEALDA", KEY_WORDS.FORCEALDA); + keyWords.put("FRAGMENTS", KEY_WORDS.FRAGMENTS); + keyWords.put("FRAGOCCUPATIONS", KEY_WORDS.FRAGOCCUPATIONS); + keyWords.put("FULLFOCK", KEY_WORDS.FULLFOCK); + keyWords.put("FULLSCF", KEY_WORDS.FULLSCF); + keyWords.put("GEOMETRY", KEY_WORDS.GEOMETRY); + keyWords.put("GEOSTEP", KEY_WORDS.GEOSTEP); + keyWords.put("GEOVAR", KEY_WORDS.GEOVAR); + keyWords.put("HARTREEFOCK", KEY_WORDS.HARTREEFOCK); + keyWords.put("HESSTEST", KEY_WORDS.HESSTEST); + keyWords.put("HFEXCHANGE", KEY_WORDS.HFEXCHANGE); + keyWords.put("INLINE", KEY_WORDS.INLINE); + keyWords.put("IRCSTART", KEY_WORDS.IRCSTART); + keyWords.put("BASIS", KEY_WORDS.BASIS); + keyWords.put("LOCORB", KEY_WORDS.LOCORB); + keyWords.put("METAGGA", KEY_WORDS.METAGGA); + keyWords.put("MMDISPERSION", KEY_WORDS.MMDISPERSION); + keyWords.put("MODIFYEXCITATION", KEY_WORDS.MODIFYEXCITATION); + keyWords.put("NONCOLLINEAR", KEY_WORDS.NONCOLLINEAR); + keyWords.put("NOPRINT", KEY_WORDS.NOPRINT); + keyWords.put("NOSAVE", KEY_WORDS.NOSAVE); + keyWords.put("OLDGRADIENTS", KEY_WORDS.OLDGRADIENTS); + keyWords.put("PRINT", KEY_WORDS.PRINT); + keyWords.put("QTENS", KEY_WORDS.QTENS); + keyWords.put("RADIALCOREGRID", KEY_WORDS.RADIALCOREGRID); + keyWords.put("REMOVEFRAGORBITALS", KEY_WORDS.REMOVEFRAGORBITALS); + keyWords.put("RELATIVISTIC", KEY_WORDS.RELATIVISTIC); + keyWords.put("RESPONSE", KEY_WORDS.RESPONSE); + keyWords.put("RESTRAINT", KEY_WORDS.RESTRAINT); + keyWords.put("SAVE", KEY_WORDS.SAVE); + keyWords.put("SFTDDFT", KEY_WORDS.SFTDDFT); + keyWords.put("SCF", KEY_WORDS.SCF); + keyWords.put("SICOEP", KEY_WORDS.SICOEP); + keyWords.put("SINGULARFIT", KEY_WORDS.SINGULARFIT); + keyWords.put("SKIP", KEY_WORDS.SKIP); + keyWords.put("SOLVATION", KEY_WORDS.SOLVATION); + keyWords.put("STCONTRIB", KEY_WORDS.STCONTRIB); + keyWords.put("STOPAFTER", KEY_WORDS.STOPAFTER); + keyWords.put("SYMMETRY", KEY_WORDS.SYMMETRY); + keyWords.put("TAILS", KEY_WORDS.TAILS); + keyWords.put("TDA", KEY_WORDS.TDA); + keyWords.put("THERMO", KEY_WORDS.THERMO); + keyWords.put("TITLE", KEY_WORDS.TITLE); + keyWords.put("UNITS", KEY_WORDS.UNITS); + keyWords.put("UNRESTRICTED", KEY_WORDS.UNRESTRICTED); + keyWords.put("VECTORLENGTH", KEY_WORDS.VECTORLENGTH); + keyWords.put("VIBRON", KEY_WORDS.VIBRON); + keyWords.put("XC", KEY_WORDS.XC); + keyWords.put("QMMM", KEY_WORDS.QMMM); + keyWords.put("INTEGRATION", KEY_WORDS.INTEGRATION); + keyWords.put("HESSDIAG", KEY_WORDS.HESSDIAG); + keyWords.put("LINEARSCALING", KEY_WORDS.LINEARSCALING); + keyWords.put("MODIFYSTARTPOTENTIAL", KEY_WORDS.MODIFYSTARTPOTENTIAL); + keyWords.put("OCCUPATIONS", KEY_WORDS.OCCUPATIONS); + keyWords.put("RESTART", KEY_WORDS.RESTART); + keyWords.put("SLATERDETERMINANTS", KEY_WORDS.SLATERDETERMINANTS); + } + private float distanceUnits = 1.0f; + private float angleUnits = DEGREES_TO_RADIANS; + private boolean symbolicParamResolved = true; + private boolean includesFrozenAtoms = false; + private boolean defaultChargeUsed = true; + private boolean internalCoordinates = false; + private int totalCharge = 0; + private List Atoms = new ArrayList(); + private ArrayList connectionTable = new ArrayList(); + private Map symbolicStrings = new HashMap(300); + private Set frozenParameters = new HashSet(); + private MathExpressionParser mathExpressionParser = new MathExpressionParser(); + static final Logger logger = Logger.getLogger(ADF.class.getCanonicalName()); + + public ADF() { + mathExpressionParser.setInDegrees(true); + } + + public static void main(String[] args) { + ADF adf = new ADF(); + } + + public void getMolecularInterface(MoleculeInterface molec) throws Exception { + if (molec == null) { + throw new Exception(this.getClass().getCanonicalName() + " : molec == null"); + } + if (Atoms.size() < 1) { + throw new Exception(this.getClass().getCanonicalName() + " : no ADF atoms"); + } + + // molec.addProperty(MoleculeInterface.ChargeProperty, new + // Integer(netCharge)); + // molec.addProperty(MoleculeInterface.MultiplicityProperty, new + // Integer(spinMultiplicity)); + molec.addMonomer("ADF"); + + for (int i = 0; i < Atoms.size(); i++) { + ADFAtom ga = Atoms.get(i); + AtomInterface atom = molec.getNewAtomInstance(); + atom.setName(ga.name); + atom.setAtomicNumber(ga.atomicNumber); + atom.setXYZ(ga.xyz[0], ga.xyz[1], ga.xyz[2]); + + if (ga.FF_Label != null) { + atom.setProperty(FF_LABEL_PROP, ga.FF_Label); + } + + if (ga.MM_Type != null) { + atom.setProperty(MM_TYPE_PROP, ga.MM_Type); + } + + molec.addAtom(atom); + } + + } + + public int validFormatScore(BufferedReader in) throws Exception { + //in.mark(65536); + String line = ""; + int score = 0; + ADF adf = new ADF(); + try { + adf.parseData(in); + } catch (Exception ex) { + return 0; + } + if (adf.getNumberMolecules() == 0) { + return 0; + } + + return 10; + } + + public void parseData(BufferedReader in) throws Exception { + MoleculeInterface mol = getMoleculeInterface(); + this.addMolecule(mol); + + String line, token; + Atoms.clear(); + + /* + * Input for ADF is structured by keywords, in short: keys. A key is a + * string of characters that does not contain a delimiter (blank, comma + * or equal sign). Keys are not case sensitive. Input is read until + * either the end-of-file condition (eof) becomes true, or until a + * record end input is encountered, whichever comes first. (end input is + * not a key.) + * + * Key-controlled input occurs with two formats. In the first you have + * only one record, which contains both the key and - depending on the + * case - associated data: the key argument: + * + * KEY argument + * + * The whole part of the line that follows after the key is the + * argument. It may consist of more than one item. + * + * The alternative format is a sequence of records, collectively denoted + * as a key block. The first record of the block gives the key (which + * may have an argument). The block is closed by a record containing + * (only) the word end. The other records in the block constitute the + * data block, and provide information related to the key. + * + * KEY {argument} data record data record ...(etc.)... ... end + * + * Block type keys may have subkeys in their data block. The subkeys may + * themselves also be block type keys. The data blocks of block type + * subkeys, however, do not end with end, but with subend: + * + * KEY {argument} data data subkey {argument} subkey data subkey data + * ... subend data data ... end + * + * Layout features such as an open line, indentation, or the number of + * spaces between items are not significant. + * + */ + try { + + while ((line = in.readLine()) != null) { + line = line.trim(); + + if (line.length() < 1) { // Blank line + continue; + } + + StringTokenizer st = new StringTokenizer(line.toUpperCase(), " =,"); + token = st.nextToken(); + + if (token.equals("ENDINPUT") || (token.equals("END") && st.nextToken().equals("INPUT"))) { + break; + } + + if (!keyWords.containsKey(token)) { + continue; + } + + KEY_WORDS keyWord = keyWords.get(token); + + switch (keyWord) { + case UNITS: + parseUNITS(in); + break; + case ATOMS: + parseATOMS(line, in); + break; + case GEOVAR: + parseGEOVAR(in); + break; + case CHARGE: + if (st.hasMoreTokens()) { + parseCHARGE(st.nextToken()); + } + break; + case DEFINE: + parseDEFINE(in); + break; + + case LINEARSCALING: + case INTEGRATION: + case MODIFYSTARTPOTENTIAL: + case SLATERDETERMINANTS: + if (st.hasMoreTokens()) { + continue; + } else { + skipSection(in); + } + break; + + case HESSDIAG: + case OCCUPATIONS: + case RESTART: + if (!st.hasMoreTokens()) { + skipSection(in); + } else if (line.endsWith(" &")) { + skipSection(in); + } else { + continue; + } + + break; + + case QMMM: + this.parseQMMM(in); + break; + + case ANALYTICALFREQ: + case BASIS: + case COMMENT: + case CONSTRAINT: + case COREPOTENTIALS: + case CURRENTRESPONSE: + case DRF: + case EFIELD: + case ENERGYFRAG: + case EPRINT: + case ESR: + case EXCITATIONS: + case EXTERNALS: + case FDE: + case FRAGMENTS: + case FRAGOCCUPATIONS: + case GEOMETRY: + case IRCSTART: + case LOCORB: + case MMDISPERSION: + case MODIFYEXCITATION: + case REMOVEFRAGORBITALS: + case RESPONSE: + case RESTRAINT: + case SCF: + case SICOEP: + case SOLVATION: + case VIBRON: + case XC: + skipSection(in); + break; + + case A1FIT: + case ADDDIFFUSEFIT: + case ALLOW: + case ALLPOINTS: + case BONDORDER: + case COLLINEAR: + case COMMTIMING: + case CREATE: + case DEBUG: + case DENSPREP: + case DEPENDENCY: + case DIPOLEMAT: + case DISK: + case EPSFIT: + case EXACTDENSITY: + case EXTENDEDPOPAN: + case FILE: + case FITELSTAT: + case FORCEALDA: + case FULLFOCK: + case FULLSCF: + case GEOSTEP: + case HARTREEFOCK: + case HESSTEST: + case HFEXCHANGE: + case INLINE: + case METAGGA: + case NONCOLLINEAR: + case NOPRINT: + case NOSAVE: + case OLDGRADIENTS: + case PRINT: + case QTENS: + case RADIALCOREGRID: + case RELATIVISTIC: + case SAVE: + case SFTDDFT: + case SINGULARFIT: + case SKIP: + case STCONTRIB: + case STOPAFTER: + case SYMMETRY: + case TAILS: + case TDA: + case THERMO: + case TITLE: + case UNRESTRICTED: + case VECTORLENGTH: + break; + default: + + } + + } + + in.close(); + } catch (Exception ex) { + if (Atoms.size() < 1) { + throw new Exception("Error while reading ADF input file: " + ex.getMessage()); + } + } + + // --- Check out whether all symbolic parameters are resolved + if (!symbolicParamResolved) { + // --- Resolve parameters + resolveSymbolicParamaters(); + + } + + if (internalCoordinates) { + fromZMatrixToCartesians(Atoms); + } + + getMolecularInterface(mol); + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } + + /** + * + * @param file_name + * @param fileType + * @throws Exception + * @deprecated Use parseData methods instead + */ + @Deprecated + public void parseInput(String file_name, int fileType) throws Exception { + String line, token; + BufferedReader in = null; + Atoms.clear(); + + if (fileType == 0) { // Read from file + try { + in = new BufferedReader(new FileReader(file_name)); + } catch (Exception ex) { + throw ex; + } + } else if (fileType == 1) { // Read from String + in = new BufferedReader(new StringReader(file_name)); + } else { + throw new Exception("parsing ADF Input: INTERNAL ERROR: Unknown file type"); + } + + /* + * Input for ADF is structured by keywords, in short: keys. A key is a + * string of characters that does not contain a delimiter (blank, comma + * or equal sign). Keys are not case sensitive. Input is read until + * either the end-of-file condition (eof) becomes true, or until a + * record end input is encountered, whichever comes first. (end input is + * not a key.) + * + * Key-controlled input occurs with two formats. In the first you have + * only one record, which contains both the key and - depending on the + * case - associated data: the key argument: + * + * KEY argument + * + * The whole part of the line that follows after the key is the + * argument. It may consist of more than one item. + * + * The alternative format is a sequence of records, collectively denoted + * as a key block. The first record of the block gives the key (which + * may have an argument). The block is closed by a record containing + * (only) the word end. The other records in the block constitute the + * data block, and provide information related to the key. + * + * KEY {argument} data record data record ...(etc.)... ... end + * + * Block type keys may have subkeys in their data block. The subkeys may + * themselves also be block type keys. The data blocks of block type + * subkeys, however, do not end with end, but with subend: + * + * KEY {argument} data data subkey {argument} subkey data subkey data + * ... subend data data ... end + * + * Layout features such as an open line, indentation, or the number of + * spaces between items are not significant. + * + */ + try { + + while ((line = in.readLine()) != null) { + line = line.trim(); + + if (line.length() < 1) { // Blank line + continue; + } + + StringTokenizer st = new StringTokenizer(line.toUpperCase(), " =,"); + token = st.nextToken(); + + if (token.equals("ENDINPUT") || (token.equals("END") && st.nextToken().equals("INPUT"))) { + break; + } + + if (!keyWords.containsKey(token)) { + continue; + } + + KEY_WORDS keyWord = keyWords.get(token); + + switch (keyWord) { + case UNITS: + parseUNITS(in); + break; + case ATOMS: + parseATOMS(line, in); + break; + case GEOVAR: + parseGEOVAR(in); + break; + case CHARGE: + if (st.hasMoreTokens()) { + parseCHARGE(st.nextToken()); + } + break; + case DEFINE: + parseDEFINE(in); + break; + + case LINEARSCALING: + case INTEGRATION: + case MODIFYSTARTPOTENTIAL: + case SLATERDETERMINANTS: + if (st.hasMoreTokens()) { + continue; + } else { + skipSection(in); + } + break; + + case HESSDIAG: + case OCCUPATIONS: + case RESTART: + if (!st.hasMoreTokens()) { + skipSection(in); + } else if (line.endsWith(" &")) { + skipSection(in); + } else { + continue; + } + + break; + + case QMMM: + this.parseQMMM(in); + break; + + case ANALYTICALFREQ: + case BASIS: + case COMMENT: + case CONSTRAINT: + case COREPOTENTIALS: + case CURRENTRESPONSE: + case DRF: + case EFIELD: + case ENERGYFRAG: + case EPRINT: + case ESR: + case EXCITATIONS: + case EXTERNALS: + case FDE: + case FRAGMENTS: + case FRAGOCCUPATIONS: + case GEOMETRY: + case IRCSTART: + case LOCORB: + case MMDISPERSION: + case MODIFYEXCITATION: + case REMOVEFRAGORBITALS: + case RESPONSE: + case RESTRAINT: + case SCF: + case SICOEP: + case SOLVATION: + case VIBRON: + case XC: + skipSection(in); + break; + + case A1FIT: + case ADDDIFFUSEFIT: + case ALLOW: + case ALLPOINTS: + case BONDORDER: + case COLLINEAR: + case COMMTIMING: + case CREATE: + case DEBUG: + case DENSPREP: + case DEPENDENCY: + case DIPOLEMAT: + case DISK: + case EPSFIT: + case EXACTDENSITY: + case EXTENDEDPOPAN: + case FILE: + case FITELSTAT: + case FORCEALDA: + case FULLFOCK: + case FULLSCF: + case GEOSTEP: + case HARTREEFOCK: + case HESSTEST: + case HFEXCHANGE: + case INLINE: + case METAGGA: + case NONCOLLINEAR: + case NOPRINT: + case NOSAVE: + case OLDGRADIENTS: + case PRINT: + case QTENS: + case RADIALCOREGRID: + case RELATIVISTIC: + case SAVE: + case SFTDDFT: + case SINGULARFIT: + case SKIP: + case STCONTRIB: + case STOPAFTER: + case SYMMETRY: + case TAILS: + case TDA: + case THERMO: + case TITLE: + case UNRESTRICTED: + case VECTORLENGTH: + break; + default: + + } + + } + + in.close(); + } catch (Exception ex) { + if (Atoms.size() < 1) { + throw new Exception("Error while reading ADF input file: " + ex.getMessage()); + } + } + + // --- Check out whether all symbolic parameters are resolved + if (!symbolicParamResolved) { + // --- Resolve parameters + resolveSymbolicParamaters(); + + } + + if (internalCoordinates) { + fromZMatrixToCartesians(Atoms); + } + } + + public void resolveSymbolicParamaters() throws Exception { + String symbolic = null; + String errorMessage = ""; + for (int i = 0; i < Atoms.size(); i++) { + ADFAtom atom = Atoms.get(i); + for (int j = 0; j < 3; j++) { + symbolic = atom.Symbolics[j]; + if (symbolic == null) { + continue; + } + // if (token.startsWith("-")) { + // symbolic = token.substring(1); + // sign = -1.0f; + // } + + // if (symbolicStrings.get(symbolic) == null) { + // errorMessage += "Symbolic parameter " + symbolic + " is not + // resolved\n"; + // continue; + // } + double value; + try { + value = this.mathExpressionParser.resolveExpression(symbolic); + logger.info(symbolic + " = " + value); + } catch (Exception ex) { + throw new Exception("Cannot resolve expression for atom " + (i + 1) + " : " + symbolic + " : " + ex.getMessage()); + } + // float value = symbolicStrings.get(symbolic); + + if (atom.Cartesian) { + atom.xyz[j] = distanceUnits * (float) value; + } else if (j == 0) { + atom.internal[j] = distanceUnits * (float) value; + } else { + atom.internal[j] = angleUnits * (float) value; + } + } + } + + if (errorMessage.length() > 0) { + throw new Exception(errorMessage); + } + + } + + public void parseCHARGE(String charge) throws Exception { + defaultChargeUsed = false; + try { + String token = charge; + if (token.startsWith("+")) { + token = token.substring(1); + } + totalCharge = Integer.parseInt(token); // (int)Float.parseFloat(charge); + } catch (Exception ex) { + throw new Exception("Cannot parse charge " + charge + " : " + ex.getMessage()); + } + } + + public void parseQMMM(BufferedReader in) throws Exception { + String line, token; + while ((line = in.readLine()) != null) { + line = line.trim().toUpperCase(); + if (line.length() < 1) { // Blank line + continue; + } + if (line.equalsIgnoreCase("END")) { + return; + } + + if (line.equals("MM_CONNECTION_TABLE")) { + connectionTable.clear(); + connectionTable.ensureCapacity(Atoms.size()); + for (int i = 0; i < Atoms.size(); i++) { + if ((line = in.readLine()) == null) { + throw new Exception( + "Unexpecting end-of-file while reading MM_CONNECTION_TABLE"); + } + + StringTokenizer st = new StringTokenizer(line, " ,\t"); + if (st.countTokens() < 3) { + throw new Exception( + "Each MM_CONNECTION_TABLE record should have at least 3 tokens, got " + + line); + } + + st.nextToken(); // Skip atom number + + ADFAtom atom = Atoms.get(i); + atom.FF_Label = st.nextToken(); + atom.MM_Type = st.nextToken(); + + if (st.hasMoreTokens()) { + int[] links = new int[st.countTokens()]; + int count = 0; + while (st.hasMoreTokens()) { + token = st.nextToken(); + try { + links[count] = Integer.parseInt(token); + --links[count]; + ++count; + } catch (Exception ex) { + throw new Exception( + "Error parsing connection within MM_CONNECTION_TABLE block. Expecting integer number, got " + + line); + } + } + connectionTable.add(links); + } + } + } + } + } + + void skipSection(BufferedReader in) throws Exception { + String line; + while ((line = in.readLine()) != null) { + line = line.trim().toUpperCase(); + if (line.length() < 1) { // Blank line + continue; + } + + if (line.equalsIgnoreCase("END") || line.startsWith("END ")) { + return; + } + + } + } + + /** + * Geometric lengths and angles are in units defined by: UNITS length Angstrom / Bohr angle Degree / Radian end + * + * @param in BufferedReader + * @throws Exception + */ + public void parseUNITS(BufferedReader in) throws Exception { + String line, token; + while ((line = in.readLine()) != null) { + line = line.trim().toUpperCase(); + if (line.length() < 1) { // Blank line + continue; + } + + if (line.equalsIgnoreCase("END")) { + return; + } + + StringTokenizer st = new StringTokenizer(line, " =,"); + if (st.countTokens() < 2) { + throw new Exception("Usage of UNITS keyword:\n UNITS\n" + " LENGTH angstrom\n ANGLE degree\nEND"); + } + token = st.nextToken(); + + if (token.equals("LENGTH")) { + token = st.nextToken(); + if (token.equalsIgnoreCase("Angstrom")) { + distanceUnits = 1.0f; + } else if (token.equalsIgnoreCase("Bohr")) { + distanceUnits = (float) ONE_BOHR; + } else { + throw new Exception("Unknown units for LENGTH: " + token + "\nValid keywords: Angstrom and Bohr"); + } + } else if (token.equals("ANGLE")) { + token = st.nextToken(); + if (token.equalsIgnoreCase("Degree")) { + angleUnits = DEGREES_TO_RADIANS; + mathExpressionParser.setInDegrees(true); + } else if (token.equalsIgnoreCase("Radian")) { + angleUnits = 1.0f; + mathExpressionParser.setInDegrees(false); + } else { + throw new Exception("Unknown units for ANGLE: " + token + + "\nValid keywords: Degree and Radian"); + } + + } else { + throw new Exception("Unknown keyword in UNITS block: " + token + + "\nValid keywords: LENGTH and ANGLE"); + } + + } + } + + /** + * ATOMS {Cartesian / Zmatrix / MOPAC / Internal / ZCart} {N} Atom Coords {F=Fragment} ... End + * + * @param keyword String + * @param in BufferedReader + * @throws Exception + */ + public void parseATOMS(String keyword, BufferedReader in) throws Exception { + String line, token = null; + line = keyword.trim().toUpperCase(); + StringTokenizer st = new StringTokenizer(line, " =,"); + st.nextToken(); + if (st.hasMoreTokens()) { + token = st.nextToken(); + } + + if (token == null || token.equalsIgnoreCase("Cartesian") + || token.equalsIgnoreCase("Cart") || token.startsWith("CART")) { + parseCartesianCoordinates(in); + } else if (token.equalsIgnoreCase("Zmatrix") || token.equalsIgnoreCase("Z-matrix") || token.equalsIgnoreCase("Internal") + || token.startsWith("Z-MAT") || token.startsWith("ZMAT")) { + internalCoordinates = true; + parseZmatrix(in); + } else { + throw new Exception("Unknown atom coordinates type: " + line); + } + } + + public void parseZmatrix(BufferedReader in) throws Exception { + String line, token = null; + while ((line = in.readLine()) != null) { + line = line.trim(); + StringTokenizer st = new StringTokenizer(line, " =,"); + if (line.length() < 2) { + throw new Exception("Expecting internal coordinates, got: " + line); + } + + if (line.equalsIgnoreCase("END") + || line.toUpperCase().startsWith("END")) { + return; + } + + // --- Skip the first token it it's a number + token = st.nextToken(); + try { + Float.parseFloat(token); + token = st.nextToken(); + } catch (Exception ex) { + // Do nothing + } + + ADFAtom atom = new ADFAtom(); + atom.name = token; + atom.atomicNumber = parseAtomLabel(atom.name); + atom.Cartesian = false; + + if (Atoms.size() == 0) { // The first atom + Atoms.add(atom); + continue; + } + + // --- Parding ia + if (!st.hasMoreTokens()) { + throw new Exception("Expecting atom's number current atom is connected to. Got " + line); + } + + token = st.nextToken(); + int ijk = 0; + try { + ijk = Integer.parseInt(token); + } catch (Exception ex) { + throw new Exception("Error parsing atom's number current atom is connected to. Got " + line); + } + + if (ijk < 1 || ijk > Atoms.size()) { + throw new Exception("Wrong atom's number current atom is connected to. Should be > 0 and < " + (Atoms.size() + 1) + + "\nGot " + line); + } + + atom.i1 = ijk - 1; + + // --- Parsing ib + if (!st.hasMoreTokens()) { + throw new Exception("Expecting atom's number current atom is forming angle with. Got " + line); + } + + token = st.nextToken(); + + if (Atoms.size() > 1) { + ijk = 0; + try { + ijk = Integer.parseInt(token); + } catch (Exception ex) { + throw new Exception( + "Error parsing atom's number current atom is forming angle with. Got " + + line); + } + + if (ijk < 1 || ijk > Atoms.size() || ijk == atom.i1 + 1) { + throw new Exception( + "Wrong atom's number current atom is forming angle with. Should be > 0, < " + + (Atoms.size() + 1) + " and not equal to " + + (atom.i1 + 1) + "\nGot " + line); + } + + atom.i2 = ijk - 1; + } + + // --- Parsing ic + if (!st.hasMoreTokens()) { + throw new Exception( + "Expecting atom's number current atom is forming torsion with. Got " + + line); + } + + token = st.nextToken(); + + if (Atoms.size() > 2) { + ijk = 0; + try { + ijk = Integer.parseInt(token); + } catch (Exception ex) { + throw new Exception( + "Error parsing atom's number current atom is forming torsion with. Got " + + line); + } + + if (ijk < 1 || ijk > Atoms.size() || ijk == atom.i1 + 1 || ijk == atom.i2 + 1) { + throw new Exception("Wrong atom's number current atom is forming torsion with. Should be > 0, <= " + + (Atoms.size() + 1) + " and not equal to " + (atom.i1 + 1) + " and " + (atom.i2 + 1) + "\nGot " + + line); + } + + atom.i3 = ijk - 1; + } + + // --- Parsing bond length + if (!st.hasMoreTokens()) { + throw new Exception("Expecting bond length. Got " + line); + } + + token = st.nextToken(); + + float value = 0; + try { + value = Float.parseFloat(token); + if (value <= 0) { + throw new Exception("Wrong value for atomic distance. Should be > 0. Got " + line); + } + atom.internal[0] = value * this.distanceUnits; + } catch (Exception ex) { + symbolicParamResolved = false; + atom.Symbolics[0] = token.toUpperCase(); + } + + if (Atoms.size() == 1) { // The Second + Atoms.add(atom); + continue; + } + + // --- Parsing angle + if (!st.hasMoreTokens()) { + throw new Exception("Expecting angle. Got " + line); + } + + token = st.nextToken(); + + value = 0; + try { + value = Float.parseFloat(token); + atom.internal[1] = value * this.angleUnits; + } catch (Exception ex) { + symbolicParamResolved = false; + atom.Symbolics[1] = token.toUpperCase(); + } + + if (Atoms.size() == 2) { // The third + Atoms.add(atom); + continue; + } + + // --- Parsing torsion + if (!st.hasMoreTokens()) { + throw new Exception("Expecting torsion. Got " + line); + } + + token = st.nextToken(); + + value = 0; + try { + value = Float.parseFloat(token); + atom.internal[2] = value * this.angleUnits; + } catch (Exception ex) { + symbolicParamResolved = false; + atom.Symbolics[2] = token.toUpperCase(); + } + + Atoms.add(atom); + + } + } + + boolean isNumber(String token) { + try { + Float.parseFloat(token); + return true; + } catch (Exception ex) { + } + return false; + } + + public void parseCartesianCoordinates(BufferedReader in) throws Exception { + String line, token = null; + while ((line = in.readLine()) != null) { + line = line.trim(); + StringTokenizer st = new StringTokenizer(line, " =,\t"); + if (line.length() < 1) { + throw new Exception("Expecting cartesian coordinates, got: " + line); + } + + if (line.equalsIgnoreCase("END") || line.toUpperCase().startsWith("END")) { + return; + } + + if (st.countTokens() < 4) { + throw new Exception("Cartesian coordinates input should contain at least 4 tokens, got: " + line); + } + + token = st.nextToken(); + if (isNumber(token)) { + // Skip atom number + token = st.nextToken(); + } + + ADFAtom atom = new ADFAtom(); + atom.name = token; + atom.atomicNumber = parseAtomLabel(atom.name); + atom.Cartesian = true; + + // --- Parse X,Y,Z-coordinates + for (int i = 0; i < 3; i++) { + token = st.nextToken(); + boolean isNumber = true; + float value = 0; + + try { + value = Float.parseFloat(token); + atom.xyz[i] = value * distanceUnits; + } catch (Exception ex) { + isNumber = false; + } + + // --- if it's a parameter + if (!isNumber) { + symbolicParamResolved = false; + token = token.toUpperCase(); + // String symbolic = token; + // if (token.startsWith("-")) { + // symbolic = token.substring(1); + // } + // if (!symbolicStrings.containsKey(symbolic)) { + // symbolicStrings.put(symbolic, null); + // } + atom.Symbolics[i] = token; + } + } + + Atoms.add(atom); + } + } + + /** + * Returns element number (0 for dummy atom) + * + * @param label String + * @return int + */ + static public int parseAtomLabel(String label) throws Exception { + int element = 0; + + if (label.length() == 1) { + element = ChemicalElements.getAtomicNumber(label); + } else if (label.indexOf(".") != -1) { + label = label.substring(0, label.indexOf(".")); + element = ChemicalElements.getAtomicNumber(label); + } else { + element = ChemicalElements.getAtomicNumber(label); + } + + return element; + } + + /** + * GEOVAR Name Data ... end + * + * @param in BufferedReader + * @throws Exception + */ + public void parseGEOVAR(BufferedReader in) throws Exception { + /* + * Data Either of the following three formats: + * + * 1 A single value simply assigns the value to the corresponding atomic + * coordinate(s). + * + * 2 Two or more values (separated by a delimiter) imply that the + * corresponding atomic coordinate is a Linear Transit or a Nudged + * Elastic Band parameter. For Linear Transit, only two values are + * allowed in which case they specify initial and final values of the LT + * path, respectively. In case of a NEB calculation one can provide more + * than just initial and final values to get a better initial + * approximation of the reaction path. It is generally recommended (and + * in some cases necessary) to use more values. Intermediate images will + * be obtained by polynomial interpolation of degree N-1, where N is the + * number of values. + * + * 3 A single value followed by a letter F assigns the value to the + * corresponding atomic coordinates and specifies that these coordinates + * are frozen: they will not be optimized. + */ + + String line, token = null; + while ((line = in.readLine()) != null) { + line = line.trim(); + StringTokenizer st = new StringTokenizer(line, " =,"); + if (line.length() < 1) { + throw new Exception("Expecting data in GEOVAR block, got empty line"); + } + + if (line.equalsIgnoreCase("END") + || line.toUpperCase().startsWith("END")) { + return; + } + + if (st.countTokens() < 2) { + throw new Exception("Data in GEOVAR block should consist of at least 2 tokens, got: " + line); + } + + // --- Get parameter name + String symbol = st.nextToken().toUpperCase(); + + if (mathExpressionParser.hasSymbol(symbol)) { + throw new Exception("GEOVAR: Symbol " + symbol + " is already defined in the DEFINE block"); + } + + // if (symbolicStrings.get(symbol) != null) { + // System.err.println("Symbolic parameter " + symbol + " is already + // resolved. Ignored..."); + // continue; + // } + // --- Getting number + mathExpressionParser.addLine(symbol + " = " + st.nextToken()); + + // token = st.nextToken(); + // try { + // float value = Float.parseFloat(token); + // symbolicStrings.put(symbol, new Float(value)); + // } + // catch (Exception ex) { + // throw new Exception("Cannot parse value for symbolic parameter " + // + symbol + " : " + token + " : " + ex.getMessage()); + // } + if (!st.hasMoreTokens()) { + continue; + } + + token = st.nextToken(); + + if (token.equalsIgnoreCase("F")) { + frozenParameters.add(symbol); + includesFrozenAtoms = true; + continue; + } + + System.err.println("Linear Transit or a Nudged Elastic Band parameters are currently not supported"); + + } + } + + public void parseDEFINE(BufferedReader in) throws Exception { + /* + */ + + String line; + while ((line = in.readLine()) != null) { + line = line.trim(); + StringTokenizer st = new StringTokenizer(line, " =,"); + if (line.length() < 1) { + continue; + // throw new Exception("Expecting data in DEFINE block, got + // empty line"); + } + + if (line.equalsIgnoreCase("END") + || line.toUpperCase().startsWith("END")) { + break; + } + + if (st.countTokens() < 2) { + throw new Exception("Data in DEFINE block should consist of at least 2 tokens, got: " + line); + } + + try { + mathExpressionParser.addLine(line); + } catch (Exception ex) { + throw new Exception("Error parsing expression " + line + " : " + ex.getMessage()); + } + } + + String errorMessage = ""; + Iterator iter = symbolicStrings.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String key = me.getValue().toString(); + if (mathExpressionParser.hasSymbol(key)) { + errorMessage += "Symbolic string " + key + " is already defined in GEOVAR block\n"; + } + } + if (errorMessage.length() > 0) { + throw new Exception("Duplicate definition " + errorMessage); + } + + } + + public static void fromZMatrixToCartesians(List atoms) throws Exception { + int i; + int natoms = atoms.size(); + ADFAtom a, a1, a2, a3; + float xyz[] = new float[3], x1[], x2[], x3[]; + + double SIN2, COS2, SIN3, COS3, VT[] = new double[3], V1[] = new double[3], V2[] = new double[3]; + double R2, V3[] = new double[3], VA1, VB1, VC1, R3, V[] = new double[3]; + + if (natoms < 1) { + return; + } + + float factor = 1.0f; + + // --- The first atom. Put it into the origin + ADFAtom atom = atoms.get(0); + atom.setXYZ(0, 0, 0); + + if (natoms < 2) { + return; + } + + // --- ther second atom: put it along the X-axis + atom = atoms.get(1); + atom.setXYZ(atom.internal[0], 0, 0); + + if (natoms < 3) { + return; + } + + // --- Third atom (put it into the XOY plane + a = atoms.get(2); + + // x1 = (float[]) cartesians.get(a.ijk[0] - 1); + x1 = new float[3]; + int index = a.i1; + a1 = atoms.get(index); + x1[0] = a1.getX(); + x1[1] = a1.getY(); + x1[2] = a1.getZ(); + + xyz[2] = 0.0f; // Z-coordinate + + if (index == 0) { // Connected to the first atom + // logger.info.println("To the 1st"); + xyz[0] = a.getBondLength() * (float) Math.cos((double) a.getAngle()); // So, we put it + // along X-axis + xyz[1] = a.getBondLength() * (float) Math.sin((double) a.getAngle()); + } else { + // logger.info.println("To the 2nd"); + xyz[0] = x1[0] - a.getBondLength() * (float) Math.cos((double) a.getAngle()); // So, we put it + // along X-axis + xyz[1] = -a.getBondLength() * (float) Math.sin((double) a.getAngle()); + } + + a.setXYZ(xyz[0], xyz[1], xyz[2]); + + // Other atoms + for (i = 3; i < natoms; i++) { + + a = atoms.get(i); + + a1 = atoms.get(a.i1); + a2 = atoms.get(a.i2); + a3 = atoms.get(a.i3); + + x1 = a1.xyz; + x2 = a2.xyz; + x3 = a3.xyz; + + SIN2 = Math.sin((double) a.getAngle()); + COS2 = Math.cos((double) a.getAngle()); + SIN3 = Math.sin((double) a.getTorsion()); + COS3 = Math.cos((double) a.getTorsion()); + + VT[0] = a.getBondLength() * factor * COS2; + VT[1] = a.getBondLength() * factor * SIN2 * SIN3; + VT[2] = a.getBondLength() * factor * SIN2 * COS3; + + V1[0] = x3[0] - x2[0]; + V1[1] = x3[1] - x2[1]; + V1[2] = x3[2] - x2[2]; + + V2[0] = x2[0] - x1[0]; + V2[1] = x2[1] - x1[1]; + V2[2] = x2[2] - x1[2]; + + R2 = Math.sqrt(V2[0] * V2[0] + V2[1] * V2[1] + V2[2] * V2[2]); + + V3[0] = V1[1] * V2[2] - V1[2] * V2[1]; + V3[1] = V1[2] * V2[0] - V1[0] * V2[2]; + V3[2] = V1[0] * V2[1] - V1[1] * V2[0]; + + R3 = Math.sqrt(V3[0] * V3[0] + V3[1] * V3[1] + V3[2] * V3[2]); + + V2[0] = V2[0] / R2; + V2[1] = V2[1] / R2; + V2[2] = V2[2] / R2; + + V3[0] = V3[0] / R3; + V3[1] = V3[1] / R3; + V3[2] = V3[2] / R3; + + V[0] = V2[1] * V3[2] - V2[2] * V3[1]; + V[1] = V2[2] * V3[0] - V2[0] * V3[2]; + V[2] = V2[0] * V3[1] - V2[1] * V3[0]; + + VA1 = V2[0] * VT[0] + V3[0] * VT[1] + V[0] * VT[2]; + VB1 = V2[1] * VT[0] + V3[1] * VT[1] + V[1] * VT[2]; + VC1 = V2[2] * VT[0] + V3[2] * VT[1] + V[2] * VT[2]; + + xyz[0] = x1[0] + (float) VA1; + xyz[1] = x1[1] + (float) VB1; + xyz[2] = x1[2] + (float) VC1; + + a.setXYZ(xyz); + } + } +} diff --git a/src/main/java/cct/adf/ADFAtom.java b/src/main/java/cct/adf/ADFAtom.java new file mode 100644 index 0000000..6f4cb68 --- /dev/null +++ b/src/main/java/cct/adf/ADFAtom.java @@ -0,0 +1,108 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.adf; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class ADFAtom { + String name; + String FF_Label, MM_Type; + int atomicNumber; + float xyz[] = new float[3]; + int opt[] = new int[3]; + float[] internal = new float[3]; + //float bondLength, angle, torsion; + String[] Symbolics = new String[3]; + int i1 = -1, i2 = -1, i3 = -1; + boolean Cartesian = true; + + public void setName(String _name) { + name = _name; + } + + public ADFAtom() { + opt[0] = opt[1] = opt[2] = 1; + } + + public void setXYZ(float x, float y, float z) { + xyz[0] = x; + xyz[1] = y; + xyz[2] = z; + } + + public void setXYZ(float[] xyz) { + this.xyz[0] = xyz[0]; + this.xyz[1] = xyz[1]; + this.xyz[2] = xyz[2]; + } + + public float getX() { + return xyz[0]; + } + + public float getY() { + return xyz[1]; + } + + public float getZ() { + return xyz[2]; + } + + public float getBondLength() { + return this.internal[0]; + } + + public float getAngle() { + return this.internal[1]; + } + + public float getTorsion() { + return this.internal[2]; + } + +} diff --git a/src/main/java/cct/adf/ADFFrequency.java b/src/main/java/cct/adf/ADFFrequency.java new file mode 100644 index 0000000..08ff7e0 --- /dev/null +++ b/src/main/java/cct/adf/ADFFrequency.java @@ -0,0 +1,61 @@ +package cct.adf; + +import java.util.ArrayList; +import java.util.List; + +import cct.vecmath.Point3f; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class ADFFrequency { + private double value; + private List vectors = new ArrayList (); + + public ADFFrequency(double value) { + this.value = value; + } + + public double getFrequencyValue() { + return value; + } + + public boolean hasDisplacementVectors() { + return !(vectors == null || vectors.size() < 1); + } + + public float[][] getDisplacementVectors() { + if (vectors == null || vectors.size() < 1) { + return null; + } + float[][] vect = new float[vectors.size()][3]; + for (int i = 0; i < vectors.size(); i++) { + ADFVector v = vectors.get(i); + vect[i][0] = v.vector.getX(); + vect[i][1] = v.vector.getY(); + vect[i][2] = v.vector.getZ(); + } + return vect; + } + + public void addVector(String atom_name, float x, float y, float z) { + ADFVector v = new ADFVector(); + v.atom_name = atom_name; + v.vector.setXYZ(x, y, z); + vectors.add(v); + } + + class ADFVector { + String atom_name; + private Point3f vector = new Point3f(); + } +} diff --git a/src/main/java/cct/adf/ADFOutput.java b/src/main/java/cct/adf/ADFOutput.java new file mode 100644 index 0000000..df605cd --- /dev/null +++ b/src/main/java/cct/adf/ADFOutput.java @@ -0,0 +1,937 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.adf; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.interfaces.OutputResultsInterface; +import cct.modelling.GeneralMolecularDataParser; +import cct.modelling.StructureManagerInterface; +import cct.modelling.VIBRATIONAL_SPECTRUM; + +/** + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class ADFOutput extends GeneralMolecularDataParser + implements OutputResultsInterface, StructureManagerInterface { + + static private final String scfEnergy = "Total Energy"; + private List sections = new ArrayList(); + private Map termVsStrReference = new HashMap(); + private boolean debug = true; + private boolean normalTermination = true; + private boolean skipBody = false; // Change with care! + private boolean skipSectionWithoutGeometry = true; + private Set propertiesToChart = new HashSet(); + private int selectedSection = 0; + static final Logger logger = Logger.getLogger(ADFOutput.class.getCanonicalName()); + + public ADFOutput() { + } + + public void selectSection(int n) { + selectedSection = n; + } + + @Override + public boolean isNormalTermination() { + return normalTermination; + } + + public int validFormatScore(BufferedReader in) throws Exception { + ADFOutput adf = new ADFOutput(); + try { + adf.parseData(in); + } catch (Exception ex) { + return 0; + } + + if (adf.getMolecule() == null || adf.getMolecule().getNumberOfAtoms() == 0) { + return 0; + } + return 10; + } + + public void parseData(BufferedReader in) throws Exception { + if (true) { + throw new Exception("parseData for ADF output is not implemented yet"); + } + MoleculeInterface mol = getMoleculeInterface(); + this.addMolecule(mol); + + try { + while (parseSection(in)) { + } + } catch (Exception ex) { + System.err.println("It was error while parsing ADF output file: " + ex.getMessage()); + throw new Exception("Error parsing ADF output: " + ex.getMessage()); + } + } + + public ADFOutputSection getSection(int section_number) throws Exception { + if (section_number >= sections.size() || section_number < 0) { + throw new Exception(this.getClass().getCanonicalName() + " : wrong section number is requested " + section_number); + } + return sections.get(section_number); + } + + public void getMolecularInterface(MoleculeInterface molec, int section_number) throws + Exception { + if (molec == null) { + throw new Exception(this.getClass().getCanonicalName() + " : molec == null"); + } + + ADFOutputSection section = getSection(section_number); + + if (!section.hasGeometry()) { + throw new Exception(this.getClass().getCanonicalName() + " : section " + section_number + " does not contain geometry"); + } + + List snapshots = section.getSnapshots(); + ADFSnapshot snapshot = snapshots.get(snapshots.size() - 1); // Take the last snapshot + if (debug) { + logger.info("getMolecularInterface: snapshot " + (snapshots.size() - 1)); + } + + List atoms = snapshot.getAtoms(); + + if (atoms.size() < 1) { + throw new Exception(this.getClass().getCanonicalName() + " : no ADF atoms in snapshot"); + } + + molec.addMonomer("ADF"); + + for (int i = 0; i < atoms.size(); i++) { + ADFAtom ga = atoms.get(i); + AtomInterface atom = molec.getNewAtomInstance(); + atom.setName(ga.name); + atom.setAtomicNumber(ga.atomicNumber); + atom.setXYZ(ga.xyz[0], ga.xyz[1], ga.xyz[2]); + /* + if (ga.FF_Label != null) { + atom.setProperty(FF_LABEL_PROP, ga.FF_Label); + } + + if (ga.MM_Type != null) { + atom.setProperty(MM_TYPE_PROP, ga.MM_Type); + } + */ + molec.addAtom(atom); + } + + } + + /** + * Parses ADF output file + * + * @param fileName String - file name + * @throws Exception + */ + public void parseFile(String fileName) throws Exception { + + try { + BufferedReader in = new BufferedReader(new FileReader(fileName)); + + try { + while (parseSection(in)) { + } + } catch (Exception ex) { + System.err.println("It was error while parsing ADF output file: " + ex.getMessage()); + return; + } + } catch (Exception ex) { + throw new Exception("Cannot open file " + fileName + " : " + ex.getMessage()); + } + } + + public boolean parseSection(BufferedReader in) throws Exception { + String line; + + if (skipBody) { // Look for log information only + ADFOutputSection section = new ADFOutputSection(); + return parseLogInfo(section, in); + } + + // --- Looking for start of the output section + boolean condition = false; + while ((line = in.readLine()) != null) { + if (line.startsWith(" * Amsterdam Density Functional (ADF)")) { + condition = true; + break; + } + } + if (!condition) { + return false; + } + + ArrayList initialGeometry = null; + ADFOutputSection section = new ADFOutputSection(); + section.addSummary(line); + + while ((line = in.readLine()) != null) { + if (line.startsWith(" NORMAL TERMINATION")) { // Do nothing + //break; + } else if (line.startsWith(" G E O M E T R Y *** 3D Molecule ***")) { + initialGeometry = parseInitialGeometry(in); + } else if (line.startsWith(" (LOGFILE)")) { + parseLogInfo(section, in); + if (skipSectionWithoutGeometry) { + if (section != null && section.hasGeometry()) { + sections.add(section); + } else if (section != null && (!section.hasGeometry()) && initialGeometry != null) { + ADFSnapshot snapshot = new ADFSnapshot(); + snapshot.setAtoms(initialGeometry); + section.addSummary("Initial Geometry"); + section.addSnapshot(snapshot); + sections.add(section); + } + } else if (section != null) { + sections.add(section); + } + return true; + } else if (line.contains("Vibrations and Normal Modes")) { + ArrayList freqs = parseFrequenciesInfo(in); + section.addFrequencies(freqs); + } else if (line.contains("* R U N T Y P E :")) { + section.addSummary(line); + } else if (line.startsWith(" SCF CONVERGED")) { + } + + } + + return true; + } + + private ArrayList parseFrequenciesInfo(BufferedReader in) throws Exception { + /* + Vibrations and Normal Modes *** (cartesian coordinates, NOT mass-weighted) *** + =========================== + + The headers on the normal mode eigenvectors below give the Frequency in cm-1 + (a negative value means an imaginary frequency, no output for (almost-)zero frequencies) + + + + */ + + // --- skip 6 lines + String line; + for (int i = 0; i < 6; i++) { + if ((line = in.readLine()) == null) { + throw new Exception("Unexpected end of file while reading frequencies info"); + } + } + + // --- Start to read freqiencies and displacement vectors + + /* + -194.118 161.727 199.897 + ------------------------ ------------------------ ------------------------ + 1.N 0.000 0.000 0.000 0.000 0.000 -0.170 0.000 -0.076 0.000 + 2.Cr 0.000 0.000 0.000 0.000 0.000 0.175 0.000 0.000 0.000 + 3.N 0.000 0.000 0.000 0.000 0.000 -0.170 -0.065 0.038 0.000 + 4.N 0.000 0.000 0.000 0.000 0.000 -0.170 0.065 0.038 0.000 + 5.H 0.000 -0.408 0.000 -0.212 0.000 -0.320 0.000 0.405 0.000 + 6.H 0.000 0.408 0.000 0.212 0.000 -0.320 0.000 0.405 0.000 + 7.H -0.354 -0.204 0.000 -0.106 0.183 -0.320 -0.351 -0.202 0.000 + 8.H 0.354 0.204 0.000 0.106 -0.183 -0.320 -0.351 -0.202 0.000 + 9.H -0.354 0.204 0.000 0.106 0.183 -0.320 0.351 -0.202 0.000 + 10.H 0.354 -0.204 0.000 -0.106 -0.183 -0.320 0.351 -0.202 0.000 + + + + */ + float[] vector = new float[3]; + ArrayList freqs = new ArrayList(); + while (true) { + // --- Read frequency's values + if ((line = in.readLine()) == null) { + throw new Exception("Unexpected end of file while reading frequencies values"); + } + StringTokenizer st = new StringTokenizer(line, " \t"); + if (st.countTokens() < 1) { // End of freq info + break; + } + + String token; + int num_freqs = st.countTokens(); + ADFFrequency[] temp_freq = new ADFFrequency[num_freqs]; + + // --- parse values + for (int i = 0; i < num_freqs; i++) { + token = st.nextToken(); + try { + double value = Double.parseDouble(token); + temp_freq[i] = new ADFFrequency(value); + } catch (Exception ex) { + throw new Exception("Error while parsing frequencies values. Got " + line + " : " + ex.getMessage()); + } + } + + // --- Skip line + if ((line = in.readLine()) == null) { + throw new Exception("Unexpected end of file after reading frequencies values"); + } + + // --- Read vectors + while (true) { + if ((line = in.readLine()) == null) { + throw new Exception("Unexpected end of file while reading vectors"); + } + line = line.trim(); + + // --- Check for end of vectors (two blank lines) + if (line.length() < 1) { // First blank line + // --- Skip line + if ((line = in.readLine()) == null) { + throw new Exception("Unexpected end of file while reading blank line after vectors"); + } + break; + } + + // --- Parse vectors + // 1.N 0.000 0.000 0.000 0.000 0.000 -0.170 0.000 -0.076 0.000 + st = new StringTokenizer(line, " \t"); + + if (st.countTokens() < num_freqs * 3 + 1) { + throw new Exception("Expected at least " + (num_freqs * 3 + 1) + " tokens for reading vectors, got " + line); + } + + // --- Parse atom name + String atom_name = st.nextToken(); + if (atom_name.contains(".")) { + atom_name = atom_name.substring(atom_name.indexOf(".") + 1); + } + + // --- Parse vector's values + try { + for (int i = 0; i < num_freqs; i++) { + for (int j = 0; j < 3; j++) { + vector[j] = Float.parseFloat(st.nextToken()); + } + temp_freq[i].addVector(atom_name, vector[0], vector[1], vector[2]); + } + } catch (Exception ex) { + throw new Exception("Error while parsing vector's values. Got " + line); + } + } + + // --- Add frequencies to the container + for (int i = 0; i < num_freqs; i++) { + freqs.add(temp_freq[i]); + } + } + return freqs; + } + + public boolean parseLogInfo(ADFOutputSection section, BufferedReader in) throws Exception { + String line, token; + boolean condition = false; + + // --- Find " (LOGFILE)" + /* + while ( (line = in.readLine()) != null) { + if (line.startsWith(" (LOGFILE)")) { + condition = true; + break; + } + } + if (!condition) { + return false; + } + */ + ADFSnapshot snapshot = null; + + boolean read_header = true; + while ((line = in.readLine()) != null) { + + if (read_header) { + //section = new ADFOutputSection(); + section.addSummary(line); + read_header = false; + continue; + } + + if (line.contains("> END")) { + read_header = true; + continue; + } + + line = line.trim(); + if (line.length() < 1) { + sections.add(section); + return true; + } + + if (line.startsWith("Coordinates in Geometry Cycle") || line.startsWith("Coordinates in Frequency Displacement")) { + /* + Coordinates in Geometry Cycle 1 + Atom X Y Z (Angstrom) + 1.H 0.000000 0.000000 1.700000 + 2.C 0.000000 0.000000 0.700000 + 3.C 0.000000 0.000000 -0.700000 + 4.H 0.000000 0.000000 -1.700000 + <15:54:59> >>>> CORORT + + */ + // Skip a line + if ((line = in.readLine()) == null) { + break; + } + snapshot = new ADFSnapshot(); + ArrayList atoms = new ArrayList(); + while (true) { + line = in.readLine(); + if (line == null || line.contains(">>>>")) { + break; + } + ADFAtom atom = new ADFAtom(); + StringTokenizer st = new StringTokenizer(line, " "); + if (st.countTokens() < 4) { + throw new Exception("Expected at least 4 tokens to parse initial coordinates, got " + line); + } + token = st.nextToken(); + atom.name = token.substring(token.indexOf(".") + 1); + atom.atomicNumber = ADF.parseAtomLabel(atom.name); + atom.Cartesian = true; + + // --- Parse X,Y,Z-coordinates + for (int i = 0; i < 3; i++) { + token = st.nextToken(); + float value = 0; + + try { + value = Float.parseFloat(token); + atom.xyz[i] = value; + } catch (Exception ex) { + throw new Exception("Cannot parse Cartesian coordinate, got " + line); + } + } + atoms.add(atom); + } + snapshot.setAtoms(atoms); + section.addSnapshot(snapshot); + } else if (line.contains("> E-test: old,new=")) { + // <15:55:01> E-test: old,new= 0.00000, -0.77752 hartree + line = line.substring(line.indexOf("=") + 1); + StringTokenizer st = new StringTokenizer(line, " "); + if (st.countTokens() < 2) { + System.err.println("Expected at least 2 tokens to get energy, got " + line); + continue; + } + // --- Skip token + st.nextToken(); + token = st.nextToken(); + try { + double value = Double.parseDouble(token); + propertiesToChart.add(scfEnergy); + if (snapshot != null) { + snapshot.addProperty(scfEnergy, value); + } + } catch (Exception ex) { + System.err.println("Cannot parse total energy, got " + line); + } + } else if (line.contains("> max gradient:")) { + // <15:55:01> max gradient: 0.55590637 au/angstrom,radian + line = line.substring(line.indexOf("t:") + 2); + StringTokenizer st = new StringTokenizer(line, " "); + if (st.countTokens() < 1) { + System.err.println("Expected at least 1 token to get max gradient, got " + line); + continue; + } + // --- Skip token + token = st.nextToken(); + try { + double value = Double.parseDouble(token); + propertiesToChart.add("Max gradient"); + if (snapshot != null) { + snapshot.addProperty("Max gradient", value); + } + } catch (Exception ex) { + System.err.println("Cannot parse max gradient, got " + line); + } + } + + } + return false; + } + + public ArrayList parseInitialGeometry(BufferedReader in) throws Exception { + /* + G E O M E T R Y *** 3D Molecule *** + =============== + + + ATOMS + ===== X Y Z CHARGE + (Angstrom) Nucl +Core At.Mass + -------------------------- ---------------- ------- + 1 H 0.0000 0.0000 1.7000 1.00 1.00 1.0078 + 2 C 0.0000 0.0000 0.7000 6.00 6.00 12.0000 + 3 C 0.0000 0.0000 -0.7000 6.00 6.00 12.0000 + 4 H 0.0000 0.0000 -1.7000 1.00 1.00 1.0078 + + */ + + // --- Line with "G E O M E T R Y *** 3D Molecule ***" is read in already... Skip 7 lines... + String token, line; + for (int i = 0; i < 7; i++) { + if ((line = in.readLine()) == null) { + throw new Exception("Unexpected end-of-file while reading initial geometry"); + } + } + // --- PArse geometry + ArrayList atoms = new ArrayList(); + while ((line = in.readLine()) != null) { + line = line.trim(); + if (line.length() < 1) { + break; + } + ADFAtom atom = new ADFAtom(); + StringTokenizer st = new StringTokenizer(line, " "); + if (st.countTokens() < 5) { + throw new Exception("Expected at least 5 tokens to parse initial coordinates, got " + line); + } + // --- Skip token... + st.nextToken(); + atom.name = st.nextToken(); + atom.atomicNumber = ADF.parseAtomLabel(atom.name); + atom.Cartesian = true; + + // --- Parse X,Y,Z-coordinates + for (int i = 0; i < 3; i++) { + token = st.nextToken(); + float value = 0; + + try { + value = Float.parseFloat(token); + atom.xyz[i] = value; + } catch (Exception ex) { + throw new Exception("Cannot parse Cartesian coordinate, got " + line); + } + } + atoms.add(atom); + } + return atoms; + } + + public ArrayList parseCoordinates(BufferedReader in) throws Exception { + /* + Coordinates (Cartesian, in Input Orientation) + ======================= + + Atom bohr angstrom Geometric Variables + X Y Z X Y Z (0:frozen, *:LT par.) + -------------------------------------------------------------------------------------------------------------- + 1 Br 0.000000 0.159318 0.000000 0.000000 0.084307 0.000000 1 2 3 + 2 F 0.000000 -0.097415 3.760555 0.000000 -0.051550 1.990000 4 5 6 + 3 F 3.760555 -0.097415 0.000000 1.990000 -0.051550 0.000000 7 8 9 + 4 F 0.000000 -0.097415 -3.760555 0.000000 -0.051550 -1.990000 10 11 12 + 5 F 0.000000 3.771879 0.000000 0.000000 1.995993 0.000000 13 14 15 + 6 F -3.760555 -0.097415 0.000000 -1.990000 -0.051550 0.000000 16 17 18 + -------------------------------------------------------------------------------------------------------------- + + */ + + // --- Line with "Coordinates..." is read in already... Skip five lines... + String token, line; + for (int i = 0; i < 5; i++) { + if ((line = in.readLine()) == null) { + throw new Exception("Unexpected end-of-file while reading initial geometry"); + } + } + + // --- Parse geometry + ArrayList atoms = new ArrayList(); + while ((line = in.readLine()) != null) { + line = line.trim(); + if (line.length() < 1 || line.contains("----------")) { + break; + } + ADFAtom atom = new ADFAtom(); + StringTokenizer st = new StringTokenizer(line, " "); + if (st.countTokens() < 8) { + throw new Exception("Expected at least 8 tokens to parse initial coordinates, got " + line); + } + // --- Skip token... + st.nextToken(); + atom.name = st.nextToken(); + atom.atomicNumber = ADF.parseAtomLabel(atom.name); + atom.Cartesian = true; + + // --- Skip 3 tokens + st.nextToken(); + st.nextToken(); + st.nextToken(); + + // --- Parse X,Y,Z-coordinates + for (int i = 0; i < 3; i++) { + token = st.nextToken(); + float value = 0; + + try { + value = Float.parseFloat(token); + atom.xyz[i] = value; + } catch (Exception ex) { + throw new Exception("Cannot parse Cartesian coordinate, got " + line); + } + } + atoms.add(atom); + } + return atoms; + } + + public int countSectionsWithGeometry() { + if (sections.size() < 1) { + return 0; + } + int count = 0; + for (int i = 0; i < sections.size(); i++) { + ADFOutputSection section = sections.get(i); + if (section.hasGeometry()) { + ++count; + } + } + return count; + } + + public int[] getSectionsWithGeometry() { + if (sections.size() < 1) { + return null; + } + + int count = countSectionsWithGeometry(); + if (count < 1) { + return null; + } + + int[] secs = new int[count]; + + count = 0; + for (int i = 0; i < sections.size(); i++) { + ADFOutputSection section = sections.get(i); + if (section.hasGeometry()) { + secs[count] = i; + ++count; + } + } + return secs; + } + + @Override + public String[] getAvailPropToChart() { + if (propertiesToChart.size() < 1) { + return null; + } + String[] sa = new String[propertiesToChart.size()]; + propertiesToChart.toArray(sa); + return sa; + } + + @Override + public double[] getAllTerms(String term) { + if (!propertiesToChart.contains(term)) { + return null; + } + + if (!hasInteractiveChart()) { + return null; + } + + ADFOutputSection section = sections.get(selectedSection); + if (!section.hasGeometry()) { + return null; + } + + List snapshots = section.getSnapshots(); + + ArrayList references = new ArrayList(snapshots.size()); + ArrayList values = new ArrayList(snapshots.size()); + + for (int i = 0; i < snapshots.size(); i++) { + ADFSnapshot snapshot = snapshots.get(i); + try { + Double value = snapshot.getProperty(term); + values.add(value); + references.add(new Integer(i)); + } catch (Exception ex) { + } + } + if (values.size() < 1) { + return null; + } + + termVsStrReference.put(term, references); + double[] energies = new double[values.size()]; + for (int i = 0; i < values.size(); i++) { + energies[i] = values.get(i); + } + return energies; + } + + @Override + public boolean hasJobSummary() { + return false; + } + + @Override + public boolean hasInteractiveChart() { + if (propertiesToChart.size() < 1) { + return false; + } + + ADFOutputSection section = sections.get(selectedSection); + if (!section.hasGeometry()) { + return false; + } + + List snapshots = section.getSnapshots(); + + return snapshots.size() >= 2; + } + + @Override + public boolean hasVCDSpectrum() { + return false; + } + + @Override + public boolean hasUDepolSpectrum() { + return false; + } + + @Override + public boolean hasPDepolSpectrum() { + return false; + } + + @Override + public boolean hasRamanSpectrum() { + return false; + } + + @Override + public boolean hasInfraredSpectrum() { + return false; + } + + @Override + public float[][] getStructure(int n) { + return getStructure(n, scfEnergy); + } + + @Override + public float[][] getStructure(int n, String term) { + if (!propertiesToChart.contains(term)) { + return null; + } + + ADFOutputSection section = sections.get(selectedSection); + List snapshots = section.getSnapshots(); + + if (snapshots == null || snapshots.size() < 1) { + return null; + } + + ArrayList references = termVsStrReference.get(term); + if (references == null) { + System.err.println("references == null"); + return null; + } else if (n >= references.size()) { + System.err.println("n >= references.size()"); + return null; + } + + if (debug) { + logger.info("getStructure: # " + n); + } + + ADFSnapshot snapshot = snapshots.get(references.get(n)); + List geom = snapshot.getAtoms(); + + if (geom == null || geom.size() < 1) { + System.err.println(this.getClass().getCanonicalName() + " : no atoms in selected snapshot"); + return null; + } + + float[][] coords = new float[geom.size()][3]; + for (int i = 0; i < geom.size(); i++) { + ADFAtom atom = geom.get(i); + + coords[i][0] = atom.getX(); + coords[i][1] = atom.getY(); + coords[i][2] = atom.getZ(); + if (debug && i == geom.size() - 1) { + logger.info(i + " : x=" + coords[i][0] + " y=" + coords[i][1] + " z=" + coords[i][2]); + } + + } + return coords; + + } + + @Override + public void selectStructure(int number) throws Exception { + throw new Exception(this.getClass().getCanonicalName() + ": selectStructure(int number) is not implemented yet"); + } + + @Override + public void selectStructure(int number, String term) throws Exception { + throw new Exception(this.getClass().getCanonicalName() + ": selectStructure(int number, String term) is not implemented yet"); + } + + @Override + public VIBRATIONAL_SPECTRUM[] availableVibrationalSpectra() { + return null; + } + + @Override + public int countFrequencies() { + try { + ADFOutputSection section = getSection(selectedSection); + if (section.getFrequencies() == null) { + return 0; + } + return section.getFrequencies().size(); + } catch (Exception ex) { + return 0; + } + } + + @Override + public int countSpectra() { + return 0; + } + + @Override + public double getFrequency(int n) { + try { + ADFOutputSection section = getSection(selectedSection); + if (section.getFrequencies() == null) { + return 0; + } + ArrayList frequencies = section.getFrequencies(); + if (n < 0 || n >= frequencies.size()) { + return 0; + } + return frequencies.get(n).getFrequencyValue(); + } catch (Exception ex) { + return 0; + } + } + + @Override + public double getSpectrumValue(int n, VIBRATIONAL_SPECTRUM spectrum) { + return 0; + } + + @Override + public boolean hasDisplacementVectors() { + try { + ADFOutputSection section = getSection(selectedSection); + if (section.getFrequencies() == null) { + return false; + } + ArrayList frequencies = section.getFrequencies(); + if (frequencies == null || frequencies.size() < 1) { + return false; + } + return frequencies.get(0).hasDisplacementVectors(); + } catch (Exception ex) { + return false; + } + } + + @Override + public float[][] getDisplacementVectors(int n) { + try { + ADFOutputSection section = getSection(selectedSection); + if (section.getFrequencies() == null) { + return null; + } + ArrayList frequencies = section.getFrequencies(); + if (n < 0 || n >= frequencies.size()) { + return null; + } + return frequencies.get(n).getDisplacementVectors(); + } catch (Exception ex) { + return null; + } + } + + @Override + public void getSpectrum(double[] x, double[] y, int dim, VIBRATIONAL_SPECTRUM type) throws Exception { + } + + @Override + public void setNormalTermination(boolean yes) { + normalTermination = yes; + } + + @Override + public String getOutputResume() { + return "No output resume"; + } + + public static void main(String[] args) { + ADFOutput adfoutput = new ADFOutput(); + } +} diff --git a/src/main/java/cct/adf/ADFOutputSection.java b/src/main/java/cct/adf/ADFOutputSection.java new file mode 100644 index 0000000..5aeaac8 --- /dev/null +++ b/src/main/java/cct/adf/ADFOutputSection.java @@ -0,0 +1,93 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.adf; + +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class ADFOutputSection { + + private StringWriter summary = new StringWriter(1024); + private List snapshots = new ArrayList (); + private ArrayList frequencies = null; + + public ADFOutputSection() { + } + + public List getSnapshots() { + return snapshots; + } + + public boolean hasGeometry() { + if (snapshots.size() < 1) { + return false; + } + ADFSnapshot snapshot = snapshots.get(0); + return !(snapshot.getAtoms() == null || snapshot.getAtoms().size() < 1); + } + + public void addSummary(String line) { + summary.append(line); + } + + public void addSnapshot(ADFSnapshot snapshot) { + snapshots.add(snapshot); + } + + public void addFrequencies(ArrayList freqs) { + this.frequencies = freqs; + } + + public ArrayList getFrequencies() { + return this.frequencies; + } + +} diff --git a/src/main/java/cct/adf/ADFSnapshot.java b/src/main/java/cct/adf/ADFSnapshot.java new file mode 100644 index 0000000..9ff2d4d --- /dev/null +++ b/src/main/java/cct/adf/ADFSnapshot.java @@ -0,0 +1,83 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.adf; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class ADFSnapshot { + + private List atoms; + private Map properties = new HashMap (10); + + public ADFSnapshot() { + } + + public List getAtoms() { + return atoms; + } + + public void addProperty(String type, double value) { + properties.put(type, new Double(value)); + } + + public double getProperty(String type) throws Exception { + if (!properties.containsKey(type)) { + throw new Exception("Snapshot does not have energy term " + type); + } + return properties.get(type); + } + + public void setAtoms(ArrayList atoms) { + this.atoms = atoms; + } +} diff --git a/src/main/java/cct/adf/package.html b/src/main/java/cct/adf/package.html new file mode 100644 index 0000000..8542c68 --- /dev/null +++ b/src/main/java/cct/adf/package.html @@ -0,0 +1,24 @@ + + + + +Begin with a one sentence summary about this package. +Follow with the remainder of your description. + +

Package Specification

+ +
+ +

Related Documentation

+ + + + + diff --git a/src/main/java/cct/amber/Amber-64x64.png b/src/main/java/cct/amber/Amber-64x64.png new file mode 100644 index 0000000..408b205 Binary files /dev/null and b/src/main/java/cct/amber/Amber-64x64.png differ diff --git a/src/main/java/cct/amber/Amber9JobDialog.java b/src/main/java/cct/amber/Amber9JobDialog.java new file mode 100644 index 0000000..f67b6ae --- /dev/null +++ b/src/main/java/cct/amber/Amber9JobDialog.java @@ -0,0 +1,97 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.amber; + +import java.awt.BorderLayout; +import java.awt.Frame; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JPanel; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Amber9JobDialog + extends JDialog { + JPanel panel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JPanel jPanel1 = new JPanel(); + Sander9JobPanel amber9JobPanel1 = new Sander9JobPanel(); + JButton jButton1 = new JButton(); + JButton jButton2 = new JButton(); + JButton jButton3 = new JButton(); + + public Amber9JobDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public Amber9JobDialog() { + this(new Frame(), "Amber9JobDialog", false); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + jButton1.setText("jButton1"); + jButton2.setText("jButton1"); + jButton3.setText("jButton1"); + getContentPane().add(panel1); + panel1.add(jPanel1, BorderLayout.SOUTH); + jPanel1.add(jButton3); + jPanel1.add(jButton2); + jPanel1.add(jButton1); + panel1.add(amber9JobPanel1, BorderLayout.CENTER); + } +} diff --git a/src/main/java/cct/amber/AmberApplet.java b/src/main/java/cct/amber/AmberApplet.java new file mode 100644 index 0000000..792f83c --- /dev/null +++ b/src/main/java/cct/amber/AmberApplet.java @@ -0,0 +1,107 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.amber; + +import java.applet.Applet; +import java.awt.BorderLayout; + +//import cct.amber.*; + +public class AmberApplet + extends Applet { + boolean isStandalone = false; + BorderLayout borderLayout1 = new BorderLayout(); + AmberSubmitDialog AmberSubmit; + //String var0; + + //Get a parameter value + public String getParameter(String key, String def) { + return isStandalone ? System.getProperty(key, def) : + (getParameter(key) != null ? getParameter(key) : def); + } + + //Construct the applet + public AmberApplet() { + } + + //Initialize the applet + @Override + public void init() { + /* + try { + var0 = this.getParameter("param0", ""); + } + catch (Exception e) { + e.printStackTrace(); + } + */ + try { + jbInit(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + //Component initialization + private void jbInit() throws Exception { + String actionURL; + actionURL = getParameter("actionURL"); + + AmberSubmit = new AmberSubmitDialog(this, "Submit Amber Job", actionURL); + AmberSubmit.setSize(600, 400); + AmberSubmit.setVisible(true); + + } + + //Get Applet information + @Override + public String getAppletInfo() { + return "Applet Information"; + } + + //Get parameter info + @Override + public String[][] getParameterInfo() { + String[][] pinfo = { + { + "param0", "String", ""}, + }; + return pinfo; + } +} diff --git a/src/main/java/cct/amber/AmberLib.java b/src/main/java/cct/amber/AmberLib.java new file mode 100644 index 0000000..526bd06 --- /dev/null +++ b/src/main/java/cct/amber/AmberLib.java @@ -0,0 +1,355 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2009 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.amber; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.StringReader; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; +import cct.interfaces.MoleculeInterface; +import cct.interfaces.MonomerInterface; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ + +enum LIB_ENTRY { + LOOKING_FOR_ENTRY, READ_INDEX, READING_UNIT_ATOMS, READING_UNIT_CONNECTIVITY, READING_UNIT_RESIDUES, READING_UNIT_POSITIONS +} + +public class AmberLib { + + private Set residues = new HashSet (); + private static final Map entries = new HashMap (); + private Map molecules = new LinkedHashMap (); + MoleculeInterface refMolec; + + static { + entries.put("!!index", LIB_ENTRY.READ_INDEX); + entries.put("unit.atoms", LIB_ENTRY.READING_UNIT_ATOMS); + entries.put("unit.connectivity", LIB_ENTRY.READING_UNIT_CONNECTIVITY); + entries.put("unit.residues", LIB_ENTRY.READING_UNIT_RESIDUES); + entries.put("unit.positions", LIB_ENTRY.READING_UNIT_POSITIONS); + } + + static final Logger logger = Logger.getLogger(AmberLib.class.getCanonicalName()); + + public AmberLib(MoleculeInterface ref) { + refMolec = ref; + } + + public int countMolecules() { + return molecules.size(); + } + + public Map getMolecules() { + Map mols = new LinkedHashMap (molecules); + return mols; + } + + public String[] getMoleculeNames() { + if (countMolecules() < 1) { + return null; + } + String[] mol_names = new String[molecules.size()]; + molecules.keySet().toArray(mol_names); + return mol_names; + } + + public MoleculeInterface getMolecule(String name) { + return molecules.get(name); + } + + public void parseLibFile(String filename, int fileType) throws Exception { + String line, token, current_residue_name = ""; + StringTokenizer st; + LIB_ENTRY progress = LIB_ENTRY.LOOKING_FOR_ENTRY; + double[] xyz = new double[3]; + + BufferedReader in = null; + + if (fileType == 0) { // Read from file + try { + in = new BufferedReader(new FileReader(filename)); + } + catch (java.io.FileNotFoundException e) { + throw new Exception("Error opening file " + filename + ": " + e.getMessage()); + } + } + else if (fileType == 1) { // Read from String + in = new BufferedReader(new StringReader(filename)); + } + else { + throw new Exception("Implementation error: unknown file type"); + } + + while ( (line = in.readLine()) != null) { + line = line.trim(); + if (line.length() < 1) { + continue; + } + + if (line.startsWith("!!index")) { + progress = LIB_ENTRY.READ_INDEX; + continue; + } + else if (line.startsWith("!entry")) { + token = line.substring(0, line.indexOf(" ")); // ERROR CHECK! + st = new StringTokenizer(token, "."); + if (st.countTokens() < 4) { + System.err.println("Reading " + token + " entry: expecting 4 tokens, got " + line + " Ignored..."); + progress = LIB_ENTRY.LOOKING_FOR_ENTRY; + continue; + } + + st.nextToken(); // Skip !entry + current_residue_name = st.nextToken(); + token = st.nextToken() + "." + st.nextToken(); + + progress = entries.get(token); + if (progress == null) { + progress = LIB_ENTRY.LOOKING_FOR_ENTRY; + } + } + + switch (progress) { + case LOOKING_FOR_ENTRY: + continue; + + case READ_INDEX: + st = new StringTokenizer(line, " \t\""); + if (!st.hasMoreTokens()) { + System.err.println("Error reading " + LIB_ENTRY.READ_INDEX.name() + " entry: expecting residue name, got " + line + + " Ignored..."); + } + else { + residues.add(st.nextToken()); + } + continue; + } + + MoleculeInterface mol = molecules.get(current_residue_name); + if (mol == null) { + mol = refMolec.getInstance(); + mol.setName(current_residue_name); + molecules.put(current_residue_name, mol); + logger.info("Created a molecule " + current_residue_name); + } + if (line.startsWith("!entry")) { + continue; + } + + switch (progress) { + case READING_UNIT_ATOMS: + st = new StringTokenizer(line, " \t\""); + if (st.countTokens() < 8) { + System.err.println("Reading " + LIB_ENTRY.READING_UNIT_ATOMS.name() + " entry: expecting 8 tokens, got " + line + + " Ignored..."); + continue; + } + AtomInterface atom = refMolec.getNewAtomInstance(); + atom.setName(st.nextToken()); + atom.setProperty(AtomInterface.NAME, atom.getName()); + atom.setProperty(AtomInterface.AMBER_NAME, st.nextToken()); + st.nextToken(); // skip int typex + token = st.nextToken(); + int resx = 0; + try { + resx = Integer.parseInt(token); + } + catch (Exception ex) { + System.err.println("Could not parse resx " + ex.getMessage() + ": Got " + line + " Ignored..."); + } + for (int i = mol.getNumberOfMonomers(); i < resx; i++) { + mol.addMonomer("UNK"); // Temporary name + } + + --resx; + atom.setSubstructureNumber(resx); + + token = st.nextToken(); + int flags = 0; + try { + flags = Integer.parseInt(token); + } + catch (Exception ex) { + System.err.println("Could not parse flags " + ex.getMessage() + ": Got " + line + " Ignored..."); + } + atom.setProperty(AmberUtilities.AmberAtomFlags, new Integer(flags)); + + st.nextToken(); // skip int sequence + + token = st.nextToken(); + int elmnt = 0; + try { + elmnt = Integer.parseInt(token); + } + catch (Exception ex) { + System.err.println("Could not parse elmnt " + ex.getMessage() + ": Got " + line + " Ignored..."); + } + if (elmnt < 0) { + elmnt = 0; + } + atom.setAtomicNumber(elmnt); + + token = st.nextToken(); + double chg = 0; + try { + chg = Double.parseDouble(token); + } + catch (Exception ex) { + System.err.println("Could not parse chg " + ex.getMessage() + ": Got " + line + " Ignored..."); + } + atom.setProperty(AtomInterface.ATOMIC_CHARGE, new Double(chg)); + mol.addAtom(atom); + break; + + case READING_UNIT_CONNECTIVITY: + st = new StringTokenizer(line, " \t"); + if (st.countTokens() < 2) { + System.err.println("Reading " + LIB_ENTRY.READING_UNIT_CONNECTIVITY.name() + + " entry: expecting at least 2 tokens, got " + line + + " Ignored..."); + break; + } + token = st.nextToken(); + int i_1 = 0, i_2 = 0; + try { + i_1 = Integer.parseInt(token) - 1; + } + catch (Exception ex) { + System.err.println("Could not parse i_1 for connectivity " + ex.getMessage() + ": Got " + line + " Ignored..."); + break; + } + token = st.nextToken(); + try { + i_2 = Integer.parseInt(token) - 1; + } + catch (Exception ex) { + System.err.println("Could not parse i_2 for connectivity " + ex.getMessage() + ": Got " + line + " Ignored..."); + break; + } + AtomInterface a1 = mol.getAtomInterface(i_1); + AtomInterface a2 = mol.getAtomInterface(i_2); + BondInterface bond = refMolec.getNewBondInstance(a1, a2); + mol.addBond(bond); + break; + + case READING_UNIT_RESIDUES: + int nres = mol.getNumberOfMonomers(); + for (int i = 0; i < nres; i++) { + if (i != 0) { + line = in.readLine(); + } + if (line == null) { + System.err.println("Unexpected end of file while reading unit residues for " + current_residue_name + " Ignored..."); + break; + } + st = new StringTokenizer(line, " \t\""); + if (st.countTokens() < 1) { + System.err.println("Reading " + LIB_ENTRY.READING_UNIT_RESIDUES.name() + " entry: expecting at least 1 token, got " + + line + " Ignored..."); + break; + } + String mname = st.nextToken(); + MonomerInterface monomer = mol.getMonomerInterface(i); + monomer.setName(mname); + } + + break; + + case READING_UNIT_POSITIONS: + + int nat = mol.getNumberOfAtoms(); + for (int i = 0; i < nat; i++) { + if (i != 0) { + line = in.readLine(); + } + if (line == null) { + System.err.println("Unexpected end of file while reading atom positions for " + current_residue_name + " Ignored..."); + break; + } + st = new StringTokenizer(line, " \t"); + if (st.countTokens() < 3) { + System.err.println("Reading " + LIB_ENTRY.READING_UNIT_POSITIONS.name() + " entry: expecting at least 3 token, got " + + line + " Ignored..."); + continue; + } + + for (int j = 0; j < 3; j++) { + token = st.nextToken(); + try { + xyz[j] = Double.parseDouble(token); + } + catch (Exception ex) { + System.err.println("Could not parse cartesian coordinate " + ex.getMessage() + ": Got " + line + " Ignored..."); + break; + } + } + + AtomInterface ac = mol.getAtomInterface(i); + ac.setXYZ( (float) xyz[0], (float) xyz[1], (float) xyz[2]); + } + break; + } + + } + } + + //public static void main(String[] args) { + // AmberLib amberlib = new AmberLib(); + //} +} diff --git a/src/main/java/cct/amber/AmberMden.java b/src/main/java/cct/amber/AmberMden.java new file mode 100644 index 0000000..d273c2e --- /dev/null +++ b/src/main/java/cct/amber/AmberMden.java @@ -0,0 +1,225 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.amber; + +import cct.interfaces.ChartDataProvider; +import cct.tools.DataSets; +import java.io.BufferedReader; +import java.io.FileReader; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * + * @author Vlad + */ +public class AmberMden extends DataSets implements ChartDataProvider { + + public void parseData(BufferedReader in) throws Exception { + String line; + int lineCount = 0; + // --- Reading in decriptors + String theFirstLine = "L0"; + List lines = new ArrayList(); + clearDescriptors(); + //descriptors.clear(); + clearData(); + int count = 0; + Map> descrRef = new LinkedHashMap>(); + + in.mark(132); + while ((line = in.readLine()) != null) { + ++lineCount; + String expectedLine = "L" + String.valueOf(count); + if (line.startsWith(expectedLine)) { + lines.add(expectedLine); + String[] tokens = line.substring(expectedLine.length()).trim().split("\\s+"); + List desc = new ArrayList(); + descrRef.put(expectedLine, desc); + for (int i = 0; i < tokens.length; i++) { + desc.add(tokens[i]); + if (hasDescriptor(tokens[i])) { + System.err.println("???: Warning descriptor " + tokens[i] + " occurs second time. Ignored..."); + } else { + this.addDescriptor(tokens[i]); + //descriptors.add(tokens[i]); + //List dt = new ArrayList(); + //data.put(tokens[i], dt); + } + } + + } // --- We finished to read in descriptors + else if (count != 0 && line.startsWith(theFirstLine)) { + in.reset(); + break; + } else { + + } + in.mark(200); + ++count; + } + + // --- Start to read data + boolean loopInProgress = true; + do { + for (String key : descrRef.keySet()) { + List desc = descrRef.get(key); + line = in.readLine(); + ++lineCount; + if (line == null) { + loopInProgress = false; + break; + } + String[] tokens = line.substring(key.length()).trim().split("\\s+"); + for (int i = 0; i < Math.min(tokens.length, desc.size()); i++) { + String label = desc.get(i); + if (label.equals("Nsteps")) { + try { + int num = Integer.parseInt(tokens[i]); + addData(label, num); + //data.get(label).add(num); + } catch (Exception ex) { + System.err.println("Cannot parse integer value for " + label + " in line: " + line); + } + } else { + try { + double dbl = Double.parseDouble(tokens[i]); + //data.get(label).add(dbl); + addData(label, dbl); + } catch (Exception ex) { + System.err.println("Cannot parse real value for " + label + " in line: " + line); + } + } + } + } + } while (loopInProgress); + + } + + public static void main(String[] args) { + AmberMden amberMden = new AmberMden(); + try { + amberMden.parseData("mden"); + System.out.println("Descriptors"); + for (String desc : amberMden.getDescriptors()) { + System.out.println(desc); + } + System.out.println("Data size: " + amberMden.getDataSize()); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public float isThisFormat(String filename) throws Exception { + + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(filename)); + } catch (Exception e) { + throw new Exception("Error opening file " + filename + " : " + e.getMessage()); + } + + float score = isThisFormat(in); + + try { + in.close(); + } catch (Exception ex) { + } + + return score; + } + + public float isThisFormat(BufferedReader in) throws Exception { + float score = 0; + String line; + + while ((line = in.readLine()) != null) { + + if (score >= 1.0) { + score = 1.0f; + return score; + } + + // --- MD info + if (line.contains("L0 Nsteps time(ps) Etot EKinetic")) { + score += 0.25; + line = in.readLine(); + if (line == null) { + return score; + } + if (line.contains("L1 Temp ")) { + score += 0.25; + } + line = in.readLine(); + if (line == null) { + return score; + } + if (line.contains("L2 ")) { + score += 0.25; + } + line = in.readLine(); + if (line == null) { + return score; + } + if (line.contains("L3 ")) { + score += 0.25; + } + if (score >= 0.5) { + return score; + } + } + // --- + if (score >= 1.0) { + score = 1.0f; + return score; + } + } + + return score; + } + + // --- Implementation of ChartDataProvider interface + public String cdpGetDescription() { + return "Amber mden file"; + } + + public void cdpParseData(String filename) throws Exception { + parseData(filename); + } + + public Set cdpGetDescriptors() { + return this.getDescriptors(); + } + + public double[] cdpGetDataAsDouble(String descriptor) { + return this.getDataAsDouble(descriptor); + } + + public float[] cdpGetDataAsFloat(String descriptor) { + return this.getDataAsFloat(descriptor); + } + + public int[] cdpGetDataAsInteger(String descriptor) { + return this.getDataAsInteger(descriptor); + } + + public String[] cdpGetDataAsString(String descriptor) { + return this.getDataAsString(descriptor); + } + + public Object[] cdpGetDataAsObject(String descriptor) { + return this.getDataAsObject(descriptor); + } + + public float cdpIsThisFormat(String filename) throws Exception { + return isThisFormat(filename); + } +} diff --git a/src/main/java/cct/amber/AmberMdout.java b/src/main/java/cct/amber/AmberMdout.java new file mode 100644 index 0000000..051f0f1 --- /dev/null +++ b/src/main/java/cct/amber/AmberMdout.java @@ -0,0 +1,526 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.amber; + +import cct.interfaces.AtomInterface; +import cct.interfaces.ChartDataProvider; +import cct.interfaces.MoleculeInterface; +import cct.modelling.ChemicalElements; +import cct.tools.DataSets; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; +import java.util.regex.Pattern; + +/** + * + * @author Vlad + */ +public class AmberMdout extends DataSets implements ChartDataProvider { + + enum STYPE { + + UNKNOWN, MIN, MD + } + static String MIN_PATTERN = "NSTEP ENERGY RMS GMAX NAME NUMBER"; + static String QMMM_PATTERN = " QMMM: QM_NO. MM_NO. ATOM"; + static String NMR_RESTR = "NMR restraints:"; + static Pattern mdPattern = Pattern.compile("\\s+NSTEP =\\s+\\d+\\s+TIME.+"); + static Pattern mdAveragesPattern = Pattern.compile("\\s+A V E R A G E S O V E R\\s*\\d+\\s+S T E P S.*"); + static Pattern mdRMSFPattern = Pattern.compile("\\s+R M S F L U C T U A T I O N S\\s*"); + + private int lineCount = 0; + private boolean debug = false; + private boolean minFinalResFound = false; + Map> descrRef = new LinkedHashMap>(); + static final Logger logger = Logger.getLogger(AmberMdout.class.getCanonicalName()); + + public void parseData(BufferedReader in) throws Exception { + STYPE stype = STYPE.UNKNOWN; + String line; + + lineCount = 0; + //Pattern minPattern = Pattern.compile("\\s+NSTEP\\s+ENERGY\\s+RMS\\s+"); + // --- Reading in decriptors + + List lines = new ArrayList(); + clearDescriptors(); //.clear(); + this.clearData(); //data.clear(); + int count = 0; + boolean mdAveragesFound = false; + boolean mdRMSFFound = false; + descrRef.clear(); + + in.mark(132); + while ((line = in.readLine()) != null) { + ++lineCount; + + switch (stype) { + case UNKNOWN: + if (line.indexOf(MIN_PATTERN) != -1) { + stype = STYPE.MIN; + String[] tokens = line.trim().split("\\s+"); + List desc = new ArrayList(); + descrRef.put(String.valueOf(descrRef.size()), desc); + for (int i = 0; i < tokens.length; i++) { + desc.add(tokens[i]); + if (this.hasDescriptor(tokens[i])) { //descriptors.contains(tokens[i] + System.err.println("???: Warning descriptor " + tokens[i] + " occurs second time. Ignored..."); + } else { + this.addDescriptor(tokens[i]); //descriptors.add(tokens[i]); + //List dt = new ArrayList(); + //this.addData(tokens[i], dt); //data.put(tokens[i], dt); + } + } + parseMinRecords(in); + } else if (mdPattern.matcher(line).matches()) { + stype = STYPE.MD; + parseMDRecords(in, line); + } + break; + // --- Minimization + case MIN: + if ((line.contains("FINAL RESULTS"))) { + minFinalResFound = true; + continue; + } + // + if ((line.indexOf(MIN_PATTERN) == -1)) { + continue; + } + parseMinRecords(in); + break; + // --- MD + case MD: + if (mdAveragesPattern.matcher(line).matches()) { + mdAveragesFound = true; + continue; + } else if (mdRMSFPattern.matcher(line).matches()) { + mdRMSFFound = true; + continue; + } + // --- + if (!mdPattern.matcher(line).matches()) { + continue; + } + + if (mdAveragesFound) { + mdAveragesFound = false; + continue; + } else if (mdRMSFFound) { + mdRMSFFound = false; + continue; + } + parseMDRecords(in, line); + break; + } + } + + if (debug) { + this.printDataSets(); + } + } + + protected void parseMDRecords(BufferedReader in, String line) throws Exception { + boolean thefirsttime = true; + while (true) { + if (thefirsttime) { + thefirsttime = false; + } else { + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected eof while parsing MD data"); + } + } + if (line.indexOf("----------------------") != -1) { + return; + } + // --- + + List terms; + if (line.startsWith(" Ewald error estimate:")) { + terms = new ArrayList(); + terms.add("Ewald error estimate"); + terms.add(line.substring(line.indexOf(":") + 1).trim()); + } else { + terms = getTokens(line); + } + + for (int i = 0; i < terms.size(); i += 2) { + this.addDescriptor(terms.get(i)); //descriptors.add(terms.get(i)); + if (i + 1 >= terms.size()) { + throw new Exception("Unexpected eof while parsing MD data"); + } + // --- + if (terms.get(i).equals("NSTEP")) { + try { + int num = Integer.parseInt(terms.get(i + 1)); + //if (!data.containsKey(terms.get(i))) { + // List dt = new ArrayList(); + // data.put(terms.get(i), dt); + //} + this.addData(terms.get(i), num); //data.get(terms.get(i)).add(num); + } catch (Exception ex) { + System.err.println("Cannot parse real value for " + terms.get(i) + " in line: " + line); + } + } else { + try { + double dbl = Double.parseDouble(terms.get(i + 1)); + //if (!data.containsKey(terms.get(i))) { + // List dt = new ArrayList(); + // data.put(terms.get(i), dt); + //} + this.addData(terms.get(i), dbl); //data.get(terms.get(i)).add(dbl); + } catch (Exception ex) { + System.err.println("Cannot parse real value for " + terms.get(i) + " in line: " + line); + } + } + } + } + } + + protected void parseMinRecords(BufferedReader in) throws Exception { + String line = null; + +// --- Read the first line + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected eof while parsing optimization data"); + } + ++lineCount; + // --- Reading the first line + List desc = descrRef.get("0"); + if (desc == null) { + desc = new ArrayList(); + descrRef.put("0", desc); + } + String[] tokens = line.trim().split("\\s+"); + for (int i = 0; i < Math.min(tokens.length, desc.size()); i++) { + String label = desc.get(i); + if (label.equals("NSTEP") || label.equals("NUMBER")) { + try { + int num = Integer.parseInt(tokens[i]); + if (minFinalResFound && label.equals("NSTEP")) { + minFinalResFound = false; + Integer prevStep = this.getLastDataAsInteger(label); + if (prevStep != null && prevStep == num) { + return; // Skip reading in this step + } + } + this.addData(label, num); //data.get(label).add(num); + } catch (Exception ex) { + System.err.println("Cannot parse integer value for " + label + " in line: " + lineCount); + } + } else if (label.equals("NAME")) { + this.addData(label, tokens[i]); //data.get(label).add(tokens[i]); + } else { + try { + double dbl = Double.parseDouble(tokens[i]); + this.addData(label, dbl); //data.get(label).add(dbl); + } catch (Exception ex) { + System.err.println("Cannot parse real value for " + label + " in line: " + lineCount); + } + } + } + // --- Skipping the second line + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected eof while parsing optimization data"); + } + // --- Reading next lines + while ((line = in.readLine()) != null) { + line = line.trim(); + if (line.length() == 0 || line.contains("============")) { + return; + } + + if (line.startsWith(NMR_RESTR)) { + line = line.substring(NMR_RESTR.length()); + } + + List terms = getTokens(line); + + //line = line.replaceAll("=", ""); + //tokens = line.split("\\s+"); + for (int i = 0; i < terms.size(); i += 2) { + //this.addDescriptor(terms.get(i)); // descriptors.add(terms.get(i)); + if (i + 1 >= terms.size()) { + throw new Exception("Unexpected eof while parsing optimization data"); + } + try { + double dbl = Double.parseDouble(terms.get(i + 1)); + //if (!data.containsKey(terms.get(i))) { + // List dt = new ArrayList(); + // data.put(terms.get(i), dt); + //} + this.addData(terms.get(i), dbl); //data.get(terms.get(i)).add(dbl); + } catch (Exception ex) { + System.err.println("Cannot parse real value for " + terms.get(i) + " in line: " + line); + } + } + } + if (line == null) { + throw new Exception("Unexpected eof while parsing optimization data"); + } + } + + public List getTokens(String line) { + List terms = new ArrayList(); + String[] tokens = line.split("="); + for (int i = 0; i < tokens.length; i++) { + if (i == 0) { + terms.add(tokens[0].trim()); + continue; + } else if (i + 1 == tokens.length) { + terms.add(tokens[i].trim()); + continue; + } + tokens[i] = tokens[i].trim(); + terms.add(tokens[i].substring(0, tokens[i].indexOf(" "))); + terms.add(tokens[i].substring(tokens[i].indexOf(" ")).trim()); + } + return terms; + } + + public static void main(String[] args) { + AmberMdout amberMden = new AmberMdout(); + try { + amberMden.parseData("01_min.out"); + System.out.println("Descriptors"); + for (String desc : amberMden.getDescriptors()) { + System.out.println(desc); + } + System.out.println("Data size: " + amberMden.getDataSize()); + // --- + amberMden.parseData("02_heat.out"); + System.out.println("Descriptors"); + for (String desc : amberMden.getDescriptors()) { + System.out.println(desc); + } + System.out.println("Data size: " + amberMden.getDataSize()); + // --- + amberMden.parseData("03_equil.out"); + System.out.println("Descriptors"); + for (String desc : amberMden.getDescriptors()) { + System.out.println(desc); + } + System.out.println("Data size: " + amberMden.getDataSize()); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public float isThisFormat(String filename) throws Exception { + + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(filename)); + } catch (Exception e) { + throw new Exception("Error opening file " + filename + " : " + e.getMessage()); + } + + float score = isThisFormat(in); + + try { + in.close(); + } catch (Exception ex) { + } + + return score; + } + + public float isThisFormat(BufferedReader in) throws Exception { + float score = 0; + String line; + + while ((line = in.readLine()) != null) { + + if (score >= 1.0) { + score = 1.0f; + return score; + } + + // --- MD info + if (line.contains(" NSTEP =") && line.contains("TIME(PS) =") && line.contains("TEMP(K) =")) { + score += 0.25; + line = in.readLine(); + if (line == null) { + return score; + } + if (line.contains(" Etot =") && line.contains("EKtot =") && line.contains("EPtot =")) { + score += 0.25; + } + line = in.readLine(); + if (line == null) { + return score; + } + if (line.contains(" BOND =") && line.contains("ANGLE =") && line.contains("DIHED =")) { + score += 0.25; + } + line = in.readLine(); + if (line == null) { + return score; + } + if (line.contains(" 1-4 NB =") && line.contains("1-4 EEL =") && line.contains("VDWAALS =")) { + score += 0.25; + } + if (score >= 0.5) { + return score; + } + } + // ---- minimization info + if (line.contains("NSTEP ENERGY") && line.contains("RMS GMAX") && line.contains("NAME NUMBER")) { + score += 0.25; + line = in.readLine(); + if (line == null) { + return score; + } + + if (line.split("\\s").length == 6) { + score += 0.25; + } + line = in.readLine(); + if (line == null) { + return score; + } + if (line.trim().length() == 0) { + score += 0.25; + } + line = in.readLine(); + if (line == null) { + return score; + } + if (line.contains("BOND =") && line.contains("ANGLE =") && line.contains("DIHED =")) { + score += 0.25; + } + if (score >= 0.5) { + return score; + } + } + // --- + if (score >= 1.0) { + score = 1.0f; + return score; + } + } + + return score; + } + + public MoleculeInterface extractQMMMAtoms(MoleculeInterface mol, String filename) throws Exception { + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(filename)); + } catch (Exception e) { + throw new Exception("Error opening Amber prmtop file " + filename + " : " + e.getMessage()); + } + try { + return extractQMMMAtoms(mol, in); + } catch (Exception e) { + throw new Exception("Error while extracting QM/MM atoms from mdout file " + filename + " : " + e.getMessage()); + } + } + + public MoleculeInterface extractQMMMAtoms(MoleculeInterface mol, BufferedReader in) throws Exception { + + int nlines, count, k; + String line; + AtomInterface atom = null; + boolean qmmm_found = false; + + // --- Statrting to read + String[] tokens = null; + + while ((line = in.readLine()) != null) { + // --- Looking for line starting with %FLAG + if (line.startsWith(QMMM_PATTERN)) { + qmmm_found = true; + break; + } + } + + if (!qmmm_found) { + throw new Exception("Didn't find QM/MM atoms"); + } + + // ----------- + while ((line = in.readLine()) != null) { + if (!line.startsWith(" QMMM:")) { + break; + } + // QMMM: 1 1 C -0.0686 1.5103 -0.2115 + + tokens = line.substring(22).trim().split("\\s+"); + if (tokens.length < 4) { + throw new Exception("Error parsing line: " + line); + } + atom = mol.getNewAtomInstance(); + atom.setName(tokens[0]); + atom.setAtomicNumber(ChemicalElements.getAtomicNumber(tokens[0])); + atom.setAtomicMass(ChemicalElements.getAtomicNumber(tokens[0])); + try { + double xyz = Double.parseDouble(tokens[1]); + atom.setX(xyz); + xyz = Double.parseDouble(tokens[2]); + atom.setY(xyz); + xyz = Double.parseDouble(tokens[3]); + atom.setZ(xyz); + } catch (Exception ex) { + throw new Exception("Error parsing Cartesian cooridnates in line " + line + " : " + ex.getMessage()); + } + + mol.addAtom(atom); + } + + return mol; + } + + // --- Implementation of ChartDataProvider interface + public String cdpGetDescription() { + return "Amber mdout file"; + } + + public void cdpParseData(String filename) throws Exception { + parseData(filename); + } + + public Set cdpGetDescriptors() { + return this.getDescriptors(); + } + + public double[] cdpGetDataAsDouble(String descriptor) { + return this.getDataAsDouble(descriptor); + } + + public float[] cdpGetDataAsFloat(String descriptor) { + return this.getDataAsFloat(descriptor); + } + + public int[] cdpGetDataAsInteger(String descriptor) { + return this.getDataAsInteger(descriptor); + } + + public String[] cdpGetDataAsString(String descriptor) { + return this.getDataAsString(descriptor); + } + + public Object[] cdpGetDataAsObject(String descriptor) { + return this.getDataAsObject(descriptor); + } + + public float cdpIsThisFormat(String filename) throws Exception { + + return isThisFormat(filename); + + } +} diff --git a/src/main/java/cct/amber/AmberPrep.java b/src/main/java/cct/amber/AmberPrep.java new file mode 100644 index 0000000..afd10dd --- /dev/null +++ b/src/main/java/cct/amber/AmberPrep.java @@ -0,0 +1,582 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.amber; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.StringTokenizer; + +import cct.Constants; +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.vecmath.VecmathTools; +import cct.vecmath.Point3f; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class AmberPrep { + + private int IDBGEN = 0; // Flag for data base generation + // = 0 No database generation. Output will be individual files. + // This is the standard procedure if you want to create a + // single small molecule. + // = 1 A new data base will be generated or the existing database + // will be appended. + private int IREST = 0; //Flag for the type of generation (assuming IDBGEN = 1) + // = 0 New data base + // = 1 Appending an existing data base + private int ITYPF = 2; // Force field type code (used in LINK stage) + /* + * Ignored if IDBGEN = 0 The following codes are used in the standard database: = 1 United atom model = 2 All atom model = 100 + * United atom charged N-terminal amino acid residues = 101 United atom charged C-terminal amino acid residues = 200 All atom + * charged N-terminal amino acid residues = 201 All atom charged C-terminal amino acid residues + * + * Note: This variable allows you to have several different models for the same residue name stored in one database. These models + * could differ in topology, charge, or other factors. The charged terminal residues are selected internally by LINK if the IFTPRO + * flag is set. The database can hold up to 510 residues. + */ + private String NAMDBF = "No name"; // Name of the data base file (maximum 80 characters) + private String TITLE = "No name"; // Descriptive header for the residue + private String NAMF = ""; // Name of the output file if an individual residue file is + // being generated. If database is being generated or + // appended this card IS read but ignored. + private String NAMRES = "UNK"; // A unique name for the residue of maximum 4 characters + private String INTX; // Flag for the type of coordinates to be saved for the LINK module + // 'INT' internal coordinates will be output (preferable) + // 'XYZ' cartesian coordinates will be output + private int KFORM = 0; // Format of output for individual residue files + // = 0 formatted output (recommended for debugging) + // = 1 binary output + private String IFIXC = "CORRECT"; // Flag for the type of input geometry of the residue(s) + // 'CORRECT' The geometry is input as internal coordinates with + // correct order according to the tree structure. + // NOTE: the tree structure types ('M', 'S', etc) and order + // must be defined correctly: NA(I), NB(I), and NC(I) on card + // 8 are always ignored. + // 'CHANGE' It is input as cartesian coordinates or part cartesian + // and part internal. Cartesians should precede internals + // to ensure that the resulting coordinates are correct. + // Coordinates need not be in correct order, since each + // is labeled with its atom number. NOTE: NA(I), NB(I), and + // NC(I) on card 8 must be omitted for cartesian coordinates + // with this option. + private String IOMIT = "OMIT"; // Flag for the omission of dummy atoms + // 'OMIT' dummy atoms will be deleted after generating all the + // information (this is used for all but the first residue + // in the system) + // 'NOMIT' they will not be deleted (dummy atoms are retained for + // the first residue of the system. others are omitted) + private String ISYMDU = "DU"; // Symbol for the dummy atoms. The symbol must be + // be unique. It is preferable to use 'DU' for it + private String IPOS = "BEG"; // Flag for the position of dummy atoms to be deleted + // 'ALL' all the dummy atoms will be deleted + // 'BEG' only the beginning dummy atoms will be deleted + private double CUT = 0; // The cutoff distance for loop closing bonds which + // cannot be defined by the tree structure. Any pair of + // atoms within this distance is assumed to be bonded. + // We recommend that CUT be set to 0.0 and explicit loop + // closing bonds be defined below. + private List atoms = new ArrayList(10); + private List loops = new ArrayList(5); + private List impropers = new ArrayList(10); + private List charges = new ArrayList(10); + + public AmberPrep() { + } + + public void getMolecularInterface(MoleculeInterface molec) throws Exception { + if (molec == null) { + throw new Exception(this.getClass().getCanonicalName() + " : Internal Error: molec == null"); + } + if (atoms.size() < 1) { + throw new Exception(this.getClass().getCanonicalName() + " : didn't find atoms in file"); + } + + molec.addMonomer(NAMRES); + + int start = 0; + boolean omit_all_dummies = false; + if (IPOS.equals("BEG")) { + start = 3; + } else if (IPOS.equals("ALL")) { + omit_all_dummies = true; + } + for (int i = start; i < atoms.size(); i++) { + AmberPrepAtom at = atoms.get(i); + if (omit_all_dummies && at.ISYMBL.equals("ISYMDU")) { + continue; + } + AtomInterface atom = molec.getNewAtomInstance(); + atom.setName(at.IGRAPH); + atom.setAtomicNumber(AmberUtilities.getElement(at.ISYMBL)); + atom.setXYZ(at.getX(), at.getY(), at.getZ()); + atom.setProperty(AtomInterface.ATOMIC_CHARGE, new Double(at.CHRG)); + atom.setProperty(AtomInterface.AMBER_NAME, at.ISYMBL); + atom.setProperty(AtomInterface.NAME, at.IGRAPH); + + molec.addAtom(atom); + } + } + + public static void main(String[] args) { + AmberPrep amberprep = new AmberPrep(); + } + + public void parsePrepFile(String filename, int fileType) throws Exception { + String line, token; + StringTokenizer st; + + BufferedReader in = null; + + if (fileType == 0) { // Read from file + try { + in = new BufferedReader(new FileReader(filename)); + } catch (java.io.FileNotFoundException e) { + throw new Exception("Error opening file " + filename + ": " + e.getMessage()); + } + } else if (fileType == 1) { // Read from String + in = new BufferedReader(new StringReader(filename)); + } else { + throw new Exception("Implementation error: unknown file type"); + } + + // read IDBGEN , IREST , ITYPF in FORMAT(3I) + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected end-of-file while reading the first line"); + } + + st = new StringTokenizer(line, " \t"); + + if (st.hasMoreTokens()) { + try { + IDBGEN = Integer.parseInt(st.nextToken()); + } catch (Exception ex) { + System.err.println("Cannot parse value for IDBGEN: " + ex.getMessage() + " Ignored..."); + } + if (IDBGEN != 0 && IDBGEN != 1) { + System.err.println("IDBGEN = " + IDBGEN + " Should be either 0 or 1. Ignored..."); + } + } + + if (st.hasMoreTokens()) { + try { + IREST = Integer.parseInt(st.nextToken()); + } catch (Exception ex) { + System.err.println("Cannot parse value for IREST: " + ex.getMessage() + " Ignored..."); + } + if (IREST != 0 && IREST != 1) { + System.err.println("IREST = " + IREST + " Should be either 0 or 1. Ignored..."); + } + } + + if (st.hasMoreTokens()) { + try { + ITYPF = Integer.parseInt(st.nextToken()); + } catch (Exception ex) { + System.err.println("Cannot parse value for ITYPF: " + ex.getMessage() + " Ignored..."); + } + if (ITYPF != 1 && ITYPF != 2 && ITYPF != 100 && ITYPF != 101 && ITYPF != 200 && ITYPF != 201) { + System.err.println("ITYPF = " + ITYPF + " Should be 1, 2, 100, 101, 200 or 201. Ignored..."); + } + } + + // --- read in NAMDBF + + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected end-of-file while reading the second line"); + } + NAMDBF = line.substring(0, Math.min(line.length(), 80)); + + // --- read in TITLE + + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected end-of-file while reading the third line (title)"); + } + TITLE = line.substring(0, Math.min(line.length(), 80)); + + // --- read in NAMF - FORMAT(A80 + + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected end-of-file while reading the forth line (NAMF)"); + } + NAMF = line.substring(0, Math.min(line.length(), 80)); + + // --- Reading NAMRES , INTX , KFORM - FORMAT(2A,I) + + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected end-of-file while reading the fifth line"); + } + st = new StringTokenizer(line, " \t"); + + if (st.hasMoreTokens()) { + token = st.nextToken(); + NAMRES = token.substring(0, Math.min(token.length(), 4)); + } + + if (st.hasMoreTokens()) { + INTX = st.nextToken().toUpperCase(); + if ((!INTX.startsWith("INT")) && (!INTX.startsWith("XYZ"))) { + throw new Exception("Unknown coordinate format: " + INTX + " Should be INT or XYZ"); + } + } + + if (st.hasMoreTokens()) { + try { + KFORM = Integer.parseInt(st.nextToken()); + } catch (Exception ex) { + System.err.println("Cannot parse value for KFORM: " + ex.getMessage() + " Ignored..."); + } + if (KFORM != 0 && KFORM != 1) { + System.err.println("KFORM = " + KFORM + " Should be 0 or 1. Ignored..."); + } + } + + // --- Reading IFIXC , IOMIT , ISYMDU , IPOS - FORMAT(4A) + + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected end-of-file while reading the sixth line"); + } + st = new StringTokenizer(line, " \t"); + + if (st.hasMoreTokens()) { + IFIXC = st.nextToken().toUpperCase(); + if ((!IFIXC.startsWith("CORRECT")) && (!IFIXC.startsWith("CHANGE"))) { + throw new Exception("Unknown Flag for the type of input geometry: " + IFIXC + " Should be CORRECT or CHANGE"); + } + } + + if (st.hasMoreTokens()) { + IOMIT = st.nextToken().toUpperCase(); + if ((!IOMIT.startsWith("OMIT")) && (!IOMIT.startsWith("NOMIT"))) { + throw new Exception("Unknown Flag for the omission of dummy atoms: " + IOMIT + " Should be OMIT or NOMIT"); + } + } + + if (st.hasMoreTokens()) { + ISYMDU = st.nextToken().toUpperCase(); + } + + if (st.hasMoreTokens()) { + IPOS = st.nextToken().toUpperCase(); + if ((!IPOS.startsWith("ALL")) && (!IPOS.startsWith("BEG"))) { + throw new Exception("Unknown Flag for the position of dummy atoms to be deleted: " + IPOS + "Should be ALL or BEG"); + } + } + + // --- Reading cutoff - FORMAT(F) + + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected end-of-file while reading the seventh line"); + } + st = new StringTokenizer(line, " \t"); + if (st.hasMoreTokens()) { + try { + CUT = Double.parseDouble(st.nextToken()); + } catch (Exception ex) { + System.err.println("Cannot parse value for CUT: " + ex.getMessage() + " Ignored..."); + } + if (CUT < 0) { + System.err.println("CUT Should be >= 0. Ignored..."); + } + } + + // --- Reading atoms - FORMAT(I,3A,3I,4F) + + while ((line = in.readLine()) != null) { + st = new StringTokenizer(line, " \t"); + if (!st.hasMoreTokens()) { + break; // End of input + } + + if (st.countTokens() < 11) { + System.err.println("Expected at least 11 tokens while reading atoms. Got: " + line); + break; + } + + AmberPrepAtom atom = new AmberPrepAtom(); + token = st.nextToken(); + + try { + atom.I = Integer.parseInt(token); + } catch (Exception ex) { + System.err.println("Cannot parse value for The actual number of the atom in the tree: " + ex.getMessage() + ": " + token + + " Ignored..."); + } + + // A unique atom name for the atom I + + token = st.nextToken(); + atom.IGRAPH = token.substring(0, Math.min(token.length(), 4)).trim(); + + // --- A symbol for the atom I which defines its force field atom type + + token = st.nextToken(); + atom.ISYMBL = token.substring(0, Math.min(token.length(), 4)); + + // --- The topological type (tree symbol) for atom I (M, S, B, E, or 3) + + token = st.nextToken(); + atom.ITREE = token; + + // --- The atom number to which atom I is connected. + + token = st.nextToken(); + try { + atom.NA = Integer.parseInt(token) - 1; + } catch (Exception ex) { + System.err.println("Cannot parse value for The atom number to which atom I is connected.: " + ex.getMessage() + ": " + + token); + break; + } + + // --- The atom number to which atom I makes an angle along with NA(I) + + token = st.nextToken(); + try { + atom.NB = Integer.parseInt(token) - 1; + } catch (Exception ex) { + System.err.println("Cannot parse value for The atom number to which atom I makes an angle along with NA: " + ex.getMessage() + + ": " + token); + break; + } + + // --- The atom number to which atom I makes a dihedral along with NA and NB + + token = st.nextToken(); + try { + atom.NC = Integer.parseInt(token) - 1; + } catch (Exception ex) { + System.err.println("Cannot parse value for The atom number to which atom I makes a dihedral along with NA and NB: " + + ex.getMessage() + ": " + token); + break; + } + + // --- Read R + + token = st.nextToken(); + try { + atom.R = Double.parseDouble(token); + } catch (Exception ex) { + System.err.println("Cannot parse value for R: " + ex.getMessage() + ": " + token); + break; + } + + // --- Read THETA + + token = st.nextToken(); + try { + atom.THETA = Double.parseDouble(token) * Constants.DEGREES_TO_RADIANS; + } catch (Exception ex) { + System.err.println("Cannot parse value for THETA: " + ex.getMessage() + ": " + token); + break; + } + + // --- Read PHI + + token = st.nextToken(); + try { + atom.PHI = Double.parseDouble(token) * Constants.DEGREES_TO_RADIANS; + } catch (Exception ex) { + System.err.println("Cannot parse value for PHI: " + ex.getMessage() + ": " + token); + break; + } + + // --- Read charge + + token = st.nextToken(); + try { + atom.CHRG = Double.parseDouble(token); + } catch (Exception ex) { + System.err.println("Cannot parse value for charge: " + ex.getMessage() + ": " + token + " Ignored..."); + } + + atoms.add(atom); + } + + if (atoms.size() < 4) { + throw new Exception("Should be at least 4 atoms in file. Got " + atoms.size()); + } + + if (line == null) { + System.err.println("End-of-file is reached. File could be truncated. Ignored..."); + } + + // --- Reading information about improper torsions, loop and so on... + + while ((line = in.readLine()) != null) { + if (line.trim().length() < 1) { + continue; + } + token = line.toUpperCase(); + if (token.equals("DONE") || token.equals("STOP")) { + break; + } + + if (token.equals("LOOP")) { + while ((line = in.readLine()) != null) { + st = new StringTokenizer(line, " \t"); + if (st.countTokens() < 1) { + break; + } + if (st.countTokens() < 2) { + System.err.println("Expected at least two tokens while reading LOOP info. Got " + line); + } + String[] loopA = new String[2]; + loopA[0] = st.nextToken(); + loopA[1] = st.nextToken(); + loops.add(loopA); + } + } else if (token.equals("CHARGE")) { + } else if (token.equals("IMPROPER")) { + while ((line = in.readLine()) != null) { + st = new StringTokenizer(line, " \t"); + if (st.countTokens() < 1) { + break; + } + if (st.countTokens() < 4) { + System.err.println("Expected at least 4 tokens while reading IMPROPER section. Got " + line); + } + String[] impr = new String[4]; + impr[0] = st.nextToken(); + impr[1] = st.nextToken(); + impr[2] = st.nextToken(); + impr[3] = st.nextToken(); + impropers.add(impr); + } + } + } + + // --- resolving coordinates, etc. + + // --- Check uniqueness of atom names + + Set anames = new HashSet(atoms.size() - 3); + for (int i = 3; i < atoms.size(); i++) { + AmberPrepAtom atom = atoms.get(i); + if (anames.contains(atom.IGRAPH)) { + System.err.println("Atom name " + atom.IGRAPH + " is not unique"); + } else { + anames.add(atom.IGRAPH); + } + } + + // --- Resolve cartesian coordinates + + AmberPrepAtom a1 = null, a2 = null, a3 = null; + for (int i = 0; i < atoms.size(); i++) { + AmberPrepAtom atom = atoms.get(i); + switch (i) { + case 0: + a1 = a2 = a3 = null; + break; + case 1: + a1 = atoms.get(atom.NA); + break; + case 2: + a1 = atoms.get(atom.NA); + a2 = atoms.get(atom.NB); + break; + default: + a1 = atoms.get(atom.NA); + a2 = atoms.get(atom.NB); + a3 = atoms.get(atom.NC); + } + VecmathTools.fromInternalToCartesians(atom, atom.R, atom.THETA, atom.PHI, a1, a2, a3); + } + + } +} + +class AmberPrepAtom + extends Point3f { + + int I; // The actual number of the atom in the tree. + String IGRAPH; // A unique atom name for the atom I. If coordinates are + // read in at the EDIT stage, this name will be used for + // matching atoms. Maximum 4 characters. + String ISYMBL; // A symbol for the atom I which defines its force field + // atom type and is used in the module PARM for assigning + // the force field parameters. + String ITREE; // The topological type (tree symbol) for atom I + // (M, S, B, E, or 3) + int NA; // The atom number to which atom I is connected. + // Read but ignored for internal coordinates; If cartesian + // coordinates are used, this must be omitted. + int NB; // The atom number to which atom I makes an angle along + // with NA(I). + // Read but ignored for internal coordinates; If cartesian + // coordinates are used, this must be omitted. + int NC; // The atom number to which atom I makes a dihedral along + // with NA(I) and NB(I). + // Read but ignored for internal coordinates; If cartesian + // coordinates are used, this must be omitted. + double R; // If IFIXC .eq. 'CORRECT' then this is the bond length + // between atoms I and NA(I) + // If IFIXC .eq. 'CHANGE' then this is the X coordinate + // of atom I + double THETA; // If IFIXC .eq. 'CORRECT' then it is the bond angle + // between atom NB(I), NA(I) and I + // If IFIXC .eq. 'CHANGE' then it is the Y coordinate of + // atom I + double PHI; // If IFIXC .eq. 'CORRECT' then it is the dihedral angle + // between NC(I), NB(I), NA(I) and I + // If IFIXC .eq. 'CHANGE' then it is the Z coordinate of + // atom I + double CHRG; // The partial atomic charge on atom I +} diff --git a/src/main/java/cct/amber/AmberPrmtop.java b/src/main/java/cct/amber/AmberPrmtop.java new file mode 100644 index 0000000..67ccf44 --- /dev/null +++ b/src/main/java/cct/amber/AmberPrmtop.java @@ -0,0 +1,2432 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.amber; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.Molecule; +import cct.tools.Utils; +import static cct.tools.Utils.printMatrix; +import java.io.BufferedWriter; +import java.io.OutputStreamWriter; +import java.io.StringWriter; +import java.util.logging.Level; + +/** + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2006

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class AmberPrmtop { + + enum PRMTOP_FLAGS { + + POINTERS, ATOM_NAME, CHARGE, ATOMIC_NUMBER, MASS, ATOM_TYPE_INDEX, NUMBER_EXCLUDED_ATOMS, NONBONDED_PARM_INDEX, RESIDUE_LABEL, + RESIDUE_POINTER, BOND_FORCE_CONSTANT, BOND_EQUIL_VALUE, ANGLE_FORCE_CONSTANT, ANGLE_EQUIL_VALUE, DIHEDRAL_FORCE_CONSTANT, + DIHEDRAL_PERIODICITY, DIHEDRAL_PHASE, SCEE_SCALE_FACTOR, SCNB_SCALE_FACTOR, SOLTY, LENNARD_JONES_ACOEF, LENNARD_JONES_BCOEF, + BONDS_INC_HYDROGEN, BONDS_WITHOUT_HYDROGEN, ANGLES_INC_HYDROGEN, ANGLES_WITHOUT_HYDROGEN, DIHEDRALS_INC_HYDROGEN, + DIHEDRALS_WITHOUT_HYDROGEN, EXCLUDED_ATOMS_LIST, HBOND_ACOEF, HBOND_BCOEF, HBCUT, AMBER_ATOM_TYPE, TREE_CHAIN_CLASSIFICATION, + JOIN_ARRAY, IROTAT, SOLVENT_POINTERS, ATOMS_PER_MOLECULE, BOX_DIMENSIONS, RADIUS_SET, RADII, SCREEN, IPOL, TITLE, UNKNOWN + } + public static float CHARGES_TO_KCAL_AMBER = 18.2223f; + boolean Debug = true; + private int repeat, dl; + private int nat = 0, ntypes, nbonh, mbona, ntheth, mtheta, nphih, mphia, + nhparm, nparm, nnb, nres, nbona, ntheta, nphia, + numbnd, numang, nptra, natyp, nphb, ifpert, nbper, ngper, ndper, + mbper, mgper, mdper, ifbox, nmxrs, ifcap, numextra; + private double[][] Aij, Bij; + private double[] eps, rho; + static final Logger logger = Logger.getLogger(AmberPrmtop.class.getCanonicalName()); + + public AmberPrmtop() { + } + + public static void main(String[] args) { + AmberPrmtop amberprmtop = new AmberPrmtop(); + MoleculeInterface mol = new Molecule(); + try { + amberprmtop.parsePrmtop(mol, "/home/vvv900/Amber/Amber14_Benchmark_Suite/PME/FactorIX_production_NPT/prmtop"); + System.out.println("Numatoms: " + mol.getNumberOfAtoms()); + } catch (Exception ex) { + Logger.getLogger(AmberPrmtop.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public int getNumberOfAtoms() { + return nat; + } + + public void exit() { + System.gc(); + return; + } + + public MoleculeInterface parsePrmtop(MoleculeInterface mol, String filename) throws + Exception { + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(filename)); + } catch (Exception e) { + throw new Exception("Error opening Amber prmtop file " + filename + " : " + e.getMessage()); + } + return parsePrmtop(mol, in); + } + + public MoleculeInterface parsePrmtop(MoleculeInterface mol, BufferedReader in) throws + Exception { + + int nlines, count, k; + String line; + AtomInterface[] atoms = null; + int[] bonds = null; + + boolean new_format = false; + + if ((line = in.readLine()) == null) { + throw new Exception("Error parsing Amber prmtop file: unexpected end of file while reading the first line"); + } + + // --- Determining file format + if (Debug) { + logger.info(line); + } + + if (line.indexOf("%VERSION") != -1) { + new_format = true; + return parseNewPrmtop(mol, in); + } else { + new_format = false; + //throw new Exception( + // "Old Amber prmtop file format is not implemented yet"); + } + + // --- Set molecule name + if (Debug) { + logger.info("Molecule name: " + line); + } + if (line.trim().length() > 0) { + mol.setName(line.trim()); + } + + // --- Statrting to read + try { + + //line = in.readLine(); + //if (new_format) { + // line = in.readLine(); // %FORMAT(20a4) + //} + //line = in.readLine(); + // --- Read options + repeat = 12; + dl = 6; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + + int[] itemp = new int[31]; + + nlines = 31 % repeat > 0 ? 31 / repeat + 1 : 31 / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + k = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + int n = 31 - (count + 1) + 1 >= repeat ? repeat : 31 - (count + 1); + for (int j = 0; j < n; j++, k++, count++) { + //strncpy(buf, bufer + dl * j, dl); + //buf[dl] = 0x00; + //itemp[k] = atoi(buf); + try { + itemp[k] = Integer.parseInt(line.substring(dl * j, dl * j + dl).trim()); + } catch (Exception ex) { + throw new Exception(); + } + } + } + + nat = itemp[0]; + ntypes = itemp[1]; + nbonh = itemp[2]; + mbona = itemp[3]; + ntheth = itemp[4]; + mtheta = itemp[5]; + nphih = itemp[6]; + mphia = itemp[7]; + nhparm = itemp[8]; + nparm = itemp[9]; + nnb = itemp[10]; + nres = itemp[11]; + + nbona = itemp[12]; + ntheta = itemp[13]; + nphia = itemp[14]; + numbnd = itemp[15]; + numang = itemp[16]; + nptra = itemp[17]; + natyp = itemp[18]; + nphb = itemp[19]; + ifpert = itemp[20]; + nbper = itemp[21]; + ngper = itemp[22]; + ndper = itemp[23]; + + mbper = itemp[24]; + mgper = itemp[25]; + mdper = itemp[26]; + ifbox = itemp[27]; + nmxrs = itemp[28]; + ifcap = itemp[29]; + numextra = itemp[30]; + + if (logger.isLoggable(Level.INFO)) { + logger.info(String.format( + "\nnatom = %7d ntypes = %7d nbonh = %7d mbona = %7d" + + "\nntheth = %7d mtheta = %7d nphih = %7d mphia = %7d" + + "\nnhparm = %7d nparm = %7d nnb = %7d nres = %7d" + + "\nnbona = %7d ntheta = %7d nphia = %7d numbnd = %7d" + + "\nnumang = %7d nptra = %7d natyp = %7d nphb = %7d" + + "\nifbox = %7d nmxrs = %7d ifcap = %7d nextra = %7d", + nat, ntypes, nbonh, mbona, ntheth, mtheta, nphih, mphia, + nhparm, nparm, nnb, nres, nbona, ntheta, nphia, + numbnd, numang, nptra, natyp, nphb, ifpert, nbper, ngper, + ndper, + mbper, mgper, mdper, ifbox, nmxrs, ifcap, numextra)); + } + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "There are " + nat + " atoms in PARM file"); + } + + atoms = new AtomInterface[nat]; + for (int i = 0; i < nat; i++) { + atoms[i] = mol.getNewAtomInstance(); + } + + if (nbonh > 0 || nbona > 0) { + bonds = new int[nbonh > nbona ? 3 * nbonh : 3 * nbona]; + } + + // Read Amber atom types (default 20a4) + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Reading atoms types..."); + } + + repeat = 20; + dl = 4; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + + nlines = nat % repeat > 0 ? nat / repeat + 1 : nat / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + int n = nat - (count + 1) + 1 >= repeat ? repeat + : nat - (count + 1) + 1; + for (int j = 0; j < n; j++) { + atoms[count].setName(line.substring(j * dl, j * dl + dl). + trim()); + //strncpy(buf, bufer + j * dl, dl); + //atom[count].Set_Atom_Name(token); + ++count; + } + } + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Finished reading atoms types...\nReading atomic charges..."); + } + + // --- Read charges (default 5e16.8) + repeat = 5; + dl = 16; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nat % repeat > 0 ? nat / repeat + 1 : nat / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + int n = nat - (count + 1) + 1 >= repeat ? repeat : nat - (count + 1) + 1; + for (int j = 0; j < n; j++) { + try { + Float charge = Float.parseFloat(line.substring(dl * j, dl * j + dl).trim()); + charge /= CHARGES_TO_KCAL_AMBER; + atoms[count].setProperty(AtomInterface.ATOMIC_CHARGE, charge); + } catch (Exception ex) { + throw new Exception(); + } + + //strncpy(buf, bufer + j * dl, dl); + //buf[dl] = 0x00; + //atom[count].charge = atof(buf) / CHARGES_TO_KCAL_AMBER; + ++count; + } + } + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Finished reading atomic charges...\nReading atomic masses..."); + } + + // -- Read atomic masses using format ( default 5e16.8) + repeat = 5; + dl = 16; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nat % repeat > 0 ? nat / repeat + 1 : nat / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + int n = nat - (count + 1) + 1 >= repeat ? repeat : nat - (count + 1) + 1; + for (int j = 0; j < n; j++) { + //strncpy(buf, bufer + j * dl, dl); + try { + float mass = Float.parseFloat(line.substring(dl * j, dl * j + dl).trim()); + atoms[count].setAtomicMass(mass); + } catch (Exception ex) { + throw new Exception(); + } + ++count; + } + } + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Finished reading atomic masses...\nReading atom type indices..."); + } + + // -- Read atom type index using format ( default 12i6) + repeat = 12; + dl = 6; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nat % repeat > 0 ? nat / repeat + 1 : nat / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + Integer index; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + int n = nat - count >= repeat ? repeat : nat - count; + for (int j = 0; j < n; j++, count++) { + try { + index = Integer.parseInt(line.substring(dl * j, dl * j + dl).trim()) - 1; + atoms[count].setProperty(AtomInterface.AMBER_TYPE_INDEX, index); + } catch (Exception ex) { + throw new Exception(); + } + } + //strncpy(buf, bufer + j * dl, dl); + //buf[dl] = 0x00; + //atom[count].charge = atof(buf) / CHARGES_TO_KCAL_AMBER; + + + /* + * int n = nat - count + 1 >= repeat ? repeat : nat - count + 1; for (int j = 0; j < n; j++) { //strncpy(buf, bufer + j * + * dl, dl); buf[dl] = 0x00; atom[count].ambtype = atoi(buf) - 1; // goto to base 0 ++count; } + */ + } + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Finished reading atom type indices...\nReading excluded atoms..."); + } + + // -- Read excluded atoms using format ( default 12i6) + repeat = 12; + dl = 6; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nat % repeat > 0 ? nat / repeat + 1 : nat / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 1; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); // fget_line(bufer, 256, parm); + /* + * int n = natoms - count + 1 >= repeat ? repeat : natoms - count + 1; for (j = 0; j < n; j++) { strncpy(buf, bufer + j * + * dl, dl); buf[dl] = 0x00; //atom[count].ambtype = atoi( buf ); // TODO ++count; } + */ + } + + int nttyp = ntypes * (ntypes + 1) / 2; + int ntype = ntypes * ntypes; + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Finished reading excluded atoms...\nReading nonbonded parm indices..."); + } + + // -- Read nonboded parm index using format ( default 12i6) + repeat = 12; + dl = 6; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = ntype % repeat > 0 ? ntype / repeat + 1 : ntype / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 1; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); // fget_line(bufer, 256, parm); + /* + * int n = ntype - count + 1 >= repeat ? repeat : ntype - count + 1; for (j = 0; j < n; j++) { strncpy(buf, bufer + j * dl, + * dl); buf[dl] = 0x00; //atom[count].ambtype = atoi( buf ); // TODO ++count; } + */ + } + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Finished reading nonbonded parm indices...\nReading residue labels..."); + } + + // -- Read residue labels using format ( default 20a4) + repeat = 20; + dl = 4; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + + nlines = nres % repeat > 0 ? nres / repeat + 1 : nres / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 1; + k = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + int n = nres - count + 1 >= repeat ? repeat + : nres - count + 1; + for (int j = 0; j < n; j++, k++, count++) { + mol.addMonomer(line.substring(dl * j, + dl * j + dl).trim()); + //strncpy(buf, bufer + j * dl, dl); + } + } + + // -- Read residue pointers using format ( default 12i6) + repeat = 12; + dl = 6; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nres % repeat > 0 ? nres / repeat + 1 : nres / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 1; + k = 0; + int[] start = new int[nres]; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + int n = nres - count + 1 >= repeat ? repeat + : nres - count + 1; + for (int j = 0; j < n; j++, k++, count++) { + //strncpy(buf, bufer + j * dl, dl); + try { + start[count - 1] = Integer.parseInt(line.substring(dl * j, + dl * j + dl).trim()); + --start[count - 1]; + } catch (Exception ex) { + throw new Exception(); + } + } + } + + for (int i = 0; i < mol.getNumberOfMonomers(); i++) { + int begin = start[i]; + int end = i < mol.getNumberOfMonomers() - 1 ? start[i + 1] + : nat; + for (int j = begin; j < end; j++) { + mol.addAtom(atoms[j], i); + } + } + + // --- // %FLAG BOND_FORCE_CONSTANT + repeat = 5; + dl = 16; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = numbnd % repeat > 0 ? numbnd / repeat + 1 + : numbnd / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + // --- read BOND_EQUIL_VALUE + repeat = 5; + dl = 16; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = numbnd % repeat > 0 ? numbnd / repeat + 1 + : numbnd / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + // --- Read ANGLE_FORCE_CONSTANT + repeat = 5; + dl = 16; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = numang % repeat > 0 ? numang / repeat + 1 + : numang / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + // --- Read ANGLE_EQUIL_VALUE + repeat = 5; + dl = 16; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = numang % repeat > 0 ? numang / repeat + 1 + : numang / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + // --- Read DIHEDRAL_FORCE_CONSTANT + repeat = 5; + dl = 16; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nptra % repeat > 0 ? nptra / repeat + 1 + : nptra / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + // --- Read DIHEDRAL_PERIODICITY + repeat = 5; + dl = 16; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nptra % repeat > 0 ? nptra / repeat + 1 + : nptra / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + // --- Read DIHEDRAL_PHASE + repeat = 5; + dl = 16; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nptra % repeat > 0 ? nptra / repeat + 1 + : nptra / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + // --- Read SOLTY + repeat = 5; + dl = 16; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + + nlines = natyp % repeat > 0 ? natyp / repeat + 1 : natyp / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 1; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + /* + * int n = natyp - count + 1 >= repeat ? repeat : natyp - count + 1; for (j = 0; j < n; j++) { strncpy(buf, bufer + j * dl, + * dl); buf[dl] = 0x00; //atom[count].charge = atof( buf )/CHARGES_TO_KCAL_AMBER; ++count; } + */ + } + + // --- Read LENNARD_JONES_ACOEF + repeat = 5; + dl = 16; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nttyp % repeat > 0 ? nttyp / repeat + 1 + : nttyp / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + // --- Read LENNARD_JONES_BCOEF + repeat = 5; + dl = 16; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nttyp % repeat > 0 ? nttyp / repeat + 1 + : nttyp / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + // --- Reading BONDS_INC_HYDROGEN + repeat = 12; + dl = 6; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = (nbonh * 3) % repeat > 0 ? nbonh * 3 / repeat + 1 + : nbonh * 3 / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 1; + k = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + int n = nbonh * 3 - count + 1 >= repeat ? repeat + : nbonh * 3 - count + 1; + for (int j = 0; j < n; j++, k++, count++) { + //strncpy(buf, bufer + j * dl, dl); + try { + bonds[k] = Integer.parseInt(line.substring(dl * j, + dl * j + dl).trim()); + } catch (Exception ex) { + throw new Exception(); + } + //itemp[k] = atoi(buf); + } + } + + for (int i = 0; i < nbonh; i++) { + int origin = bonds[3 * i] / 3; // + 1; + int target = bonds[3 * i + 1] / 3; // + 1; + AtomInterface a_i = mol.getAtomInterface(origin); + AtomInterface a_j = mol.getAtomInterface(target); + BondInterface bond = mol.getNewBondInstance(a_i, a_j); + mol.addBond(bond); + + //inter12[i].i = bond[i + 1].origin; + //inter12[i].j = bond[i + 1].target; + //int ref = itemp[3 * i + 2] - 1; + //inter12[i].keq = ff.bondParTable[ref].fc; + //inter12[i].req = ff.bondParTable[ref].ebl; + } + + // --- Reading BONDS_WITHOUT_HYDROGEN + repeat = 12; + dl = 6; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = (nbona * 3) % repeat > 0 ? nbona * 3 / repeat + 1 + : nbona * 3 / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 1; + k = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + int n = 3 * nbona - count + 1 >= repeat ? repeat + : 3 * nbona - count + 1; + for (int j = 0; j < n; j++, k++, count++) { + //strncpy(buf, bufer + j * dl, dl); + try { + bonds[k] = Integer.parseInt(line.substring(dl * j, + dl * j + dl).trim()); + } catch (Exception ex) { + throw new Exception(); + } + //itemp[k] = atoi(buf); + } + } + + for (int i = 0; i < nbona; i++) { + //bond[i + 1].origin = itemp[3 * j] / 3 + 1; + //bond[i + 1].target = itemp[3 * j + 1] / 3 + 1; + + int origin = bonds[3 * i] / 3; // + 1; + int target = bonds[3 * i + 1] / 3; // + 1; + AtomInterface a_i = mol.getAtomInterface(origin); + AtomInterface a_j = mol.getAtomInterface(target); + BondInterface bond = mol.getNewBondInstance(a_i, a_j); + mol.addBond(bond); + + //inter12[i].i = bond[i + 1].origin; + //inter12[i].j = bond[i + 1].target; + //int ref = itemp[3 * j + 2] - 1; + //inter12[i].keq = ff.bondParTable[ref].fc; + //inter12[i].req = ff.bondParTable[ref].ebl; + } + + // --- Read ANGLES_INC_HYDROGEN + repeat = 12; + dl = 6; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = ntheth * 4 % repeat > 0 ? ntheth * 4 / repeat + 1 + : ntheth * 4 / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + // --- Read ANGLES_WITHOUT_HYDROGEN + repeat = 12; + dl = 6; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = mtheta * 4 % repeat > 0 ? mtheta * 4 / repeat + 1 + : mtheta * 4 / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + // --- Read DIHEDRALS_INC_HYDROGEN + repeat = 12; + dl = 6; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nphih * 5 % repeat > 0 ? nphih * 5 / repeat + 1 + : nphih * 5 / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + // --- Read DIHEDRALS_WITHOUT_HYDROGEN + repeat = 12; + dl = 6; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nphia * 5 % repeat > 0 ? nphia * 5 / repeat + 1 + : nphia * 5 / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + // --- Read EXCLUDED_ATOMS_LIST + repeat = 12; + dl = 6; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nnb % repeat > 0 ? nnb / repeat + 1 : nnb / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + // --- Read HBOND_ACOEF + repeat = 5; + dl = 16; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nphb % repeat > 0 ? nphb / repeat + 1 : nphb / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + // --- Read HBOND_BCOEF + repeat = 5; + dl = 16; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nphb % repeat > 0 ? nphb / repeat + 1 : nphb / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + // --- Read HBCUT + repeat = 5; + dl = 16; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nphb % repeat > 0 ? nphb / repeat + 1 : nphb / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + // --- Read AMBER_ATOM_TYPE + repeat = 20; + dl = 4; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nat % repeat > 0 ? nat / repeat + 1 : nat / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 1; + k = 0; + int element; + String aType; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + int n = nat - count + 1 >= repeat ? repeat : nat - count + 1; + for (int j = 0; j < n; j++, k++, count++) { + //strncpy(buf, bufer + dl * j, dl); + //buf[dl] = 0x00; + //atom[count].Set_Amber_Name( buf ); + //atom[count].Set_Amber_Name(strtok(buf, " ")); + aType = line.substring(dl * j, dl * j + dl).trim(); + atoms[count - 1].setProperty(AtomInterface.AMBER_NAME, aType); + element = AmberUtilities.getElement(aType); + atoms[count - 1].setAtomicNumber(element); + } + } + + // --- Read TREE_CHAIN_CLASSIFICATION + repeat = 20; + dl = 4; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nat % repeat > 0 ? nat / repeat + 1 : nat / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + // --- Read JOIN_ARRAY + repeat = 12; + dl = 6; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nat % repeat > 0 ? nat / repeat + 1 : nat / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + // --- Read IROTAT + repeat = 12; + dl = 6; + if (new_format) { + line = in.readLine(); + line = in.readLine(); // %FORMAT( + parseFormat(line); + } + nlines = nat % repeat > 0 ? nat / repeat + 1 : nat / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); //fget_line(bufer, 256, parm); + } + + } catch (Exception e) { + throw new Exception("Error parsing Amber prmtop file: " + e.getMessage()); + } + + return mol; + } + + /** + * This subroutine parses only a NEW prmtop format + * + * @param mol + * @param filename + * @return + * @throws Exception + */ + public MoleculeInterface parseNewPrmtop(MoleculeInterface mol, String filename) throws Exception { + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(filename)); + } catch (Exception e) { + throw new Exception("Error opening Amber prmtop file " + filename + " : " + e.getMessage()); + } + try { + return parseNewPrmtop(mol, in); + } catch (IOException e) { + throw new Exception("Error parsing Amber prmtop file " + filename + " : " + e.getMessage()); + } + } + + /** + * This subroutine parses only a NEW prmtop format + * + * @param mol + * @param filename + * @return + * @throws Exception + */ + public MoleculeInterface parseNewPrmtop(MoleculeInterface mol, BufferedReader in) throws Exception { + + int nlines, count, k; + String line; + AtomInterface[] atoms = null; + int[] bonds = null; + int nttyp = 0; + double[] nbTemp = null; + boolean new_format = false; + boolean atomicNumbersAlreadyRead = false; + + // --- Statrting to read + String[] tokens = null; + + try { + + while ((line = in.readLine()) != null) { + // --- Looking for line starting with %FLAG + if (!line.startsWith("%FLAG ")) { + continue; + } + // Decide what kind of flag... + + tokens = line.trim().split("\\s+"); + + if (tokens.length < 2) { + logger.severe("%FLAG does not have the second parameter! Ignoring..."); + continue; + } + + PRMTOP_FLAGS flag = PRMTOP_FLAGS.UNKNOWN; + + tokens[1] = tokens[1].toUpperCase(); + try { + flag = PRMTOP_FLAGS.valueOf(tokens[1]); + } catch (Exception ex) { + logger.severe("Uknown %FLAG \"" + tokens[1] + "\"! Ignoring..."); + continue; + } + + // --- Reading format... + line = in.readLine(); + if (line == null) { + throw new Exception("Got EOF while expecting a %FORMAT line for flag " + tokens[1]); + } else if (!line.startsWith("%FORMAT")) { + throw new Exception("Expected a %FORMAT line for flag " + tokens[1] + ". Got \"" + line + "\""); + } + + parseFormat(line); + + try { + switch (flag) { + case TITLE: + // --- Read molecule name + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected EOF while reading Molecule name (TITLE section)"); + } + if (logger.isLoggable(Level.INFO)) { + logger.info("Molecule name: " + line); + } + mol.setName(line.trim()); + break; + + case POINTERS: + // --- Read options + + int[] itemp = new int[31]; + + nlines = 31 % repeat > 0 ? 31 / repeat + 1 : 31 / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + k = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected EOF while reading POINTERS section"); + } + int n = 31 - (count + 1) + 1 >= repeat ? repeat : 31 - (count + 1) + 1; + for (int j = 0; j < n; j++, k++, count++) { + + try { + itemp[k] = Integer.parseInt(line.substring(dl * j, dl * j + dl).trim()); + } catch (Exception ex) { + throw new Exception("Error parsing POINTERS section: line: " + line + " : " + ex.getMessage()); + } + } + } + + nat = itemp[0]; + ntypes = itemp[1]; + nbonh = itemp[2]; + mbona = itemp[3]; + ntheth = itemp[4]; + mtheta = itemp[5]; + nphih = itemp[6]; + mphia = itemp[7]; + nhparm = itemp[8]; + nparm = itemp[9]; + nnb = itemp[10]; + nres = itemp[11]; + + nbona = itemp[12]; + ntheta = itemp[13]; + nphia = itemp[14]; + numbnd = itemp[15]; + numang = itemp[16]; + nptra = itemp[17]; + natyp = itemp[18]; + nphb = itemp[19]; + ifpert = itemp[20]; + nbper = itemp[21]; + ngper = itemp[22]; + ndper = itemp[23]; + + mbper = itemp[24]; + mgper = itemp[25]; + mdper = itemp[26]; + ifbox = itemp[27]; + nmxrs = itemp[28]; + ifcap = itemp[29]; + numextra = itemp[30]; + + if (logger.isLoggable(Level.INFO)) { + logger.info(String.format( + "\nnatom = %7d ntypes = %7d nbonh = %7d mbona = %7d" + + "\nntheth = %7d mtheta = %7d nphih = %7d mphia = %7d" + + "\nnhparm = %7d nparm = %7d nnb = %7d nres = %7d" + + "\nnbona = %7d ntheta = %7d nphia = %7d numbnd = %7d" + + "\nnumang = %7d nptra = %7d natyp = %7d nphb = %7d" + + "\nifbox = %7d nmxrs = %7d ifcap = %7d nextra = %7d", + nat, ntypes, nbonh, mbona, ntheth, mtheta, nphih, mphia, + nhparm, nparm, nnb, nres, nbona, ntheta, nphia, + numbnd, numang, nptra, natyp, nphb, ifpert, nbper, ngper, + ndper, + mbper, mgper, mdper, ifbox, nmxrs, ifcap, numextra)); + } + + nttyp = ntypes * (ntypes + 1) / 2; + Aij = new double[ntypes][ntypes]; + Bij = new double[ntypes][ntypes]; + eps = new double[ntypes]; + rho = new double[ntypes]; + nbTemp = new double[nttyp]; + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "There are " + nat + " atoms in PARM file"); + } + + atoms = new AtomInterface[nat]; + for (int i = 0; i < nat; i++) { + atoms[i] = mol.getNewAtomInstance(); + } + + if (nbonh > 0 || nbona > 0) { + bonds = new int[nbonh > nbona ? 3 * nbonh : 3 * nbona]; + } + break; + + case ATOM_NAME: + // Read Amber atom types (default 20a4) + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Reading atoms types..."); + } + + nlines = nat % repeat > 0 ? nat / repeat + 1 : nat / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected EOF while reading " + tokens[1] + " section"); + } + int n = nat - (count + 1) + 1 >= repeat ? repeat : nat - (count + 1) + 1; + for (int j = 0; j < n; j++) { + atoms[count].setName(line.substring(j * dl, j * dl + dl).trim()); + ++count; + } + } + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Finished reading atoms types..."); + } + + break; + + case CHARGE: + // --- Read charges (default 5e16.8) + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Started reading atomic charges..."); + } + + nlines = nat % repeat > 0 ? nat / repeat + 1 : nat / repeat; + if (nlines == 0) { + nlines = 1; + } + float total_charge = 0; + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected EOF while reading " + tokens[1] + " section"); + } + int n = nat - (count + 1) + 1 >= repeat ? repeat : nat - (count + 1) + 1; + for (int j = 0; j < n; j++) { + try { + Float charge = Float.parseFloat(line.substring(dl * j, dl * j + dl).trim()); + charge /= CHARGES_TO_KCAL_AMBER; + total_charge += charge; + atoms[count].setProperty(AtomInterface.ATOMIC_CHARGE, charge); + } catch (Exception ex) { + throw new Exception("Error parsing charge in line: " + line + " : " + ex.getMessage()); + } + ++count; + } + } + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Finished reading atomic charges..."); + logger.log(Level.INFO, "Total charge: " + String.valueOf(total_charge)); + } + break; + + //************************************************************************ + case ATOMIC_NUMBER: + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Started reading atomic numbers..."); + } + + nlines = nat % repeat > 0 ? nat / repeat + 1 : nat / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected EOF while reading " + tokens[1] + " section"); + } + int n = nat - (count + 1) + 1 >= repeat ? repeat : nat - (count + 1) + 1; + for (int j = 0; j < n; j++) { + try { + Integer atNumber = Integer.parseInt(line.substring(dl * j, dl * j + dl).trim()); + atoms[count].setAtomicNumber(atNumber); + } catch (Exception ex) { + throw new Exception("Error parsing atomic number in line: " + line + " : " + ex.getMessage()); + } + ++count; + } + } + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Finished reading atomic numbers..."); + } + + atomicNumbersAlreadyRead = true; + break; + + //************************************************************************ + case MASS: + // -- Read atomic masses using format ( default 5e16.8) + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Reading atomic masses..."); + } + + nlines = nat % repeat > 0 ? nat / repeat + 1 : nat / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected EOF while reading " + tokens[1] + " section"); + } + int n = nat - (count + 1) + 1 >= repeat ? repeat : nat - (count + 1) + 1; + for (int j = 0; j < n; j++) { + try { + float mass = Float.parseFloat(line.substring(dl * j, dl * j + dl).trim()); + atoms[count].setAtomicMass(mass); + } catch (Exception ex) { + throw new Exception("Error parsing atomic mass in line: " + line + " : " + ex.getMessage()); + } + ++count; + } + } + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Finished reading atomic masses..."); + } + break; + + case ATOM_TYPE_INDEX: + // -- Read atom type index using format ( default 12i6) + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Reading atom type indices..."); + } + + nlines = nat % repeat > 0 ? nat / repeat + 1 : nat / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 1; + Integer index; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected EOF while reading " + tokens[1] + " section"); + } + int n = nat - count + 1 >= repeat ? repeat : nat - count + 1; + for (int j = 0; j < n; j++, count++) { + try { + index = Integer.parseInt(line.substring(dl * j, dl * j + dl).trim()) - 1; + if (index < 0 || index > ntypes - 1) { + logger.severe("ATOM TYPE INDEX for atom " + count + " = " + (index + 1) + " Should be in 1-" + ntypes + " range"); + } + atoms[count - 1].setProperty(AtomInterface.AMBER_TYPE_INDEX, index); + } catch (Exception ex) { + throw new Exception("Error parsing atom index in line: " + line + " : " + ex.getMessage()); + } + } + } + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Finished reading atom type indices..."); + } + break; + + //case NUMBER_EXCLUDED_ATOMS: + // -- Read excluded atoms using format ( default 12i6) + //nlines = nat % repeat > 0 ? nat / repeat + 1 : nat / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 1; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //int nttyp = ntypes * (ntypes + 1) / 2; + //int ntype = ntypes * ntypes; + //if (logger.isLoggable(Level.INFO)) { + // logger.log(Level.INFO, "Finished reading excluded atoms...\nReading nonbonded parm indices..."); + //} + //break; + //case NONBONDED_PARM_INDEX: + // -- Read nonboded parm index using format ( default 12i6) + //nlines = ntype % repeat > 0 ? ntype / repeat + 1 : ntype / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 1; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //if (logger.isLoggable(Level.INFO)) { + // logger.log(Level.INFO, "Finished reading nonbonded parm indices...\nReading residue labels..."); + //} + //break; + case RESIDUE_LABEL: + // -- Read residue labels using format ( default 20a4) + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Reading residue labels..."); + } + + nlines = nres % repeat > 0 ? nres / repeat + 1 : nres / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 1; + k = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected EOF while reading " + tokens[1] + " section"); + } + int n = nres - count + 1 >= repeat ? repeat : nres - count + 1; + for (int j = 0; j < n; j++, k++, count++) { + mol.addMonomer(line.substring(dl * j, dl * j + dl).trim()); + } + } + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Finished reading residue labels..."); + } + break; + + //****************************************************** + case RESIDUE_POINTER: + // -- Read residue pointers using format ( default 12i6) + + nlines = nres % repeat > 0 ? nres / repeat + 1 : nres / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 1; + k = 0; + int[] start = new int[nres]; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected EOF while reading " + tokens[1] + " section"); + } + int n = nres - count + 1 >= repeat ? repeat : nres - count + 1; + for (int j = 0; j < n; j++, k++, count++) { + try { + start[k] = Integer.parseInt(line.substring(dl * j, dl * j + dl).trim()); + --start[k]; + } catch (Exception ex) { + throw new Exception("Error parsing residue pointer in line: " + line + " : " + ex.getMessage()); + } + } + } + + for (int i = 0; i < mol.getNumberOfMonomers(); i++) { + int begin = start[i]; + int end = i < mol.getNumberOfMonomers() - 1 ? start[i + 1] : nat; + for (int j = begin; j < end; j++) { + mol.addAtom(atoms[j], i); + } + } + break; + + //************************************************* + //case BOND_FORCE_CONSTANT: + // --- // %FLAG BOND_FORCE_CONSTANT + //nlines = numbnd % repeat > 0 ? numbnd / repeat + 1 : numbnd / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 0; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //break; + //***************************************************** + //case BOND_EQUIL_VALUE: + // --- read BOND_EQUIL_VALUE + //nlines = numbnd % repeat > 0 ? numbnd / repeat + 1 : numbnd / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 0; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //break; + //************************************************ + //case ANGLE_FORCE_CONSTANT: + // --- Read ANGLE_FORCE_CONSTANT + //nlines = numang % repeat > 0 ? numang / repeat + 1 : numang / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 0; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //break; + //************************************************ + //case ANGLE_EQUIL_VALUE: + // --- Read ANGLE_EQUIL_VALUE + //nlines = numang % repeat > 0 ? numang / repeat + 1 : numang / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 0; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //break; + //******************************************** + //case DIHEDRAL_FORCE_CONSTANT: + // --- Read DIHEDRAL_FORCE_CONSTANT + //nlines = nptra % repeat > 0 ? nptra / repeat + 1 : nptra / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 0; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //break; + //********************************************* + //case DIHEDRAL_PERIODICITY: + // --- Read DIHEDRAL_PERIODICITY + //nlines = nptra % repeat > 0 ? nptra / repeat + 1 : nptra / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 0; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //break; + //************************************************ + //case DIHEDRAL_PHASE: + // --- Read DIHEDRAL_PHASE + //nlines = nptra % repeat > 0 ? nptra / repeat + 1 : nptra / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 0; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //break; + //************************************** + //case SOLTY: + // --- Read SOLTY + //nlines = natyp % repeat > 0 ? natyp / repeat + 1 : natyp / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 1; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //break; + //***************************************************** + case LENNARD_JONES_ACOEF: + // --- Read LENNARD_JONES_ACOEF + + nlines = nttyp % repeat > 0 ? nttyp / repeat + 1 : nttyp / repeat; + if (nlines == 0) { + nlines = 1; + } + + k = 0; + count = 1; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); + // ************** + int n = nttyp - count + 1 >= repeat ? repeat : nttyp - count + 1; + for (int j = 0; j < n; j++, count++, k++) { + try { + String temp = line.substring(dl * j, dl * j + dl).trim(); + nbTemp[k] = Double.parseDouble(temp); + } catch (Exception ex) { + //throw new Exception("Error parsing LJ A Coeff in line: " + line + " : " + ex.getMessage()); + logger.severe("Error parsing LJ A Coeff in line: " + line + " : " + ex.getMessage()); + } + } + } + System.out.println("Aij"); + Utils.printVector(nbTemp); + try { + for (int i = 0; i < ntypes; i++) { + for (int j = 0; j <= i; j++) { + Aij[i][j] = nbTemp[i * (i + 1) / 2 + j]; + Aij[j][i] = Aij[i][j]; + } + } + } catch (Exception ex) { + logger.severe("Error while assigning Aij: " + ex.getMessage()); + } + + break; + //*************************************************** + case LENNARD_JONES_BCOEF: + // --- Read LENNARD_JONES_BCOEF + nlines = nttyp % repeat > 0 ? nttyp / repeat + 1 : nttyp / repeat; + if (nlines == 0) { + nlines = 1; + } + k = 0; + count = 1; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); + // ************** + int n = nttyp - count + 1 >= repeat ? repeat : nttyp - count + 1; + for (int j = 0; j < n; j++, count++, k++) { + try { + nbTemp[k] = Double.parseDouble(line.substring(dl * j, dl * j + dl).trim()); + } catch (Exception ex) { + //throw new Exception("Error parsing LJ A Coeff in line: " + line + " : " + ex.getMessage()); + logger.severe("Error parsing LJ B Coeff in line: " + line + " : " + ex.getMessage()); + } + } + } + + System.out.println("Bij"); + Utils.printVector(nbTemp); + + try { + for (int i = 0; i < ntypes; i++) { + for (int j = 0; j <= i; j++) { + Bij[i][j] = nbTemp[i * (i + 1) / 2 + j]; + Bij[j][i] = Bij[i][j]; + } + } + } catch (Exception ex) { + logger.severe("Error while assigning Bij: " + ex.getMessage()); + } + break; + //********************************************************* + case BONDS_INC_HYDROGEN: + // --- Reading BONDS_INC_HYDROGEN + + nlines = (nbonh * 3) % repeat > 0 ? nbonh * 3 / repeat + 1 : nbonh * 3 / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 1; + k = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected EOF while reading " + tokens[1] + " section"); + } + int n = nbonh * 3 - count + 1 >= repeat ? repeat : nbonh * 3 - count + 1; + for (int j = 0; j < n; j++, k++, count++) { + + try { + bonds[k] = Integer.parseInt(line.substring(dl * j, dl * j + dl).trim()); + } catch (Exception ex) { + throw new Exception(); + } + + } + } + + for (int i = 0; i < nbonh; i++) { + int origin = bonds[3 * i] / 3; // + 1; + int target = bonds[3 * i + 1] / 3; // + 1; + AtomInterface a_i = mol.getAtomInterface(origin); + AtomInterface a_j = mol.getAtomInterface(target); + BondInterface bond = mol.getNewBondInstance(a_i, a_j); + mol.addBond(bond); + } + break; + + //**************************************************** + case BONDS_WITHOUT_HYDROGEN: + // --- Reading BONDS_WITHOUT_HYDROGEN + nlines = (nbona * 3) % repeat > 0 ? nbona * 3 / repeat + 1 : nbona * 3 / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 1; + k = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected EOF while reading " + tokens[1] + " section"); + } + int n = 3 * nbona - count + 1 >= repeat ? repeat : 3 * nbona - count + 1; + for (int j = 0; j < n; j++, k++, count++) { + try { + bonds[k] = Integer.parseInt(line.substring(dl * j, dl * j + dl).trim()); + } catch (Exception ex) { + throw new Exception(); + } + } + } + + for (int i = 0; i < nbona; i++) { + int origin = bonds[3 * i] / 3; // + 1; + int target = bonds[3 * i + 1] / 3; // + 1; + AtomInterface a_i = mol.getAtomInterface(origin); + AtomInterface a_j = mol.getAtomInterface(target); + BondInterface bond = mol.getNewBondInstance(a_i, a_j); + mol.addBond(bond); + } + break; + + //*************************************************************** + //case ANGLES_INC_HYDROGEN: + // --- Read ANGLES_INC_HYDROGEN + //nlines = ntheth * 4 % repeat > 0 ? ntheth * 4 / repeat + 1 : ntheth * 4 / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 0; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //break; + //******************************************************************** + //case ANGLES_WITHOUT_HYDROGEN: + // --- Read ANGLES_WITHOUT_HYDROGEN + //nlines = mtheta * 4 % repeat > 0 ? mtheta * 4 / repeat + 1 : mtheta * 4 / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 0; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //break; + //******************************************************************** + //case DIHEDRALS_INC_HYDROGEN: + // --- Read DIHEDRALS_INC_HYDROGEN + //nlines = nphih * 5 % repeat > 0 ? nphih * 5 / repeat + 1 : nphih * 5 / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 0; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //break; + //********************************************************************* + //case DIHEDRALS_WITHOUT_HYDROGEN: + // --- Read DIHEDRALS_WITHOUT_HYDROGEN + //nlines = nphia * 5 % repeat > 0 ? nphia * 5 / repeat + 1 : nphia * 5 / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 0; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //break; + //*********************************************************************** + //case EXCLUDED_ATOMS_LIST: + // --- Read EXCLUDED_ATOMS_LIST + //nlines = nnb % repeat > 0 ? nnb / repeat + 1 : nnb / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 0; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //break; + //********************************************************************** + //case HBOND_ACOEF: + // --- Read HBOND_ACOEF + //nlines = nphb % repeat > 0 ? nphb / repeat + 1 : nphb / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 0; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //break; + //*********************************************************************** + //case HBOND_BCOEF: + // --- Read HBOND_BCOEF + //nlines = nphb % repeat > 0 ? nphb / repeat + 1 : nphb / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 0; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //break; + //************************************************************************ + //case HBCUT: + // --- Read HBCUT + //nlines = nphb % repeat > 0 ? nphb / repeat + 1 : nphb / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 0; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //break; + //*************************************************************************** + case AMBER_ATOM_TYPE: + // --- Read AMBER_ATOM_TYPE + + nlines = nat % repeat > 0 ? nat / repeat + 1 : nat / repeat; + if (nlines == 0) { + nlines = 1; + } + count = 1; + k = 0; + int element; + String aType; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected EOF while reading " + tokens[1] + " section"); + } + int n = nat - count + 1 >= repeat ? repeat : nat - count + 1; + for (int j = 0; j < n; j++, k++, count++) { + aType = line.substring(dl * j, dl * j + dl).trim(); + atoms[count - 1].setProperty(AtomInterface.AMBER_NAME, aType); + if (!atomicNumbersAlreadyRead) { + element = AmberUtilities.getElement(aType); + atoms[count - 1].setAtomicNumber(element); + } + } + } + break; + + //********************************************************************* + //case TREE_CHAIN_CLASSIFICATION: + // --- Read TREE_CHAIN_CLASSIFICATION + //nlines = nat % repeat > 0 ? nat / repeat + 1 : nat / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 0; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //break; + //************************************************************************* + //case JOIN_ARRAY: + // - -- Read JOIN_ARRAY + //nlines = nat % repeat > 0 ? nat / repeat + 1 : nat / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 0; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //break; + //************************************************************************** + //case IROTAT: + // --- Read IROTAT + //nlines = nat % repeat > 0 ? nat / repeat + 1 : nat / repeat; + //if (nlines == 0) { + // nlines = 1; + //} + //count = 0; + //for (int i = 0; i < nlines; i++) { + // line = in.readLine(); + //} + //break; + default: + if (logger.isLoggable(Level.WARNING)) { + logger.log(Level.WARNING, "Ignoring section " + tokens[1]); + } + break; + } + } catch (Exception ex) { + throw new Exception("Error parsing data for flag " + tokens[1] + ": " + ex.getMessage()); + } + + } + + } catch (Exception e) { + throw new Exception("Error parsing Amber prmtop file: " + e.getMessage()); + } + + // --- Post-processing + StringBuilder sb = new StringBuilder(); + + if (logger.isLoggable(Level.INFO)) { + sb.delete(0, sb.length()); + + StringWriter sw = new StringWriter(); + sw.append("\nAij\n"); + printMatrix(Aij, sw); + + sw.append("\nBij\n"); + printMatrix(Bij, sw); + sb.append(sw.toString()); + + sb.append("\nRho & Eps\n"); + } + try { + int ambtype = 0; + for (int i = 0; i < ntypes; i++) { + ambtype = -1; + if (Bij[i][i] == 0.0) { + rho[i] = 0.0; + eps[i] = 0.0; + } else { + rho[i] = 0.5 * Math.pow(2.0 * Aij[i][i] / Bij[i][i], 1.0 / 6.0); + eps[i] = Aij[i][i] / Math.pow(2.0 * rho[i], 12); + } + if (logger.isLoggable(Level.INFO)) { + sb.append(String.format("%3d: %8.4f %12.4f", i + 1, rho[i], eps[i])); + for (int j = 0; j < nat; j++) { + if (atoms[j].getProperty(AtomInterface.AMBER_TYPE_INDEX) != null) { + ambtype = ((Integer) atoms[j].getProperty(AtomInterface.AMBER_TYPE_INDEX)); + if (ambtype == i) { + sb.append(" " + atoms[j].getProperty(AtomInterface.AMBER_NAME) + "\n"); + break; + } + } + } + if (ambtype == -1) { + sb.append(" UNKNOWN\n"); + } + } + } + if (logger.isLoggable(Level.INFO)) { + logger.info(sb.toString()); + } + + } catch (Exception e) { + logger.severe("Error while deriving eps and/or rho: " + e.getMessage()); + } + + return mol; + } + + private void parseFormat(String format) throws Exception { + StringTokenizer st = new StringTokenizer(format, "()", false); + if (st.countTokens() < 2) { + throw new Exception("Cannot parse format string: " + format); + } + st.nextToken(); + String value = st.nextToken(); + + st = new StringTokenizer(value, "aAiIeEfF", false); + if (st.countTokens() == 1) { + repeat = 0; + } else { + try { + repeat = Integer.parseInt(st.nextToken()); + } catch (Exception ex) { + throw new Exception("Cannot parse repeat in format string: " + format); + } + } + + value = st.nextToken(); + if (value.contains(".")) { + value = value.substring(0, value.indexOf(".")); + } + try { + dl = Integer.parseInt(value); + } catch (Exception ex) { + throw new Exception("Cannot parse field length in format string: " + format); + } + + } + + /* + * int parse_format( char *format, int &rep, int &dl) { char *s = strdup(format); char *token = strtok( s, "()"); token = + * strtok(NULL,"()"); //printf("\n1st parse: %s",token); token = strtok( token, "aAiIeEfF"); rep = atoi( token ); dl = atoi( + * strtok(NULL," .")); //printf("\nRepeat: %d Length: %d",rep,dl); delete [] s; if ( dl <= 0 ) return 1; else return 0; } + */ + /* + * int Molecule Read_AMBER_PARM(const char * fname, FFParam & ff) { + * + * + * // Allocate parameter tables + * + * ff.nBondPar = numbnd; if (ff.bondParTable != NULL) { delete[] ff.bondParTable; } ff.bondParTable = new + * BondParameters[ff.nBondPar]; assert (ff.bondParTable); memset(ff.bondParTable, 0, sizeof(BondParameters) * ff.nBondPar); + * + * ff.nAnglePar = numang; if (ff.angleParTable != NULL) { delete[] ff.angleParTable; } ff.angleParTable = new + * AngleParameters[ff.nAnglePar]; assert (ff.angleParTable); + * + * ff.nTorsionPar = nptra; if (ff.torsionParTable != NULL) { delete[] ff.torsionParTable; } ff.torsionParTable = new + * TorsionParameters[ff.nTorsionPar]; assert (ff.torsionParTable); memset(ff.torsionParTable, 0, sizeof(TorsionParameters) * + * ff.nTorsionPar); + * + * //fmtin = rfmt //type = 'bond_force_constant' //call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) //read(nf,fmt) (rk(i), i = + * 1,numbnd) + * + * repeat = 5; dl = 16; if (new_format) { fget_line(bufer, 256, parm); // %FLAG BOND_FORCE_CONSTANT fget_line(bufer, 256, parm); + * // %FORMAT( if (parse_format(bufer, repeat, dl)) { //SimpleExit("Can't parse format",1); Log_to_GUI( "Read_AMBER_PARM: Cannot + * parse BOND_FORCE_CONSTANT format: %s\n", bufer); return -1; } } + * + * nlines = ff.nBondPar % repeat ? ff.nBondPar / repeat + 1 : ff.nBondPar / repeat; if (nlines == 0) { nlines = 1; } count = 1; + * for (i = 0; i < nlines; i++) { fget_line(bufer, 256, parm); int n = ff.nBondPar - count + 1 >= repeat ? repeat : ff.nBondPar - + * count + 1; for (j = 0; j < n; j++) { strncpy(buf, bufer + j * dl, dl); buf[dl] = 0x00; ff.bondParTable[count - 1].fc = 2.0 * + * atof(buf); // !!! Multiplied by 2 to be compatible with energy calc ++count; } } + * + * //fmtin = rfmt //type = 'bond_equil_value' //call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) //read(nf,fmt) (req(i), i = 1,numbnd + * + * repeat = 5; dl = 16; if (new_format) { fget_line(bufer, 256, parm); // %FLAG BOND_EQUIL_VALUE fget_line(bufer, 256, parm); // + * %FORMAT( if (parse_format(bufer, repeat, dl)) { //SimpleExit("Can't parse format",1); Log_to_GUI( "Read_AMBER_PARM: Cannot + * parse BOND_EQUIL_VALUE format: %s\n", bufer); return -1; } } + * + * nlines = ff.nBondPar % repeat ? ff.nBondPar / repeat + 1 : ff.nBondPar / repeat; if (nlines == 0) { nlines = 1; } count = 1; + * for (i = 0; i < nlines; i++) { fget_line(bufer, 256, parm); int n = ff.nBondPar - count + 1 >= repeat ? repeat : ff.nBondPar - + * count + 1; for (j = 0; j < n; j++) { strncpy(buf, bufer + j * dl, dl); buf[dl] = 0x00; ff.bondParTable[count - 1].ebl = + * atof(buf); ++count; } } + * + * //fmtin = rfmt //type = 'angle_force_constant' //call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) //read(nf,fmt) (tk(i), i = + * 1,numang) + * + * repeat = 5; dl = 16; if (new_format) { fget_line(bufer, 256, parm); // %FLAG ANGLE_FORCE_CONSTANT fget_line(bufer, 256, parm); + * // %FORMAT( if (parse_format(bufer, repeat, dl)) { //SimpleExit("Can't parse format",1); Log_to_GUI( "Read_AMBER_PARM: Cannot + * parse ANGLE_FORCE_CONSTANT format: %s\n", bufer); return -1; } } + * + * nlines = ff.nAnglePar % repeat ? ff.nAnglePar / repeat + 1 : ff.nAnglePar / repeat; if (nlines == 0) { nlines = 1; } count = 1; + * for (i = 0; i < nlines; i++) { fget_line(bufer, 256, parm); int n = ff.nAnglePar - count + 1 >= repeat ? repeat : ff.nAnglePar + * - count + 1; for (j = 0; j < n; j++) { strncpy(buf, bufer + j * dl, dl); buf[dl] = 0x00; ff.angleParTable[count - 1].fc = + * atof(buf) / Pow2(RAD2DEG) * 2.0; // !!! ++count; } } + * + * //fmtin = rfmt //type = 'angle_equil_value' //call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) //read(nf,fmt) (teq(i), i = + * 1,numang) + * + * repeat = 5; dl = 16; if (new_format) { fget_line(bufer, 256, parm); // %FLAG ANGLE_EQUIL_VALUE fget_line(bufer, 256, parm); // + * %FORMAT( if (parse_format(bufer, repeat, dl)) { //SimpleExit("Can't parse format",1); Log_to_GUI( "Read_AMBER_PARM: Cannot + * parse ANGLE_EQUIL_VALUE format: %s\n", bufer); return -1; } } + * + * nlines = ff.nAnglePar % repeat ? ff.nAnglePar / repeat + 1 : ff.nAnglePar / repeat; if (nlines == 0) { nlines = 1; } count = 1; + * for (i = 0; i < nlines; i++) { fget_line(bufer, 256, parm); int n = ff.nAnglePar - count + 1 >= repeat ? repeat : ff.nAnglePar + * - count + 1; for (j = 0; j < n; j++) { strncpy(buf, bufer + j * dl, dl); buf[dl] = 0x00; ff.angleParTable[count - 1].ebl = 180. + * / PI * atof(buf); // !!! Convert to degrees ++count; } } + * + * printf("\n\nAngle parameter table:\n"); for (i = 0; i < ff.nAnglePar; i++) { printf("\n%4d %8.3lf %8.3lf", i + 1, + * ff.angleParTable[i].ebl, ff.angleParTable[i].fc); } + * + * //fmtin = rfmt //type = 'dihedral_force_constant' //call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) //read(nf,fmt) (pk(i), i = + * 1,nptra) + * + * repeat = 5; dl = 16; if (new_format) { fget_line(bufer, 256, parm); // %FLAG DIHEDRAL_FORCE_CONSTANT fget_line(bufer, 256, + * parm); // %FORMAT( if (parse_format(bufer, repeat, dl)) { //SimpleExit("Can't parse format",1); Log_to_GUI( "Read_AMBER_PARM: + * Cannot parse DIHEDRAL_FORCE_CONSTANT format: %s\n", bufer); return -1; } } + * + * nlines = ff.nTorsionPar % repeat ? ff.nTorsionPar / repeat + 1 : ff.nTorsionPar / repeat; if (nlines == 0) { nlines = 1; } + * count = 1; for (i = 0; i < nlines; i++) { fget_line(bufer, 256, parm); int n = ff.nTorsionPar - count + 1 >= repeat ? repeat : + * ff.nTorsionPar - count + 1; for (j = 0; j < n; j++) { strncpy(buf, bufer + j * dl, dl); buf[dl] = 0x00; + * ff.torsionParTable[count - 1].npar = 1; ff.torsionParTable[count - 1].par[0].fc = 2.0 * atof(buf); // Mult by 2 to be + * compatible with us ++count; } } + * + * //fmtin = rfmt //type = 'dihedral_periodicity' //call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) //read(nf,fmt) (pn(i), i = + * 1,nptra) + * + * repeat = 5; dl = 16; if (new_format) { fget_line(bufer, 256, parm); // %FLAG DIHEDRAL_PERIODICITY fget_line(bufer, 256, parm); + * // %FORMAT( if (parse_format(bufer, repeat, dl)) { //SimpleExit("Can't parse format",1); Log_to_GUI( "Read_AMBER_PARM: Cannot + * parse DIHEDRAL_PERIODICITY format: %s\n", bufer); return -1; } } + * + * nlines = ff.nTorsionPar % repeat ? ff.nTorsionPar / repeat + 1 : ff.nTorsionPar / repeat; if (nlines == 0) { nlines = 1; } + * count = 1; for (i = 0; i < nlines; i++) { fget_line(bufer, 256, parm); int n = ff.nTorsionPar - count + 1 >= repeat ? repeat : + * ff.nTorsionPar - count + 1; for (j = 0; j < n; j++) { strncpy(buf, bufer + j * dl, dl); buf[dl] = 0x00; + * ff.torsionParTable[count - 1].par[0].per = atof(buf); ++count; } } + * + * //fmtin = rfmt //type = 'dihedral_phase' //call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) //read(nf,fmt) (phase(i), i = 1,nptra) + * + * repeat = 5; dl = 16; if (new_format) { fget_line(bufer, 256, parm); // %FLAG DIHEDRAL_PHASE fget_line(bufer, 256, parm); // + * %FORMAT( if (parse_format(bufer, repeat, dl)) { //SimpleExit("Can't parse format",1); Log_to_GUI( "Read_AMBER_PARM: Cannot + * parse DIHEDRAL_PHASE format: %s\n", bufer); return -1; } } + * + * nlines = ff.nTorsionPar % repeat ? ff.nTorsionPar / repeat + 1 : ff.nTorsionPar / repeat; if (nlines == 0) { nlines = 1; } + * count = 1; for (i = 0; i < nlines; i++) { fget_line(bufer, 256, parm); int n = ff.nTorsionPar - count + 1 >= repeat ? repeat : + * ff.nTorsionPar - count + 1; for (j = 0; j < n; j++) { strncpy(buf, bufer + j * dl, dl); buf[dl] = 0x00; + * ff.torsionParTable[count - 1].par[0].phase = atof(buf); ++count; } } + * + * printf("\n\nDihedral parameter table\n"); for (i = 0; i < ff.nTorsionPar; i++) { printf("\n%4d %8.3lf %8.3lf %8.3lf", i + 1, + * ff.torsionParTable[i].par[0].fc, ff.torsionParTable[i].par[0].per, ff.torsionParTable[i].par[0].phase); } //fmtin = rfmt //type + * = 'solty' //call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) //read(nf,fmt) (solty(i), i = 1,natyp) + * + * repeat = 5; dl = 16; if (new_format) { fget_line(bufer, 256, parm); // %FLAG SOLTY fget_line(bufer, 256, parm); // %FORMAT( if + * (parse_format(bufer, repeat, dl)) { //SimpleExit("Can't parse format",1); Log_to_GUI("Read_AMBER_PARM: Cannot parse SOLTY + * format: %s\n", bufer); return -1; } } + * + * nlines = natyp % repeat ? natyp / repeat + 1 : natyp / repeat; if (nlines == 0) { nlines = 1; } count = 1; for (i = 0; i < + * nlines; i++) { fget_line(bufer, 256, parm); int n = natyp - count + 1 >= repeat ? repeat : natyp - count + 1; for (j = 0; j < + * n; j++) { strncpy(buf, bufer + j * dl, dl); buf[dl] = 0x00; //atom[count].charge = atof( buf )/CHARGES_TO_KCAL_AMBER; ++count; + * } } + * + * // --- Allocate eps, rho, Aij & Bij + * + * ff.nAtypes = ntypes; + * + * if (ff.eps != NULL) { delete[] ff.eps; } ff.eps = new double[ntypes]; assert (ff.eps); if (ff.rho != NULL) { delete[] ff.rho; } + * ff.rho = new double[ntypes]; assert (ff.rho); + * + * ff.Allocate_Aij_and_Bij(ntypes); + * + * //fmtin = rfmt //type = 'lennard_jones_acoef' //call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) //read(nf,fmt) (cn1(i), i = + * 1,nttyp) + * + * if (rmax < nttyp) { rmax = nttyp; rtemp = (double * ) realloc(rtemp, sizeof(double) * nttyp); assert (rtemp); } + * + * repeat = 5; dl = 16; if (new_format) { fget_line(bufer, 256, parm); // %FLAG LENNARD_JONES_ACOEF fget_line(bufer, 256, parm); + * // %FORMAT( if (parse_format(bufer, repeat, dl)) { //SimpleExit("Can't parse format",1); Log_to_GUI( "Read_AMBER_PARM: Cannot + * parse LENNARD_JONES_ACOEF format: %s\n", bufer); return -1; } } + * + * nlines = nttyp % repeat ? nttyp / repeat + 1 : nttyp / repeat; if (nlines == 0) { nlines = 1; } count = 1; k = 0; for (i = 0; i + * < nlines; i++) { fget_line(bufer, 256, parm); int n = nttyp - count + 1 >= repeat ? repeat : nttyp - count + 1; for (j = 0; j < + * n; j++, k++, count++) { strncpy(buf, bufer + j * dl, dl); buf[dl] = 0x00; rtemp[k] = atof(buf); } } + * + * for (i = 0; i < ntypes; i++) { for (j = 0; j <= i; j++) { ff.Aij[i][j] = rtemp[i * (i + 1) / 2 + j]; ff.Aij[j][i] = + * ff.Aij[i][j]; } } + * + * //fmtin = rfmt //type = 'lennard_jones_bcoef' //call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) //read(nf,fmt) (cn2(i), i = + * 1,nttyp) + * + * repeat = 5; dl = 16; if (new_format) { fget_line(bufer, 256, parm); // %FLAG LENNARD_JONES_BCOEF fget_line(bufer, 256, parm); + * // %FORMAT( if (parse_format(bufer, repeat, dl)) { //SimpleExit("Can't parse format",1); Log_to_GUI( "Read_AMBER_PARM: Cannot + * parse LENNARD_JONES_BCOEF format: %s\n", bufer); return -1; } } + * + * nlines = nttyp % repeat ? nttyp / repeat + 1 : nttyp / repeat; if (nlines == 0) { nlines = 1; } count = 1; k = 0; for (i = 0; i + * < nlines; i++) { fget_line(bufer, 256, parm); int n = nttyp - count + 1 >= repeat ? repeat : nttyp - count + 1; for (j = 0; j < + * n; j++, k++, count++) { strncpy(buf, bufer + j * dl, dl); buf[dl] = 0x00; rtemp[k] = atof(buf); } } + * + * for (i = 0; i < ntypes; i++) { for (j = 0; j <= i; j++) { ff.Bij[i][j] = rtemp[i * (i + 1) / 2 + j]; ff.Bij[j][i] = + * ff.Bij[i][j]; } } + * + * // --- Allocate bonds + * + * nbonds = 0; if (bond != NULL) { delete[] bond; } bond = new Bond[nbonh + nbona + 1]; memset(bond, 0, (nbonh + nbona + 1) * + * sizeof(Bond)); //ReAlloc_Bonds( nbonh + nbona ); nbonds = nbonh + nbona; ninter12 = nbonds; if (inter12 != NULL) { delete[] + * inter12; } inter12 = new Inter12[ninter12]; assert (inter12); memset(inter12, 0, ninter12 * sizeof(Inter12)); + * + * //fmtin = ifmt //type = 'bonds_inc_hydrogen' //call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) //read(nf,fmt) + * (ix(i+i12-1),ix(i+i14-1),ix(i+i16-1), //$ i = 1,nbonh) + * + * if (imax < nbonh * 3) { imax = nbonh * 3; itemp = (int * ) realloc(itemp, sizeof(int) * imax); assert (itemp); } + * + * repeat = 12; dl = 6; if (new_format) { fget_line(bufer, 256, parm); // %FLAG BONDS_INC_HYDROGEN fget_line(bufer, 256, parm); // + * %FORMAT( if (parse_format(bufer, repeat, dl)) { //SimpleExit("Can't parse format",1); Log_to_GUI( "Read_AMBER_PARM: Cannot + * parse BONDS_INC_HYDROGEN format: %s\n", bufer); return -1; } } + * + * nlines = nbonh * 3 % repeat ? nbonh * 3 / repeat + 1 : nbonh * 3 / repeat; if (nlines == 0) { nlines = 1; } count = 1; k = 0; + * for (i = 0; i < nlines; i++) { fget_line(bufer, 256, parm); int n = nbonh * 3 - count + 1 >= repeat ? repeat : nbonh * 3 - + * count + 1; for (j = 0; j < n; j++, k++, count++) { strncpy(buf, bufer + j * dl, dl); buf[dl] = 0x00; itemp[k] = atoi(buf); } } + * + * for (i = 0; i < nbonh; i++) { bond[i + 1].origin = itemp[3 * i] / 3 + 1; inter12[i].i = bond[i + 1].origin; bond[i + 1].target + * = itemp[3 * i + 1] / 3 + 1; inter12[i].j = bond[i + 1].target; int ref = itemp[3 * i + 2] - 1; inter12[i].keq = + * ff.bondParTable[ref].fc; inter12[i].req = ff.bondParTable[ref].ebl; } //fmtin = ifmt //type = 'bonds_without_hydrogen' //call + * nxtsec(nf, 6, 0,fmtin, type, fmt, iok) //read(nf,fmt) (ix(i+i18-1),ix(i+i20-1),ix(i+i22-1),i = 1,nbona) + * + * if (imax < nbona * 3) { imax = nbona * 3; itemp = (int * ) realloc(itemp, sizeof(int) * imax); assert (itemp); } + * + * repeat = 12; dl = 6; if (new_format) { fget_line(bufer, 256, parm); // %FLAG BONDS_WITHOUT_HYDROGEN fget_line(bufer, 256, + * parm); // %FORMAT( if (parse_format(bufer, repeat, dl)) { //SimpleExit("Can't parse format",1); Log_to_GUI( "Read_AMBER_PARM: + * Cannot parse BONDS_WITHOUT_HYDROGEN format: %s\n", bufer); return -1; } } + * + * nlines = nbona * 3 % repeat ? nbona * 3 / repeat + 1 : nbona * 3 / repeat; if (nlines == 0) { nlines = 1; } int count_2 = nbonh + * + 1; count = 1; k = 0; for (i = 0; i < nlines; i++) { fget_line(bufer, 256, parm); int n = 3 * nbona - count + 1 >= repeat ? + * repeat : 3 * nbona - count + 1; for (j = 0; j < n; j++, k++, count++) { strncpy(buf, bufer + j * dl, dl); buf[dl] = 0x00; + * itemp[k] = atoi(buf); } } + * + * for (i = nbonh, j = 0; j < nbona; i++, j++) { bond[i + 1].origin = itemp[3 * j] / 3 + 1; inter12[i].i = bond[i + 1].origin; + * bond[i + 1].target = itemp[3 * j + 1] / 3 + 1; inter12[i].j = bond[i + 1].target; int ref = itemp[3 * j + 2] - 1; + * inter12[i].keq = ff.bondParTable[ref].fc; inter12[i].req = ff.bondParTable[ref].ebl; } + * + * int errors = 0; for (i = 1; i <= nbonds; i++) { if (bond[i].origin < 1 || bond[i].origin > natoms || bond[i].target < 1 || + * bond[i].target > natoms) { ++errors; printf("\nbond: %d i: %d j: %d natoms: %d", i, bond[i].origin, bond[i].target, natoms); } + * } if (errors) { //SimpleExit("Error(s) in bonds",1); Log_to_GUI("Read_AMBER_PARM: Error(s) in bond definition\n"); return -1; } + * + * //printf("\nBond energy: %lf",Energy12() ); // assert( !feof(Mol2File) ); //MakeBondedToList(); //BuildBondMatrix(); //return + * 0; // --- Allocate angles + * + * ninter13 = ntheth + ntheta; if (inter13 != NULL) { delete[] inter13; } inter13 = new Inter13[ninter13]; assert (inter13); + * + * // // fmtin = ifmt // type = 'angles_inc_hydrogen' // call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) // read(nf,fmt) + * (ix(i+i24-1),ix(i+i26-1),ix(i+i28-1),ix(i+i30-1), // + i = 1,ntheth) + * + * + * if (imax < ntheth * 4) { imax = ntheth * 4; itemp = (int * ) realloc(itemp, sizeof(int) * imax); assert (itemp); } + * + * repeat = 12; dl = 6; if (new_format) { fget_line(bufer, 256, parm); // %FLAG ANGLES_INC_HYDROGEN fget_line(bufer, 256, parm); + * // %FORMAT( if (parse_format(bufer, repeat, dl)) { //SimpleExit("Can't parse format",1); Log_to_GUI( "Read_AMBER_PARM: Cannot + * parse ANGLES_INC_HYDROGEN format: %s\n", bufer); return -1; } } + * + * nlines = ntheth * 4 % repeat ? ntheth * 4 / repeat + 1 : ntheth * 4 / repeat; if (nlines == 0) { nlines = 1; } count = 1; k = + * 0; for (i = 0; i < nlines; i++) { fget_line(bufer, 256, parm); int n = 4 * ntheth - count + 1 >= repeat ? repeat : 4 * ntheth - + * count + 1; for (j = 0; j < n; j++, k++, count++) { strncpy(buf, bufer + j * dl, dl); buf[dl] = 0x00; itemp[k] = atoi(buf); } } + * + * for (i = 0; i < ntheth; i++) { inter13[i].i = itemp[4 * i] / 3 + 1; inter13[i].j = itemp[4 * i + 1] / 3 + 1; inter13[i].k = + * itemp[4 * i + 2] / 3 + 1; int ref = itemp[4 * i + 3] - 1; if (ref < 0) { printf("\n???: ref < 0 for ntheth: %d", ref); } + * inter13[i].keq = ff.angleParTable[ref].fc; inter13[i].aeq = ff.angleParTable[ref].ebl; } + * + * + * // fmtin = ifmt // type = 'angles_without_hydrogen' // call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) // read(nf,fmt) + * (ix(i+i32-1),ix(i+i34-1),ix(i+i36-1),ix(i+i38-1), // + i = 1,ntheta) + * + * if (imax < mtheta * 4) { imax = mtheta * 4; itemp = (int * ) realloc(itemp, sizeof(int) * imax); assert (itemp); } + * + * repeat = 12; dl = 6; if (new_format) { fget_line(bufer, 256, parm); // %FLAG ANGLES_WITHOUT_HYDROGEN fget_line(bufer, 256, + * parm); // %FORMAT( if (parse_format(bufer, repeat, dl)) { //SimpleExit("Can't parse format",1); Log_to_GUI( "Read_AMBER_PARM: + * Cannot parse ANGLES_WITHOUT_HYDROGEN format: %s\n", bufer); return -1; } } + * + * nlines = mtheta * 4 % repeat ? mtheta * 4 / repeat + 1 : mtheta * 4 / repeat; if (nlines == 0) { nlines = 1; } count = 1; k = + * 0; for (i = 0; i < nlines; i++) { fget_line(bufer, 256, parm); int n = 4 * mtheta - count + 1 >= repeat ? repeat : 4 * mtheta - + * count + 1; for (j = 0; j < n; j++, k++, count++, count_2++) { strncpy(buf, bufer + j * dl, dl); buf[dl] = 0x00; itemp[k] = + * atoi(buf); } } + * + * for (k = ntheth, i = 0; i < mtheta; i++, k++) { inter13[k].i = itemp[4 * i] / 3 + 1; inter13[k].j = itemp[4 * i + 1] / 3 + 1; + * inter13[k].k = itemp[4 * i + 2] / 3 + 1; int ref = itemp[4 * i + 3] - 1; if (ref < 0) { printf("\n???: ref < 0 for mtheta: %d", + * ref); } inter13[k].keq = ff.angleParTable[ref].fc; inter13[k].aeq = ff.angleParTable[ref].ebl; } + * + * // --- Test errors = 0; for (i = 0; i < ninter13; i++) { if (inter13[i].i < 1 || inter13[i].i > natoms || inter13[i].j < 1 || + * inter13[i].j > natoms || inter13[i].k < 1 || inter13[i].k > natoms) { ++errors; printf("\nangle: %d i: %d j: %d k: %d natoms: + * %d", i, inter13[i].i, inter13[i].j, inter13[i].k, natoms); } } + * + * // --- Allocate torsions + * + * nintertor = nphih + nphia; if (intertor != NULL) { delete[] intertor; } intertor = new InterTor[nintertor]; assert (intertor); + * + * + * // fmtin = ifmt // type = 'dihedrals_inc_hydrogen' // call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) // read(nf,fmt) + * (ix(i+i40-1),ix(i+i42-1),ix(i+i44-1),ix(i+i46-1), // + ix(i+i48-1),i = 1,nphih) + * + * if (5 * nphih > imax) { imax = 5 * nphih; itemp = (int * ) realloc(itemp, sizeof(int) * imax); assert (itemp); } + * + * repeat = 12; dl = 6; if (new_format) { fget_line(bufer, 256, parm); // %FLAG DIHEDRALS_INC_HYDROGEN fget_line(bufer, 256, + * parm); // %FORMAT( if (parse_format(bufer, repeat, dl)) { //SimpleExit("Can't parse format",1); Log_to_GUI( "Read_AMBER_PARM: + * Cannot parse DIHEDRALS_INC_HYDROGEN format: %s\n", bufer); return -1; } } + * + * nlines = nphih * 5 % repeat ? nphih * 5 / repeat + 1 : nphih * 5 / repeat; if (nlines == 0) { nlines = 1; } count = 1; k = 0; + * for (i = 0; i < nlines; i++) { fget_line(bufer, 256, parm); int n = 5 * nphih - count + 1 >= repeat ? repeat : 5 * nphih - + * count + 1; for (j = 0; j < n; j++, k++, count++) { strncpy(buf, bufer + dl * j, dl); buf[dl] = 0x00; itemp[k] = atoi(buf); } } + * + * for (i = 0; i < nphih; i++) { intertor[i].i = itemp[5 * i] / 3 + 1; intertor[i].j = itemp[5 * i + 1] / 3 + 1; intertor[i].k = + * abs(itemp[5 * i + 2] / 3) + 1; intertor[i].l = abs(itemp[5 * i + 3] / 3) + 1; //intertor[i].n = (double)(itemp[5*i + 4] - 1); + * int pos = itemp[5 * i + 4] - 1; if (pos >= ff.nTorsionPar) { printf("\npos >= ff.nTorsionPar"); } + * + * if (fabs(ff.torsionParTable[pos].par[0].phase - 0.0) < 0.1) { intertor[i].n = ff.torsionParTable[pos].par[0].per; } else if + * (fabs(ff.torsionParTable[pos].par[0].phase - PI) < 0.1) { intertor[i].n = -ff.torsionParTable[pos].par[0].per; } else { + * printf("\n\nDon't know how to work with this phase: %8.3lf\n", ff.torsionParTable[pos].par[0].phase * RAD2DEG); //exit(1); + * Log_to_GUI("Read_AMBER_PARM: Wrong Phase definition\n"); return -1; } + * + * intertor[i].u = ff.torsionParTable[pos].par[0].fc; + * + * } + * + * + * // fmtin = ifmt // type = 'dihedrals_without_hydrogen' // call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) // read(nf,fmt) + * (ix(i+i50-1),ix(i+i52-1),ix(i+i54-1),ix(i+i56-1), // + ix(i+i58-1),i = 1,nphia) + * + * if (5 * nphia > imax) { imax = 5 * nphia; itemp = (int * ) realloc(itemp, sizeof(int) * imax); assert (itemp); } + * + * repeat = 12; dl = 6; if (new_format) { fget_line(bufer, 256, parm); // %FLAG DIHEDRALS_WITHOUT_HYDROGEN fget_line(bufer, 256, + * parm); // %FORMAT( if (parse_format(bufer, repeat, dl)) { //SimpleExit("Can't parse format",1); Log_to_GUI( "Read_AMBER_PARM: + * Cannot parse DIHEDRALS_WITHOUT_HYDROGEN format: %s\n", bufer); return -1; } } + * + * nlines = nphia * 5 % repeat ? nphia * 5 / repeat + 1 : nphia * 5 / repeat; if (nlines == 0) { nlines = 1; } count = 1; k = 0; + * for (i = 0; i < nlines; i++) { fget_line(bufer, 256, parm); int n = 5 * nphia - count + 1 >= repeat ? repeat : 5 * nphia - + * count + 1; for (j = 0; j < n; j++, k++, count++) { strncpy(buf, bufer + dl * j, dl); buf[dl] = 0x00; itemp[k] = atoi(buf); } } + * + * for (i = 0, j = nphih; i < nphia; i++, j++) { intertor[j].i = itemp[5 * i] / 3 + 1; intertor[j].j = itemp[5 * i + 1] / 3 + 1; + * intertor[j].k = abs(itemp[5 * i + 2] / 3) + 1; intertor[j].l = abs(itemp[5 * i + 3] / 3) + 1; //intertor[i].n = + * (double)(itemp[5*i + 4] - 1); + * + * int pos = itemp[5 * i + 4] - 1; if (pos >= ff.nTorsionPar) { printf("\nHeavy: pos >= ff.nTorsionPar"); } + * + * if (fabs(ff.torsionParTable[pos].par[0].phase - 0.0) < 0.1) { intertor[j].n = ff.torsionParTable[pos].par[0].per; } else if + * (fabs(ff.torsionParTable[pos].par[0].phase - PI) < 0.1) { intertor[j].n = -ff.torsionParTable[pos].par[0].per; } else { + * printf("\n\nDon't know how to work with this phase: %8.3lf\n", ff.torsionParTable[pos].par[0].phase * RAD2DEG); exit(1); } + * + * intertor[j].u = ff.torsionParTable[pos].par[0].fc; + * + * } + * + * // --- parameter assignment (and Test) + * + * errors = 0; for (i = 0; i < nintertor; i++) { //int pos = (int)(intertor[i].n); //if ( + * fabs(ff.torsionParTable[pos].par[0].phase - 0.0 ) < 0.1 ) // intertor[i].n = ff.torsionParTable[pos].par[0].per; //else if ( + * fabs(ff.torsionParTable[pos].par[0].phase - PI ) < 0.1 ) // intertor[i].n = -ff.torsionParTable[pos].par[0].per; //else { // + * printf("\n\nDon't know how to work with this phase: %8.3lf\n", // ff.torsionParTable[pos].par[0].phase*RAD2DEG); // exit(1); // + * } //intertor[i].u = ff.torsionParTable[pos].par[0].fc; + * + * + * //printf("\n%5d %s %s %s %s %s fc: %8.3lf n: %8.3lf", // i,atom[intertor[i].i].name, atom[intertor[i].j].name, + * atom[intertor[i].k].name, // atom[intertor[i].l].name, atom[intertor[i].i].sname,intertor[i].u, intertor[i].n); + * + * if (intertor[i].i < 1 || intertor[i].i > natoms || intertor[i].j < 1 || intertor[i].j > natoms || intertor[i].k < 1 || + * intertor[i].k > natoms || intertor[i].l < 1 || intertor[i].l > natoms) { ++errors; printf("\ntorsion: %d i: %d j: %d k: %d l: + * %d natoms: %d", i, intertor[i].i, intertor[i].j, intertor[i].k, intertor[i].l, natoms); } } + * + * + * // fmtin = ifmt // type = 'excluded_atoms_list' // call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) // read(nf,fmt) + * (ix(i+i10-1),i=1,nnb) + * + * + * if (nnb > imax) { imax = nnb; itemp = (int * ) realloc(itemp, sizeof(int) * imax); assert (itemp); } + * + * repeat = 12; dl = 6; if (new_format) { fget_line(bufer, 256, parm); // %FLAG EXCLUDED_ATOMS_LIST fget_line(bufer, 256, parm); + * // %FORMAT( if (parse_format(bufer, repeat, dl)) { SimpleExit("Can't parse format", 1); } } + * + * nlines = nnb % repeat ? nnb / repeat + 1 : nnb / repeat; if (nlines == 0) { nlines = 1; } count = 1; k = 0; for (i = 0; i < + * nlines; i++) { fget_line(bufer, 256, parm); int n = nnb - count + 1 >= repeat ? repeat : nnb - count + 1; for (j = 0; j < n; + * j++, k++, count++) { strncpy(buf, bufer + dl * j, dl); buf[dl] = 0x00; itemp[k] = atoi(buf); } } + * + * // ----- read the h-bond parameters ----- + * + * // fmtin = rfmt // type = 'hbond_acoef' // call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) // read(nf,fmt) (asol(i),i=1,nphb) + * + * repeat = 5; dl = 16; if (new_format) { fget_line(bufer, 256, parm); // %FLAG HBOND_ACOEF fget_line(bufer, 256, parm); // + * %FORMAT( if (parse_format(bufer, repeat, dl)) { SimpleExit("Can't parse format", 1); } } + * + * if (nphb > rmax) { rmax = nphb; rtemp = (double * ) realloc(rtemp, sizeof(double) * rmax); assert (rtemp); } + * + * nlines = nphb % repeat ? nphb / repeat + 1 : nphb / repeat; if (nlines == 0) { nlines = 1; } count = 1; k = 0; for (i = 0; i < + * nlines; i++) { fget_line(bufer, 256, parm); int n = nphb - count + 1 >= repeat ? repeat : nphb - count + 1; for (j = 0; j < n; + * j++, k++, count++) { strncpy(buf, bufer + dl * j, dl); buf[dl] = 0x00; rtemp[k] = atof(buf); } } + * + * // // fmtin = rfmt // type = 'hbond_bcoef' // call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) // read(nf,fmt) (bsol(i),i=1,nphb) + * + * repeat = 5; dl = 16; if (new_format) { fget_line(bufer, 256, parm); // %FLAG HBOND_BCOEF fget_line(bufer, 256, parm); // + * %FORMAT( if (parse_format(bufer, repeat, dl)) { SimpleExit("Can't parse format", 1); } } + * + * if (nphb > rmax) { rmax = nphb; rtemp = (double * ) realloc(rtemp, sizeof(double) * rmax); assert (rtemp); } + * + * nlines = nphb % repeat ? nphb / repeat + 1 : nphb / repeat; if (nlines == 0) { nlines = 1; } count = 1; k = 0; for (i = 0; i < + * nlines; i++) { fget_line(bufer, 256, parm); int n = nphb - count + 1 >= repeat ? repeat : nphb - count + 1; for (j = 0; j < n; + * j++, k++, count++) { strncpy(buf, bufer + dl * j, dl); buf[dl] = 0x00; rtemp[k] = atof(buf); } } + * + * // fmtin = rfmt // type = 'hbcut' // call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) // read(nf,fmt) (hbcut(i),i=1,nphb) + * + * repeat = 5; dl = 16; if (new_format) { fget_line(bufer, 256, parm); // %FLAG HBCUT fget_line(bufer, 256, parm); // %FORMAT( if + * (parse_format(bufer, repeat, dl)) { SimpleExit("Can't parse format", 1); } } + * + * if (nphb > rmax) { rmax = nphb; rtemp = (double * ) realloc(rtemp, sizeof(double) * rmax); assert (rtemp); } + * + * nlines = nphb % repeat ? nphb / repeat + 1 : nphb / repeat; if (nlines == 0) { nlines = 1; } count = 1; k = 0; for (i = 0; i < + * nlines; i++) { fget_line(bufer, 256, parm); int n = nphb - count + 1 >= repeat ? repeat : nphb - count + 1; for (j = 0; j < n; + * j++, k++, count++) { strncpy(buf, bufer + dl * j, dl); buf[dl] = 0x00; rtemp[k] = atof(buf); } } + * + * // ----- read isymbl,itree,join and irotat arrays ----- // fmtin = afmt // type = 'amber_atom_type' // call nxtsec(nf, 6, + * 0,fmtin, type, fmt, iok) // read(nf,fmt) (ih(i+m06-1),i=1,natom) + * + * repeat = 20; dl = 4; if (new_format) { fget_line(bufer, 256, parm); // %FLAG AMBER_ATOM_TYPE fget_line(bufer, 256, parm); // + * %FORMAT( if (parse_format(bufer, repeat, dl)) { //SimpleExit("Can't parse format",1); Log_to_GUI( "Read_AMBER_PARM: Cannot + * parse AMBER_ATOM_TYPE format: %s\n", bufer); return -1; } } + * + * nlines = natoms % repeat ? natoms / repeat + 1 : natoms / repeat; if (nlines == 0) { nlines = 1; } count = 1; k = 0; for (i = + * 0; i < nlines; i++) { fget_line(bufer, 256, parm); int n = natoms - count + 1 >= repeat ? repeat : natoms - count + 1; for (j = + * 0; j < n; j++, k++, count++) { strncpy(buf, bufer + dl * j, dl); buf[dl] = 0x00; //atom[count].Set_Amber_Name( buf ); + * atom[count].Set_Amber_Name(strtok(buf, " ")); } } + * + * // // fmtin = afmt // type = 'tree_chain_classification' // call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) // read(nf,fmt) + * (ih(i+m08-1),i=1,natoms) + * + * repeat = 20; dl = 4; if (new_format) { fget_line(bufer, 256, parm); // %FLAG TREE_CHAIN_CLASSIFICATION fget_line(bufer, 256, + * parm); // %FORMAT( if (parse_format(bufer, repeat, dl)) { SimpleExit("Can't parse format", 1); } } + * + * nlines = natoms % repeat ? natoms / repeat + 1 : natoms / repeat; if (nlines == 0) { nlines = 1; } count = 1; k = 0; for (i = + * 0; i < nlines; i++) { fget_line(bufer, 256, parm); int n = natoms - count + 1 >= repeat ? repeat : natoms - count + 1; for (j = + * 0; j < n; j++, k++, count++) { strncpy(buf, bufer + dl * j, dl); buf[dl] = 0x00; + * + * } + * } + * + * // // fmtin = ifmt // type = 'join_array' // call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) // read(nf,fmt) + * (ix(i+i64-1),i=1,natom) // repeat = 12; dl = 6; if (new_format) { fget_line(bufer, 256, parm); // %FLAG JOIN_ARRAY + * fget_line(bufer, 256, parm); // %FORMAT( if (parse_format(bufer, repeat, dl)) { SimpleExit("Can't parse format", 1); } } + * + * nlines = natoms % repeat ? natoms / repeat + 1 : natoms / repeat; if (nlines == 0) { nlines = 1; } count = 1; k = 0; for (i = + * 0; i < nlines; i++) { fget_line(bufer, 256, parm); int n = natoms - count + 1 >= repeat ? repeat : natoms - count + 1; for (j = + * 0; j < n; j++, k++, count++) { strncpy(buf, bufer + dl * j, dl); buf[dl] = 0x00; + * + * } + * } + * + * // // fmtin = ifmt // type = 'irotat' // call nxtsec(nf, 6, 0,fmtin, type, fmt, iok) // read(nf,fmt) (ix(i+i66-1),i=1,natom) + * // repeat = 12; dl = 6; if (new_format) { fget_line(bufer, 256, parm); // %FLAG IROTAT fget_line(bufer, 256, parm); // %FORMAT( + * if (parse_format(bufer, repeat, dl)) { SimpleExit("Can't parse format", 1); } } + * + * nlines = natoms % repeat ? natoms / repeat + 1 : natoms / repeat; if (nlines == 0) { nlines = 1; } count = 1; k = 0; for (i = + * 0; i < nlines; i++) { fget_line(bufer, 256, parm); int n = natoms - count + 1 >= repeat ? repeat : natoms - count + 1; for (j = + * 0; j < n; j++, k++, count++) { strncpy(buf, bufer + dl * j, dl); buf[dl] = 0x00; + * + * } + * } + * + * fclose(parm); + * + * printf("\n\nVDW Parameters\n"); for (i = 0; i < ntypes; i++) { if (ff.Bij[i][i] == 0.0) { ff.rho[i] = 0.0; ff.eps[i] = 0.0; } + * else { ff.rho[i] = 0.5 * pow(2.0 * ff.Aij[i][i] / ff.Bij[i][i], 1.0 / 6.0); ff.eps[i] = ff.Aij[i][i] / pow(2.0 * ff.rho[i], + * 12); } + * + * printf("\n%3d: %8.4lf %8.4lf", i + 1, ff.rho[i], ff.eps[i]); for (j = 1; j <= natoms; j++) { if (atom[j].ambtype == i) { + * printf(" %s", atom[j].amber_name); break; } } } + * + * } + */ +} diff --git a/src/main/java/cct/amber/AmberSubmitDialog.java b/src/main/java/cct/amber/AmberSubmitDialog.java new file mode 100644 index 0000000..5960081 --- /dev/null +++ b/src/main/java/cct/amber/AmberSubmitDialog.java @@ -0,0 +1,178 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.amber; + +import java.awt.Frame; +import java.awt.Menu; +import java.awt.MenuBar; +import java.awt.MenuItem; +import java.awt.TextArea; +import java.util.logging.Logger; + +import cct.awtdialogs.MessageWindow; + +public class AmberSubmitDialog + extends Frame { + public String mdin = null, prmtop = null, inpcrd = null; + public String mdin_dir = null, prmtop_dir = null, inpcrd_dir = null; + public int numberOfAtoms = 0; + String actionURL; + TextArea fileContent; + Sander8JobControl sanderJC = new Sander8JobControl(); + SanderJobControlDialog resources = null; + SanderResourcesEval eval = null; + AmberApplet daddy; + static final Logger logger = Logger.getLogger(AmberSubmitDialog.class.getCanonicalName()); + + public AmberSubmitDialog(AmberApplet parent, String title, String aURL) { + super(title); + + daddy = parent; + actionURL = aURL; + resources = new SanderJobControlDialog(this, "Required Resources", false); + resources.setVisible(false); + + eval = new SanderResourcesEval(); + + AmberSubmitMenuHandler handler = new AmberSubmitMenuHandler(this); + + // create menu bar and add it to frame + MenuBar mbar = new MenuBar(); + setMenuBar(mbar); + + // --- File Menu + + Menu file = new Menu("File"); + MenuItem openAJCF = new MenuItem("Open Amber Job Control File"); + openAJCF.addActionListener(handler); + file.add(openAJCF); + MenuItem attachPrmtop = new MenuItem("Attach Topology File"); + attachPrmtop.addActionListener(handler); + file.add(attachPrmtop); + MenuItem attachInpcrd = new MenuItem("Attach Coordinates File"); + attachInpcrd.addActionListener(handler); + file.add(attachInpcrd); + + mbar.add(file); + + // --- Check Menu + + Menu check = new Menu("Check"); + MenuItem checkInput = new MenuItem("Check Input"); + checkInput.addActionListener(handler); + check.add(checkInput); + + mbar.add(check); + + Menu Submit = new Menu("Submit"); + MenuItem sendFiles = new MenuItem("Send Files"); + sendFiles.addActionListener(handler); + Submit.add(sendFiles); + + mbar.add(Submit); + + fileContent = new TextArea("Load Amber Job Control file here"); + add(fileContent); + + } + + public void setTextArea(String newText) { + fileContent.setText(newText); + } + + /** + * + * @return int + * =0 - OK, =1 - Warning (OK for checkup, not for submition); =2 - Error + */ + public int checkDataIntegrity() { + if (mdin == null) { + MessageWindow d = new MessageWindow("Error Message", + "Load Amber Job Control File First", true); + d.setVisible(true); + return 2; + } + + String mess = sanderJC.getGeneralParameters(fileContent.getText(), 1); + //if (!mess.contentEquals("Ok")) { // Java 1.5 + if (!mess.equalsIgnoreCase("Ok")) { + MessageWindow d = new MessageWindow("Error Message", mess, true); + d.setVisible(true); + return 2; + } + + int natoms = 0; + if (inpcrd != null) { + natoms = AmberUtilities.getNAtomsFromCoordFile(inpcrd_dir + inpcrd); + } + + sanderJC.setNumberOfAtoms(natoms); + + float memory = eval.evaluateMemoryRequirement(sanderJC); + float time = eval.evaluateTimeRequirement(sanderJC); + + resources.setNumberOfAtoms(eval.getNumberOfAtoms()); + resources.setNumberOfSteps(sanderJC.numberOfEnergySteps()); + resources.setCutoff(sanderJC.getCutoff()); + resources.setMemoryRequirement(memory); + resources.setTimeRequirement(time); + + resources.setVisible(true); + return 0; // -- Ok + } + + public int sendFiles() { + try { + java.net.URL url = new java.net.URL(actionURL + "&exec=/opt/amber8/exe/sander" + + "&args=%20-O%20-i%20" + mdin + "%20-o%20mdout%20-p%20" + prmtop + "%20-c%20" + inpcrd + + "&mdin=" + mdin_dir + mdin + + "&inpcrd=" + inpcrd_dir + inpcrd + "&prmtop=" + + prmtop_dir + prmtop + "&step=1a&jobname=amber_calc"); + + daddy.getAppletContext().showDocument(url, "_top"); + logger.info(url.toString()); + logger.info("daddy's CodeBase" + daddy.getCodeBase()); + logger.info("daddy's DocumentBase" + daddy.getDocumentBase()); + } + catch (java.net.MalformedURLException e) { + e.printStackTrace(); + } + + return 0; + } +} diff --git a/src/main/java/cct/amber/AmberSubmitMenuHandler.java b/src/main/java/cct/amber/AmberSubmitMenuHandler.java new file mode 100644 index 0000000..9359914 --- /dev/null +++ b/src/main/java/cct/amber/AmberSubmitMenuHandler.java @@ -0,0 +1,123 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.amber; + +import java.awt.FileDialog; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.logging.Logger; + +import cct.tools.IOUtils; + +public class AmberSubmitMenuHandler + implements ActionListener, ItemListener { + AmberSubmitDialog menuFrame; + String fileName, directory; + static final Logger logger = Logger.getLogger(AmberSubmitMenuHandler.class.getCanonicalName()); + + public AmberSubmitMenuHandler(AmberSubmitDialog parent) { + this.menuFrame = parent; + } + + // Handle action events + @Override + public void actionPerformed(ActionEvent ae) { + //String msg = "You selected "; + String arg = ae.getActionCommand(); + if (arg.equals("New...")) { + + } + else if (arg.equals("Open Amber Job Control File")) { + FileDialog fd = new FileDialog(menuFrame, "Open File", + FileDialog.LOAD); +// FilenameFilter x; x. + fd.setFile("*"); + fd.setVisible(true); + if (fd.getFile() != null) { + fileName = new String(fd.getFile()); + directory = new String(fd.getDirectory()); + String fileContents = IOUtils.loadFileIntoString(directory + fileName); + menuFrame.setTextArea(fileContents); + menuFrame.mdin = fileName; + menuFrame.mdin_dir = directory; + } + } + else if (arg.equals("Attach Topology File")) { + FileDialog fd = new FileDialog(menuFrame, "Specify Molecular Topology File", + FileDialog.LOAD); + fd.setFile("*"); + fd.setVisible(true); + if (fd.getFile() != null) { + fileName = new String(fd.getFile()); + directory = new String(fd.getDirectory()); + menuFrame.prmtop = fileName; + menuFrame.prmtop_dir = directory; + } + + } + else if (arg.equals("Attach Coordinates File")) { + FileDialog fd = new FileDialog(menuFrame, "Specify Coordinates File", + FileDialog.LOAD); + fd.setFile("*"); + fd.setVisible(true); + if (fd.getFile() != null) { + fileName = fd.getFile(); + directory = fd.getDirectory(); + menuFrame.inpcrd = fileName; + menuFrame.inpcrd_dir = directory; + logger.info("Coord file: " + directory + fileName); + } + } + else if (arg.equals("Check Input")) { + menuFrame.checkDataIntegrity(); + } + else if (arg.equals("Send Files")) { + menuFrame.sendFiles(); + } + + menuFrame.repaint(); + } + + // Handle item events + @Override + public void itemStateChanged(ItemEvent ie) { + menuFrame.repaint(); + } +} diff --git a/src/main/java/cct/amber/AmberUtilities.java b/src/main/java/cct/amber/AmberUtilities.java new file mode 100644 index 0000000..2a205f6 --- /dev/null +++ b/src/main/java/cct/amber/AmberUtilities.java @@ -0,0 +1,282 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.amber; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; +import java.util.ResourceBundle; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.ChemicalElements; + +/** + *

+ * Title: Picking

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005

+ * + *

+ * Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class AmberUtilities { + + public static final String AmberAtomFlags = "Amber Atom Flags"; + + static String defaultAtomTypesTableFile = "cct.amber.amber-elements"; + + static Map defaultElementsTable = null; + + private static ResourceBundle resources; + + private AmberUtilities setDefault = new AmberUtilities(); + static final Logger logger = Logger.getLogger(AmberUtilities.class.getCanonicalName()); + + public AmberUtilities() { + defaultElementsTable = readAmberElementsTable(defaultAtomTypesTableFile); + } + + public static int getElement(String amberType) { + if (defaultElementsTable == null) { + defaultElementsTable = readAmberElementsTable( + defaultAtomTypesTableFile); + if (defaultElementsTable == null) { + return 0; + } + } + + if (amberType == null) { + return 0; + } + + if (defaultElementsTable.containsKey(amberType.toUpperCase())) { + Integer el = defaultElementsTable.get(amberType); + return el; + } + return 0; + } + + public static Map readAmberElementsTable(String propertiesName) { + try { + resources = ResourceBundle.getBundle(propertiesName); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + if (resources == null) { + System.err.println("Resources " + propertiesName + " are not found"); + return null; + } + } + + Map table = new HashMap(100); + Enumeration en = resources.getKeys(); + int el; + while (en.hasMoreElements()) { + String key = en.nextElement(); + String element = resources.getString(key); + if (element == null) { + System.err.println("Warning: no element matching for Amber atom type " + key); + el = 0; + } else { + el = ChemicalElements.getAtomicNumber(element.toUpperCase()); + } + table.put(key.toUpperCase(), new Integer(el)); + } + + return table; + } + + public static int getNAtomsFromCoordFile(String filename) { + String line; + int natoms = 0; + try { + BufferedReader in = new BufferedReader(new FileReader(filename)); + line = in.readLine(); // Skip first line + line = in.readLine(); + if (line == null) { + return 0; + } + + StringTokenizer st = new StringTokenizer(line, " "); + + try { + natoms = Integer.parseInt(st.nextToken()); + } catch (NumberFormatException e) { + return 0; + } + + in.close(); + } catch (IOException e) { + logger.info("\nERROR: getNAtomsFromCoordFile: " + e.getMessage() + + "\n"); + return 0; + } + + return natoms; + } + + public static void updateCoordFromInpcrd(MoleculeInterface molecule, + String file_name) throws Exception { + if (molecule == null || molecule.getNumberOfAtoms() < 1) { + throw new Exception( + "Error updating coordinates: Reference molecule has no atoms"); + } + + String line; + int natoms = 0; + try { + BufferedReader in = new BufferedReader(new FileReader(file_name)); + line = in.readLine(); // Skip first line + line = in.readLine(); + if (line == null) { + throw new Exception( + "Error: updateCoordFromInpcrd: unexpected eof while reading number of atoms"); + } + + StringTokenizer st = new StringTokenizer(line, " "); + + try { + natoms = Integer.parseInt(st.nextToken()); + } catch (NumberFormatException e) { + throw new Exception( + "Error: updateCoordFromInpcrd: error parsing number of atoms: " + + e.getMessage()); + } + + if (natoms != molecule.getNumberOfAtoms()) { + throw new Exception("Number of atoms in reference molecule (" + + molecule.getNumberOfAtoms() + + ") does not match that in inpcrd file (" + + natoms); + } + + int repeat = 6; + int dl = 12; + int nlines = natoms * 3 % repeat > 0 ? 3 * natoms / repeat + 1 + : 3 * natoms / repeat; + if (nlines == 0) { + nlines = 1; + } + int count = 0; + int nat = 0; + int xyz = 0; + for (int i = 0; i < nlines; i++) { + line = in.readLine(); + int n = 3 * natoms - count >= repeat ? repeat : 3 * natoms - count; + for (int j = 0; j < n; j++) { + try { + float coord = Float.parseFloat(line.substring(dl * j, + dl * j + dl).trim()); + + if (xyz == 3) { + xyz = 0; + ++nat; + } + + AtomInterface atom = molecule.getAtomInterface(nat); + + switch (xyz) { + case 0: + atom.setX(coord); + break; + case 1: + atom.setY(coord); + break; + case 2: + atom.setZ(coord); + break; + } + + } catch (Exception ex) { + throw new Exception("Cannot parse " + line.substring(dl * j, + dl * j + dl).trim() + " : " + ex.getMessage()); + } + + ++xyz; + ++count; + } + } + + in.close(); + } catch (IOException e) { + throw new Exception("Error: updateCoordFromInpcrd: cannot read file " + + file_name + " : " + e.getMessage()); + } + + } + + public static void main(String[] args) { + String prmtop = "prmtop"; + String mdcrd = "mdcrd"; + String input = "input"; + AmberUtilities amberUtilities = new AmberUtilities(); + int count = 0; + while (args.length < count) { + if (args[count].equals("-p")) { + if (args.length <= count + 1) { + System.err.println("Expected prmtop file name"); + System.exit(1); + } + ++count; + prmtop = args[count]; + } + else if (args[count].equals("-x")) { + if (args.length <= count + 1) { + System.err.println("Expected mdcrd file name"); + System.exit(1); + } + ++count; + mdcrd = args[count]; + } + // --- Increment ++count; + ++count; + } + } + +} diff --git a/src/main/java/cct/amber/AmberUtilities.jbx b/src/main/java/cct/amber/AmberUtilities.jbx new file mode 100644 index 0000000..0113ff3 --- /dev/null +++ b/src/main/java/cct/amber/AmberUtilities.jbx @@ -0,0 +1,6 @@ +[PropertyInfo] +[IconNames] + + + + diff --git a/src/main/java/cct/amber/BuildRestraintMask.java b/src/main/java/cct/amber/BuildRestraintMask.java new file mode 100644 index 0000000..3ec261b --- /dev/null +++ b/src/main/java/cct/amber/BuildRestraintMask.java @@ -0,0 +1,186 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.amber; + +import cct.interfaces.MoleculeInterface; +import cct.modelling.Molecule; +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + * @author Vlad + */ +public class BuildRestraintMask { + + public static void main(String[] args) { + String prmtop = null; + String input = null; + int count = 0, numResidues = -1; + BufferedReader prmtopReader; + AmberPrmtop amberPrmtop; + MoleculeInterface mol = new Molecule(); + Set residues = new LinkedHashSet(); + + if (args.length == 0) { + System.out.println("Enter residues, one per line:"); + + try { + BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in)); + while (true) { + String s = bufferRead.readLine(); + + System.out.println(s); + } + } catch (Exception e) { + e.printStackTrace(); + } + } else { + while (count < args.length) { + if (args[count].equals("-t")) { + if ((count + 1 >= args.length)) { + System.err.println("Expected topology file name"); + System.exit(1); + } + ++count; + prmtop = args[count]; + } else if (args[count].equals("-i")) { + if ((count + 1 >= args.length)) { + System.err.println("Expected imput file name"); + System.exit(1); + } + ++count; + input = args[count]; + } + // --- Increment counter + ++count; + } + + // --- reading topology file, if any + if (prmtop != null) { + try { + prmtopReader = new BufferedReader(new FileReader(prmtop)); + amberPrmtop = new AmberPrmtop(); + System.out.println("Reading prmtop file " + prmtop + "..."); + amberPrmtop.parsePrmtop(mol, prmtopReader); + System.out.println("Number of atoms: " + mol.getNumberOfAtoms() + " Number of residues: " + mol.getNumberOfMonomers()); + if (numResidues != -1) { + System.out.println("Getting number of residues from prmtop file..."); + } + numResidues = mol.getNumberOfMonomers(); + prmtopReader.close(); + } catch (Exception ex) { + Logger.getLogger(BuildRestraintMask.class.getName()).log(Level.SEVERE, null, ex); + System.exit(1); + } + } + + // --- reading imput file, if any + if (input != null) { + int res = -1; + try { + prmtopReader = new BufferedReader(new FileReader(input)); + String line; + while ((line = prmtopReader.readLine()) != null) { + line = line.trim(); + if (line.startsWith("#") || line.startsWith(";") || line.length() < 1) { + continue; + } + // --- + res = -1; + try { + res = Integer.parseInt(line); + residues.add(res); + continue; + } catch (Exception ex) { + } + + if (line.matches("\\w{3}\\s*\\d+")) { + String str = line.substring(3).trim(); + try { + res = Integer.parseInt(str); + residues.add(res); + continue; + } catch (Exception ex) { + System.err.println("Cannot parse line " + line); + System.exit(1); + } + } + + System.err.println("Cannot parse line " + line); + System.exit(1); + } + prmtopReader.close(); + // --- + + } catch (Exception ex) { + Logger.getLogger(BuildRestraintMask.class.getName()).log(Level.SEVERE, null, ex); + System.exit(1); + } + } + } + + Integer[] resArray = residues.toArray(new Integer[0]); + Arrays.sort(resArray); + System.out.println("Read " + residues.size() + " residues (in sorted order)"); + for (Integer r : resArray) { + System.out.println(r); + } + // --- + if (numResidues < resArray[resArray.length - 1]) { + numResidues = resArray[resArray.length - 1]; + System.out.println("Total number of residues is set to " + numResidues); + } + // --- + int firstRestr = 1, lastRestr = 1; + String restraintmask = ""; + + for (Integer res : resArray) { + if (res > firstRestr) { + lastRestr = res - 1; + } else if (res == firstRestr) { + firstRestr = res + 1; + } + + if (lastRestr >= firstRestr) { + if (restraintmask.length() > 0) { + restraintmask += ","; + } + restraintmask += String.valueOf(firstRestr); + if (lastRestr > firstRestr) { + restraintmask += "-" + String.valueOf(lastRestr); + } + + firstRestr = lastRestr = res + 1; + } + } + + firstRestr = resArray[resArray.length - 1] + 1; + lastRestr = numResidues; + + if (firstRestr <= numResidues) { + if (restraintmask.length() > 0) { + restraintmask += ","; + } + restraintmask += String.valueOf(firstRestr); + } + + if (lastRestr > firstRestr) { + restraintmask += "-" + String.valueOf(lastRestr); + } + + System.out.println("restraintmask=':" + restraintmask + "'"); + System.exit(0); + } +} diff --git a/src/main/java/cct/amber/ReadPrmtopDialog.java b/src/main/java/cct/amber/ReadPrmtopDialog.java new file mode 100644 index 0000000..6edcc2b --- /dev/null +++ b/src/main/java/cct/amber/ReadPrmtopDialog.java @@ -0,0 +1,394 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.amber; + +import java.awt.BorderLayout; +import java.awt.FileDialog; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.util.logging.Logger; +import java.util.prefs.Preferences; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTextField; + +import cct.interfaces.MoleculeInterface; +import cct.modelling.MolecularFileFormats; +import cct.modelling.Molecule; +import cct.tools.FileFilterImpl; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class ReadPrmtopDialog + extends JDialog { + + private JPanel panel1 = new JPanel(); + private BorderLayout borderLayout1 = new BorderLayout(); + private JButton helpButton = new JButton(); + private JLabel jLabel1 = new JLabel(); + private JPanel filesPanel = new JPanel(); + private JPanel buttonsPanel = new JPanel(); + private JLabel jLabel2 = new JLabel(); + private JButton cancelButton = new JButton(); + private JButton loadButton = new JButton(); + private JButton coordButton = new JButton(); + private JButton browsePrmtopButton = new JButton(); + private JTextField inpcrdTextField = new JTextField(); + private JTextField prmtopTextField = new JTextField(); + private GridBagLayout gridBagLayout1 = new GridBagLayout(); + private JFileChooser chooser = null; + private AmberPrmtop prmtop = null; + private MoleculeInterface molecule = null; + private static String lastPWDKey = "lastPWD"; + private Preferences prefs = Preferences.userNodeForPackage(getClass()); + private File currentWorkingDirectory = null; + private boolean OKPressed = false; + static final Logger logger = Logger.getLogger(ReadPrmtopDialog.class.getCanonicalName()); + + public ReadPrmtopDialog(Frame owner, String title, boolean modal, + MoleculeInterface mol) { + super(owner, title, modal); + molecule = mol; + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public void setMolecule(MoleculeInterface mol) { + molecule = mol; + } + + public MoleculeInterface getMolecule() { + return molecule; + } + + private ReadPrmtopDialog() { + this(new Frame(), "ReadPrmtopDialog", false, null); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + helpButton.setToolTipText(""); + helpButton.setText("Help"); + helpButton.addActionListener(new ReadPrmtopDialog_helpButton_actionAdapter(this)); + jLabel1.setToolTipText(""); + jLabel1.setText("Coordinate File:"); + jLabel2.setToolTipText(""); + jLabel2.setText("Topology file:"); + cancelButton.setToolTipText(""); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new ReadPrmtopDialog_cancelButton_actionAdapter(this)); + loadButton.setEnabled(false); + loadButton.setToolTipText(""); + loadButton.setText("Load"); + loadButton.addActionListener(new ReadPrmtopDialog_loadButton_actionAdapter(this)); + coordButton.setEnabled(false); + coordButton.setToolTipText(""); + coordButton.setText("Browse"); + coordButton.addActionListener(new ReadPrmtopDialog_coordButton_actionAdapter(this)); + browsePrmtopButton.setToolTipText(""); + browsePrmtopButton.setText("Browse"); + browsePrmtopButton.addActionListener(new ReadPrmtopDialog_browsePrmtopButton_actionAdapter(this)); + inpcrdTextField.setEnabled(false); + inpcrdTextField.setEditable(false); + inpcrdTextField.setText(""); + inpcrdTextField.setColumns(30); + prmtopTextField.setToolTipText(""); + prmtopTextField.setEditable(false); + prmtopTextField.setText(""); + prmtopTextField.setColumns(30); + filesPanel.setLayout(gridBagLayout1); + this.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); + getContentPane().add(panel1); + buttonsPanel.add(loadButton); + buttonsPanel.add(cancelButton); + buttonsPanel.add(helpButton); + panel1.add(buttonsPanel, BorderLayout.SOUTH); + panel1.add(filesPanel, BorderLayout.CENTER); + filesPanel.add(jLabel2, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + filesPanel.add(prmtopTextField, + new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + filesPanel.add(browsePrmtopButton, + new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + filesPanel.add(jLabel1, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + filesPanel.add(inpcrdTextField, + new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.NORTH, + GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + filesPanel.add(coordButton, new GridBagConstraints(2, 1, 1, 1, 0.0, 1.0, GridBagConstraints.NORTH, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + } + + public boolean isOKPressed() { + return OKPressed; + } + + public void coordButton_actionPerformed(ActionEvent e) { + if (chooser == null) { + javax.swing.filechooser.FileFilter[] filters = FileFilterImpl.getFileFilters( + MolecularFileFormats.getUpdateCoordFormats()); + chooser = new JFileChooser(); + for (int i = 0; i < filters.length; i++) { + chooser.addChoosableFileFilter(filters[i]); + } + + chooser.setAcceptAllFileFilterUsed(false); + chooser.setDialogTitle("Open File with coordinates"); + chooser.setDialogType(JFileChooser.OPEN_DIALOG); + } + + if (currentWorkingDirectory != null) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } else { + String lastPWD = prefs.get(lastPWDKey, ""); + if (lastPWD.length() > 0) { + currentWorkingDirectory = new File(lastPWD); + if (currentWorkingDirectory.isDirectory() + && currentWorkingDirectory.exists()) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } + } + } + + int returnVal = chooser.showOpenDialog(this); + + if (returnVal == JFileChooser.APPROVE_OPTION) { + String fileName = chooser.getSelectedFile().getPath(); + currentWorkingDirectory = chooser.getCurrentDirectory(); + + try { + prefs.put(lastPWDKey, currentWorkingDirectory.getAbsolutePath()); + } catch (Exception ex) { + System.err.println("Cannot save cwd: " + ex.getMessage() + + " Ignored..."); + } + logger.info("You chose to open this file: " + + fileName); + + try { + Molecule.updateCoordinates(molecule, + chooser.getFileFilter(). + getDescription(), + fileName); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + this.loadButton.setEnabled(true); + inpcrdTextField.setText(fileName); + //return fileName; + } + + } + + public void browsePrmtopButton_actionPerformed(ActionEvent e) { + FileDialog fd = new FileDialog(this, "Open Amber Topology File (prmtop)", + FileDialog.LOAD); + fd.setFile("*.top;prmtop"); + fd.setVisible(true); + if (fd.getFile() == null) { + return; + } + + String fileName = fd.getFile(); + String workingDirectory = fd.getDirectory(); + + prmtop = new AmberPrmtop(); + try { + prmtop.parsePrmtop(molecule, workingDirectory + fileName); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + if (prmtop.getNumberOfAtoms() < 1) { + JOptionPane.showMessageDialog(this, + "Didn't find atoms in file", + "Didn't find atoms in file", + JOptionPane.ERROR_MESSAGE); + return; + } + + JOptionPane.showMessageDialog(this, + "Found " + prmtop.getNumberOfAtoms() + + " atoms in file", "Info", + JOptionPane.INFORMATION_MESSAGE); + + inpcrdTextField.setEnabled(true); + coordButton.setEnabled(true); + + prmtopTextField.setEnabled(false); + prmtopTextField.setText(workingDirectory + fileName); + prmtopTextField.setEnabled(true); + } + + public void loadButton_actionPerformed(ActionEvent e) { + this.OKPressed = true; + prmtopTextField.setText(""); + inpcrdTextField.setText(""); + this.loadButton.setEnabled(false); + coordButton.setEnabled(false); + this.setVisible(false); + } + + public void cancelButton_actionPerformed(ActionEvent e) { + this.OKPressed = false; + prmtopTextField.setText(""); + inpcrdTextField.setText(""); + this.loadButton.setEnabled(false); + coordButton.setEnabled(false); + this.setVisible(false); + } + + public void helpButton_actionPerformed(ActionEvent e) { + JOptionPane.showMessageDialog(this, + "Download topology file first. Then download coordinates and press Load button", + "Help", + JOptionPane.INFORMATION_MESSAGE); + } +} + +class ReadPrmtopDialog_helpButton_actionAdapter + implements ActionListener { + + private ReadPrmtopDialog adaptee; + + ReadPrmtopDialog_helpButton_actionAdapter(ReadPrmtopDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.helpButton_actionPerformed(e); + } +} + +class ReadPrmtopDialog_cancelButton_actionAdapter + implements ActionListener { + + private ReadPrmtopDialog adaptee; + + ReadPrmtopDialog_cancelButton_actionAdapter(ReadPrmtopDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.cancelButton_actionPerformed(e); + } +} + +class ReadPrmtopDialog_loadButton_actionAdapter + implements ActionListener { + + private ReadPrmtopDialog adaptee; + + ReadPrmtopDialog_loadButton_actionAdapter(ReadPrmtopDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.loadButton_actionPerformed(e); + } +} + +class ReadPrmtopDialog_browsePrmtopButton_actionAdapter + implements ActionListener { + + private ReadPrmtopDialog adaptee; + + ReadPrmtopDialog_browsePrmtopButton_actionAdapter(ReadPrmtopDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.browsePrmtopButton_actionPerformed(e); + } +} + +class ReadPrmtopDialog_coordButton_actionAdapter + implements ActionListener { + + private ReadPrmtopDialog adaptee; + + ReadPrmtopDialog_coordButton_actionAdapter(ReadPrmtopDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.coordButton_actionPerformed(e); + } +} diff --git a/src/main/java/cct/amber/Sander8Frame.java b/src/main/java/cct/amber/Sander8Frame.java new file mode 100644 index 0000000..5eacec2 --- /dev/null +++ b/src/main/java/cct/amber/Sander8Frame.java @@ -0,0 +1,3992 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.amber; + +import java.awt.BorderLayout; +import java.awt.CardLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FileDialog; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTabbedPane; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.JToolBar; +import javax.swing.SwingConstants; +import javax.swing.border.TitledBorder; + +import cct.tools.FortranNamelist; +import cct.tools.IOUtils; + +/** + *

Title: Preparation of input file for Sander 8 program

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Sander8Frame + extends JFrame implements SanderInputParserInterface { + JPanel contentPane; + BorderLayout borderLayout1 = new BorderLayout(); + JMenuBar jMenuBar1 = new JMenuBar(); + JMenu jMenuFile = new JMenu(); + JMenuItem jMenuFileExit = new JMenuItem(); + JMenu jMenuHelp = new JMenu(); + JMenuItem jMenuHelpAbout = new JMenuItem(); + JToolBar jToolBar = new JToolBar(); + JButton openFile_Button = new JButton(); + JButton newFile_Button = new JButton(); + JButton help_Button = new JButton(); + ImageIcon image1 = new ImageIcon(Sander8Frame.class.getResource("openFile.png")); + ImageIcon image2 = new ImageIcon(Sander8Frame.class.getResource("closeFile.png")); + ImageIcon saveFileImage = new ImageIcon(Sander8Frame.class.getResource("Save-Icon-16x16.gif")); + ImageIcon image3 = new ImageIcon(Sander8Frame.class.getResource("help.png")); + JTabbedPane jTabbedPane1 = new JTabbedPane(); + JPanel jobTypePanel = new JPanel(); + JPanel potentialFuncPanel = new JPanel(); + JTextArea descriptionPane = new JTextArea(); + JPanel descrPanel = new JPanel(); + BorderLayout borderLayout2 = new BorderLayout(); + BorderLayout borderLayout3 = new BorderLayout(); + + Sander8JobControl s8jc = null; + FortranNamelist cntrl = null; + String fileContent = null; + String fileName = null; + String workingDirectory = null; + TextEditorFrame inputEditor = null; + Map controlsTable = new HashMap(); + boolean comboBoxAdjusting = false; + + JComboBox NTF_ComboBox = new JComboBox(); + JComboBox NTB_ComboBox = new JComboBox(); + JTextField DIELC_TextField = new JTextField(); + JTextField CUT_TextField = new JTextField(); + JTextField SCNB_TextField = new JTextField(); + JTextField SCEE_TextField = new JTextField(); + JTextField NSNB_TextField = new JTextField(); + JComboBox IPOL_ComboBox = new JComboBox(); + JPanel GB_Panel = new JPanel(); + JPanel PME_Panel = new JPanel(); + JPanel jPanel1 = new JPanel(); + BorderLayout borderLayout5 = new BorderLayout(); + JComboBox IMIN_ComboBox = new JComboBox(); + JPanel ioPanel = new JPanel(); + JPanel outputPanel = new JPanel(); + JPanel inputPanel = new JPanel(); + BorderLayout borderLayout6 = new BorderLayout(); + JPanel restrainPanel = new JPanel(); + JPanel cardsPanel = new JPanel(); + CardLayout cardLayout1 = new CardLayout(); + JPanel minCard = new JPanel(); + JPanel mdCard = new JPanel(); + JLabel methodLabel = new JLabel(); + JComboBox NTMIN_ComboBox = new JComboBox(); + JLabel maxIterLabel = new JLabel(); + JTextField MAXCYC_TextField = new JTextField(); + JLabel dxLabel = new JLabel(); + JLabel switchLabel = new JLabel(); + JLabel covergLabel = new JLabel(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + JTextField NCYC_TextField = new JTextField(); + JTextField DX0_TextField = new JTextField(); + JTextField DRMS_TextField = new JTextField(); + GridBagLayout gridBagLayout2 = new GridBagLayout(); + JComboBox IREST_ComboBox = new JComboBox(); + GridBagLayout gridBagLayout3 = new GridBagLayout(); + JLabel NSTLIM_Label = new JLabel(); + JTextField NSTLIM_TextField = new JTextField(); + JLabel TEMP0_Label = new JLabel(); + JTextField TEMP0_TextField = new JTextField(); + JLabel DT_Label = new JLabel(); + JTextField DT_TextField = new JTextField(); + JPanel MolDynPanel = new JPanel(); + GridBagLayout gridBagLayout4 = new GridBagLayout(); + JLabel NSCM_Label = new JLabel(); + JTextField NSCM_TextField = new JTextField(); + JLabel NRESPA_Label = new JLabel(); + JTextField NRESPA_TextField = new JTextField(); + JLabel T_Label = new JLabel(); + JTextField T_TextField = new JTextField(); + JLabel NTT_Label = new JLabel(); + JComboBox NTT_ComboBox = new JComboBox(); + JLabel TEMP0LES_Label = new JLabel(); + JTextField TEMP0LES_TextField = new JTextField(); + JLabel TEMPI_Label = new JLabel(); + JTextField TEMPI_TextField = new JTextField(); + JLabel IG_Label = new JLabel(); + JTextField IG_TextField = new JTextField(); + JLabel TAUTP_Label = new JLabel(); + JTextField TAUTP_TextField = new JTextField(); + JLabel GAMMA_LN_Label = new JLabel(); + JTextField GAMMA_LN_TextField = new JTextField(); + JLabel VRAND_Label = new JLabel(); + JTextField VRAND_TextField = new JTextField(); + JLabel VLIMIT_Label = new JLabel(); + JTextField VLIMIT_TextField = new JTextField(); + JPanel TempControlPanel = new JPanel(); + GridBagLayout gridBagLayout5 = new GridBagLayout(); + JLabel NTP_Label = new JLabel(); + JComboBox NTP_ComboBox = new JComboBox(); + JLabel PRES0_Label = new JLabel(); + JTextField PRES0_TextField = new JTextField(); + JLabel COMP_Label = new JLabel(); + JTextField COMP_TextField = new JTextField(); + JPanel PressureControlPanel = new JPanel(); + JLabel TAUP_Label = new JLabel(); + JTextField TAUP_TextField = new JTextField(); + JLabel NSNB_Label = new JLabel(); + JLabel SCEE_Label = new JLabel(); + JLabel IPOL_Label = new JLabel(); + JLabel NTF_Label = new JLabel(); + JLabel NTB_Label = new JLabel(); + JLabel NTXO_Label = new JLabel(); + JComboBox NTXO_ComboBox = new JComboBox(); + JLabel NTPR_Label = new JLabel(); + JTextField NTPR_TextField = new JTextField(); + JLabel NTX_Label = new JLabel(); + JComboBox NTX_ComboBox = new JComboBox(); + JLabel NTRX_Label = new JLabel(); + JComboBox NTRX_ComboBox = new JComboBox(); + JLabel NTAVE_Label = new JLabel(); + JTextField NTAVE_TextField = new JTextField(); + JLabel NTWR_Label = new JLabel(); + JTextField NTWR_TextField = new JTextField(); + JLabel IWRAP_Label = new JLabel(); + JComboBox IWRAP_ComboBox = new JComboBox(); + FlowLayout flowLayout2 = new FlowLayout(); + JLabel NTWX_Label = new JLabel(); + JTextField NTWX_TextField = new JTextField(); + JLabel NTWV_Label = new JLabel(); + JTextField NTWV_TextField = new JTextField(); + JLabel NTWE_Label = new JLabel(); + JTextField NTWE_TextField = new JTextField(); + JLabel IOUTFM_Label = new JLabel(); + JComboBox IOUTFM_ComboBox = new JComboBox(); + JLabel NTWPRT_Label = new JLabel(); + JTextField NTWPRT_TextField = new JTextField(); + JLabel IDECOMP_Label = new JLabel(); + JComboBox IDECOMP_ComboBox = new JComboBox(); + JComboBox IGB_ComboBox = new JComboBox(); + JLabel INTDIEL_Label = new JLabel(); + JTextField INTDIEL_TextField = new JTextField(); + JLabel EXTDIEL_Label = new JLabel(); + JTextField EXTDIEL_TextField = new JTextField(); + JLabel SALTCON_Label = new JLabel(); + JTextField SALTCON_TextField = new JTextField(); + JLabel RGBMAX_Label = new JLabel(); + JTextField RGBMAX_TextField = new JTextField(); + JLabel RBORNSTAT_Label = new JLabel(); + JComboBox RBORNSTAT_ComboBox = new JComboBox(); + JLabel OFFSET_Label = new JLabel(); + JTextField OFFSET_TextField = new JTextField(); + JLabel GBSA_Label = new JLabel(); + JComboBox GBSA_ComboBox = new JComboBox(); + JLabel RDT_Label = new JLabel(); + JLabel SURFTEN_Label = new JLabel(); + JTextField RDT_TextField = new JTextField(); + JTextField SURFTEN_TextField = new JTextField(); + GridBagLayout gridBagLayout7 = new GridBagLayout(); + GridBagLayout gridBagLayout8 = new GridBagLayout(); + JLabel GB_Dummy_Label = new JLabel(); + JLabel DIELC_Label = new JLabel(); + JLabel CUT_Label = new JLabel(); + JLabel SCNB_Label = new JLabel(); + JMenuItem Edit_MenuItem = new JMenuItem(); + FlowLayout flowLayout3 = new FlowLayout(); + JLabel NTR_Label = new JLabel(); + JComboBox NTR_ComboBox = new JComboBox(); + JLabel IBELLY_Label = new JLabel(); + JComboBox IBELLY_ComboBox = new JComboBox(); + JLabel BELLYMASK_Label = new JLabel(); + JLabel RESTRAINTMASK_Label = new JLabel(); + JLabel RESTRAINT_WT_Label = new JLabel(); + JTextField BELLYMASK_TextField = new JTextField(); + JTextField RESTRAINTMASK_TextField = new JTextField(); + JTextField RESTRAINT_WT_TextField = new JTextField(); + JLabel FCAP_Label = new JLabel(); + JLabel IVCAP_Label = new JLabel(); + JComboBox IVCAP_ComboBox = new JComboBox(); + JTextField FCAP_TextField = new JTextField(); + JPanel shakePanel = new JPanel(); + JLabel HWTNM2_Label = new JLabel(); + JLabel HWTNM1_Label = new JLabel(); + JLabel OWTNM_Label = new JLabel(); + JLabel WATNAM_Label = new JLabel(); + JLabel TOL_Label = new JLabel(); + JLabel JFASTW_Label = new JLabel(); + JLabel NTC_Label = new JLabel(); + JComboBox JFASTW_ComboBox = new JComboBox(); + JComboBox NTC_ComboBox = new JComboBox(); + JTextField HWTNM2_TextField = new JTextField(); + JTextField HWTNM1_TextField = new JTextField(); + JTextField WATNAM_TextField = new JTextField(); + JTextField OWTNM_TextField = new JTextField(); + JTextField TOL_TextField = new JTextField(); + GridBagLayout gridBagLayout6 = new GridBagLayout(); + GridBagLayout gridBagLayout9 = new GridBagLayout(); + JLabel jLabel6 = new JLabel(); + private GridBagLayout gridBagLayout10 = new GridBagLayout(); + private JLabel Dummy_MD_Label = new JLabel(); + private JButton saveFile_Button = new JButton(); + private JMenuItem jMenuItem1 = new JMenuItem(); + private JMenuItem jMenuItem2 = new JMenuItem(); + + public Sander8Frame(Sander8JobControl jc) { + try { + setDefaultCloseOperation(EXIT_ON_CLOSE); + s8jc = jc; + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + /** + * Component initialization. + * + * @throws Exception + */ + private void jbInit() throws Exception { + contentPane = (JPanel) getContentPane(); + contentPane.setLayout(borderLayout1); + setSize(new Dimension(694, 337)); + setTitle("Sander 8 Job Controls"); + jMenuFile.setText("File"); + jMenuFileExit.setToolTipText("Exit Program"); + jMenuFileExit.setText("Exit"); + jMenuFileExit.addActionListener(new + Sander8Frame_jMenuFileExit_ActionAdapter(this)); + jMenuHelp.setText("Help"); + jMenuHelpAbout.setText("About"); + jMenuHelpAbout.addActionListener(new + Sander8Frame_jMenuHelpAbout_ActionAdapter(this)); + descriptionPane.setToolTipText(""); + descriptionPane.setEditable(false); + descriptionPane.setText("Options description will be shown here"); + descriptionPane.setLineWrap(true); + descriptionPane.setRows(6); + descriptionPane.setWrapStyleWord(true); + descrPanel.setLayout(borderLayout2); + descrPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color. + lightGray, 1), "Option Description")); + potentialFuncPanel.setLayout(gridBagLayout10); + NTF_ComboBox.addItemListener(new Sander8Frame_NTF_ComboBox_itemAdapter(this)); + NTB_ComboBox.addItemListener(new Sander8Frame_NTB_ComboBox_itemAdapter(this)); + DIELC_TextField.setToolTipText("Enter new value and press Enter"); + DIELC_TextField.setText(" "); + DIELC_TextField.setColumns(5); + CUT_TextField.setToolTipText("Enter new value and press Enter"); + CUT_TextField.setText(" "); + CUT_TextField.setColumns(5); + SCNB_TextField.setToolTipText("Enter new value and press Enter"); + SCNB_TextField.setText(" "); + SCNB_TextField.setColumns(5); + SCEE_TextField.setToolTipText("Enter new value and press Enter"); + SCEE_TextField.setText(" "); + SCEE_TextField.setColumns(5); + NSNB_TextField.setToolTipText("Enter new value and press Enter"); + NSNB_TextField.setText(" "); + NSNB_TextField.setColumns(5); + IPOL_ComboBox.addItemListener(new Sander8Frame_IPOL_ComboBox_itemAdapter(this)); + GB_Panel.setEnabled(false); + GB_Panel.setToolTipText("Generalized Born/Surface Area options"); + GB_Panel.setLayout(gridBagLayout8); + PME_Panel.setEnabled(false); + PME_Panel.setToolTipText("The Particle Mesh Ewald (PME) method options"); + jobTypePanel.setLayout(borderLayout5); + jPanel1.setLayout(gridBagLayout2); + IMIN_ComboBox.addItemListener(new Sander8Frame_IMIN_ComboBox_itemAdapter(this)); + ioPanel.setToolTipText("Nature and format of the input and output"); + ioPanel.setLayout(borderLayout6); + inputPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color. + lightGray, 1), "Nature and format of the input")); + inputPanel.setLayout(flowLayout2); + outputPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color. + lightGray, 1), "Nature and format of the output")); + outputPanel.setLayout(gridBagLayout7); + restrainPanel.setToolTipText("Option for the Frozen or restrained atoms"); + restrainPanel.setLayout(gridBagLayout9); + cardsPanel.setLayout(cardLayout1); + NTMIN_ComboBox.addItemListener(new Sander8Frame_NTMIN_ComboBox_itemAdapter(this)); + maxIterLabel.setToolTipText(""); + maxIterLabel.setHorizontalAlignment(SwingConstants.RIGHT); + maxIterLabel.setText("Max Iterations (MAXCYC):"); + maxIterLabel.addMouseListener(new Sander8Frame_maxIterLabel_mouseAdapter(this)); + MAXCYC_TextField.setToolTipText(""); + MAXCYC_TextField.setText(" "); + MAXCYC_TextField.setColumns(6); + MAXCYC_TextField.addActionListener(new + Sander8Frame_MAXCYC_TextField_actionAdapter(this)); + minCard.setLayout(gridBagLayout1); + dxLabel.setToolTipText(""); + dxLabel.setHorizontalAlignment(SwingConstants.RIGHT); + dxLabel.setText("Initial step length (DX0): "); + dxLabel.addMouseListener(new Sander8Frame_dxLabel_mouseAdapter(this)); + switchLabel.setToolTipText(""); + switchLabel.setHorizontalAlignment(SwingConstants.RIGHT); + switchLabel.setText("Switch (NCYC): "); + switchLabel.addMouseListener(new Sander8Frame_switchLabel_mouseAdapter(this)); + covergLabel.setToolTipText(""); + covergLabel.setHorizontalAlignment(SwingConstants.RIGHT); + covergLabel.setText("Convergence criterion (DRMS): "); + covergLabel.addMouseListener(new Sander8Frame_covergLabel_mouseAdapter(this)); + NCYC_TextField.setToolTipText(""); + NCYC_TextField.setText(" "); + NCYC_TextField.setColumns(6); + NCYC_TextField.addActionListener(new + Sander8Frame_NCYC_TextField_actionAdapter(this)); + DX0_TextField.setColumns(6); + DX0_TextField.addActionListener(new + Sander8Frame_DX0_TextField_actionAdapter(this)); + DRMS_TextField.setToolTipText(""); + DRMS_TextField.setColumns(6); + DRMS_TextField.addActionListener(new + Sander8Frame_DRMS_TextField_actionAdapter(this)); + IREST_ComboBox.addItemListener(new Sander8Frame_IREST_ComboBox_itemAdapter(this)); + mdCard.setLayout(gridBagLayout3); + NSTLIM_Label.setToolTipText(""); + NSTLIM_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NSTLIM_Label.setText("Number of MD Steps (nstlim): "); + NSTLIM_Label.addMouseListener(new Sander8Frame_NSTLIM_Label_mouseAdapter(this)); + NSTLIM_TextField.setText(" "); + NSTLIM_TextField.setColumns(6); + NSTLIM_TextField.setHorizontalAlignment(SwingConstants.LEFT); + NSTLIM_TextField.addActionListener(new + Sander8Frame_NSTLIM_TextField_actionAdapter(this)); + TEMP0_Label.setToolTipText("Reference Temperature, K"); + TEMP0_Label.setHorizontalAlignment(SwingConstants.RIGHT); + TEMP0_Label.setText("Temperature (temp0), K: "); + TEMP0_Label.addMouseListener(new Sander8Frame_TEMP0_Label_mouseAdapter(this)); + TEMP0_TextField.setText(" "); + TEMP0_TextField.setColumns(6); + DT_Label.setToolTipText(""); + DT_Label.setHorizontalAlignment(SwingConstants.RIGHT); + DT_Label.setText("Time Step, psec (dt): "); + DT_Label.addMouseListener(new Sander8Frame_DT_Label_mouseAdapter(this)); + DT_TextField.setText(" "); + DT_TextField.setColumns(6); + MolDynPanel.setToolTipText( + "Additional Options for Molecular Dynamics Simulation"); + MolDynPanel.setLayout(gridBagLayout4); + jTabbedPane1.setToolTipText(""); + NSCM_Label.setToolTipText(""); + NSCM_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NSCM_Label.setText("NSCM: "); + NSCM_Label.addMouseListener(new Sander8Frame_jLabel10_mouseAdapter(this)); + NSCM_TextField.setColumns(6); + NRESPA_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NRESPA_Label.setText("NRESPA: "); + NRESPA_Label.addMouseListener(new Sander8Frame_NRESPA_Label_mouseAdapter(this)); + NRESPA_TextField.setText(" "); + NRESPA_TextField.setColumns(6); + T_Label.setHorizontalAlignment(SwingConstants.RIGHT); + T_Label.setText("T: "); + T_Label.addMouseListener(new Sander8Frame_T_Label_mouseAdapter(this)); + T_TextField.setText(" "); + T_TextField.setColumns(6); + NTT_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTT_Label.setText("Temperature Scaling (ntt): "); + NTT_Label.addMouseListener(new Sander8Frame_NTT_Label_mouseAdapter(this)); + TEMP0LES_Label.setToolTipText(""); + TEMP0LES_Label.setHorizontalAlignment(SwingConstants.RIGHT); + TEMP0LES_Label.setText("TEMP0LES: "); + TEMP0LES_Label.addMouseListener(new + Sander8Frame_TEMP0LES_Label_mouseAdapter(this)); + TEMP0LES_TextField.setToolTipText(""); + TEMP0LES_TextField.setColumns(6); + TEMPI_Label.setToolTipText(""); + TEMPI_Label.setHorizontalAlignment(SwingConstants.RIGHT); + TEMPI_Label.setText("TEMPI: "); + TEMPI_Label.addMouseListener(new Sander8Frame_TEMPI_Label_mouseAdapter(this)); + TEMPI_TextField.setText(" "); + TEMPI_TextField.setColumns(6); + IG_Label.setHorizontalAlignment(SwingConstants.RIGHT); + IG_Label.setText("Seed (ig): "); + IG_Label.addMouseListener(new Sander8Frame_IG_Label_mouseAdapter(this)); + IG_TextField.setToolTipText(""); + IG_TextField.setText(" "); + IG_TextField.setColumns(6); + TAUTP_Label.setToolTipText(""); + TAUTP_Label.setHorizontalAlignment(SwingConstants.RIGHT); + TAUTP_Label.setText("Temperature coupling, ps (tautp): "); + TAUTP_Label.addMouseListener(new Sander8Frame_TAUTP_Label_mouseAdapter(this)); + TAUTP_TextField.setToolTipText(""); + TAUTP_TextField.setText(" "); + TAUTP_TextField.setColumns(6); + GAMMA_LN_Label.setToolTipText(""); + GAMMA_LN_Label.setHorizontalAlignment(SwingConstants.RIGHT); + GAMMA_LN_Label.setText("GAMMA_LN: "); + GAMMA_LN_Label.addMouseListener(new + Sander8Frame_GAMMA_LN_Label_mouseAdapter(this)); + GAMMA_LN_TextField.setText(" "); + GAMMA_LN_TextField.setColumns(6); + VRAND_Label.setHorizontalAlignment(SwingConstants.RIGHT); + VRAND_Label.setText("VRAND: "); + VRAND_Label.addMouseListener(new Sander8Frame_VRAND_Label_mouseAdapter(this)); + VRAND_TextField.setToolTipText(""); + VRAND_TextField.setText(" "); + VRAND_TextField.setColumns(6); + VLIMIT_Label.setToolTipText(""); + VLIMIT_Label.setHorizontalAlignment(SwingConstants.RIGHT); + VLIMIT_Label.setText("VLIMIT: "); + VLIMIT_Label.addMouseListener(new Sander8Frame_VLIMIT_Label_mouseAdapter(this)); + VLIMIT_TextField.setText(" "); + VLIMIT_TextField.setColumns(6); + TempControlPanel.setLayout(gridBagLayout5); + TempControlPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder( + Color.lightGray, 1), "Temperature Regulation")); + NTP_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTP_Label.setText("Pressure Scaling (ntp): "); + NTP_Label.addMouseListener(new Sander8Frame_NTP_Label_mouseAdapter(this)); + PRES0_Label.setToolTipText("Reference Pressure, bars"); + PRES0_Label.setHorizontalAlignment(SwingConstants.RIGHT); + PRES0_Label.setText("Pressure, bars (pres0): "); + PRES0_Label.addMouseListener(new Sander8Frame_PRES0_Label_mouseAdapter(this)); + PRES0_TextField.setToolTipText(""); + PRES0_TextField.setText(" "); + PRES0_TextField.setColumns(6); + COMP_Label.setHorizontalAlignment(SwingConstants.RIGHT); + COMP_Label.setText("COMP: "); + COMP_Label.addMouseListener(new Sander8Frame_COMP_Label_mouseAdapter(this)); + COMP_TextField.setToolTipText(""); + COMP_TextField.setText(" "); + COMP_TextField.setColumns(6); + PressureControlPanel.setLayout(flowLayout3); + TAUP_Label.setHorizontalAlignment(SwingConstants.RIGHT); + TAUP_Label.setText("Pressure Coupling, ps (taup): "); + TAUP_Label.addMouseListener(new Sander8Frame_TAUP_Label_mouseAdapter(this)); + TAUP_TextField.setToolTipText(""); + TAUP_TextField.setText(" "); + TAUP_TextField.setColumns(6); + PressureControlPanel.setBorder(new TitledBorder(BorderFactory. + createLineBorder(Color.lightGray, 2), "Pressure Regulation")); + NTT_ComboBox.addItemListener(new Sander8Frame_NTT_ComboBox_itemAdapter(this)); + NTP_ComboBox.addItemListener(new Sander8Frame_NTP_ComboBox_itemAdapter(this)); + jPanel1.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color. + lightGray, 1), "Job Control")); + minCard.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color. + lightGray, 1), "Energy Minimization Options")); + mdCard.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color. + lightGray, 1), "Molecular Dynamics Options")); + NSNB_Label.setToolTipText(""); + NSNB_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NSNB_Label.setText("NB List Update (nsnb): "); + NSNB_Label.addMouseListener(new Sander8Frame_NSNB_Label_mouseAdapter(this)); + SCEE_Label.setToolTipText(""); + SCEE_Label.setHorizontalAlignment(SwingConstants.RIGHT); + SCEE_Label.setText("SCEE: "); + SCEE_Label.addMouseListener(new Sander8Frame_SCEE_Label_mouseAdapter(this)); + IPOL_Label.setToolTipText(""); + IPOL_Label.setHorizontalAlignment(SwingConstants.RIGHT); + IPOL_Label.setText("Polarization On/Off (ipol): "); + IPOL_Label.addMouseListener(new Sander8Frame_IPOL_Label_mouseAdapter(this)); + NTF_Label.setToolTipText(""); + NTF_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTF_Label.setText("Force Evaluation (ntf): "); + NTF_Label.addMouseListener(new Sander8Frame_NTF_Label_mouseAdapter(this)); + NTB_Label.setToolTipText(""); + NTB_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTB_Label.setText("Periodic Boundary (ntb): "); + NTB_Label.addMouseListener(new Sander8Frame_NTB_Label_mouseAdapter(this)); + openFile_Button.addActionListener(new Sander8Frame_jButton1_actionAdapter(this)); + newFile_Button.addActionListener(new Sander8Frame_jButton2_actionAdapter(this)); + help_Button.addActionListener(new Sander8Frame_jButton3_actionAdapter(this)); + NTXO_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTXO_Label.setText("NTXO: "); + NTXO_Label.addMouseListener(new Sander8Frame_NTXO_Label_mouseAdapter(this)); + NTPR_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTPR_Label.setText("NTPR: "); + NTPR_Label.addMouseListener(new Sander8Frame_NTPR_Label_mouseAdapter(this)); + NTPR_TextField.setText(" "); + NTPR_TextField.setColumns(6); + NTX_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTX_Label.setText("NTX: "); + NTX_Label.addMouseListener(new Sander8Frame_NTX_Label_mouseAdapter(this)); + NTRX_Label.setToolTipText(""); + NTRX_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTRX_Label.setText(" NTRX: "); + NTRX_Label.addMouseListener(new Sander8Frame_NTRX_Label_mouseAdapter(this)); + NTAVE_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTAVE_Label.setText("NTAVE: "); + NTAVE_Label.addMouseListener(new Sander8Frame_NTAVE_Label_mouseAdapter(this)); + NTAVE_TextField.setText(" "); + NTAVE_TextField.setColumns(6); + NTWR_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTWR_Label.setText("NTWR: "); + NTWR_Label.addMouseListener(new Sander8Frame_NTWR_Label_mouseAdapter(this)); + NTWR_TextField.setText(" "); + NTWR_TextField.setColumns(6); + IWRAP_Label.setHorizontalAlignment(SwingConstants.RIGHT); + IWRAP_Label.setText("IWRAP: "); + IWRAP_Label.addMouseListener(new Sander8Frame_IWRAP_Label_mouseAdapter(this)); + flowLayout2.setAlignment(FlowLayout.LEFT); + NTWX_Label.setToolTipText(""); + NTWX_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTWX_Label.setText("NTWX: "); + NTWX_Label.addMouseListener(new Sander8Frame_NTWX_Label_mouseAdapter(this)); + NTWX_TextField.setText(" "); + NTWX_TextField.setColumns(6); + NTWV_Label.setToolTipText(""); + NTWV_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTWV_Label.setText(" NTWV: "); + NTWV_Label.addMouseListener(new Sander8Frame_NTWV_Label_mouseAdapter(this)); + NTWV_TextField.setText(" "); + NTWV_TextField.setColumns(6); + NTWE_Label.setToolTipText(""); + NTWE_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTWE_Label.setText(" NTWE: "); + NTWE_Label.addMouseListener(new Sander8Frame_NTWE_Label_mouseAdapter(this)); + NTWE_TextField.setText(" "); + NTWE_TextField.setColumns(6); + IOUTFM_Label.setToolTipText(""); + IOUTFM_Label.setHorizontalAlignment(SwingConstants.RIGHT); + IOUTFM_Label.setText(" IOUTFM: "); + IOUTFM_Label.addMouseListener(new Sander8Frame_IOUTFM_Label_mouseAdapter(this)); + NTWPRT_Label.setToolTipText(""); + NTWPRT_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTWPRT_Label.setText(" NTWPRT: "); + NTWPRT_Label.addMouseListener(new Sander8Frame_NTWPRT_Label_mouseAdapter(this)); + NTWPRT_TextField.setText(" "); + NTWPRT_TextField.setColumns(6); + IDECOMP_Label.setToolTipText(""); + IDECOMP_Label.setHorizontalAlignment(SwingConstants.RIGHT); + IDECOMP_Label.setText(" IDECOMP: "); + IDECOMP_Label.addMouseListener(new Sander8Frame_IDECOMP_Label_mouseAdapter(this)); + IMIN_ComboBox.setToolTipText("Type of calculation"); + IMIN_ComboBox.addMouseListener(new Sander8Frame_IMIN_ComboBox_mouseAdapter(this)); + IGB_ComboBox.setToolTipText("General Born/Surface Area"); + IGB_ComboBox.addMouseListener(new Sander8Frame_IGB_ComboBox_mouseAdapter(this)); + IGB_ComboBox.addItemListener(new Sander8Frame_IGB_ComboBox_itemAdapter(this)); + INTDIEL_Label.setToolTipText(""); + INTDIEL_Label.setHorizontalAlignment(SwingConstants.RIGHT); + INTDIEL_Label.setText(" INTDIEL: "); + INTDIEL_Label.addMouseListener(new Sander8Frame_INTDIEL_Label_mouseAdapter(this)); + INTDIEL_TextField.setToolTipText(""); + INTDIEL_TextField.setText(" "); + INTDIEL_TextField.setColumns(6); + EXTDIEL_Label.setToolTipText(""); + EXTDIEL_Label.setHorizontalAlignment(SwingConstants.RIGHT); + EXTDIEL_Label.setText(" EXTDIEL: "); + EXTDIEL_Label.addMouseListener(new Sander8Frame_EXTDIEL_Label_mouseAdapter(this)); + EXTDIEL_TextField.setToolTipText(""); + EXTDIEL_TextField.setText(" "); + EXTDIEL_TextField.setColumns(6); + SALTCON_Label.setToolTipText(""); + SALTCON_Label.setHorizontalAlignment(SwingConstants.RIGHT); + SALTCON_Label.setText(" SALTCON: "); + SALTCON_Label.addMouseListener(new Sander8Frame_SALTCON_Label_mouseAdapter(this)); + SALTCON_TextField.setToolTipText(""); + SALTCON_TextField.setText(" "); + SALTCON_TextField.setColumns(6); + RGBMAX_Label.setToolTipText(""); + RGBMAX_Label.setHorizontalAlignment(SwingConstants.RIGHT); + RGBMAX_Label.setText(" RGBMAX: "); + RGBMAX_Label.addMouseListener(new Sander8Frame_RGBMAX_Label_mouseAdapter(this)); + RGBMAX_TextField.setToolTipText(""); + RGBMAX_TextField.setText(" "); + RGBMAX_TextField.setColumns(6); + RBORNSTAT_Label.setToolTipText(""); + RBORNSTAT_Label.setHorizontalAlignment(SwingConstants.RIGHT); + RBORNSTAT_Label.setText(" RBORNSTAT: "); + RBORNSTAT_Label.addMouseListener(new + Sander8Frame_RBORNSTAT_Label_mouseAdapter(this)); + OFFSET_Label.setToolTipText(""); + OFFSET_Label.setHorizontalAlignment(SwingConstants.RIGHT); + OFFSET_Label.setText(" OFFSET: "); + OFFSET_Label.addMouseListener(new Sander8Frame_OFFSET_Label_mouseAdapter(this)); + OFFSET_TextField.setToolTipText(""); + OFFSET_TextField.setText(" "); + OFFSET_TextField.setColumns(6); + GBSA_Label.setToolTipText(""); + GBSA_Label.setHorizontalAlignment(SwingConstants.RIGHT); + GBSA_Label.setText(" GBSA: "); + GBSA_Label.addMouseListener(new Sander8Frame_GBSA_Label_mouseAdapter(this)); + RDT_Label.setToolTipText(""); + RDT_Label.setHorizontalAlignment(SwingConstants.RIGHT); + RDT_Label.setText(" RDT: "); + RDT_Label.addMouseListener(new Sander8Frame_RDT_Label_mouseAdapter(this)); + SURFTEN_Label.setToolTipText(""); + SURFTEN_Label.setHorizontalAlignment(SwingConstants.RIGHT); + SURFTEN_Label.setText(" SURFTEN: "); + SURFTEN_Label.addMouseListener(new Sander8Frame_SURFTEN_Label_mouseAdapter(this)); + RDT_TextField.setToolTipText(""); + RDT_TextField.setText(" "); + RDT_TextField.setColumns(6); + SURFTEN_TextField.setToolTipText(""); + SURFTEN_TextField.setText(" "); + SURFTEN_TextField.setColumns(6); + GB_Dummy_Label.setToolTipText(""); + GB_Dummy_Label.setHorizontalAlignment(SwingConstants.RIGHT); + GB_Dummy_Label.setText(" "); + RBORNSTAT_ComboBox.addItemListener(new + Sander8Frame_RBORNSTAT_ComboBox_itemAdapter(this)); + GBSA_ComboBox.addItemListener(new Sander8Frame_GBSA_ComboBox_itemAdapter(this)); + NTXO_ComboBox.addItemListener(new Sander8Frame_NTXO_ComboBox_itemAdapter(this)); + IWRAP_ComboBox.addItemListener(new Sander8Frame_IWRAP_ComboBox_itemAdapter(this)); + IOUTFM_ComboBox.addItemListener(new + Sander8Frame_IOUTFM_ComboBox_itemAdapter(this)); + IDECOMP_ComboBox.addItemListener(new + Sander8Frame_IDECOMP_ComboBox_itemAdapter(this)); + NTX_ComboBox.addItemListener(new Sander8Frame_NTX_ComboBox_itemAdapter(this)); + NTRX_ComboBox.addItemListener(new Sander8Frame_NTRX_ComboBox_itemAdapter(this)); + DIELC_Label.setToolTipText(""); + DIELC_Label.setHorizontalAlignment(SwingConstants.RIGHT); + DIELC_Label.setText("Dielectric Constant (dielc):"); + DIELC_Label.addMouseListener(new Sander8Frame_DIELC_Label_mouseAdapter(this)); + CUT_Label.setToolTipText(""); + CUT_Label.setHorizontalAlignment(SwingConstants.RIGHT); + CUT_Label.setText("Nonbonded Cutoff (cut):"); + CUT_Label.addMouseListener(new Sander8Frame_CUT_Label_mouseAdapter(this)); + SCNB_Label.setToolTipText(""); + SCNB_Label.setHorizontalAlignment(SwingConstants.RIGHT); + SCNB_Label.setText("SCNB:"); + SCNB_Label.addMouseListener(new Sander8Frame_SCNB_Label_mouseAdapter(this)); + Edit_MenuItem.setToolTipText("Edit Job Control File in text editor"); + Edit_MenuItem.setActionCommand("Edit"); + Edit_MenuItem.setText("Edit File"); + Edit_MenuItem.addActionListener(new + Sander8Frame_Edit_MenuItem_actionAdapter(this)); + flowLayout3.setAlignment(FlowLayout.LEFT); + NTR_Label.setToolTipText(""); + NTR_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTR_Label.setText("Position Restraints (ntr): "); + NTR_Label.addMouseListener(new Sander8Frame_NTR_Label_mouseAdapter(this)); + NTR_ComboBox.addItemListener(new Sander8Frame_NTR_ComboBox_itemAdapter(this)); + IBELLY_Label.setToolTipText(""); + IBELLY_Label.setHorizontalAlignment(SwingConstants.RIGHT); + IBELLY_Label.setText("Belly Run (ibelly): "); + IBELLY_Label.addMouseListener(new Sander8Frame_IBELLY_Label_mouseAdapter(this)); + IBELLY_ComboBox.addItemListener(new + Sander8Frame_IBELLY_ComboBox_itemAdapter(this)); + BELLYMASK_Label.setToolTipText(""); + BELLYMASK_Label.setHorizontalAlignment(SwingConstants.RIGHT); + BELLYMASK_Label.setText("BELLYMASK: "); + BELLYMASK_Label.addMouseListener(new + Sander8Frame_BELLYMASK_Label_mouseAdapter(this)); + RESTRAINTMASK_Label.setToolTipText(""); + RESTRAINTMASK_Label.setHorizontalAlignment(SwingConstants.RIGHT); + RESTRAINTMASK_Label.setText("RESTRAINTMASK: "); + RESTRAINTMASK_Label.addMouseListener(new + Sander8Frame_RESTRAINTMASK_Label_mouseAdapter(this)); + RESTRAINT_WT_Label.setToolTipText(""); + RESTRAINT_WT_Label.setHorizontalAlignment(SwingConstants.RIGHT); + RESTRAINT_WT_Label.setText("RESTRAINT_WT: "); + RESTRAINT_WT_Label.addMouseListener(new + Sander8Frame_RESTRAINT_WT_Label_mouseAdapter(this)); + BELLYMASK_TextField.setText(" "); + BELLYMASK_TextField.setColumns(6); + RESTRAINTMASK_TextField.setText(" "); + RESTRAINTMASK_TextField.setColumns(6); + RESTRAINT_WT_TextField.setText(" "); + RESTRAINT_WT_TextField.setColumns(6); + FCAP_Label.setToolTipText(""); + FCAP_Label.setHorizontalAlignment(SwingConstants.RIGHT); + FCAP_Label.setText("Force Constant (fcap): "); + FCAP_Label.addMouseListener(new Sander8Frame_FCAP_Label_mouseAdapter(this)); + IVCAP_Label.setToolTipText(""); + IVCAP_Label.setHorizontalAlignment(SwingConstants.RIGHT); + IVCAP_Label.setText("Water cap (ivcap): "); + IVCAP_Label.addMouseListener(new Sander8Frame_IVCAP_Label_mouseAdapter(this)); + FCAP_TextField.setText(" "); + FCAP_TextField.setColumns(6); + IVCAP_ComboBox.addItemListener(new Sander8Frame_IVCAP_ComboBox_itemAdapter(this)); + HWTNM2_Label.setToolTipText(""); + HWTNM2_Label.setHorizontalAlignment(SwingConstants.RIGHT); + HWTNM2_Label.setText("HWTNM2: "); + HWTNM2_Label.addMouseListener(new Sander8Frame_HWTNM2_Label_mouseAdapter(this)); + HWTNM1_Label.setToolTipText(""); + HWTNM1_Label.setHorizontalAlignment(SwingConstants.RIGHT); + HWTNM1_Label.setText("HWTNM1: "); + HWTNM1_Label.addMouseListener(new Sander8Frame_HWTNM1_Label_mouseAdapter(this)); + OWTNM_Label.setToolTipText(""); + OWTNM_Label.setHorizontalAlignment(SwingConstants.RIGHT); + OWTNM_Label.setText("OWTNM: "); + OWTNM_Label.addMouseListener(new Sander8Frame_OWTNM_Label_mouseAdapter(this)); + WATNAM_Label.setToolTipText(""); + WATNAM_Label.setHorizontalAlignment(SwingConstants.RIGHT); + WATNAM_Label.setText("WATNAM: "); + WATNAM_Label.addMouseListener(new Sander8Frame_WATNAM_Label_mouseAdapter(this)); + TOL_Label.setToolTipText(""); + TOL_Label.setHorizontalAlignment(SwingConstants.RIGHT); + TOL_Label.setText("Tolerance (tol): "); + TOL_Label.addMouseListener(new Sander8Frame_TOL_Label_mouseAdapter(this)); + JFASTW_Label.setToolTipText(""); + JFASTW_Label.setHorizontalAlignment(SwingConstants.RIGHT); + JFASTW_Label.setText("Fast Water Flag (jfastw): "); + JFASTW_Label.addMouseListener(new Sander8Frame_JFASTW_Label_mouseAdapter(this)); + NTC_Label.setToolTipText(""); + NTC_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTC_Label.setText("Apply SHAKE (ntc): "); + NTC_Label.addMouseListener(new Sander8Frame_NTC_Label_mouseAdapter(this)); + shakePanel.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color. + lightGray, 1), "SHAKE bond length constraints")); + shakePanel.setLayout(gridBagLayout6); + HWTNM2_TextField.setText(" "); + HWTNM2_TextField.setColumns(6); + HWTNM1_TextField.setText(" "); + HWTNM1_TextField.setColumns(6); + WATNAM_TextField.setText(" "); + WATNAM_TextField.setColumns(6); + OWTNM_TextField.setText(" "); + OWTNM_TextField.setColumns(6); + TOL_TextField.setText(" "); + TOL_TextField.setColumns(6); + NTC_ComboBox.addItemListener(new Sander8Frame_NTC_ComboBox_itemAdapter(this)); + JFASTW_ComboBox.addItemListener(new + Sander8Frame_JFASTW_ComboBox_itemAdapter(this)); + jLabel6.setToolTipText(""); + jLabel6.setHorizontalAlignment(SwingConstants.RIGHT); + jLabel6.setText(" "); + Dummy_MD_Label.setToolTipText(""); + Dummy_MD_Label.setHorizontalAlignment(SwingConstants.RIGHT); + IREST_ComboBox.addMouseListener(new + Sander8Frame_IREST_ComboBox_mouseAdapter(this)); + NTMIN_ComboBox.addMouseListener(new + Sander8Frame_NTMIN_ComboBox_mouseAdapter(this)); + NTT_ComboBox.addMouseListener(new Sander8Frame_NTT_ComboBox_mouseAdapter(this)); + NTP_ComboBox.addMouseListener(new Sander8Frame_NTP_ComboBox_mouseAdapter(this)); + saveFile_Button.setToolTipText("Save File"); + saveFile_Button.setIcon(saveFileImage); + saveFile_Button.addActionListener(new + Sander8Frame_saveFile_Button_actionAdapter(this)); + NTF_ComboBox.addMouseListener(new Sander8Frame_NTF_ComboBox_mouseAdapter(this)); + IPOL_ComboBox.addMouseListener(new Sander8Frame_IPOL_ComboBox_mouseAdapter(this)); + NTB_ComboBox.addMouseListener(new Sander8Frame_NTB_ComboBox_mouseAdapter(this)); + NTX_ComboBox.addMouseListener(new Sander8Frame_NTX_ComboBox_mouseAdapter(this)); + NTRX_ComboBox.addMouseListener(new Sander8Frame_NTRX_ComboBox_mouseAdapter(this)); + NTXO_ComboBox.addMouseListener(new Sander8Frame_NTXO_ComboBox_mouseAdapter(this)); + IWRAP_ComboBox.addMouseListener(new + Sander8Frame_IWRAP_ComboBox_mouseAdapter(this)); + IOUTFM_ComboBox.addMouseListener(new + Sander8Frame_IOUTFM_ComboBox_mouseAdapter(this)); + IDECOMP_ComboBox.addMouseListener(new + Sander8Frame_IDECOMP_ComboBox_mouseAdapter(this)); + NTR_ComboBox.addMouseListener(new Sander8Frame_NTR_ComboBox_mouseAdapter(this)); + IBELLY_ComboBox.addMouseListener(new + Sander8Frame_IBELLY_ComboBox_mouseAdapter(this)); + IVCAP_ComboBox.addMouseListener(new + Sander8Frame_IVCAP_ComboBox_mouseAdapter(this)); + NTC_ComboBox.addMouseListener(new Sander8Frame_NTC_ComboBox_mouseAdapter(this)); + JFASTW_ComboBox.addMouseListener(new + Sander8Frame_JFASTW_ComboBox_mouseAdapter(this)); + RBORNSTAT_ComboBox.addMouseListener(new + Sander8Frame_RBORNSTAT_ComboBox_mouseAdapter(this)); + GBSA_ComboBox.addMouseListener(new Sander8Frame_GBSA_ComboBox_mouseAdapter(this)); + jMenuItem1.setText("Open Job Control File"); + jMenuItem1.addActionListener(new Sander8Frame_jMenuItem1_actionAdapter(this)); + jMenuItem2.setText("Save File"); + jMenuItem2.addActionListener(new Sander8Frame_jMenuItem2_actionAdapter(this)); + jMenuBar1.add(jMenuFile); + jMenuFile.add(jMenuItem1); + jMenuFile.add(jMenuItem2); + jMenuFile.add(Edit_MenuItem); + jMenuFile.addSeparator(); + jMenuFile.add(jMenuFileExit); + jMenuBar1.add(jMenuHelp); + jMenuHelp.add(jMenuHelpAbout); + setJMenuBar(jMenuBar1); + openFile_Button.setIcon(image1); + openFile_Button.setToolTipText("Open File"); + newFile_Button.setIcon(image2); + newFile_Button.setToolTipText("Reset the variables to their default values"); + help_Button.setIcon(image3); + help_Button.setToolTipText("Help"); + jToolBar.add(openFile_Button); + jToolBar.add(newFile_Button); + jToolBar.add(saveFile_Button); + jToolBar.add(help_Button); + jTabbedPane1.add(jobTypePanel, "Job Type"); + jTabbedPane1.add(potentialFuncPanel, "Potential Function"); + jTabbedPane1.add(MolDynPanel, "Molecular Dynamics"); + contentPane.add(descrPanel, BorderLayout.SOUTH); + descrPanel.add(descriptionPane, BorderLayout.CENTER); + jTabbedPane1.add(ioPanel, "Input/Output"); + jTabbedPane1.add(restrainPanel, "Restrains"); + jTabbedPane1.add(GB_Panel, "GB/SA"); + jTabbedPane1.add(PME_Panel, "PME"); + ioPanel.add(inputPanel, BorderLayout.NORTH); + ioPanel.add(outputPanel, BorderLayout.CENTER); + jobTypePanel.add(jPanel1, BorderLayout.WEST); + jobTypePanel.add(cardsPanel, BorderLayout.CENTER); + cardsPanel.add(minCard, "minCard"); + cardsPanel.add(mdCard, "mdCard"); + + contentPane.add(jTabbedPane1, BorderLayout.CENTER); + MolDynPanel.add(PressureControlPanel, + new GridBagConstraints(0, 4, 8, 2, 1.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.BOTH, + new Insets(5, 5, 5, 5), 0, 0)); + MolDynPanel.add(TempControlPanel, + new GridBagConstraints(0, 1, 8, 3, 1.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.BOTH, + new Insets(5, 5, 5, 5), 0, 0)); + inputPanel.add(NTX_Label, null); + inputPanel.add(NTX_ComboBox, null); + inputPanel.add(NTRX_Label, null); + inputPanel.add(NTRX_ComboBox, null); + jPanel1.add(IMIN_ComboBox, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0 + , GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(IREST_ComboBox, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(IGB_ComboBox, new GridBagConstraints(0, 2, 1, 1, 0.0, 1.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + GB_Panel.add(INTDIEL_TextField, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(EXTDIEL_Label, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(EXTDIEL_TextField, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(SALTCON_Label, new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(SALTCON_TextField, new GridBagConstraints(5, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(RGBMAX_Label, new GridBagConstraints(6, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(RDT_TextField, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(RBORNSTAT_ComboBox, + new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(OFFSET_Label, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(OFFSET_TextField, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(GBSA_Label, new GridBagConstraints(4, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(GBSA_ComboBox, new GridBagConstraints(5, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(SURFTEN_Label, new GridBagConstraints(6, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(SURFTEN_TextField, new GridBagConstraints(7, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(RDT_Label, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(RBORNSTAT_Label, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + PressureControlPanel.add(COMP_Label, null); + PressureControlPanel.add(COMP_TextField, null); + contentPane.add(jToolBar, BorderLayout.NORTH); + restrainPanel.add(IBELLY_Label, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(shakePanel, new GridBagConstraints(0, 3, 12, 1, 1.0, 1.0 + , GridBagConstraints.CENTER, GridBagConstraints.BOTH, + new Insets(5, 0, 5, 0), 0, 0)); + shakePanel.add(OWTNM_Label, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + shakePanel.add(WATNAM_Label, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + shakePanel.add(NTC_Label, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 0), 0, 0)); + shakePanel.add(HWTNM1_Label, new GridBagConstraints(4, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(RESTRAINTMASK_Label, + new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + shakePanel.add(JFASTW_Label, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + shakePanel.add(TOL_Label, new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + shakePanel.add(HWTNM2_Label, new GridBagConstraints(6, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 5), 0, 0)); + GB_Panel.add(INTDIEL_Label, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(RGBMAX_TextField, new GridBagConstraints(7, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(GB_Dummy_Label, new GridBagConstraints(8, 3, 1, 1, 1.0, 1.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(0, 0, 0, 0), 0, 0)); + outputPanel.add(jLabel6, new GridBagConstraints(8, 3, 1, 1, 1.0, 1.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(0, 0, 0, 0), 0, 0)); + outputPanel.add(NTXO_Label, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 0, 0), 0, 0)); + outputPanel.add(NTXO_ComboBox, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTPR_Label, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTAVE_Label, new GridBagConstraints(4, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 0, 0), 0, 0)); + outputPanel.add(NTWR_Label, new GridBagConstraints(6, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(IWRAP_Label, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(IWRAP_ComboBox, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTWX_Label, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTWV_Label, new GridBagConstraints(4, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTWE_Label, new GridBagConstraints(6, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(NTF_Label, + new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(NTB_Label, + new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + potentialFuncPanel.add(NTF_ComboBox, + new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + minCard.add(covergLabel, new GridBagConstraints(0, 5, 1, 1, 0.0, 1.0 + , GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, + new Insets(0, 0, 0, 0), 1, 1)); + minCard.add(methodLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 1, 1)); + minCard.add(DRMS_TextField, new GridBagConstraints(1, 5, 4, 1, 1.0, 0.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, + new Insets(1, 0, 1, 0), 0, 0)); + mdCard.add(NSTLIM_Label, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(NSTLIM_TextField, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(DT_Label, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 1, 1)); + mdCard.add(DT_TextField, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 1, 1)); + mdCard.add(TEMP0_Label, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(TEMP0_TextField, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(PRES0_Label, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + mdCard.add(PRES0_TextField, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(NTT_Label, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(NTT_ComboBox, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 1, 0)); + mdCard.add(NTP_Label, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + mdCard.add(NTP_ComboBox, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(TAUTP_TextField, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(TAUTP_Label, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(TAUP_TextField, new GridBagConstraints(3, 3, 1, 1, 1.0, 0.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(TAUP_Label, new GridBagConstraints(2, 3, 1, 1, 0.0, 1.0 + , GridBagConstraints.NORTH, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + restrainPanel.add(RESTRAINT_WT_TextField, + new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(BELLYMASK_TextField, + new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(RESTRAINTMASK_TextField, + new GridBagConstraints(5, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(NTR_Label, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 0), 0, 0)); + restrainPanel.add(NTR_ComboBox, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(IBELLY_ComboBox, + new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(IVCAP_Label, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(BELLYMASK_Label, + new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + restrainPanel.add(RESTRAINT_WT_Label, + new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + restrainPanel.add(IVCAP_ComboBox, + new GridBagConstraints(1, 2, 5, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(FCAP_TextField, + new GridBagConstraints(7, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(FCAP_Label, new GridBagConstraints(6, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + shakePanel.add(NTC_ComboBox, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + shakePanel.add(JFASTW_ComboBox, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + shakePanel.add(WATNAM_TextField, + new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + shakePanel.add(OWTNM_TextField, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + shakePanel.add(HWTNM1_TextField, + new GridBagConstraints(5, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + shakePanel.add(HWTNM2_TextField, + new GridBagConstraints(7, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + shakePanel.add(TOL_TextField, new GridBagConstraints(5, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + TempControlPanel.add(VLIMIT_Label, + new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + TempControlPanel.add(VRAND_Label, + new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + TempControlPanel.add(VRAND_TextField, + new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 5), 0, 0)); + TempControlPanel.add(GAMMA_LN_Label, + new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + TempControlPanel.add(GAMMA_LN_TextField, + new GridBagConstraints(5, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 5), 0, 0)); + TempControlPanel.add(TEMPI_Label, + new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + TempControlPanel.add(TEMPI_TextField, + new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 5), 0, 0)); + TempControlPanel.add(TEMP0LES_Label, + new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 0), 0, 0)); + TempControlPanel.add(TEMP0LES_TextField, + new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + TempControlPanel.add(VLIMIT_TextField, + new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 5), 0, 0)); + TempControlPanel.add(Dummy_MD_Label, + new GridBagConstraints(6, 1, 1, 1, 1.0, 1.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(0, 0, 0, 0), 0, 0)); + MolDynPanel.add(NSCM_Label, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 15, 5, 0), 0, 0)); + MolDynPanel.add(NRESPA_Label, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 15, 5, 0), 0, 0)); + MolDynPanel.add(NRESPA_TextField, + new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 5), 0, 0)); + MolDynPanel.add(T_Label, new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 15, 5, 5), 0, 0)); + MolDynPanel.add(T_TextField, new GridBagConstraints(5, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + MolDynPanel.add(IG_Label, new GridBagConstraints(6, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 15, 5, 5), 0, 0)); + MolDynPanel.add(IG_TextField, new GridBagConstraints(7, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + MolDynPanel.add(NSCM_TextField, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 5), 0, 0)); + potentialFuncPanel.add(IPOL_Label, + new GridBagConstraints(0, 3, 1, 1, 0.0, 1.0 + , GridBagConstraints.NORTH, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(DIELC_Label, + new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(DIELC_TextField, + new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(SCEE_Label, + new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + potentialFuncPanel.add(SCEE_TextField, + new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(SCNB_Label, + new GridBagConstraints(4, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + potentialFuncPanel.add(NSNB_Label, + new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + potentialFuncPanel.add(CUT_Label, + new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + potentialFuncPanel.add(CUT_TextField, + new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(IPOL_ComboBox, + new GridBagConstraints(1, 3, 2, 1, 0.0, 0.0 + , + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(NTB_ComboBox, + new GridBagConstraints(3, 0, 3, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(NSNB_TextField, + new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(SCNB_TextField, + new GridBagConstraints(5, 2, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTWE_TextField, new GridBagConstraints(7, 2, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTWR_TextField, new GridBagConstraints(7, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(IOUTFM_Label, new GridBagConstraints(0, 3, 1, 1, 0.0, 1.0 + , GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(IOUTFM_ComboBox, + new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTWPRT_Label, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTWPRT_TextField, new GridBagConstraints(3, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(IDECOMP_Label, + new GridBagConstraints(4, 3, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(IDECOMP_ComboBox, + new GridBagConstraints(5, 3, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTPR_TextField, + new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTWX_TextField, + new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTAVE_TextField, + new GridBagConstraints(5, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTWV_TextField, new GridBagConstraints(5, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + minCard.add(NTMIN_ComboBox, new GridBagConstraints(0, 0, 2, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 2, 0), 1, 1)); + minCard.add(maxIterLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 2, 0), 1, 1)); + minCard.add(MAXCYC_TextField, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 2, 0), 1, 1)); + minCard.add(switchLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 2, 0), 1, 1)); + minCard.add(NCYC_TextField, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 2, 0), 0, 0)); + minCard.add(dxLabel, + new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 2, 1), 1, 1)); + minCard.add(DX0_TextField, new GridBagConstraints(1, 4, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 2, 0), 0, 0)); + jTabbedPane1.setSelectedIndex(0); + + // --- setup all text fields, combo boxes etc... + setupControls(); + + Font currentFont = descriptionPane.getFont(); + if (currentFont.getSize() < 12) { + currentFont = new Font(currentFont.getFontName(), currentFont.getStyle(), 12); + descriptionPane.setFont(currentFont); + } + } + + public void setupControls() { + + Map allVars = s8jc.getAllVariablesInfo(); + SanderVariable var; + + setupList("NTF", NTF_ComboBox, true); + setupList("NTB", NTB_ComboBox, false); + setupValue("DIELC", DIELC_TextField); + setupValue("CUT", CUT_TextField); + setupValue("SCNB", SCNB_TextField); + setupValue("SCEE", SCEE_TextField); + setupValue("NSNB", NSNB_TextField); + setupValue("MAXCYC", MAXCYC_TextField); + setupValue("NCYC", NCYC_TextField); + setupValue("DX0", DX0_TextField); + setupValue("DRMS", DRMS_TextField); + setupList("IPOL", IPOL_ComboBox, false); + +// --- Setup mdCard Panel + + setupValue("NSTLIM", NSTLIM_TextField); + setupValue("TEMP0", TEMP0_TextField); + setupValue("DT", DT_TextField); + setupValue("TAUTP", TAUTP_TextField); + setupValue("PRES0", PRES0_TextField); + setupValue("TAUP", TAUP_TextField); + setupList("NTT", NTT_ComboBox, true); + setupList("NTP", NTP_ComboBox, true); + +// --- Setup Molecular Dynamics Panel + + setupValue("NSCM", NSCM_TextField); + setupValue("NRESPA", NRESPA_TextField); + setupValue("T", T_TextField); + setupValue("IG", IG_TextField); + setupValue("T", T_TextField); + setupValue("VLIMIT", VLIMIT_TextField); + setupValue("VRAND", VRAND_TextField); + setupValue("TEMPI", TEMPI_TextField); + setupValue("GAMMA_LN", GAMMA_LN_TextField); + setupValue("TEMP0LES", TEMP0LES_TextField); + setupValue("COMP", COMP_TextField); + +// --- Input panel + + setupList("NTRX", NTRX_ComboBox, true); + setupList("NTX", NTX_ComboBox, true); + +// --- Output panel + + setupList("NTXO", NTXO_ComboBox, true); + setupList("IWRAP", IWRAP_ComboBox, true); + setupList("IOUTFM", IOUTFM_ComboBox, true); + setupList("IDECOMP", IDECOMP_ComboBox, true); + + setupValue("NTPR", NTPR_TextField); + setupValue("NTAVE", NTAVE_TextField); + setupValue("NTWR", NTWR_TextField); + setupValue("NTWX", NTWX_TextField); + setupValue("NTWV", NTWV_TextField); + setupValue("NTWE", NTWE_TextField); + setupValue("NTWPRT", NTWPRT_TextField); + + // --- General Born + + setupList("IGB", IGB_ComboBox, false); + + setupList("RBORNSTAT", RBORNSTAT_ComboBox, true); + setupList("GBSA", GBSA_ComboBox, true); + + setupValue("INTDIEL", INTDIEL_TextField); + setupValue("EXTDIEL", EXTDIEL_TextField); + setupValue("SALTCON", SALTCON_TextField); + setupValue("RGBMAX", RGBMAX_TextField); + setupValue("OFFSET", OFFSET_TextField); + setupValue("SURFTEN", SURFTEN_TextField); + setupValue("RDT", RDT_TextField); + + // --- Frozen or restrained atoms. + + setupValue("RESTRAINT_WT", RESTRAINT_WT_TextField); + setupValue("RESTRAINTMASK", RESTRAINTMASK_TextField); + setupValue("BELLYMASK", BELLYMASK_TextField); + + // --- Water cap + + setupList("IVCAP", IVCAP_ComboBox, false); + setupValue("FCAP", FCAP_TextField); + + // -- SHAKE + + setupList("NTC", NTC_ComboBox, true); + setupList("JFASTW", JFASTW_ComboBox, true); + setupValue("TOL", TOL_TextField); + setupValue("WATNAM", WATNAM_TextField); + setupValue("OWTNM", OWTNM_TextField); + setupValue("HWTNM1", HWTNM1_TextField); + setupValue("HWTNM2", HWTNM2_TextField); + + // --- Special setup + + comboBoxAdjusting = true; + var = (SanderVariable) allVars.get("IMIN"); + IMIN_ComboBox.removeAllItems(); + IMIN_ComboBox.addItem("Molecular Dynamics"); + IMIN_ComboBox.addItem("Energy Minimization"); + IMIN_ComboBox.setSelectedIndex(var.getSelectedIndex()); + + var = (SanderVariable) allVars.get("IREST"); + IREST_ComboBox.removeAllItems(); + IREST_ComboBox.addItem("New Calculation"); + IREST_ComboBox.addItem("Restart"); + IREST_ComboBox.setSelectedIndex(var.getSelectedIndex()); + + var = (SanderVariable) allVars.get("NTMIN"); + NTMIN_ComboBox.removeAllItems(); + NTMIN_ComboBox.addItem("Conjugate Gradient"); + NTMIN_ComboBox.addItem("Steepest Descent + Conjugate Gradient"); + NTMIN_ComboBox.addItem("XMIN"); + NTMIN_ComboBox.addItem("LMOD"); + NTMIN_ComboBox.setSelectedIndex(var.getSelectedIndex()); + + var = (SanderVariable) allVars.get("NTR"); + NTR_ComboBox.removeAllItems(); + NTR_ComboBox.addItem("No"); + NTR_ComboBox.addItem("Yes"); + NTR_ComboBox.setSelectedIndex(var.getSelectedIndex()); + + var = (SanderVariable) allVars.get("IBELLY"); + IBELLY_ComboBox.removeAllItems(); + IBELLY_ComboBox.addItem("No"); + IBELLY_ComboBox.addItem("Yes"); + IBELLY_ComboBox.setSelectedIndex(var.getSelectedIndex()); + comboBoxAdjusting = false; + + // --- More of Special setup + + if (IGB_ComboBox.getSelectedIndex() == 0) { + jTabbedPane1.setEnabledAt(5, false); + } + else { + jTabbedPane1.setEnabledAt(5, true); + } + + if (IMIN_ComboBox.getSelectedIndex() == 0) { + jTabbedPane1.setEnabledAt(2, true); + } + else { + jTabbedPane1.setEnabledAt(2, false); + } + } + + /** + * + * @param amberVarName String + * @param jBox JComboBox + * @param use_values boolean - if "true" use variable's possible values, + * otherwise use values descriptions + */ + public void setupList(String amberVarName, JComboBox jBox, boolean use_values) { + if (s8jc == null) { + JOptionPane.showMessageDialog(this, + "INTERNAL ERROR: setupList: s8jc == null", + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + comboBoxAdjusting = true; + jBox.removeAllItems(); + + Map allVars = s8jc.getAllVariablesInfo(); + SanderVariable var = (SanderVariable) allVars.get(amberVarName); + + if (var == null) { + JOptionPane.showMessageDialog(this, + "INTERNAL ERROR: setupList: var == null : var name: " + + amberVarName, + "Error", + JOptionPane.ERROR_MESSAGE); + comboBoxAdjusting = false; + return; + } + + String s_value; + for (int i = 0; i < var.getNumberOfValues(); i++) { + SanderVariableValue value = var.getValue(i); + + if (use_values) { + s_value = value.getValue(); + } + else { + s_value = value.getDescription(); + } + + if (value.isDefault()) { + s_value += " (default)"; + } + jBox.addItem(s_value); + } + + if (var.getSelectedIndex() == -1) { + JOptionPane.showMessageDialog(this, + "INTERNAL ERROR: setupList: var.getSelectedIndex() == -1 : var name: " + + amberVarName, + "Error", + JOptionPane.ERROR_MESSAGE); + + } + else { + jBox.setSelectedIndex(var.getSelectedIndex()); + } + comboBoxAdjusting = false; + //logger.info("Var: " + amberVarName + " selected: " + + // var.getSelectedIndex()); + controlsTable.put(amberVarName, jBox); + this.pack(); + } + + public void setupValue(String amberVarName, JTextField jText) { + if (s8jc == null) { + return; + } + jText.removeAll(); + + Map allVars = s8jc.getAllVariablesInfo(); + SanderVariable var = (SanderVariable) allVars.get(amberVarName); + + if (var == null || var.isEnumerated()) { + JOptionPane.showMessageDialog(this, + "INTERNAL ERROR: setupValue: var == null || var.isEnumerated(): var name: " + + amberVarName, + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + String s_value; + + //SanderVariableValue value = var.getValue(0); + //s_value = value.getValue(); + + s_value = var.getValue(); + + jText.setText(s_value); + jText.setToolTipText("Enter new Value and Press Enter"); + controlsTable.put(amberVarName, jText); + this.pack(); + } + + void showVarDescription(String var_name) { + Map allVars = s8jc.getAllVariablesInfo(); + SanderVariable var = (SanderVariable) allVars.get(var_name); + descriptionPane.removeAll(); + descriptionPane.setText(var.getDescription()); + } + + void setNewValue(String amberVarName, JTextField new_value) { + Map allVars = s8jc.getAllVariablesInfo(); + SanderVariable var = (SanderVariable) allVars.get(amberVarName); + String message = var.setValue(new_value.getText()); + if (message == null) { + descriptionPane.removeAll(); + descriptionPane.setText("Set " + amberVarName + " = " + new_value.getText()); + } + else { + JOptionPane.showMessageDialog(this, + message, + "Error", + JOptionPane.ERROR_MESSAGE); + } + + } + + /** + * + * @param var_name String + * @param comboBox JComboBox + */ + void showValueDescription(String var_name, JComboBox comboBox) { + if (comboBoxAdjusting) { + return; + } + if (comboBox.getItemCount() == 0) { + return; + } + Map allVars = s8jc.getAllVariablesInfo(); + SanderVariable var = (SanderVariable) allVars.get(var_name); + SanderVariableValue value = var.getValue(comboBox.getSelectedIndex()); + descriptionPane.removeAll(); + descriptionPane.setText(value.getDescription()); + var.setSelectedIndex(comboBox.getSelectedIndex()); + } + + /** + * File | Exit action performed. + * + * @param actionEvent ActionEvent + */ + void jMenuFileExit_actionPerformed(ActionEvent actionEvent) { + System.exit(0); + } + + /** + * Help | About action performed. + * + * @param actionEvent ActionEvent + */ + void jMenuHelpAbout_actionPerformed(ActionEvent actionEvent) { + Sander8Frame_AboutBox dlg = new Sander8Frame_AboutBox(this); + Dimension dlgSize = dlg.getPreferredSize(); + Dimension frmSize = getSize(); + Point loc = getLocation(); + dlg.setLocation( (frmSize.width - dlgSize.width) / 2 + loc.x, + (frmSize.height - dlgSize.height) / 2 + loc.y); + dlg.setModal(true); + dlg.pack(); + dlg.setVisible(true); + } + + public void forceEvalButton_actionPerformed(ActionEvent e) { + showVarDescription("NTF"); + } + + public void NTF_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTF", NTF_ComboBox); + } + + public void NTB_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTB", NTB_ComboBox); + } + + public void DIELC_Button_actionPerformed(ActionEvent e) { + showVarDescription("DIELC"); + } + + public void CUT_Button_actionPerformed(ActionEvent e) { + showVarDescription("CUT"); + } + + public void SCNB_Button_actionPerformed(ActionEvent e) { + showVarDescription("SCNB"); + } + + public void NBListButton_actionPerformed(ActionEvent e) { + showVarDescription("NSNB"); + } + + public void SCEE_Button_actionPerformed(ActionEvent e) { + showVarDescription("SCEE"); + } + + public void jButton5_actionPerformed(ActionEvent e) { + showVarDescription("IPOL"); + } + + public void IPOL_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("IPOL", IPOL_ComboBox); + } + + public void IMIN_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("IMIN", IMIN_ComboBox); + + CardLayout cl = (CardLayout) cardsPanel.getLayout(); + if (IMIN_ComboBox.getSelectedIndex() == 0) { + cl.show(cardsPanel, "mdCard"); + jTabbedPane1.setEnabledAt(2, true); + } + else if (IMIN_ComboBox.getSelectedIndex() == 1) { + cl.show(cardsPanel, "minCard"); + jTabbedPane1.setEnabledAt(2, false); + } + } + + public void NTMIN_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTMIN", NTMIN_ComboBox); + } + + public void jLabel6_mouseEntered(MouseEvent e) { + showVarDescription("NTMIN"); + } + + public void maxIterLabel_mouseEntered(MouseEvent e) { + showVarDescription("MAXCYC"); + } + + public void switchLabel_mouseEntered(MouseEvent e) { + showVarDescription("NCYC"); + } + + public void dxLabel_mouseEntered(MouseEvent e) { + showVarDescription("DX0"); + } + + public void covergLabel_mouseEntered(MouseEvent e) { + showVarDescription("DRMS"); + } + + public void IREST_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("IREST", IREST_ComboBox); + } + + public void jLabel10_mouseEntered(MouseEvent e) { + showVarDescription("NSCM"); + } + + public void NRESPA_Label_mouseEntered(MouseEvent e) { + showVarDescription("NRESPA"); + } + + public void T_Label_mouseEntered(MouseEvent e) { + showVarDescription("T"); + } + + public void NTT_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTT"); + } + + public void TEMP0LES_Label_mouseEntered(MouseEvent e) { + showVarDescription("TEMP0LES"); + } + + public void IG_Label_mouseEntered(MouseEvent e) { + showVarDescription("IG"); + } + + public void TAUTP_Label_mouseEntered(MouseEvent e) { + showVarDescription("TAUTP"); + } + + public void GAMMA_LN_Label_mouseEntered(MouseEvent e) { + showVarDescription("GAMMA_LN"); + } + + public void VRAND_Label_mouseEntered(MouseEvent e) { + showVarDescription("VRAND"); + } + + public void NTP_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTP"); + } + + public void TEMP0_Label_mouseEntered(MouseEvent e) { + showVarDescription("TEMP0"); + } + + public void NSTLIM_Label_mouseEntered(MouseEvent e) { + showVarDescription("NSTLIM"); + } + + public void DT_Label_mouseEntered(MouseEvent e) { + showVarDescription("DT"); + } + + public void COMP_Label_mouseEntered(MouseEvent e) { + showVarDescription("COMP"); + } + + public void TAUP_Label_mouseEntered(MouseEvent e) { + showVarDescription("TAUP"); + } + + public void PRES0_Label_mouseEntered(MouseEvent e) { + showVarDescription("PRES0"); + } + + public void NTT_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTT", NTT_ComboBox); + } + + public void NTP_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTP", NTP_ComboBox); + } + + public void VLIMIT_Label_mouseEntered(MouseEvent e) { + showVarDescription("VLIMIT"); + } + + public void TEMPI_Label_mouseEntered(MouseEvent e) { + showVarDescription("TEMPI"); + } + + public void NSNB_Label_mouseEntered(MouseEvent e) { + showVarDescription("NSNB"); + } + + public void SCEE_Label_mouseEntered(MouseEvent e) { + showVarDescription("SCEE"); + } + + public void IPOL_Label_mouseEntered(MouseEvent e) { + showVarDescription("IPOL"); + } + + public void NTF_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTF"); + } + + public void NTB_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTB"); + } + + public void jButton1_actionPerformed(ActionEvent e) { + FileDialog fd = new FileDialog(this, "Open Sander 8 Job Control File", + FileDialog.LOAD); + fd.setFile("*.in;*.sh"); + fd.setVisible(true); + if (fd.getFile() != null) { + fileName = new String(fd.getFile()); + workingDirectory = new String(fd.getDirectory()); + s8jc = new Sander8JobControl(); + setupControls(); + parseInputData(IOUtils.loadFileIntoString(workingDirectory + fileName)); + } + } + + public Map parseInputData(String data) { + fileContent = data; + if (cntrl == null) { + cntrl = new FortranNamelist(); + } + Map vars = Sander8JobControl.getGeneralParameters(fileContent, 1, + cntrl, "cntrl"); + if (s8jc.setCntrlVariables(vars)) { + + } + else { + JOptionPane.showMessageDialog(this, + s8jc.getErrorMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + } + setupControls(); + return vars; + } + + public void jButton2_actionPerformed(ActionEvent e) { + s8jc = new Sander8JobControl(); + this.setupControls(); + fileContent = null; + JOptionPane.showMessageDialog(this, + "All variables are reset to their default values", + "Info", + JOptionPane.INFORMATION_MESSAGE); + + } + + public void jButton3_actionPerformed(ActionEvent e) { + JOptionPane.showMessageDialog(this, + "Program allows to edit \"cntrl\" namelist for Sander 8\n" + + "Select the tab corresponding to the desired component\n" + + "Set options using either text fields or combo boxes\n" + + "Toolbar provides access to commonly used features:\n" + + " Open Sander-8 job control file\n" + + " Reset the options to their default values\n" + + " Save File, and Help\n" + + "To see the description for a particular option point your cursor to an option\n" + + " and its description will be in the Option Description panel", + "Help", + JOptionPane.INFORMATION_MESSAGE); + } + + public void NTRX_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTRX"); + } + + public void NTX_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTX"); + } + + public void NTWR_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTWR"); + } + + public void NTAVE_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTAVE"); + } + + public void IWRAP_Label_mouseEntered(MouseEvent e) { + showVarDescription("IWRAP"); + } + + public void NTXO_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTXO"); + } + + public void NTPR_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTPR"); + } + + public void NTWX_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTWX"); + } + + public void NTWV_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTWV"); + } + + public void NTWE_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTWE"); + } + + public void IOUTFM_Label_mouseEntered(MouseEvent e) { + showVarDescription("IOUTFM"); + } + + public void NTWPRT_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTWPRT"); + } + + public void IDECOMP_Label_mouseEntered(MouseEvent e) { + showVarDescription("IDECOMP"); + } + + public void INTDIEL_Label_mouseEntered(MouseEvent e) { + showVarDescription("INTDIEL"); + } + + public void EXTDIEL_Label_mouseEntered(MouseEvent e) { + showVarDescription("EXTDIEL"); + } + + public void SALTCON_Label_mouseEntered(MouseEvent e) { + showVarDescription("SALTCON"); + } + + public void RGBMAX_Label_mouseEntered(MouseEvent e) { + showVarDescription("RGBMAX"); + } + + public void RBORNSTAT_Label_mouseEntered(MouseEvent e) { + showVarDescription("RBORNSTAT"); + } + + public void OFFSET_Label_mouseEntered(MouseEvent e) { + showVarDescription("OFFSET"); + } + + public void GBSA_Label_mouseEntered(MouseEvent e) { + showVarDescription("GBSA"); + } + + public void SURFTEN_Label_mouseEntered(MouseEvent e) { + showVarDescription("SURFTEN"); + } + + public void RDT_Label_mouseEntered(MouseEvent e) { + showVarDescription("RDT"); + } + + public void RBORNSTAT_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("RBORNSTAT", RBORNSTAT_ComboBox); + } + + public void GBSA_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("GBSA", GBSA_ComboBox); + } + + public void NTXO_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTXO", NTXO_ComboBox); + } + + public void IWRAP_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("IWRAP", IWRAP_ComboBox); + } + + public void IOUTFM_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("IOUTFM", IOUTFM_ComboBox); + } + + public void IDECOMP_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("IDECOMP", IDECOMP_ComboBox); + } + + public void NTX_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTX", NTX_ComboBox); + } + + public void NTRX_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTRX", NTRX_ComboBox); + } + + public void DIELC_Label_mouseEntered(MouseEvent e) { + showVarDescription("DIELC"); + } + + public void CUT_Label_mouseEntered(MouseEvent e) { + showVarDescription("CUT"); + } + + public void SCNB_Label_mouseEntered(MouseEvent e) { + showVarDescription("SCNB"); + } + + public void Edit_MenuItem_actionPerformed(ActionEvent e) { + if (inputEditor == null) { + inputEditor = new TextEditorFrame(this, "Text Editor", ""); + inputEditor.setSize(450, 300); + } + //this.setEnabled(false); + inputEditor.setVisible(true); + if (fileContent == null) { + fileContent = generateFileContents("This is automatically generated file"); + } + else { + fileContent = updateFileContents(fileContent, "cntrl"); + } + inputEditor.setTextToEdit(fileContent); + this.setEnabled(false); + } + + String updateFileContents(String data, String namelistName) { + Map vars = parseInputData(data); + if (vars.size() < 1) { + return data; // i.e. no cntrl namelist + } + + Map allVars = s8jc.getAllVariablesInfo(); + Map cntrlVars = cntrl.getVariables(); + String mess = Sander8JobControl.updateNamelistVariables(cntrlVars, allVars); + if (mess != null) { + JOptionPane.showMessageDialog(this, + mess, "Warning", + JOptionPane.WARNING_MESSAGE); + } + + StringReader sReader = new StringReader(data); + StringWriter sWriter = new StringWriter(); + + try { + int character, count = 0; + char cbuf[] = new char[120]; + String line = null; + boolean skippingNamelist = false; + boolean theRest = false; + + while ( (character = sReader.read()) != -1) { + if (theRest) { + sWriter.write(character); + continue; + } + + if (character == '\n') { + if (line == null) { + line = String.copyValueOf(cbuf, 0, count); + } + else { + line += String.copyValueOf(cbuf, 0, count); + } + count = 0; + + if (skippingNamelist && cct.tools.FortranNamelist.hasNamelistEnd(line)) { + theRest = true; + continue; + } + else if (skippingNamelist) { + continue; + } + + if (cct.tools.FortranNamelist.hasNamelistStart(line, "cntrl")) { + cct.tools.FortranNamelist.writeNamelistBody(sWriter, "cntrl", cntrlVars); + skippingNamelist = true; + } + + if (cct.tools.FortranNamelist.hasNamelistEnd(line)) { + theRest = true; + continue; + } + + if (skippingNamelist) { + continue; + } + + sWriter.write(line + "\n"); + line = null; + + } + else if (count < 120) { + cbuf[count] = (char) character; + ++count; + } + else { + if (line == null) { + line = String.copyValueOf(cbuf, 0, count); + } + else { + line += String.copyValueOf(cbuf, 0, count); + } + count = 0; + } + } + } + catch (IOException er) { + + } + + return sWriter.toString(); + } + + /** + * + * @param title String + * @return String + */ + String generateFileContents(String title) { + + StringWriter sWriter = new StringWriter(); + sWriter.write(title + "\n &cntrl\n"); + + Map allVars = s8jc.getAllVariablesInfo(); + SanderVariable var; + + Set set = controlsTable.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String option = me.getKey().toString(); + var = (SanderVariable) allVars.get(option); + Object control = me.getValue(); + + if (control instanceof JComboBox) { + JComboBox jBox = (JComboBox) control; + if (var.isDefaultValue()) { + continue; + } + sWriter.write(" " + option + "=" + var.getValue() + "\n"); + } + else if (control instanceof JTextField) { + JTextField jText = (JTextField) control; + String value = jText.getText().trim(); + String reference = var.getValue(); + + if (!reference.equalsIgnoreCase(value)) { + String message = var.setValue(value); + if (message != null) { + JOptionPane.showMessageDialog(this, + option + ": " + message, + "Error", + JOptionPane.ERROR_MESSAGE); + setupValue(option, jText); + continue; + } + } + if (var.isDefaultValue()) { + continue; + } + sWriter.write(" " + option + "=" + var.getValue() + "\n"); + } + + } + + sWriter.write(" &end\n"); + return sWriter.toString(); + } + + public void IGB_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("IGB", IGB_ComboBox); + if (IGB_ComboBox.getSelectedIndex() == 0) { + jTabbedPane1.setEnabledAt(5, false); + } + else { + jTabbedPane1.setEnabledAt(5, true); + } + } + + public void NTR_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTR"); + } + + public void NTR_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTR", NTR_ComboBox); + } + + public void IBELLY_Label_mouseEntered(MouseEvent e) { + showVarDescription("IBELLY"); + } + + public void IBELLY_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("IBELLY", IBELLY_ComboBox); + } + + public void RESTRAINT_WT_Label_mouseEntered(MouseEvent e) { + showVarDescription("RESTRAINT_WT"); + } + + public void RESTRAINTMASK_Label_mouseEntered(MouseEvent e) { + showVarDescription("RESTRAINTMASK"); + } + + public void BELLYMASK_Label_mouseEntered(MouseEvent e) { + showVarDescription("BELLYMASK"); + } + + public void IVCAP_Label_mouseEntered(MouseEvent e) { + showVarDescription("IVCAP"); + } + + public void IVCAP_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("IVCAP", IVCAP_ComboBox); + } + + public void FCAP_Label_mouseEntered(MouseEvent e) { + showVarDescription("FCAP"); + } + + public void NTC_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTC"); + } + + public void NTC_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTC", NTC_ComboBox); + } + + public void JFASTW_Label_mouseEntered(MouseEvent e) { + showVarDescription("JFASTW"); + } + + public void JFASTW_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("JFASTW", JFASTW_ComboBox); + } + + public void TOL_Label_mouseEntered(MouseEvent e) { + showVarDescription("TOL"); + } + + public void WATNAM_Label_mouseEntered(MouseEvent e) { + showVarDescription("WATNAM"); + } + + public void OWTNM_Label_mouseEntered(MouseEvent e) { + showVarDescription("OWTNM"); + } + + public void HWTNM1_Label_mouseEntered(MouseEvent e) { + showVarDescription("HWTNM1"); + } + + public void HWTNM2_Label_mouseEntered(MouseEvent e) { + showVarDescription("HWTNM2"); + } + + public void NCYC_TextField_actionPerformed(ActionEvent e) { + setNewValue("NCYC", NCYC_TextField); + } + + public void DX0_TextField_actionPerformed(ActionEvent e) { + setNewValue("DX0", DX0_TextField); + } + + public void DRMS_TextField_actionPerformed(ActionEvent e) { + setNewValue("DRMS", DRMS_TextField); + } + + public void MAXCYC_TextField_actionPerformed(ActionEvent e) { + setNewValue("MAXCYC", MAXCYC_TextField); + } + + public void IMIN_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("IMIN", IMIN_ComboBox); + } + + public void IREST_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("IREST", IREST_ComboBox); + } + + public void IGB_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("IGB", IGB_ComboBox); + } + + public void NTMIN_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTMIN", NTMIN_ComboBox); + } + + public void NTT_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTT", NTT_ComboBox); + } + + public void NTP_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTP", NTP_ComboBox); + } + + public void NSTLIM_TextField_actionPerformed(ActionEvent e) { + setNewValue("NSTLIM", NSTLIM_TextField); + } + + public void saveFile_Button_actionPerformed(ActionEvent e) { + if (fileContent == null) { + fileContent = generateFileContents("This is automatically generated file"); + } + else { + fileContent = updateFileContents(fileContent, "cntrl"); + } + + FileDialog fd = new FileDialog(this, "Save Sander 8 Job Control File", + FileDialog.SAVE); + + if (fileName == null) { + fileName = "sander8.in"; + } + if (workingDirectory == null) { + workingDirectory = "./"; + } + + fd.setFile(fileName); + fd.setDirectory(workingDirectory); + fd.setVisible(true); + if (fd.getFile() != null) { + fileName = new String(fd.getFile()); + workingDirectory = new String(fd.getDirectory()); + try { + IOUtils.saveStringIntoFile(fileContent, workingDirectory + fileName); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + } + } + + } + + public void NTF_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTF", NTF_ComboBox); + } + + public void IPOL_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("IPOL", IPOL_ComboBox); + } + + public void NTB_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTB", NTB_ComboBox); + } + + public void NTX_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTX", NTX_ComboBox); + } + + public void NTRX_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTRX", NTRX_ComboBox); + } + + public void NTXO_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTXO", NTXO_ComboBox); + } + + public void IWRAP_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("IWRAP", IWRAP_ComboBox); + } + + public void IOUTFM_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("IOUTFM", IOUTFM_ComboBox); + } + + public void IDECOMP_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("IDECOMP", IDECOMP_ComboBox); + } + + public void NTR_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTR", NTR_ComboBox); + } + + public void IBELLY_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("IBELLY", IBELLY_ComboBox); + } + + public void IVCAP_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("IVCAP", IVCAP_ComboBox); + } + + public void NTC_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTC", NTC_ComboBox); + } + + public void JFASTW_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("JFASTW", JFASTW_ComboBox); + } + + public void RBORNSTAT_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("RBORNSTAT", RBORNSTAT_ComboBox); + } + + public void GBSA_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("GBSA", GBSA_ComboBox); + } + + public void jMenuItem1_actionPerformed(ActionEvent e) { + jButton1_actionPerformed(e); + } + + public void jMenuItem2_actionPerformed(ActionEvent e) { + saveFile_Button_actionPerformed(e); + } +} + +class Sander8Frame_jMenuItem2_actionAdapter + implements ActionListener { + private Sander8Frame adaptee; + Sander8Frame_jMenuItem2_actionAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.jMenuItem2_actionPerformed(e); + } +} + +class Sander8Frame_jMenuItem1_actionAdapter + implements ActionListener { + private Sander8Frame adaptee; + Sander8Frame_jMenuItem1_actionAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.jMenuItem1_actionPerformed(e); + } +} + +class Sander8Frame_NSTLIM_TextField_actionAdapter + implements ActionListener { + private Sander8Frame adaptee; + Sander8Frame_NSTLIM_TextField_actionAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.NSTLIM_TextField_actionPerformed(e); + } +} + +class Sander8Frame_HWTNM2_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_HWTNM2_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.HWTNM2_Label_mouseEntered(e); + } +} + +class Sander8Frame_HWTNM1_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_HWTNM1_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.HWTNM1_Label_mouseEntered(e); + } +} + +class Sander8Frame_OWTNM_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_OWTNM_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.OWTNM_Label_mouseEntered(e); + } +} + +class Sander8Frame_WATNAM_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_WATNAM_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.WATNAM_Label_mouseEntered(e); + } +} + +class Sander8Frame_TOL_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_TOL_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.TOL_Label_mouseEntered(e); + } +} + +class Sander8Frame_JFASTW_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_JFASTW_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.JFASTW_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_RBORNSTAT_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_RBORNSTAT_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.RBORNSTAT_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_JFASTW_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_JFASTW_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.JFASTW_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_JFASTW_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_JFASTW_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.JFASTW_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTC_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_NTC_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTC_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_FCAP_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_FCAP_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.FCAP_Label_mouseEntered(e); + } +} + +class Sander8Frame_IVCAP_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_IVCAP_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.IVCAP_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_NTC_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTC_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTC_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_NTC_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTC_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTC_Label_mouseEntered(e); + } +} + +class Sander8Frame_IVCAP_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_IVCAP_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IVCAP_Label_mouseEntered(e); + } +} + +class Sander8Frame_BELLYMASK_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_BELLYMASK_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.BELLYMASK_Label_mouseEntered(e); + } +} + +class Sander8Frame_RESTRAINTMASK_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_RESTRAINTMASK_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.RESTRAINTMASK_Label_mouseEntered(e); + } +} + +class Sander8Frame_IBELLY_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_IBELLY_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.IBELLY_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_IVCAP_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_IVCAP_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IVCAP_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_IBELLY_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_IBELLY_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IBELLY_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_IBELLY_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_IBELLY_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IBELLY_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTR_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_NTR_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTR_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_RESTRAINT_WT_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_RESTRAINT_WT_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.RESTRAINT_WT_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTR_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTR_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTR_Label_mouseEntered(e); + } +} + +class Sander8Frame_IGB_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_IGB_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.IGB_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_IGB_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_IGB_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IGB_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_SCNB_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_SCNB_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.SCNB_Label_mouseEntered(e); + } +} + +class Sander8Frame_CUT_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_CUT_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.CUT_Label_mouseEntered(e); + } +} + +class Sander8Frame_DIELC_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_DIELC_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.DIELC_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTRX_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_NTRX_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTRX_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_NTRX_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTRX_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTRX_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_IDECOMP_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_IDECOMP_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.IDECOMP_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_NTR_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTR_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTR_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_IDECOMP_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_IDECOMP_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IDECOMP_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_NTX_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_NTX_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTX_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_NTX_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTX_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTX_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_IOUTFM_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_IOUTFM_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.IOUTFM_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_IOUTFM_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_IOUTFM_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IOUTFM_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_IWRAP_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_IWRAP_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.IWRAP_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_NTXO_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_NTXO_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTXO_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_IWRAP_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_IWRAP_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IWRAP_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_NTXO_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTXO_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTXO_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_GBSA_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_GBSA_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.GBSA_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_RBORNSTAT_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_RBORNSTAT_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.RBORNSTAT_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_GBSA_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_GBSA_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.GBSA_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_RDT_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_RDT_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.RDT_Label_mouseEntered(e); + } +} + +class Sander8Frame_SURFTEN_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_SURFTEN_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.SURFTEN_Label_mouseEntered(e); + } +} + +class Sander8Frame_GBSA_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_GBSA_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.GBSA_Label_mouseEntered(e); + } +} + +class Sander8Frame_OFFSET_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_OFFSET_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.OFFSET_Label_mouseEntered(e); + } +} + +class Sander8Frame_RBORNSTAT_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_RBORNSTAT_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.RBORNSTAT_Label_mouseEntered(e); + } +} + +class Sander8Frame_RGBMAX_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_RGBMAX_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.RGBMAX_Label_mouseEntered(e); + } +} + +class Sander8Frame_SALTCON_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_SALTCON_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.SALTCON_Label_mouseEntered(e); + } +} + +class Sander8Frame_EXTDIEL_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_EXTDIEL_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.EXTDIEL_Label_mouseEntered(e); + } +} + +class Sander8Frame_INTDIEL_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_INTDIEL_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.INTDIEL_Label_mouseEntered(e); + } +} + +class Sander8Frame_IDECOMP_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_IDECOMP_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IDECOMP_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTWPRT_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTWPRT_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTWPRT_Label_mouseEntered(e); + } +} + +class Sander8Frame_IOUTFM_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_IOUTFM_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IOUTFM_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTWE_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTWE_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTWE_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTWV_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTWV_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTWV_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTPR_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTPR_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTPR_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTXO_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTXO_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTXO_Label_mouseEntered(e); + } +} + +class Sander8Frame_IWRAP_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_IWRAP_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IWRAP_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTWX_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTWX_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTWX_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTWR_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTWR_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTWR_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTAVE_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTAVE_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTAVE_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTX_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTX_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTX_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTRX_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTRX_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTRX_Label_mouseEntered(e); + } +} + +class Sander8Frame_jButton3_actionAdapter + implements ActionListener { + private Sander8Frame adaptee; + Sander8Frame_jButton3_actionAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.jButton3_actionPerformed(e); + } +} + +class Sander8Frame_jButton2_actionAdapter + implements ActionListener { + private Sander8Frame adaptee; + Sander8Frame_jButton2_actionAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.jButton2_actionPerformed(e); + } +} + +class Sander8Frame_jButton1_actionAdapter + implements ActionListener { + private Sander8Frame adaptee; + Sander8Frame_jButton1_actionAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.jButton1_actionPerformed(e); + } +} + +class Sander8Frame_TEMPI_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_TEMPI_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.TEMPI_Label_mouseEntered(e); + } +} + +class Sander8Frame_VLIMIT_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_VLIMIT_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.VLIMIT_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTP_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_NTP_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTP_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_NTP_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTP_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTP_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_NTT_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_NTT_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTT_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_NTT_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTT_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTT_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_PRES0_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_PRES0_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.PRES0_Label_mouseEntered(e); + } +} + +class Sander8Frame_TAUP_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_TAUP_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.TAUP_Label_mouseEntered(e); + } +} + +class Sander8Frame_COMP_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_COMP_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.COMP_Label_mouseEntered(e); + } +} + +class Sander8Frame_DT_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_DT_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.DT_Label_mouseEntered(e); + } +} + +class Sander8Frame_NSTLIM_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NSTLIM_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NSTLIM_Label_mouseEntered(e); + } +} + +class Sander8Frame_TEMP0_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_TEMP0_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.TEMP0_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTP_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTP_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTP_Label_mouseEntered(e); + } +} + +class Sander8Frame_VRAND_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_VRAND_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.VRAND_Label_mouseEntered(e); + } +} + +class Sander8Frame_GAMMA_LN_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_GAMMA_LN_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.GAMMA_LN_Label_mouseEntered(e); + } +} + +class Sander8Frame_TAUTP_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_TAUTP_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.TAUTP_Label_mouseEntered(e); + } +} + +class Sander8Frame_IG_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_IG_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IG_Label_mouseEntered(e); + } +} + +class Sander8Frame_TEMP0LES_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_TEMP0LES_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.TEMP0LES_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTT_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTT_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTT_Label_mouseEntered(e); + } +} + +class Sander8Frame_T_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_T_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.T_Label_mouseEntered(e); + } +} + +class Sander8Frame_NRESPA_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NRESPA_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NRESPA_Label_mouseEntered(e); + } +} + +class Sander8Frame_jLabel10_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_jLabel10_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.jLabel10_mouseEntered(e); + } +} + +class Sander8Frame_IREST_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_IREST_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.IREST_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_IREST_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_IREST_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IREST_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_covergLabel_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_covergLabel_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.covergLabel_mouseEntered(e); + } +} + +class Sander8Frame_dxLabel_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_dxLabel_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.dxLabel_mouseEntered(e); + } +} + +class Sander8Frame_switchLabel_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_switchLabel_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.switchLabel_mouseEntered(e); + } +} + +class Sander8Frame_maxIterLabel_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_maxIterLabel_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.maxIterLabel_mouseEntered(e); + } +} + +class Sander8Frame_NTMIN_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_NTMIN_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTMIN_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_NTMIN_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTMIN_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTMIN_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_saveFile_Button_actionAdapter + implements ActionListener { + private Sander8Frame adaptee; + Sander8Frame_saveFile_Button_actionAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.saveFile_Button_actionPerformed(e); + } +} + +class Sander8Frame_SCEE_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_SCEE_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.SCEE_Label_mouseEntered(e); + } +} + +class Sander8Frame_NSNB_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NSNB_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NSNB_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTF_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_NTF_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTF_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_IPOL_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_IPOL_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IPOL_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_NTF_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTF_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTF_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_NTF_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTF_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTF_Label_mouseEntered(e); + } +} + +class Sander8Frame_IPOL_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_IPOL_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IPOL_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTB_Label_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTB_Label_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTB_Label_mouseEntered(e); + } +} + +class Sander8Frame_NTB_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_NTB_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTB_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_IPOL_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_IPOL_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.IPOL_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_NTB_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_NTB_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTB_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_IMIN_ComboBox_itemAdapter + implements ItemListener { + private Sander8Frame adaptee; + Sander8Frame_IMIN_ComboBox_itemAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.IMIN_ComboBox_itemStateChanged(e); + } +} + +class Sander8Frame_IMIN_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander8Frame adaptee; + Sander8Frame_IMIN_ComboBox_mouseAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IMIN_ComboBox_mouseEntered(e); + } +} + +class Sander8Frame_jMenuFileExit_ActionAdapter + implements ActionListener { + Sander8Frame adaptee; + + Sander8Frame_jMenuFileExit_ActionAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent actionEvent) { + adaptee.jMenuFileExit_actionPerformed(actionEvent); + } +} + +class Sander8Frame_Edit_MenuItem_actionAdapter + implements ActionListener { + private Sander8Frame adaptee; + Sander8Frame_Edit_MenuItem_actionAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.Edit_MenuItem_actionPerformed(e); + } +} + +class Sander8Frame_NCYC_TextField_actionAdapter + implements ActionListener { + private Sander8Frame adaptee; + Sander8Frame_NCYC_TextField_actionAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.NCYC_TextField_actionPerformed(e); + } +} + +class Sander8Frame_DX0_TextField_actionAdapter + implements ActionListener { + private Sander8Frame adaptee; + Sander8Frame_DX0_TextField_actionAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.DX0_TextField_actionPerformed(e); + } +} + +class Sander8Frame_DRMS_TextField_actionAdapter + implements ActionListener { + private Sander8Frame adaptee; + Sander8Frame_DRMS_TextField_actionAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.DRMS_TextField_actionPerformed(e); + } +} + +class Sander8Frame_MAXCYC_TextField_actionAdapter + implements ActionListener { + private Sander8Frame adaptee; + Sander8Frame_MAXCYC_TextField_actionAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.MAXCYC_TextField_actionPerformed(e); + } +} + +class Sander8Frame_jMenuHelpAbout_ActionAdapter + implements ActionListener { + Sander8Frame adaptee; + + Sander8Frame_jMenuHelpAbout_ActionAdapter(Sander8Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent actionEvent) { + adaptee.jMenuHelpAbout_actionPerformed(actionEvent); + } +} diff --git a/src/main/java/cct/amber/Sander8Frame_AboutBox.java b/src/main/java/cct/amber/Sander8Frame_AboutBox.java new file mode 100644 index 0000000..52c52e3 --- /dev/null +++ b/src/main/java/cct/amber/Sander8Frame_AboutBox.java @@ -0,0 +1,154 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.amber; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; + +/** + *

Title: Preparation of input file for Sander 8 program

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Sander8Frame_AboutBox + extends JDialog implements ActionListener { + JPanel panel1 = new JPanel(); + JPanel panel2 = new JPanel(); + JPanel insetsPanel1 = new JPanel(); + JPanel insetsPanel2 = new JPanel(); + JPanel insetsPanel3 = new JPanel(); + JButton button1 = new JButton(); + JLabel imageLabel = new JLabel(); + JLabel label1 = new JLabel(); + JLabel label2 = new JLabel(); + JLabel label3 = new JLabel(); + JLabel label4 = new JLabel(); + ImageIcon image1 = new ImageIcon(); + BorderLayout borderLayout1 = new BorderLayout(); + BorderLayout borderLayout2 = new BorderLayout(); + FlowLayout flowLayout1 = new FlowLayout(); + GridLayout gridLayout1 = new GridLayout(); + String product = "Preparation of input file for Sander 8 program"; + String version = "1.0"; + String copyright = "Copyright (c) 2005"; + String comments = "Computational Chemistry Toolkit"; + + public Sander8Frame_AboutBox(Frame parent) { + super(parent); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public Sander8Frame_AboutBox() { + this(null); + } + + /** + * Component initialization. + * + * @throws Exception + */ + private void jbInit() throws Exception { + image1 = new ImageIcon(Sander8Frame.class.getResource("Amber-64x64.png")); + imageLabel.setIcon(image1); + setTitle("About"); + panel1.setLayout(borderLayout1); + panel2.setLayout(borderLayout2); + insetsPanel1.setLayout(flowLayout1); + insetsPanel2.setLayout(flowLayout1); + insetsPanel2.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + gridLayout1.setRows(4); + gridLayout1.setColumns(1); + label1.setText("Preparation of input file for Sander 8"); + label2.setText("Version 1.0 beta"); + label3.setText("Copyright (c) 2006 ANU"); + label4.setToolTipText(""); + label4.setText("Written by Dr. V. Vasilyev (vvv900@gmail.com)"); + insetsPanel3.setLayout(gridLayout1); + insetsPanel3.setBorder(BorderFactory.createEmptyBorder(10, 60, 10, 10)); + button1.setText("OK"); + button1.addActionListener(this); + insetsPanel2.add(imageLabel, null); + panel2.add(insetsPanel2, BorderLayout.WEST); + getContentPane().add(panel1, null); + insetsPanel3.add(label1, null); + insetsPanel3.add(label2, null); + insetsPanel3.add(label3, null); + insetsPanel3.add(label4, null); + panel2.add(insetsPanel3, BorderLayout.CENTER); + insetsPanel1.add(button1, null); + panel1.add(insetsPanel1, BorderLayout.SOUTH); + panel1.add(panel2, BorderLayout.NORTH); + setResizable(true); + } + + /** + * Close the dialog on a button event. + * + * @param actionEvent ActionEvent + */ + @Override + public void actionPerformed(ActionEvent actionEvent) { + if (actionEvent.getSource() == button1) { + dispose(); + } + } +} diff --git a/src/main/java/cct/amber/Sander8JobControl.java b/src/main/java/cct/amber/Sander8JobControl.java new file mode 100644 index 0000000..1c7f377 --- /dev/null +++ b/src/main/java/cct/amber/Sander8JobControl.java @@ -0,0 +1,1444 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.amber; + +import java.io.BufferedReader; +import java.io.StringReader; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; + +import cct.tools.FortranNamelist; + +public class Sander8JobControl { + + FortranNamelist cntrl_namelist = new FortranNamelist(); + String ControlData = "mdin"; + String OutpusFile = "mdout"; + String LatestEnergyInfo = "mdinfo"; + String MolecularTopology = "prmtop"; + String InitialCoord = "inpcrd"; + String PositionRestraints = "refc"; + String CoordOverTrajectory = "mdcrd"; + String VelocitiesOverTrajectory = "mdvel"; + String EnergyOverTrajectory = "mden"; + String Restart = "restrt"; + String PolarDipoleInput = "inpdip"; + String PolarDipoleOutput = "rstdip"; + String ProtonationStateDefs = "cpin"; + String ProtonationStateDefsRestart = "cprestrt"; + String ProtonationStateOverTraj = "cpout"; + String MMTSB_Server = "mmtsb_setup.job"; + String Message = null; + static final public int TYPE_INTEGER = 0; + static final public int TYPE_FLOAT = 1; + static final public int TYPE_STRING = 2; + static final public int TYPE_UNDEFINED = 3; + int numberOfAtoms = 0; + Map FileUsage = new HashMap(); + static final Logger logger = Logger.getLogger(Sander8JobControl.class.getCanonicalName()); + // --- Some most common options + // They set to their default values according to Sander-8 Manual + int IMIN = 0; // Flag to run minimization + int NTB = 1; // Periodic boundary. If NTB .EQ. 0 then a boundary is NOT applied + float CUT = 8.0f; // This is used to specify the nonbonded cutoff, in Angstroms. + float SCNB = 2.0f; // 1-4 vdw interactions are divided by SCNB. Default 2.0. + float SCEE = 1.2f; // 1-4 electrostatic interactions are divided by SCEE; + int NSNB = 25; // Determines the frequency of nonbonded list updates when igb=0 and nbflag=0; + int IPOL = 0; // Inclusion of polarizabilities in the force field + int IGB = 0; // generalized Born solvation model + int MAXCYC = 1; // The maximum number of cycles of minimization. + int NCYC = 10; // If NTMIN is 1 then the method of minimization will be switched from steepest + //descent to conjugate gradient after NCYC cycles. + int NTMIN = 1; // Flag for the method of minimization. + int NSTLIM = 1; // Number of MD-steps to be performed. Default 1. + float DT = 0.001f; // The time step (psec). + int NTT = 1; // Switch for temperature scaling + float TEMP0 = 300.0f; // Reference temperature at which the system is to be kept, if ntt > 0. + float TEMPI = 0.0f; // Initial temperature. For the initial dynamics run, + float TAUTP = 1.0f; // Time constant, in ps, for heat bath coupling for the system, if ntt = 1. + int NTP = 0; // Flag for constant pressure dynamics. + float PRES0 = 1.0f; // Reference pressure (in units of bars, where 1 bar 1 atm) + float TAUP = 1.0f; // Pressure relaxation time (in ps), when NTP > 0. + int NTC = 1; // Flag for SHAKE to perform bond length constraints + Map ImportantVars = new HashMap(); + static Map allVars = new HashMap(); + static Map ewaldVars = new HashMap(); + + public Sander8JobControl() { + FileUsage.put("-i", ControlData); + FileUsage.put("-o", OutpusFile); + // --- Default values for the most important variables + ImportantVars.put("IMIN", new Integer(IMIN)); + ImportantVars.put("NTB", new Integer(NTB)); + ImportantVars.put("CUT", new Float(CUT)); + ImportantVars.put("SCNB", new Float(SCNB)); + ImportantVars.put("SCEE", new Float(SCEE)); + ImportantVars.put("NSNB", new Integer(NSNB)); + ImportantVars.put("IPOL", new Integer(IPOL)); + ImportantVars.put("IGB", new Integer(IGB)); + ImportantVars.put("MAXCYC", new Integer(MAXCYC)); + ImportantVars.put("NCYC", new Integer(NCYC)); + ImportantVars.put("NTMIN", new Integer(NTMIN)); + ImportantVars.put("NSTLIM", new Integer(NSTLIM)); + ImportantVars.put("DT", new Float(DT)); + ImportantVars.put("NTT", new Integer(NTT)); + ImportantVars.put("TEMP0", new Float(TEMP0)); + ImportantVars.put("TEMPI", new Float(TEMPI)); + ImportantVars.put("TAUTP", new Float(TAUTP)); + ImportantVars.put("NTP", new Integer(NTP)); + ImportantVars.put("PRES0", new Float(PRES0)); + ImportantVars.put("TAUP", new Float(TAUP)); + ImportantVars.put("NTC", new Integer(NTC)); + + SanderVariable var; + + // IMIN + var = new SanderVariable("Flag to run minimization", true); + var.addValue(new SanderVariableValue("0", + "No minimization (only do molecular dynamics)", true)); + var.addValue(new SanderVariableValue("1", + "Perform minimization (and no molecular dynamics)", false)); + var.addValue(new SanderVariableValue("5", + "Read in a trajectory for analysis", false)); + + allVars.put("IMIN", var); + + // IREST + var = new SanderVariable("Flag to restart the run.", true); + var.addValue(new SanderVariableValue("0", + "No effect", true)); + var.addValue(new SanderVariableValue("1", + "Restart calculation. Requires velocities in coordinate input file", false)); + allVars.put("IREST", var); + + // NMROPT + + var = new SanderVariable("", true); + var.addValue(new SanderVariableValue("0", + "No nmr-type analysis will be done", true)); + var.addValue(new SanderVariableValue("1", + "NOESY volume restraints or chemical shift restraints" + + " will be read as well", false)); + var.addValue(new SanderVariableValue("2", + "NOESY volume restraints or chemical shift restraints" + + " will be read as well", false)); + allVars.put("NMROPT", var); + + // --- Energy minimization. *********************** + + // MAXCYC + + var = new SanderVariable( + "The maximum number of cycles of minimization", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("1", + "", true)); + allVars.put("MAXCYC", var); + + // NCYC + + var = new SanderVariable( + "If NTMIN is 1 then the method of minimization will be switched from steepest " + + " descent to conjugate gradient after NCYC cycles", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("10", + "", true)); + allVars.put("NCYC", var); + + // NTMIN + + var = new SanderVariable( + "Flag for the method of minimization", true); + var.addValue(new SanderVariableValue("0", + "Full conjugate gradient minimization. The first 4 cycles are steepest" + + " descent at the start of the run and after every nonbonded pairlist" + + " update.", false)); + var.addValue(new SanderVariableValue("1", + "For NCYC cycles the steepest descent method is used then conjugate" + + " gradient is switched on", true)); + var.addValue(new SanderVariableValue("2", + "Only the steepest descent method is used", false)); + var.addValue(new SanderVariableValue("3", + "The XMIN method is used, see amber8/doc/lmod.pdf", false)); + var.addValue(new SanderVariableValue("4", + "The LMOD method is used, see amber8/doc/lmod.pdf", false)); + allVars.put("NTMIN", var); + + // DX0 + + var = new SanderVariable( + "The initial step length. If the initial step length is big then the minimizer will" + + " try to leap the energy surface and sometimes the first few cycles will give a" + + " huge energy, howev er the minimizer is smart enough to adjust itself", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.01", + "", true)); + allVars.put("DX0", var); + + // DRMS + + var = new SanderVariable( + "The convergence criterion for the energy gradient: minimization will halt" + + " when the root-mean-square of the Cartesian elements of the gradient is less" + + " than DRMS. Default 1.0E-4 kcal/mole A�", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("1.0E-4", + "", true)); + allVars.put("DRMS", var); + + // --- Potential function options ************************** + + // NTF + + var = new SanderVariable( + "Force evaluation. Note: If SHAKE is used (see NTC), it is not necessary to " + + "calculate forces for the constrained bonds", true); + var.addValue(new SanderVariableValue("1", + "Complete interaction is calculated", true)); + var.addValue(new SanderVariableValue("2", + "Bond interactions involving H-atoms omitted (use with NTC=2)", false)); + var.addValue(new SanderVariableValue("3", + "All the bond interactions are omitted (use with NTC=3)", false)); + var.addValue(new SanderVariableValue("4", + "Angle involving H-atoms and all bonds are omitted", false)); + var.addValue(new SanderVariableValue("5", + "All bond and angle interactions are omitted", false)); + var.addValue(new SanderVariableValue("6", + "Dihedrals involving H-atoms and all bonds and all angle interactions are omitted", false)); + var.addValue(new SanderVariableValue("7", + "All bond, angle and dihedral interactions are omitted", false)); + var.addValue(new SanderVariableValue("8", + "All bond, angle, dihedral and non-bonded interactions are omitted", false)); + + allVars.put("NTF", var); + + // NTB + + var = new SanderVariable( + "Periodic boundary. If NTB .EQ. 0 then a boundary is NOT applied regardless" + + " of any boundary condition information in the topology file. The value of NTB " + + "specifies whether constant volume or constant pressure dynamics will be used", true); + + var.addValue(new SanderVariableValue("0", + "No periodicity is applied and PME is off", false)); + var.addValue(new SanderVariableValue("1", + "Constant volume", true)); + var.addValue(new SanderVariableValue("2", + "Constant Pressure", false)); + + allVars.put("NTB", var); + + // DIELC + + var = new SanderVariable( + "Dielectric multiplicative constant for the electrostatic interactions. " + + "Please note this is NOT related to dielectric constants for generalized " + + "Born simulations.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("1.0", + "", true)); + allVars.put("DIELC", var); + + // CUT + + var = new SanderVariable( + "This is used to specify the nonbonded cutoff, in Angstroms. For PME, the " + + "cutoff is used to limit direct space sum, and the default value of 8.0 is usually " + + "a good value. When igb>0, the cutoff is used to truncate nonbonded pairs (on " + + "an atom-by-atom basis.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + + var.addValue(new SanderVariableValue("8.0", + "", true)); + allVars.put("CUT", var); + + // SCNB + + var = new SanderVariable( + "1-4 vdw interactions are divided by SCNB", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + + var.addValue(new SanderVariableValue("2.0", "", true)); + allVars.put("SCNB", var); + + // SCEE + + var = new SanderVariable( + "1-4 electrostatic interactions are divided by SCEE; the 1991 and previous " + + "force fields used 2.0, while the 1994 force field uses 1.2", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("1.2", "", true)); + allVars.put("SCEE", var); + + // NSNB + + var = new SanderVariable( + "Determines the frequency of nonbonded list updates when igb=0 and " + + "nbflag=0; see the description of nbflag for more information", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("25", "", true)); + allVars.put("NSNB", var); + + // IPOL + + var = new SanderVariable( + "Inclusion of polarizabilities in the force field.\n= 0 non polar calc (default)\n" + + "= 1 turn on polarization calculation. Polarizabilities must be present in prmtop.", true); + + var.addValue(new SanderVariableValue("0", + "Nonpolar calc", true)); + var.addValue(new SanderVariableValue("1", + "Polar calc", false)); + allVars.put("IPOL", var); + + // --- General flags describing the calculation + + // NTX + + var = new SanderVariable( + "Option to read the initial coordinates, velocities and box size from the" + + " \"inpcrd\" file. The options 1-2 must be used when one is starting from minimized" + + " or model-built coordinates. If an MD restrt file is used as inpcrd, then" + + "options 4-7 may be used.", true); + + var.addValue(new SanderVariableValue("1", + "Formatted X", true)); + var.addValue(new SanderVariableValue("2", + "Unformatted X", false)); + var.addValue(new SanderVariableValue("4", + "Unformatted X and V", false)); + var.addValue(new SanderVariableValue("5", + "Formatted X and V", false)); + var.addValue(new SanderVariableValue("6", + "Unformatted X, V and BOX(1..3)", false)); + var.addValue(new SanderVariableValue("7", + "Unformatted X, V and BOX(1..3)", false)); + allVars.put("NTX", var); + + // NTRX + + var = new SanderVariable( + "Format of the Cartesian coordinates for restraint from file \"refc\". Note: the" + + " program expects file \"refc\" to contain coordinates for all the atoms in the system." + + " A subset for the actual restraints is selected by restraintmask in the control" + + "namelist.", true); + + var.addValue(new SanderVariableValue("0", + "Unformatted (binary) form)", false)); + var.addValue(new SanderVariableValue("1", + "Formatted (ascii) form", true)); + allVars.put("NTRX", var); + + // --- Nature and format of the output. + + // NTXO + + var = new SanderVariable( + "Format of the final coordinates, velocities, and box size (if constant volume or" + + " pressure run) written to file \"restrt\".", true); + + var.addValue(new SanderVariableValue("0", + "Unformatted)", false)); + var.addValue(new SanderVariableValue("1", + "Formatted", true)); + allVars.put("NTXO", var); + + // NTPR + + var = new SanderVariable( + "Every NTPR steps energy information will be printed in human-readable form" + + " to files \"mdout\" and \"mdinfo\". \"mdinfo\" is closed and reopened each time, so" + + " it always contains the most recent energy and temperature.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("50", + "", true)); + allVars.put("NTPR", var); + + // NTAVE + + var = new SanderVariable( + "Every NTAVE steps of dynamics, running averages of average energies and" + + " fluctuations over the last NTAVE steps will be printed out. Default value of 0" + + " disables this printout.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", + "", true)); + allVars.put("NTAVE", var); + + // NTWR + + var = new SanderVariable( + "Every NTWR steps during dynamics, the \"restrt\" file will be written, ensuring" + + " that recovery from a crash will not be so painful. If" + + " NTWR<0, a unique copy of the file, restrt_nstep, is written every abs(NTWR)" + + "steps. Default 500.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("500", + "", true)); + allVars.put("NTWR", var); + + // IWRAP + + var = new SanderVariable( + "If set to 1, the coordinates written to the restart and trajectory files will be" + + " \"wrapped\" into a primary box. This often makes the resulting structures" + + " look better visually, but has no effect on the energy or forces. Performing" + + " such wrapping, however, can mess up diffusion and other calculations. The" + + " default (when iwrap=0) is to not perform any such manipulations", true); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", + "No \"Wrapping\" coordinates into a primary box", true)); + var.addValue(new SanderVariableValue("1", + "\"Wrap\" coordinates into a primary box", false)); + allVars.put("IWRAP", var); + + // NTWX + + var = new SanderVariable( + "Every NTWX steps the coordinates will be written to file \"mdcrd\". NTWX=0" + + " inhibits all output. Default 0.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", + "", true)); + allVars.put("NTWX", var); + + // NTWV + + var = new SanderVariable( + "Every NTWV steps the velocities will be written to file \"mdvel\". NTWV=0" + + " inhibits all output. Default 0.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", + "", true)); + allVars.put("NTWV", var); + + // NTWE + + var = new SanderVariable( + "Every NTWE steps the energies and temperatures will be written to file" + + " \"mden\" in compact form. NTWE=0 inhibits all output. Default 0.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", + "", true)); + allVars.put("NTWE", var); + + // IOUTFM - obsolete + + var = new SanderVariable( + "Format of velocity, coordinate, and energy sets. Note: these values are \"backwards\"" + + " compared to NTRX and NTXO; this is an ancient mistake that we are" + + " reluctant to change, since it would break existing scripts.", true); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", + "Formatted (default)", true)); + var.addValue(new SanderVariableValue("1", + "Binary", false)); + allVars.put("IOUTFM", var); + + // NTWPRT + + var = new SanderVariable( + "Coordinate/velocity archive limit flag. This flag can be used to decrease the" + + " size of the coordinate / velocity archive files, by only including that portion of" + + " the system of greatest interest. The Coord/velocity archives will include:\n" + + "= 0 all atoms of the system (default)\n" + + "> 0 only atoms 1->NTWPRT", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", + "", true)); + allVars.put("NTWPRT", var); + + // IDECOMP + + var = new SanderVariable( + "This option is only really useful in conjunction with mm_pbsa, where it is" + + " turned on automatically if required.", true); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", + "Do nothing (default).", true)); + var.addValue(new SanderVariableValue("1", + "Decompose energies on a per-residue basis; 1-4 EEL + 1-4 VDW are" + + " added to internal (bond, angle, dihedral) energies.", false)); + var.addValue(new SanderVariableValue("2", + "Decompose energies on a per-residue basis; 1-4 EEL + 1-4 VDW are" + + " added to EEL and VDW.", false)); + var.addValue(new SanderVariableValue("3", + "Decompose energies on a pairwise per-residue basis; the rest is equal" + + " to \"1\".", false)); + var.addValue(new SanderVariableValue("4", + "Decompose energies on a pairwise per-residue basis; the rest is" + + " equal to \"2\".", false)); + allVars.put("IDECOMP", var); + + // --- Generalized Born/Surface Area options. + + // IGB + + var = new SanderVariable( + "The generalized Born solvation model can be used instead of explicit water for non-polarizable" + + " force fields such as ff94 or ff99. Users should understand that all" + + " (current) GB models have limitations and should proceed with caution. Generalized Born simulations" + + " can only be run for non-periodic systems The nonbonded cutoff for GB" + + " calculations should be greater than that for PME calculations, perhaps cut=16.", true); + + var.addValue(new SanderVariableValue("0", + "No GB", true)); + var.addValue(new SanderVariableValue("1", + "Hawkins et all model", false)); + var.addValue(new SanderVariableValue("2", + "Onufriev et all model", false)); + var.addValue(new SanderVariableValue("5", + "Onufriev et all model II", false)); + var.addValue(new SanderVariableValue("10", + "Poisson-Boltzmann solver", false)); + allVars.put("IGB", var); + + // INTDIEL + + var = new SanderVariable( + "Sets the interior dielectric constant of the molecule of interest. Default is 1.0." + + " Other values have not been extensively tested.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("1.0", + "", true)); + allVars.put("INTDIEL", var); + + // EXTDIEL + + var = new SanderVariable( + "Sets the exterior or solvent dielectric constant. Default is 78.5.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("78.5", + "", true)); + allVars.put("EXTDIEL", var); + + // SALTCON + + var = new SanderVariable( + "Sets the concentration (M) of 1-1 mobile counterions in solution, using a" + + " modified generalized Born theory based on the Debye-H�ckel limiting law for" + + " ion screening of interactions. Default is 0.0 M (i.e. no Debye-H�ckel" + + " screening.) Setting saltcon to a non-zero value does result in some increase in" + + "computation time.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.0", + "", true)); + allVars.put("SALTCON", var); + + // RGBMAX + + var = new SanderVariable( + "This parameter controls the maximum distance between atom pairs that will" + + " be considered in carrying out the pairwise summation involved in calculating" + + " the effective Born radii. Atoms whose associated spheres are farther way than" + + " rgbmax from given atom will not contribute to that atom�s effective Born" + + " radius. The default is 25 �, which is usually plenty for single-domain proteins of a few hundred residues.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("25.0", + "", true)); + allVars.put("RGBMAX", var); + + // RBORNSTAT + + var = new SanderVariable( + "If rbornstat = 1, the statistics of the effective Born radii for each atom of the" + + " molecule throughout the molecular dynamics simulation are reported in the" + + " output file. Default is 0.", true); + var.addValue(new SanderVariableValue("0", + "No output of the statistics of the effective Born radii for each atom", true)); + var.addValue(new SanderVariableValue("1", + "The statistics of the effective Born radii for each atom of the" + + " molecule throughout the molecular dynamics simulation are reported in the" + + " output file.", false)); + allVars.put("RBORNSTAT", var); + + // OFFSET + + var = new SanderVariable( + "The dielectric radii for generalized Born calculations are decreased by a uniform" + + " value \"offset\" to give the \"intrinsic radii\" used to obtain effective Born" + + " radii. Default 0.09 �.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.09", + "", true)); + allVars.put("OFFSET", var); + + // SURFTEN + + var = new SanderVariable( + "Surface tension used to calculate the nonpolar contribution to the free energy" + + " of solvation (when gbsa = 1), as Enp = surften*SA. The default is 0.005" + + " kcal/mol-�2", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.005", + "", true)); + allVars.put("SURFTEN", var); + + // RDT + + var = new SanderVariable( + "This parameter is only used for GB simulations with LES (Locally Enhanced" + + " Sampling). In GB+LES simulations, non-LES atoms require multiple effective" + + " Born radii due to alternate descreening effects of different LES copies." + + " Default 0.01 �.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.01", + "", true)); + allVars.put("RDT", var); + + // GBSA + + var = new SanderVariable( + "Option to carry out GB/SA (generalized Born/surface area) simulations. For" + + " the default value of 0, surface area will not be computed and included in the" + + " solvation term. If gbsa = 1, surface area will be computed using the LCPO" + + " model. If gbsa = 2, surface area will be computed by recursively approximating" + + " a sphere around an atom, starting from an icosahedra.", true); + + var.addValue(new SanderVariableValue("0", + "No surface area will not be computed and included in the solvation term.", true)); + var.addValue(new SanderVariableValue("1", + "Surface area will be computed using the LCPO model.", false)); + var.addValue(new SanderVariableValue("2", + "Surface area will be computed by recursively approximating a sphere around an atom, starting from an icosahedra.", false)); + allVars.put("GBSA", var); + + // --- Frozen or restrained atoms. + + // --- Molecular dynamics. + + // NSTLIM + + var = new SanderVariable( + "Number of MD-steps to be performed. Default 1.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("1", + "", true)); + allVars.put("NSTLIM", var); + + // NSCM + + var = new SanderVariable( + "Flag for the removal of translational and rotational center-of-mass (COM)" + + " motion at regular intervals. For non-periodic simulations, after every NSCM" + + " steps, translational and rotational motion will be removed. For periodic systems," + + " just the translational center-of-mass motion will be removed. This flag" + + " is ignored for belly simulations. Default 1000.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("1000", + "", true)); + allVars.put("NSCM", var); + + // T + + var = new SanderVariable( + "The time at the start (psec) this is for your own reference and is not critical." + + " Start time is taken from the coordinate input file if IREST=1. Default 0.0.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.0", + "", true)); + allVars.put("T", var); + + // DT + + var = new SanderVariable( + "The time step (psec). Recommended MAXIMUM is .002 if SHAKE is used," + + " or .001 if it isn�t. Note that for temperatures above 300K, the step size should" + + " be reduced since greater temperatures mean increased velocities and longer" + + " distance traveled between each force evaluation, which can lead to anomalously" + + " high energies and system blowup. Default 0.001.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.001", + "", true)); + allVars.put("DT", var); + + // NRESPA + + var = new SanderVariable( + "This variable allows the user to evaluate slowly-varying terms in the force" + + " field less frequently. If NRESPA>1 these slowly-varying forces are evaluated every nrespa steps." + + " The forces are adjusted appropriately, leading to an impulse at that step. If" + + " nrespa*dt is less than or equal to 4 fs the energy conservation is not seriously" + + " compromised. However if nrespa*dt > 4 fs the simulation becomes less stable.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("1", + "", true)); + allVars.put("NRESPA", var); + + // --- Temperature regulation + + // NTT + + var = new SanderVariable( + "Switch for temperature scaling. Note that setting ntt=0 corresponds to the" + + " microcanonical (NVE) ensemble (which should approach the canonical one" + + " for large numbers of degrees of freedom). Some aspects of the \"weak-coupling" + + " ensemble\" (ntt=1) have been examined, and roughly interpolate between" + + " the microcanonical and canonical ensembles. The ntt=2 and 3 options" + + " correspond to the canonical (constant T) ensemble. The ntt=4 option is" + + " included for historical reasons, but does not correspond to any of the traditional" + + " ensembles.", true); + + var.addValue(new SanderVariableValue("0", + "Constant total energy classical dynamics (assuming that ntb<2, as" + + " should probably always be the case when ntt=0).", true)); + var.addValue(new SanderVariableValue("1", + "Constant temperature, using the weak-coupling algorithm. A" + + " single scaling factor is used for all atoms.", false)); + var.addValue(new SanderVariableValue("2", + "Andersen temperature coupling scheme, in which imaginary" + + " \"collisions\" randomize the velocities to a distribution corresponding" + + " to temp0 every vrand steps.", false)); + var.addValue(new SanderVariableValue("3", + "Use Langevin dynamics with the collision frequency gamma given by" + + " gamma_ln. Note that when gamma has its default value" + + " of zero, this is the same as setting ntt = 0.", false)); + + allVars.put("NTT", var); + + // TEMP0 + + var = new SanderVariable( + "Reference temperature at which the system is to be kept, if ntt > 0. Note that" + + " for temperatures above 300K, the step size should be reduced since increased" + + " distance traveled between evaluations can lead to SHAKE and other problems." + + " Default 300.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("300", + "", true)); + allVars.put("TEMP0", var); + + // TEMP0LES + + var = new SanderVariable( + "This is the target temperature for all LES particles. If" + + " temp0les<0, a single temperature bath is used for all atoms, otherwise separate" + + " thermostats are used for LES and non-LES particles. Default is -1, corresponding" + + " to a single (weak-coupling) temperature bath.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("-1", + "", true)); + allVars.put("TEMP0LES", var); + + // TEMPI + + var = new SanderVariable( + "Initial temperature. For the initial dynamics run, (NTX .lt. 3) the velocities" + + " are assigned from a Maxwellian distribution at TEMPI K. If TEMPI = 0.0," + + " the velocities will be calculated from the forces instead. TEMPI has no effect" + + " if NTX .gt. 3. Default 0.0.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.0", + "", true)); + allVars.put("TEMPI", var); + + // IG + + var = new SanderVariable( + "The seed for the random number generator. The MD starting velocity is" + + " dependent on the random number generator seed if NTX .lt. 3 .and. TEMPI" + + " .ne. 0.0. Default 71277.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("71277", + "", true)); + allVars.put("IG", var); + + // TAUTP + + var = new SanderVariable( + "Time constant, in ps, for heat bath coupling for the system, if ntt = 1. Default" + + " is 1.0. Generally, values for TAUTP should be in the range of 0.5-5.0 ps, with" + + " a smaller value providing tighter coupling to the heat bath and, thus, faster" + + " heating and a less natural trajectory. Smaller values of TAUTP result in" + + " smaller fluctuations in kinetic energy, but larger fluctuations in the total" + + " energy. Values much larger than the length of the simulation result in a return" + + "to constant energy conditions.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("1.0", + "", true)); + allVars.put("TAUTP", var); + + // GAMMA_LN + + var = new SanderVariable( + "The collision frequency gamma , in ps-1, when ntt = 3. A simple Leapfrog integrator" + + " is used to propagate the dynamics, with the kinetic energy adjusted to be correct" + + " for the harmonic oscillator case. Note that it is not necessary that" + + " gamma approximate the physical collision frequency. In fact, it is often advantageous," + + " in terms of sampling or stability of integration, to use much smaller" + + " values. Default is 0", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0", + "", true)); + allVars.put("GAMMA_LN", var); + + // VRAND + + var = new SanderVariable( + "If vrand>0 and ntt=2, the velocities will be randomized to temperature" + + " TEMP0 every vrand steps.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", + "", true)); + allVars.put("VRAND", var); + + // VLIMIT + + var = new SanderVariable( + "If not equal to 0.0, then any component of the velocity that is greater than" + + " abs(VLIMIT) will be reduced to VLIMIT (preserving the sign). This can be" + + " used to avoid occasional instabilities in molecular dynamics runs. VLIMIT" + + " should generally be set to a value like 20 (the default), which is well above the" + + " most probable velocity in a Maxwell-Boltzmann distribution at room temperature.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("20", + "", true)); + allVars.put("VLIMIT", var); + + // --- Pressure regulation. + + // NTP + + var = new SanderVariable( + "Flag for constant pressure dynamics. This option should be set to 1 or 2 when" + + " Constant Pressure periodic boundary conditions are used (NTB = 2).", true); + + var.addValue(new SanderVariableValue("0", + "No pressure scaling", true)); + var.addValue(new SanderVariableValue("1", + "Isotropic scaling", false)); + var.addValue(new SanderVariableValue("2", + "MD with anisotropic (x-,y-,z-) pressure scaling: this should only be" + + " used with orthogonal boxes (i.e. with all angles set to 90 degrees)." + + " Anisotropic scaling is primarily intended for non-isotropic systems," + + " such as membrane simulations, where the surface tensions are different" + + " in different directions; it is generally not appropriate for solutes" + + " dissolved in water.", false)); + allVars.put("NTP", var); + + // PRES0 + + var = new SanderVariable( + "Reference pressure (in units of bars, where 1 bar � 1 atm) at which the system" + + " is maintained ( when NTP > 0). Default 1.0.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("1", + "", true)); + allVars.put("PRES0", var); + + // COMP + + var = new SanderVariable( + "Compressibility of the system when NTP > 0. The units are in 1.0E-06/bar; a" + + " value of 44.6 (default) is appropriate for water.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("44.6", + "", true)); + allVars.put("COMP", var); + + // TAUP + + var = new SanderVariable( + "Pressure relaxation time (in ps), when NTP > 0. The recommended value is" + + " between 1.0 and 5.0 psec. Default value is 1.0, but larger values may sometimes" + + " be necessary (if your trajectories seem unstable).", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("1.0", + "", true)); + allVars.put("TAUP", var); + + // --- Frozen or restrained atoms. + + // IBELLY + + var = new SanderVariable( + "Flag for belly type dynamics.", true); + + var.addValue(new SanderVariableValue("0", + "No belly run (default).", true)); + var.addValue(new SanderVariableValue("1", + "Belly run. A subset of the atoms in the system will be allowed to" + + " move, and the coordinates of the rest will be frozen. The moving" + + " atoms are specified bellymask. This option is not available when" + + " igb>0. Note also that this option does not provide any significant" + + " speed advantage, and is maintained primarily for backwards compatibility" + + " with older version of Amber. Most applications should use the" + + "ntr variable instead", false)); + allVars.put("IBELLY", var); + + // NTR + + var = new SanderVariable( + "Flag for restraining specified atoms in Cartesian space using a harmonic" + + " potential. The restrained atoms are determined by the restraintmask string." + + " The force constant is given by restraint_wt. The coordinates are read in" + + " \"restrt\" format from the \"refc\" file", true); + + var.addValue(new SanderVariableValue("0", + "No position restraints (default)", true)); + var.addValue(new SanderVariableValue("1", + "MD with restraint of specified atoms", false)); + allVars.put("NTR", var); + + // RESTRAINT_WT + + var = new SanderVariable( + "The weight (in kcal/mol \u2212 �2) for the positional restraints. The restraint is of" + + " the form k(\u0394x)2, where k is the value given by this variable, and \u0394x is the difference" + + " between one of the Cartesian coordinates of a restrained atom and its" + + " reference position. There is a term like this for each Cartesian coordinate of" + + " each restrainted atom.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("1.0", + "", true)); + allVars.put("RESTRAINT_WT", var); + + // RESTRAINTMASK + + var = new SanderVariable( + "String that specifies the restrained atoms when ntr=1.", false); + var.setVarType(Sander8JobControl.TYPE_STRING); + var.addValue(new SanderVariableValue(" ", + "", true)); + allVars.put("RESTRAINTMASK", var); + + // BELLYMASK + + var = new SanderVariable( + "String that specifies the moving atoms when ibelly=1. Note that these mask" + + " strings are limited to a maximum of 80 characters.", false); + var.setVarType(Sander8JobControl.TYPE_STRING); + var.addValue(new SanderVariableValue(" ", + "", true)); + allVars.put("BELLYMASK", var); + + // --- SHAKE bond length constraints. + + // NTC + + var = new SanderVariable( + "Flag for SHAKE to perform bond length constraints. (See also NTF in" + + " the Potential function section. In particular, typically NTF = NTC.) The" + + " SHAKE option should be used for most MD calculations. Since SHAKE is an " + + " algorithm based on dynamics, the minimizer is not aware of what SHAKE is doing;" + + " for this reason, minimizations generally should be carried out without SHAKE." + + " One exception is short minimizations whose purpose is to remove bad contacts" + + " before dynamics can begin.", true); + + var.addValue(new SanderVariableValue("1", + "SHAKE is not performed (default)", true)); + var.addValue(new SanderVariableValue("2", + "Bonds involving hydrogen are constrained", false)); + var.addValue(new SanderVariableValue("3", + "All bonds are constrained (not available for parallel runs in sander)", false)); + allVars.put("NTC", var); + + // TOL + + var = new SanderVariable( + "Relative geometrical tolerance for coordinate resetting in shake. Recommended" + + " maximum: <0.00005 Angstrom Default 0.00001.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.00001", + "", true)); + allVars.put("TOL", var); + + // JFASTW + + var = new SanderVariable( + "Fast water definition flag. By default, the system is searched for water" + + " residues, and special routines are used to SHAKE these systems", true); + + var.addValue(new SanderVariableValue("0", + "Normal operation. Waters are identified by the default names (given" + + " below), unless they are redefined, as described below.", true)); + var.addValue(new SanderVariableValue("4", + "Do not use the fast SHAKE routines for waters.", false)); + allVars.put("JFASTW", var); + + // WATNAM + + var = new SanderVariable( + "The residue name the program expects for water. Default �WAT �.", false); + var.setVarType(Sander8JobControl.TYPE_STRING); + var.addValue(new SanderVariableValue("WAT ", + "", true)); + allVars.put("WATNAM", var); + + // OWTNM + + var = new SanderVariable( + "The atom name the program expects for the oxygen of water. Default �O �.", false); + var.setVarType(Sander8JobControl.TYPE_STRING); + var.addValue(new SanderVariableValue("O ", + "", true)); + allVars.put("OWTNM", var); + + // HWTNM1 + + var = new SanderVariable( + "The atom name the program expects for the 1st H of water. Default �H1 �.", false); + var.setVarType(Sander8JobControl.TYPE_STRING); + var.addValue(new SanderVariableValue("H1 ", + "", true)); + allVars.put("HWTNM1", var); + + // HWTNM2 + + var = new SanderVariable( + "The atom name the program expects for the 2nd H of water. Default �H2 �.", false); + var.setVarType(Sander8JobControl.TYPE_STRING); + var.addValue(new SanderVariableValue("H2 ", + "", true)); + allVars.put("HWTNM2", var); + + // --- Water cap. + + // IVCAP + + var = new SanderVariable( + "Flag to control cap option. The \"cap\" refers to a spherical portion of water" + + " centered on a point in the solute and restrained by a soft half-harmonic potential." + + " For the best physical realism, this option should be combined with" + + " igb=10, in order to include the reaction field of waters that are beyond the cap" + + "radius.", true); + + var.addValue(new SanderVariableValue("0", + "Cap will be in effect if it is in the prmtop file (default).", true)); + var.addValue(new SanderVariableValue("2", + "Cap will be inactivated, even if parameters are present in the prmtop file.", false)); + allVars.put("IVCAP", var); + + // FCAP + + var = new SanderVariable( + "The force constant for the cap restraint potential.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("1", "", true)); + allVars.put("FCAP", var); + + // Variables WHICH ARE NOT PARSED !!! + + // ISCALE + + var = new SanderVariable( + "Number of additional variables to optimize beyond the 3N structural parameters." + + " (Default = 0). At present, this is only used with residual dipolar coupling" + + "restraints", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", "", true)); + allVars.put("ISCALE", var); + + // NOESKP --- !!! should be enumerated + var = new SanderVariable( + "The NOESY volumes will only be evaluated if mod(nstep, noeskp) = 0; otherwise" + + " the last computed values for intensities and derivatives will be used." + + " (default = 1, i.e. evaluate volumes at every step)", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("1", "", true)); + allVars.put("NOESKP", var); + + // IPNLTY --- !!! should be enumerated + var = new SanderVariable( + "", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("1", "", true)); + allVars.put("IPNLTY", var); + + // MXSUB + + var = new SanderVariable( + "Maximum number of submolecules that will be used. This is used to determine" + + " how much space to allocate for the NOESY calculations. Default 1.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("1", "", true)); + allVars.put("MXSUB", var); + + // SCALM + + var = new SanderVariable( + "\"Mass\" for the additional scaling parameters. Right now they are restricted to" + + " all have the same value. The larger this value, the slower these extra variables" + + " will respond to their environment. Default 100 amu.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("100", "", true)); + allVars.put("SCALM", var); + + // PENCUT + + var = new SanderVariable( + "In the summaries of the constraint deviations, entries will only be made if the" + + " penalty for that term is greater than PENCUT. Default 0.1.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.1", "", true)); + allVars.put("PENCUT", var); + + // TAUSW + + var = new SanderVariable( + "For noesy volume calculations (NMROPT = 2), intensities with mixing times" + + " less that TAUSW (in seconds) will be computed using perturbation theory," + + " whereas those greater than TAUSW will use a more exact theory." + + " To always use the \"exact\" intensities and" + + " derivatives, set TAUSW = 0.0; to always use perturbation theory, set TAUSW" + + " to a value larger than the largest mixing time in the input. Default is TAUSW" + + " of 0.1 second, which should work pretty well for most systems.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.1", "", true)); + allVars.put("TAUSW", var); + + // ---- Variables for ewald namelist + + // ORDER + + var = new SanderVariable( + "The order of the B-spline interpolation. The higher the order, the better the" + + " accuracy (unless the charge grid is too coarse). The minimum order is 3. An" + + " order of 4 (the default) implies a cubic spline approximation which is a good" + + " standard value. Note that the cost of the PME goes as roughly the order to the" + + " third power.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("4", "", true)); + ewaldVars.put("ORDER", var); + + // VERBOSE + + var = new SanderVariable( + "Standard use is to have VERBOSE = 0. Setting VERBOSE to higher values" + + " (up to a maximum of 3) leads to voluminous output of information about the" + + " PME run.", true); + + var.addValue(new SanderVariableValue("0", + "", true)); + var.addValue(new SanderVariableValue("1", + "", false)); + var.addValue(new SanderVariableValue("2", + "", false)); + var.addValue(new SanderVariableValue("3", + "", false)); + ewaldVars.put("VERBOSE", var); + + // EW_TYPE + + var = new SanderVariable( + "Standard use is to have EW_TYPE = 0 which turns on the particle mesh" + + " ewald (PME) method. When EW_TYPE = 1, instead of the approximate," + + " interpolated PME, a regular Ewald calculation is run. The number of reciprocal" + + " vectors used depends upon RSUM_TOL, or can be set by the user. The" + + " exact Ewald summation is present mainly to serve as an accuracy check" + + " allowing users to determine if the PME grid spacing, order and direct sum tolerance" + + " lead to acceptable results.", true); + + var.addValue(new SanderVariableValue("0", + "Turns on the particle mesh ewald (PME) method", true)); + var.addValue(new SanderVariableValue("1", + "A regular Ewald calculation is run.", false)); + ewaldVars.put("EW_TYPE", var); + + // DSUM_TOL + + var = new SanderVariable( + "This relates to the width of the direct sum part of the Ewald sum, requiring" + + " that the value of the direct sum at the Lennard-Jones cutoff value (specified in" + + " CUT as during standard dynamics) be less than DSUM_TOL. In practice it" + + " has been found that the relative error in the Ewald forces (RMS) due to cutting" + + " off the direct sum at CUT is between 10.0 and 50.0 times DSUM_TOL.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.00001", "", true)); + ewaldVars.put("DSUM_TOL", var); + + // RSUM_TOL + + var = new SanderVariable( + "This serves as a way to generate the number of reciprocal vectors used in an" + + " Ewald sum. Typically the relative RMS reciprocal sum error is about 5-10" + + " times RSUM_TOL. Default is 5 x 10\u22125.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.00005", "", true)); + ewaldVars.put("RSUM_TOL", var); + + // --- MLIMIT(1,2,3) - !!! not implemented yet + + // EW_COEFF + + var = new SanderVariable( + "Ewald coefficient, in �\u22121. Default is determined by dsum_tol and cutoff. If it" + + " is explicitly inputed then that value is used, and dsum_tol is computed from" + + " ew_coeff and cutoff.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + //var.addValue(new SanderVariableValue("0.00005", "", true)); + ewaldVars.put("EW_COEFF", var); + + } + + public float getCutoff() { + Float f = (Float) ImportantVars.get("CUT"); + return f.floatValue(); + } + + public Map getAllVariablesInfo() { + return allVars; + } + + public int getNumberOfAtoms() { + return numberOfAtoms; + } + + public void setNumberOfAtoms(int n) { + numberOfAtoms = n; + } + + public int numberOfEnergySteps() { + Integer i = (Integer) ImportantVars.get("NSTLIM"); + //logger.info("NSTLIM: "+i.toString()); + return i.intValue(); + } + + public String getGeneralParameters(String filename, int fileType) { + String mess = null; + + if (fileType == 0) { // --- Read in from file + mess = cntrl_namelist.findAndParseFortranNamelist(filename, "cntrl"); + } else if (fileType == 1) { // --- Read in from string bufer + BufferedReader in = new BufferedReader(new StringReader(filename)); + //logger.info("Internal Text: "+filename); + mess = cntrl_namelist.findAndParseFortranNamelist(in, "cntrl"); + //in.close(); + //logger.info("After reading text bufer: "+mess); + } else { + return "getGeneralParameters: Internal Error: Unknown file type"; + } + + if (mess.compareTo("Ok") != 0) { + return mess; + } + Map vars = cntrl_namelist.getVariables(); + Set set = vars.entrySet(); + Iterator i = set.iterator(); + + // --- Debug print out + + while (i.hasNext()) { + Map.Entry me = (Map.Entry) i.next(); + String key = (String) me.getKey(); + System.out.print(key + " : "); + key = (String) me.getValue(); + logger.info(key); + } + + // --- End of debug + + // Get the most common options + + set = ImportantVars.entrySet(); + i = set.iterator(); + while (i.hasNext()) { + Map.Entry me = (Map.Entry) i.next(); + String key = (String) me.getKey(); + if (!vars.containsKey(key)) { + continue; + } + String value = (String) vars.get(key); + Number num = (Number) me.getValue(); + // --- Parse integer value + if (num instanceof Integer) { + try { + Integer ival = Integer.valueOf(value); + ImportantVars.put(key, ival); + logger.info("Key " + key + " is updated: " + + ival.toString()); + } catch (NumberFormatException e) { + logger.info("Not integer value for " + key + " : " + + value); + return "Not integer value for " + key + " : " + value; + } + } // Parse float value + else if (num instanceof Float) { + try { + Float fval = Float.valueOf(value); + ImportantVars.put(key, fval); + logger.info("Key " + key + " is updated: " + + fval.toString()); + } catch (NumberFormatException e) { + logger.info("Not float value for " + key + " : " + + value); + return "Not float value for " + key + " : " + value; + } + } + } + + return "Ok"; + } + + static public Map getGeneralParameters(String filename, int fileType, + FortranNamelist namelist, + String nm_name) { + String mess = null; + + if (fileType == 0) { // --- Read in from file + mess = namelist.findAndParseFortranNamelist(filename, nm_name); + } else if (fileType == 1) { // --- Read in from string bufer + BufferedReader in = new BufferedReader(new StringReader(filename)); + //logger.info("Internal Text: "+filename); + mess = namelist.findAndParseFortranNamelist(in, nm_name); + //in.close(); + //logger.info("After reading text bufer: "+mess); + } else { + logger.info( + "getGeneralParameters: Internal Error: Unknown file type"); + return null; + } + + if (mess.compareTo("Ok") != 0) { + return null; + } + Map vars = namelist.getVariables(); + Set set = vars.entrySet(); + Iterator i = set.iterator(); + + // --- Debug print out + + while (i.hasNext()) { + Map.Entry me = (Map.Entry) i.next(); + String key = (String) me.getKey(); + System.out.print(key + " : "); + key = (String) me.getValue(); + logger.info(key); + } + return vars; + } + + /** + * + * @param vars Map + * @return boolean + */ + public boolean setCntrlVariables(Map vars) { + Message = ""; + boolean no_errors = true; + + Set set = vars.entrySet(); + Iterator i = set.iterator(); + while (i.hasNext()) { + Map.Entry me = (Map.Entry) i.next(); + String key = me.getKey().toString(); + if (!allVars.containsKey(key)) { + no_errors = false; + Message += "Error: Unknown variable: " + key + + " in cntrl namelist\n"; + continue; + } + + String value = me.getValue().toString(); + + logger.info("Setting " + key + " = " + value); + + SanderVariable variable = (SanderVariable) allVars.get(key); + + String mess = variable.setValue(value); + if (mess != null) { + Message += "Error: " + key + " " + mess + "\n"; + no_errors = false; + } + + } + return no_errors; + } + + public String getErrorMessage() { + return Message; + } + + /** + * + * @param namelistVars Map + * @param s8jcVars Map + * @return String + */ + public static String updateNamelistVariables(Map namelistVars, Map s8jcVars) { + SanderVariable var; + String message = ""; + + Set set = s8jcVars.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String option = me.getKey().toString(); + var = (SanderVariable) me.getValue(); + + // If it's default value we remove it from the namelist + if (var.isDefaultValue()) { + if (namelistVars.containsKey(option)) { + namelistVars.remove(option); + } + } else { + namelistVars.put(option, var.getValue()); + } + } + + // -- Now check again all namelist variables and remove those which has + // no mapping + + Map newNamelistVars = new HashMap(); + + set = namelistVars.entrySet(); + iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String option = me.getKey().toString(); + + if (s8jcVars.containsKey(option)) { + newNamelistVars.put(option, me.getValue().toString()); + continue; + } + message += "Warning: No variable " + option + + " in Sander-8 job control list\n"; + //namelistVars.remove(option); + } + + namelistVars.clear(); + namelistVars.putAll(newNamelistVars); + + if (message.length() == 0) { + return null; + } + return message; + } +} diff --git a/src/main/java/cct/amber/Sander8Start.java b/src/main/java/cct/amber/Sander8Start.java new file mode 100644 index 0000000..168c98c --- /dev/null +++ b/src/main/java/cct/amber/Sander8Start.java @@ -0,0 +1,134 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.amber; + +import java.awt.Dimension; +import java.awt.Toolkit; + +import javax.swing.JFrame; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +/** + *

Title: Preparation of input file for Sander 8 program

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Sander8Start { + boolean packFrame = false; + static final String VERSION_8 = "8"; + static final String VERSION_9 = "9"; + static private String Version = VERSION_9; + + /** + * Construct and show the application. + */ + public Sander8Start(String sanderVersion) { + JFrame frame = null; + Sander8Frame s8 = null; + Sander9Frame s9 = null; + + if (sanderVersion.equalsIgnoreCase(VERSION_8)) { + s8 = new Sander8Frame(new Sander8JobControl()); + frame = s8; + } + else if (sanderVersion.equalsIgnoreCase(VERSION_9)) { + s9 = new Sander9Frame(new Sander9JobControl()); + frame = s9; + } + // Validate frames that have preset sizes + // Pack frames that have useful preferred size info, e.g. from their layout + if (packFrame) { + frame.pack(); + } + else { + frame.validate(); + } + + // Center the window + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension frameSize = frame.getSize(); + if (frameSize.height > screenSize.height) { + frameSize.height = screenSize.height; + } + if (frameSize.width > screenSize.width) { + frameSize.width = screenSize.width; + } + frame.setLocation( (screenSize.width - frameSize.width) / 2, + (screenSize.height - frameSize.height) / 2); + frame.setVisible(true); + } + + /** + * Application entry point. + * + * @param args String[] + */ + public static void main(String[] args) { + if (args.length > 0 && args[0].equalsIgnoreCase(VERSION_8)) { + Version = VERSION_8; + } + else if (args.length > 0 && args[0].equalsIgnoreCase(VERSION_9)) { + Version = VERSION_9; + } + else if (args.length > 0) { + System.err.println("Unknown version: " + args[0] + " Using default version " + Version); + } + + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } + catch (Exception exception) { + exception.printStackTrace(); + } + + new Sander8Start(Version); + } + }); + } +} diff --git a/src/main/java/cct/amber/Sander8Variable.java b/src/main/java/cct/amber/Sander8Variable.java new file mode 100644 index 0000000..200df9b --- /dev/null +++ b/src/main/java/cct/amber/Sander8Variable.java @@ -0,0 +1,330 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.amber; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Sander8Variable { + + boolean enumerated = false; + int varType = Sander8JobControl.TYPE_INTEGER; + String Description; + List Values = new ArrayList(); + int selectedValue = -1; // For enumerated variables + String newValue = null; // For non-enumerated variables + boolean defaultIsSet = false; + boolean currentValueIsNotDefault = false; + Object nondefaultParsedValue = null; + String nondefaultValue = null; + static final Logger logger = Logger.getLogger(Sander8Variable.class.getCanonicalName()); + + Sander8Variable(String descr, boolean isEnum) { + Description = descr; + enumerated = isEnum; + if (enumerated) { + varType = Sander8JobControl.TYPE_INTEGER; + } + } + + public int getNumberOfValues() { + return Values.size(); + } + + public void addValue(Sander8VariableValue value) { + if (!enumerated && Values.size() > 0) { + logger.info("INTERNAL ERROR: addValue: Only one value for non-enumerated variables is allowed!"); + return; + } + + if (defaultIsSet && value.isDefault()) { + logger.info( + "INTERNAL ERROR: addValue: Only one value can be default one!"); + return; + } + + if (value.isDefault()) { + defaultIsSet = true; + } + + if (enumerated) { + try { + Integer ival = Integer.valueOf(value.getValue()); + value.setParsedValue(ival); + } catch (NumberFormatException e) { + logger.info( + "INTERNAL ERROR: addValue: Expected integer value for enumerated variable, got: " + + value); + return; + } + + if (value.isDefault()) { + selectedValue = Values.size(); + //logger.info("Selected changed: " + selectedValue); + } + } else if (varType == Sander8JobControl.TYPE_INTEGER) { + try { + Integer ival = Integer.valueOf(value.getValue()); + value.setParsedValue(ival); + } catch (NumberFormatException e) { + logger.info( + "INTERNAL ERROR: addValue: Expected integer value, got: " + + value); + return; + } + } else if (varType == Sander8JobControl.TYPE_FLOAT) { + try { + Float fval = Float.valueOf(value.getValue()); + value.setParsedValue(fval); + } catch (NumberFormatException e) { + logger.info( + "INTERNAL ERROR: addValue: Expected float value, got: " + + value); + return; + } + + } + + Values.add(value); + + } + + public int getSelectedIndex() { + return selectedValue; + } + + public String getDescription() { + return this.Description; + } + + /** + * + * @return String + */ + public String getValue() { + if (enumerated) { + Sander8VariableValue value = (Sander8VariableValue) Values.get( + selectedValue); + return value.getValue(); + } + + if (currentValueIsNotDefault) { + return nondefaultValue; + } + Sander8VariableValue value = (Sander8VariableValue) Values.get(0); + return value.getValue(); + } + + /** + * + * @return Object + */ + public Object getParsedValue() { + if (enumerated) { + Sander8VariableValue value = (Sander8VariableValue) Values.get( + selectedValue); + return value.getParsedValue(); + } + + if (currentValueIsNotDefault) { + return nondefaultParsedValue; + } + Sander8VariableValue value = (Sander8VariableValue) Values.get(0); + return value.getParsedValue(); + } + + public Sander8VariableValue getValue(int n) { + if (n < 0 || n >= getNumberOfValues()) { + return null; + } + return (Sander8VariableValue) Values.get(n); + } + + public boolean isEnumerated() { + return enumerated; + } + + public boolean isDefaultValue() { + return !currentValueIsNotDefault; + } + + public void setNewValue(String new_value) { + if (enumerated) { + logger.info( + "INTERNAL ERROR: setNewValue: Attempt to set enumerated variable!"); + return; + } + newValue = new_value; + } + + /** + * + * @param index int + */ + public void setSelectedIndex(int index) { + if (!enumerated) { + logger.info( + "INTERNAL ERROR: setSelectedIndex: Attempt to set non-enumerated variable!"); + return; + } + + if (index < 0 || index >= Values.size()) { + logger.info( + "INTERNAL ERROR: setSelectedIndex: index < 0 || index >= Values.size()!"); + return; + } + + Sander8VariableValue valid_value = (Sander8VariableValue) Values.get(index); + currentValueIsNotDefault = !valid_value.isDefault(); + + selectedValue = index; + //logger.info("Selected changed: setSelectedIndex" + selectedValue); + } + + void setVarType(int type) { + varType = type; + } + + /** + * + * @param value String + * @return String + */ + public String setValue(String new_value) { + + if (new_value == null) { + return "INTERNAL ERROR: setValue: Attempt to set null value"; + } + String val = new_value.trim(); + logger.info("Parsing value: " + val); + + // --- Check enumerated variable + + if (enumerated) { + Integer ival; + try { + ival = Integer.valueOf(val); + } catch (NumberFormatException e) { + return "Enumerated variable is not integer: " + val; + } + + for (int i = 0; i < Values.size(); i++) { + Sander8VariableValue valid_value = (Sander8VariableValue) Values.get(i); + Integer proper_value = (Integer) valid_value.getParsedValue(); + if (ival.intValue() == proper_value.intValue()) { + selectedValue = i; + //logger.info("Selected changed: setValue: " + selectedValue); + if (valid_value.isDefault()) { + currentValueIsNotDefault = false; + logger.info("Value is a default one"); + } else { + currentValueIsNotDefault = true; + logger.info("Value is not a default one"); + } + return null; + } + } + return val + " is not a valid enumerated value"; + + } // --- Check integer value + else if (varType == Sander8JobControl.TYPE_INTEGER) { + try { + Integer ival = Integer.valueOf(val); + Sander8VariableValue valid_value = (Sander8VariableValue) Values.get(0); + + // --- Is new value equal to default one? + + Integer default_value = (Integer) valid_value.getParsedValue(); + + if (default_value.intValue() == ival.intValue()) { + currentValueIsNotDefault = false; + logger.info("Value is a default one"); + } else { + currentValueIsNotDefault = true; + nondefaultParsedValue = ival; + nondefaultValue = val; + logger.info("Value is not a default one"); + } + return null; + } catch (NumberFormatException e) { + return "Expected integer value, got: " + val; + } + } // --- Check float value + else if (varType == Sander8JobControl.TYPE_FLOAT) { + try { + Float fval = Float.valueOf(val); + Sander8VariableValue valid_value = (Sander8VariableValue) Values.get(0); + // --- Is new value equal to default one? + + Float default_value = (Float) valid_value.getParsedValue(); + + if (default_value.floatValue() == fval.floatValue()) { + currentValueIsNotDefault = false; + logger.info("Value is a default one"); + } else { + currentValueIsNotDefault = true; + nondefaultParsedValue = fval; + nondefaultValue = val; + logger.info("Value is not a default one"); + } + + return null; + } catch (NumberFormatException e) { + return "Expected float value, got: " + val; + } + } + + return null; + } + + public int getType() { + return varType; + } +} diff --git a/src/main/java/cct/amber/Sander8VariableValue.java b/src/main/java/cct/amber/Sander8VariableValue.java new file mode 100644 index 0000000..1139837 --- /dev/null +++ b/src/main/java/cct/amber/Sander8VariableValue.java @@ -0,0 +1,87 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.amber; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Sander8VariableValue { + boolean defaultValue = false; + String Description; + String Value; + Object parsedValue = null; + + public Sander8VariableValue(String value, String description, boolean isDefault) { + defaultValue = isDefault; + Description = description; + Value = value; + } + + public boolean isDefault() { + return defaultValue; + } + + public String getDescription() { + return Description; + } + + public String getValue() { + return Value; + } + + public Object getParsedValue() { + return parsedValue; + } + + public void setParsedValue(Object value) { + parsedValue = value; + } + + public void setValue(String value) { + Value = value; + } +} diff --git a/src/main/java/cct/amber/Sander9Frame.java b/src/main/java/cct/amber/Sander9Frame.java new file mode 100644 index 0000000..eb820aa --- /dev/null +++ b/src/main/java/cct/amber/Sander9Frame.java @@ -0,0 +1,4065 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.amber; + +import java.awt.BorderLayout; +import java.awt.CardLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FileDialog; +import java.awt.FlowLayout; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTabbedPane; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.JToolBar; +import javax.swing.SwingConstants; +import javax.swing.border.TitledBorder; + +import cct.tools.FortranNamelist; +import cct.tools.IOUtils; + +/** + *

Title: Preparation of input file for Sander 9 program

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Sander9Frame + extends JFrame implements SanderInputParserInterface { + JPanel contentPane; + BorderLayout borderLayout1 = new BorderLayout(); + JMenuBar jMenuBar1 = new JMenuBar(); + JMenu jMenuFile = new JMenu(); + JMenuItem jMenuFileExit = new JMenuItem(); + JMenu jMenuHelp = new JMenu(); + JMenuItem jMenuHelpAbout = new JMenuItem(); + JToolBar jToolBar = new JToolBar(); + JButton openFile_Button = new JButton(); + JButton newFile_Button = new JButton(); + JButton help_Button = new JButton(); + ImageIcon image1 = new ImageIcon(Sander9Frame.class.getResource( + "openFile.png")); + ImageIcon image2 = new ImageIcon(Sander9Frame.class.getResource( + "closeFile.png")); + ImageIcon saveFileImage = new ImageIcon(Sander9Frame.class. + getResource( + "Save-Icon-16x16.gif")); + ImageIcon image3 = new ImageIcon(Sander9Frame.class.getResource( + "help.png")); + JTabbedPane jTabbedPane1 = new JTabbedPane(); + JPanel jobTypePanel = new JPanel(); + JPanel potentialFuncPanel = new JPanel(); + JTextArea descriptionPane = new JTextArea(); + JPanel descrPanel = new JPanel(); + BorderLayout borderLayout2 = new BorderLayout(); + BorderLayout borderLayout3 = new BorderLayout(); + + Sander9JobControl s8jc = null; + FortranNamelist cntrl = null; + String fileContent = null; + String fileName = null; + String workingDirectory = null; + TextEditorFrame inputEditor = null; + Map controlsTable = new HashMap(); + boolean comboBoxAdjusting = false; + + JComboBox NTF_ComboBox = new JComboBox(); + JComboBox NTB_ComboBox = new JComboBox(); + JTextField DIELC_TextField = new JTextField(); + JTextField CUT_TextField = new JTextField(); + JTextField SCNB_TextField = new JTextField(); + JTextField SCEE_TextField = new JTextField(); + JTextField NSNB_TextField = new JTextField(); + JComboBox IPOL_ComboBox = new JComboBox(); + JPanel GB_Panel = new JPanel(); + JPanel PME_Panel = new JPanel(); + JPanel jPanel1 = new JPanel(); + BorderLayout borderLayout5 = new BorderLayout(); + JComboBox IMIN_ComboBox = new JComboBox(); + JPanel ioPanel = new JPanel(); + JPanel outputPanel = new JPanel(); + JPanel inputPanel = new JPanel(); + BorderLayout borderLayout6 = new BorderLayout(); + JPanel restrainPanel = new JPanel(); + JPanel cardsPanel = new JPanel(); + CardLayout cardLayout1 = new CardLayout(); + JPanel minCard = new JPanel(); + JPanel mdCard = new JPanel(); + JLabel methodLabel = new JLabel(); + JComboBox NTMIN_ComboBox = new JComboBox(); + JLabel maxIterLabel = new JLabel(); + JTextField MAXCYC_TextField = new JTextField(); + JLabel dxLabel = new JLabel(); + JLabel switchLabel = new JLabel(); + JLabel covergLabel = new JLabel(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + JTextField NCYC_TextField = new JTextField(); + JTextField DX0_TextField = new JTextField(); + JTextField DRMS_TextField = new JTextField(); + GridBagLayout gridBagLayout2 = new GridBagLayout(); + JComboBox IREST_ComboBox = new JComboBox(); + GridBagLayout gridBagLayout3 = new GridBagLayout(); + JLabel NSTLIM_Label = new JLabel(); + JTextField NSTLIM_TextField = new JTextField(); + JLabel TEMP0_Label = new JLabel(); + JTextField TEMP0_TextField = new JTextField(); + JLabel DT_Label = new JLabel(); + JTextField DT_TextField = new JTextField(); + JPanel MolDynPanel = new JPanel(); + GridBagLayout gridBagLayout4 = new GridBagLayout(); + JLabel NSCM_Label = new JLabel(); + JTextField NSCM_TextField = new JTextField(); + JLabel NRESPA_Label = new JLabel(); + JTextField NRESPA_TextField = new JTextField(); + JLabel T_Label = new JLabel(); + JTextField T_TextField = new JTextField(); + JLabel NTT_Label = new JLabel(); + JComboBox NTT_ComboBox = new JComboBox(); + JLabel TEMP0LES_Label = new JLabel(); + JTextField TEMP0LES_TextField = new JTextField(); + JLabel TEMPI_Label = new JLabel(); + JTextField TEMPI_TextField = new JTextField(); + JLabel IG_Label = new JLabel(); + JTextField IG_TextField = new JTextField(); + JLabel TAUTP_Label = new JLabel(); + JTextField TAUTP_TextField = new JTextField(); + JLabel GAMMA_LN_Label = new JLabel(); + JTextField GAMMA_LN_TextField = new JTextField(); + JLabel VRAND_Label = new JLabel(); + JTextField VRAND_TextField = new JTextField(); + JLabel VLIMIT_Label = new JLabel(); + JTextField VLIMIT_TextField = new JTextField(); + JPanel TempControlPanel = new JPanel(); + GridBagLayout gridBagLayout5 = new GridBagLayout(); + JLabel NTP_Label = new JLabel(); + JComboBox NTP_ComboBox = new JComboBox(); + JLabel PRES0_Label = new JLabel(); + JTextField PRES0_TextField = new JTextField(); + JLabel COMP_Label = new JLabel(); + JTextField COMP_TextField = new JTextField(); + JPanel PressureControlPanel = new JPanel(); + JLabel TAUP_Label = new JLabel(); + JTextField TAUP_TextField = new JTextField(); + JLabel NSNB_Label = new JLabel(); + JLabel SCEE_Label = new JLabel(); + JLabel IPOL_Label = new JLabel(); + JLabel NTF_Label = new JLabel(); + JLabel NTB_Label = new JLabel(); + JLabel NTXO_Label = new JLabel(); + JComboBox NTXO_ComboBox = new JComboBox(); + JLabel NTPR_Label = new JLabel(); + JTextField NTPR_TextField = new JTextField(); + JLabel NTX_Label = new JLabel(); + JComboBox NTX_ComboBox = new JComboBox(); + JLabel NTRX_Label = new JLabel(); + JComboBox NTRX_ComboBox = new JComboBox(); + JLabel NTAVE_Label = new JLabel(); + JTextField NTAVE_TextField = new JTextField(); + JLabel NTWR_Label = new JLabel(); + JTextField NTWR_TextField = new JTextField(); + JLabel IWRAP_Label = new JLabel(); + JComboBox IWRAP_ComboBox = new JComboBox(); + FlowLayout flowLayout2 = new FlowLayout(); + JLabel NTWX_Label = new JLabel(); + JTextField NTWX_TextField = new JTextField(); + JLabel NTWV_Label = new JLabel(); + JTextField NTWV_TextField = new JTextField(); + JLabel NTWE_Label = new JLabel(); + JTextField NTWE_TextField = new JTextField(); + JLabel IOUTFM_Label = new JLabel(); + JComboBox IOUTFM_ComboBox = new JComboBox(); + JLabel NTWPRT_Label = new JLabel(); + JTextField NTWPRT_TextField = new JTextField(); + JLabel IDECOMP_Label = new JLabel(); + JComboBox IDECOMP_ComboBox = new JComboBox(); + JComboBox IGB_ComboBox = new JComboBox(); + JLabel INTDIEL_Label = new JLabel(); + JTextField INTDIEL_TextField = new JTextField(); + JLabel EXTDIEL_Label = new JLabel(); + JTextField EXTDIEL_TextField = new JTextField(); + JLabel SALTCON_Label = new JLabel(); + JTextField SALTCON_TextField = new JTextField(); + JLabel RGBMAX_Label = new JLabel(); + JTextField RGBMAX_TextField = new JTextField(); + JLabel RBORNSTAT_Label = new JLabel(); + JComboBox RBORNSTAT_ComboBox = new JComboBox(); + JLabel OFFSET_Label = new JLabel(); + JTextField OFFSET_TextField = new JTextField(); + JLabel GBSA_Label = new JLabel(); + JComboBox GBSA_ComboBox = new JComboBox(); + JLabel RDT_Label = new JLabel(); + JLabel SURFTEN_Label = new JLabel(); + JTextField RDT_TextField = new JTextField(); + JTextField SURFTEN_TextField = new JTextField(); + GridBagLayout gridBagLayout7 = new GridBagLayout(); + GridBagLayout gridBagLayout8 = new GridBagLayout(); + JLabel GB_Dummy_Label = new JLabel(); + JLabel DIELC_Label = new JLabel(); + JLabel CUT_Label = new JLabel(); + JLabel SCNB_Label = new JLabel(); + JMenuItem Edit_MenuItem = new JMenuItem(); + FlowLayout flowLayout3 = new FlowLayout(); + JLabel NTR_Label = new JLabel(); + JComboBox NTR_ComboBox = new JComboBox(); + JLabel IBELLY_Label = new JLabel(); + JComboBox IBELLY_ComboBox = new JComboBox(); + JLabel BELLYMASK_Label = new JLabel(); + JLabel RESTRAINTMASK_Label = new JLabel(); + JLabel RESTRAINT_WT_Label = new JLabel(); + JTextField BELLYMASK_TextField = new JTextField(); + JTextField RESTRAINTMASK_TextField = new JTextField(); + JTextField RESTRAINT_WT_TextField = new JTextField(); + JLabel FCAP_Label = new JLabel(); + JLabel IVCAP_Label = new JLabel(); + JComboBox IVCAP_ComboBox = new JComboBox(); + JTextField FCAP_TextField = new JTextField(); + JPanel shakePanel = new JPanel(); + JLabel HWTNM2_Label = new JLabel(); + JLabel HWTNM1_Label = new JLabel(); + JLabel OWTNM_Label = new JLabel(); + JLabel WATNAM_Label = new JLabel(); + JLabel TOL_Label = new JLabel(); + JLabel JFASTW_Label = new JLabel(); + JLabel NTC_Label = new JLabel(); + JComboBox JFASTW_ComboBox = new JComboBox(); + JComboBox NTC_ComboBox = new JComboBox(); + JTextField HWTNM2_TextField = new JTextField(); + JTextField HWTNM1_TextField = new JTextField(); + JTextField WATNAM_TextField = new JTextField(); + JTextField OWTNM_TextField = new JTextField(); + JTextField TOL_TextField = new JTextField(); + GridBagLayout gridBagLayout6 = new GridBagLayout(); + GridBagLayout gridBagLayout9 = new GridBagLayout(); + JLabel jLabel6 = new JLabel(); + GridBagLayout gridBagLayout10 = new GridBagLayout(); + JLabel Dummy_MD_Label = new JLabel(); + JButton saveFile_Button = new JButton(); + JMenuItem jMenuItem1 = new JMenuItem(); + JMenuItem jMenuItem2 = new JMenuItem(); + public Sander9Frame(Sander9JobControl jc) { + try { + setDefaultCloseOperation(EXIT_ON_CLOSE); + s8jc = jc; + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + /** + * Component initialization. + * + * @throws Exception + */ + private void jbInit() throws Exception { + contentPane = (JPanel) getContentPane(); + contentPane.setLayout(borderLayout1); + setSize(new Dimension(694, 337)); + setTitle("Sander 9 Job Controls"); + jMenuFile.setText("File"); + jMenuFileExit.setToolTipText("Exit Program"); + jMenuFileExit.setText("Exit"); + jMenuFileExit.addActionListener(new + Sander9Frame_jMenuFileExit_ActionAdapter(this)); + jMenuHelp.setText("Help"); + jMenuHelpAbout.setText("About"); + jMenuHelpAbout.addActionListener(new + Sander9Frame_jMenuHelpAbout_ActionAdapter(this)); + descriptionPane.setToolTipText(""); + descriptionPane.setEditable(false); + descriptionPane.setText("Options description will be shown here"); + descriptionPane.setLineWrap(true); + descriptionPane.setRows(6); + descriptionPane.setWrapStyleWord(true); + descrPanel.setLayout(borderLayout2); + descrPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder( + Color. + lightGray, 1), "Option Description")); + potentialFuncPanel.setLayout(gridBagLayout10); + NTF_ComboBox.addItemListener(new Sander9Frame_NTF_ComboBox_itemAdapter(this)); + NTB_ComboBox.addItemListener(new Sander9Frame_NTB_ComboBox_itemAdapter(this)); + DIELC_TextField.setToolTipText("Enter new value and press Enter"); + DIELC_TextField.setText(" "); + DIELC_TextField.setColumns(5); + CUT_TextField.setToolTipText("Enter new value and press Enter"); + CUT_TextField.setText(" "); + CUT_TextField.setColumns(5); + SCNB_TextField.setToolTipText("Enter new value and press Enter"); + SCNB_TextField.setText(" "); + SCNB_TextField.setColumns(5); + SCEE_TextField.setToolTipText("Enter new value and press Enter"); + SCEE_TextField.setText(" "); + SCEE_TextField.setColumns(5); + NSNB_TextField.setToolTipText("Enter new value and press Enter"); + NSNB_TextField.setText(" "); + NSNB_TextField.setColumns(5); + IPOL_ComboBox.addItemListener(new Sander9Frame_IPOL_ComboBox_itemAdapter(this)); + GB_Panel.setEnabled(false); + GB_Panel.setToolTipText("Generalized Born/Surface Area options"); + GB_Panel.setLayout(gridBagLayout8); + PME_Panel.setEnabled(false); + PME_Panel.setToolTipText("The Particle Mesh Ewald (PME) method options"); + jobTypePanel.setLayout(borderLayout5); + jPanel1.setLayout(gridBagLayout2); + IMIN_ComboBox.addItemListener(new Sander9Frame_IMIN_ComboBox_itemAdapter(this)); + ioPanel.setToolTipText("Nature and format of the input and output"); + ioPanel.setLayout(borderLayout6); + inputPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder( + Color. + lightGray, 1), "Nature and format of the input")); + inputPanel.setLayout(flowLayout2); + outputPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder( + Color. + lightGray, 1), "Nature and format of the output")); + outputPanel.setLayout(gridBagLayout7); + restrainPanel.setToolTipText("Option for the Frozen or restrained atoms"); + restrainPanel.setLayout(gridBagLayout9); + cardsPanel.setLayout(cardLayout1); + NTMIN_ComboBox.addItemListener(new + Sander9Frame_NTMIN_ComboBox_itemAdapter(this)); + maxIterLabel.setToolTipText(""); + maxIterLabel.setHorizontalAlignment(SwingConstants.RIGHT); + maxIterLabel.setText("Max Iterations (MAXCYC):"); + maxIterLabel.addMouseListener(new Sander9Frame_maxIterLabel_mouseAdapter(this)); + MAXCYC_TextField.setToolTipText(""); + MAXCYC_TextField.setText(" "); + MAXCYC_TextField.setColumns(6); + MAXCYC_TextField.addActionListener(new + Sander9Frame_MAXCYC_TextField_actionAdapter(this)); + minCard.setLayout(gridBagLayout1); + dxLabel.setToolTipText(""); + dxLabel.setHorizontalAlignment(SwingConstants.RIGHT); + dxLabel.setText("Initial step length (DX0): "); + dxLabel.addMouseListener(new Sander9Frame_dxLabel_mouseAdapter(this)); + switchLabel.setToolTipText(""); + switchLabel.setHorizontalAlignment(SwingConstants.RIGHT); + switchLabel.setText("Switch (NCYC): "); + switchLabel.addMouseListener(new Sander9Frame_switchLabel_mouseAdapter(this)); + covergLabel.setToolTipText(""); + covergLabel.setHorizontalAlignment(SwingConstants.RIGHT); + covergLabel.setText("Convergence criterion (DRMS): "); + covergLabel.addMouseListener(new Sander9Frame_covergLabel_mouseAdapter(this)); + NCYC_TextField.setToolTipText(""); + NCYC_TextField.setText(" "); + NCYC_TextField.setColumns(6); + NCYC_TextField.addActionListener(new + Sander9Frame_NCYC_TextField_actionAdapter(this)); + DX0_TextField.setColumns(6); + DX0_TextField.addActionListener(new + Sander9Frame_DX0_TextField_actionAdapter(this)); + DRMS_TextField.setToolTipText(""); + DRMS_TextField.setColumns(6); + DRMS_TextField.addActionListener(new + Sander9Frame_DRMS_TextField_actionAdapter(this)); + IREST_ComboBox.addItemListener(new + Sander9Frame_IREST_ComboBox_itemAdapter(this)); + mdCard.setLayout(gridBagLayout3); + NSTLIM_Label.setToolTipText(""); + NSTLIM_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NSTLIM_Label.setText("Number of MD Steps (nstlim): "); + NSTLIM_Label.addMouseListener(new Sander9Frame_NSTLIM_Label_mouseAdapter(this)); + NSTLIM_TextField.setText(" "); + NSTLIM_TextField.setColumns(6); + NSTLIM_TextField.setHorizontalAlignment(SwingConstants.LEFT); + NSTLIM_TextField.addActionListener(new + Sander9Frame_NSTLIM_TextField_actionAdapter(this)); + TEMP0_Label.setToolTipText("Reference Temperature, K"); + TEMP0_Label.setHorizontalAlignment(SwingConstants.RIGHT); + TEMP0_Label.setText("Temperature (temp0), K: "); + TEMP0_Label.addMouseListener(new Sander9Frame_TEMP0_Label_mouseAdapter(this)); + TEMP0_TextField.setText(" "); + TEMP0_TextField.setColumns(6); + DT_Label.setToolTipText(""); + DT_Label.setHorizontalAlignment(SwingConstants.RIGHT); + DT_Label.setText("Time Step, psec (dt): "); + DT_Label.addMouseListener(new Sander9Frame_DT_Label_mouseAdapter(this)); + DT_TextField.setText(" "); + DT_TextField.setColumns(6); + MolDynPanel.setToolTipText( + "Additional Options for Molecular Dynamics Simulation"); + MolDynPanel.setLayout(gridBagLayout4); + jTabbedPane1.setToolTipText(""); + NSCM_Label.setToolTipText(""); + NSCM_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NSCM_Label.setText("NSCM: "); + NSCM_Label.addMouseListener(new Sander9Frame_jLabel10_mouseAdapter(this)); + NSCM_TextField.setColumns(6); + NRESPA_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NRESPA_Label.setText("NRESPA: "); + NRESPA_Label.addMouseListener(new Sander9Frame_NRESPA_Label_mouseAdapter(this)); + NRESPA_TextField.setText(" "); + NRESPA_TextField.setColumns(6); + T_Label.setHorizontalAlignment(SwingConstants.RIGHT); + T_Label.setText("T: "); + T_Label.addMouseListener(new Sander9Frame_T_Label_mouseAdapter(this)); + T_TextField.setText(" "); + T_TextField.setColumns(6); + NTT_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTT_Label.setText("Temperature Scaling (ntt): "); + NTT_Label.addMouseListener(new Sander9Frame_NTT_Label_mouseAdapter(this)); + TEMP0LES_Label.setToolTipText(""); + TEMP0LES_Label.setHorizontalAlignment(SwingConstants.RIGHT); + TEMP0LES_Label.setText("TEMP0LES: "); + TEMP0LES_Label.addMouseListener(new + Sander9Frame_TEMP0LES_Label_mouseAdapter(this)); + TEMP0LES_TextField.setToolTipText(""); + TEMP0LES_TextField.setColumns(6); + TEMPI_Label.setToolTipText(""); + TEMPI_Label.setHorizontalAlignment(SwingConstants.RIGHT); + TEMPI_Label.setText("TEMPI: "); + TEMPI_Label.addMouseListener(new Sander9Frame_TEMPI_Label_mouseAdapter(this)); + TEMPI_TextField.setText(" "); + TEMPI_TextField.setColumns(6); + IG_Label.setHorizontalAlignment(SwingConstants.RIGHT); + IG_Label.setText("Seed (ig): "); + IG_Label.addMouseListener(new Sander9Frame_IG_Label_mouseAdapter(this)); + IG_TextField.setToolTipText(""); + IG_TextField.setText(" "); + IG_TextField.setColumns(6); + TAUTP_Label.setToolTipText(""); + TAUTP_Label.setHorizontalAlignment(SwingConstants.RIGHT); + TAUTP_Label.setText("Temperature coupling, ps (tautp): "); + TAUTP_Label.addMouseListener(new Sander9Frame_TAUTP_Label_mouseAdapter(this)); + TAUTP_TextField.setToolTipText(""); + TAUTP_TextField.setText(" "); + TAUTP_TextField.setColumns(6); + GAMMA_LN_Label.setToolTipText(""); + GAMMA_LN_Label.setHorizontalAlignment(SwingConstants.RIGHT); + GAMMA_LN_Label.setText("GAMMA_LN: "); + GAMMA_LN_Label.addMouseListener(new + Sander9Frame_GAMMA_LN_Label_mouseAdapter(this)); + GAMMA_LN_TextField.setText(" "); + GAMMA_LN_TextField.setColumns(6); + VRAND_Label.setHorizontalAlignment(SwingConstants.RIGHT); + VRAND_Label.setText("VRAND: "); + VRAND_Label.addMouseListener(new Sander9Frame_VRAND_Label_mouseAdapter(this)); + VRAND_TextField.setToolTipText(""); + VRAND_TextField.setText(" "); + VRAND_TextField.setColumns(6); + VLIMIT_Label.setToolTipText(""); + VLIMIT_Label.setHorizontalAlignment(SwingConstants.RIGHT); + VLIMIT_Label.setText("VLIMIT: "); + VLIMIT_Label.addMouseListener(new Sander9Frame_VLIMIT_Label_mouseAdapter(this)); + VLIMIT_TextField.setText(" "); + VLIMIT_TextField.setColumns(6); + TempControlPanel.setLayout(gridBagLayout5); + TempControlPanel.setBorder(new TitledBorder(BorderFactory. + createLineBorder( + Color.lightGray, 1), "Temperature Regulation")); + NTP_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTP_Label.setText("Pressure Scaling (ntp): "); + NTP_Label.addMouseListener(new Sander9Frame_NTP_Label_mouseAdapter(this)); + PRES0_Label.setToolTipText("Reference Pressure, bars"); + PRES0_Label.setHorizontalAlignment(SwingConstants.RIGHT); + PRES0_Label.setText("Pressure, bars (pres0): "); + PRES0_Label.addMouseListener(new Sander9Frame_PRES0_Label_mouseAdapter(this)); + PRES0_TextField.setToolTipText(""); + PRES0_TextField.setText(" "); + PRES0_TextField.setColumns(6); + COMP_Label.setHorizontalAlignment(SwingConstants.RIGHT); + COMP_Label.setText("COMP: "); + COMP_Label.addMouseListener(new Sander9Frame_COMP_Label_mouseAdapter(this)); + COMP_TextField.setToolTipText(""); + COMP_TextField.setText(" "); + COMP_TextField.setColumns(6); + PressureControlPanel.setLayout(flowLayout3); + TAUP_Label.setHorizontalAlignment(SwingConstants.RIGHT); + TAUP_Label.setText("Pressure Coupling, ps (taup): "); + TAUP_Label.addMouseListener(new Sander9Frame_TAUP_Label_mouseAdapter(this)); + TAUP_TextField.setToolTipText(""); + TAUP_TextField.setText(" "); + TAUP_TextField.setColumns(6); + PressureControlPanel.setBorder(new TitledBorder(BorderFactory. + createLineBorder(Color.lightGray, 2), "Pressure Regulation")); + NTT_ComboBox.addItemListener(new Sander9Frame_NTT_ComboBox_itemAdapter(this)); + NTP_ComboBox.addItemListener(new Sander9Frame_NTP_ComboBox_itemAdapter(this)); + jPanel1.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color. + lightGray, 1), "Job Control")); + minCard.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color. + lightGray, 1), "Energy Minimization Options")); + mdCard.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color. + lightGray, 1), "Molecular Dynamics Options")); + NSNB_Label.setToolTipText(""); + NSNB_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NSNB_Label.setText("NB List Update (nsnb): "); + NSNB_Label.addMouseListener(new Sander9Frame_NSNB_Label_mouseAdapter(this)); + SCEE_Label.setToolTipText(""); + SCEE_Label.setHorizontalAlignment(SwingConstants.RIGHT); + SCEE_Label.setText("SCEE: "); + SCEE_Label.addMouseListener(new Sander9Frame_SCEE_Label_mouseAdapter(this)); + IPOL_Label.setToolTipText(""); + IPOL_Label.setHorizontalAlignment(SwingConstants.RIGHT); + IPOL_Label.setText("Polarization On/Off (ipol): "); + IPOL_Label.addMouseListener(new Sander9Frame_IPOL_Label_mouseAdapter(this)); + NTF_Label.setToolTipText(""); + NTF_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTF_Label.setText("Force Evaluation (ntf): "); + NTF_Label.addMouseListener(new Sander9Frame_NTF_Label_mouseAdapter(this)); + NTB_Label.setToolTipText(""); + NTB_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTB_Label.setText("Periodic Boundary (ntb): "); + NTB_Label.addMouseListener(new Sander9Frame_NTB_Label_mouseAdapter(this)); + openFile_Button.addActionListener(new Sander9Frame_jButton1_actionAdapter(this)); + newFile_Button.addActionListener(new Sander9Frame_jButton2_actionAdapter(this)); + help_Button.addActionListener(new Sander9Frame_jButton3_actionAdapter(this)); + NTXO_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTXO_Label.setText("NTXO: "); + NTXO_Label.addMouseListener(new Sander9Frame_NTXO_Label_mouseAdapter(this)); + NTPR_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTPR_Label.setText("NTPR: "); + NTPR_Label.addMouseListener(new Sander9Frame_NTPR_Label_mouseAdapter(this)); + NTPR_TextField.setText(" "); + NTPR_TextField.setColumns(6); + NTX_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTX_Label.setText("NTX: "); + NTX_Label.addMouseListener(new Sander9Frame_NTX_Label_mouseAdapter(this)); + NTRX_Label.setToolTipText(""); + NTRX_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTRX_Label.setText(" NTRX: "); + NTRX_Label.addMouseListener(new Sander9Frame_NTRX_Label_mouseAdapter(this)); + NTAVE_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTAVE_Label.setText("NTAVE: "); + NTAVE_Label.addMouseListener(new Sander9Frame_NTAVE_Label_mouseAdapter(this)); + NTAVE_TextField.setText(" "); + NTAVE_TextField.setColumns(6); + NTWR_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTWR_Label.setText("NTWR: "); + NTWR_Label.addMouseListener(new Sander9Frame_NTWR_Label_mouseAdapter(this)); + NTWR_TextField.setText(" "); + NTWR_TextField.setColumns(6); + IWRAP_Label.setHorizontalAlignment(SwingConstants.RIGHT); + IWRAP_Label.setText("IWRAP: "); + IWRAP_Label.addMouseListener(new Sander9Frame_IWRAP_Label_mouseAdapter(this)); + flowLayout2.setAlignment(FlowLayout.LEFT); + NTWX_Label.setToolTipText(""); + NTWX_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTWX_Label.setText("NTWX: "); + NTWX_Label.addMouseListener(new Sander9Frame_NTWX_Label_mouseAdapter(this)); + NTWX_TextField.setText(" "); + NTWX_TextField.setColumns(6); + NTWV_Label.setToolTipText(""); + NTWV_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTWV_Label.setText(" NTWV: "); + NTWV_Label.addMouseListener(new Sander9Frame_NTWV_Label_mouseAdapter(this)); + NTWV_TextField.setText(" "); + NTWV_TextField.setColumns(6); + NTWE_Label.setToolTipText(""); + NTWE_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTWE_Label.setText(" NTWE: "); + NTWE_Label.addMouseListener(new Sander9Frame_NTWE_Label_mouseAdapter(this)); + NTWE_TextField.setText(" "); + NTWE_TextField.setColumns(6); + IOUTFM_Label.setToolTipText(""); + IOUTFM_Label.setHorizontalAlignment(SwingConstants.RIGHT); + IOUTFM_Label.setText(" IOUTFM: "); + IOUTFM_Label.addMouseListener(new Sander9Frame_IOUTFM_Label_mouseAdapter(this)); + NTWPRT_Label.setToolTipText(""); + NTWPRT_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTWPRT_Label.setText(" NTWPRT: "); + NTWPRT_Label.addMouseListener(new Sander9Frame_NTWPRT_Label_mouseAdapter(this)); + NTWPRT_TextField.setText(" "); + NTWPRT_TextField.setColumns(6); + IDECOMP_Label.setToolTipText(""); + IDECOMP_Label.setHorizontalAlignment(SwingConstants.RIGHT); + IDECOMP_Label.setText(" IDECOMP: "); + IDECOMP_Label.addMouseListener(new + Sander9Frame_IDECOMP_Label_mouseAdapter(this)); + IMIN_ComboBox.setToolTipText("Type of calculation"); + IMIN_ComboBox.addMouseListener(new + Sander9Frame_IMIN_ComboBox_mouseAdapter(this)); + IGB_ComboBox.setToolTipText("General Born/Surface Area"); + IGB_ComboBox.addMouseListener(new Sander9Frame_IGB_ComboBox_mouseAdapter(this)); + IGB_ComboBox.addItemListener(new Sander9Frame_IGB_ComboBox_itemAdapter(this)); + INTDIEL_Label.setToolTipText(""); + INTDIEL_Label.setHorizontalAlignment(SwingConstants.RIGHT); + INTDIEL_Label.setText(" INTDIEL: "); + INTDIEL_Label.addMouseListener(new + Sander9Frame_INTDIEL_Label_mouseAdapter(this)); + INTDIEL_TextField.setToolTipText(""); + INTDIEL_TextField.setText(" "); + INTDIEL_TextField.setColumns(6); + EXTDIEL_Label.setToolTipText(""); + EXTDIEL_Label.setHorizontalAlignment(SwingConstants.RIGHT); + EXTDIEL_Label.setText(" EXTDIEL: "); + EXTDIEL_Label.addMouseListener(new + Sander9Frame_EXTDIEL_Label_mouseAdapter(this)); + EXTDIEL_TextField.setToolTipText(""); + EXTDIEL_TextField.setText(" "); + EXTDIEL_TextField.setColumns(6); + SALTCON_Label.setToolTipText(""); + SALTCON_Label.setHorizontalAlignment(SwingConstants.RIGHT); + SALTCON_Label.setText(" SALTCON: "); + SALTCON_Label.addMouseListener(new + Sander9Frame_SALTCON_Label_mouseAdapter(this)); + SALTCON_TextField.setToolTipText(""); + SALTCON_TextField.setText(" "); + SALTCON_TextField.setColumns(6); + RGBMAX_Label.setToolTipText(""); + RGBMAX_Label.setHorizontalAlignment(SwingConstants.RIGHT); + RGBMAX_Label.setText(" RGBMAX: "); + RGBMAX_Label.addMouseListener(new Sander9Frame_RGBMAX_Label_mouseAdapter(this)); + RGBMAX_TextField.setToolTipText(""); + RGBMAX_TextField.setText(" "); + RGBMAX_TextField.setColumns(6); + RBORNSTAT_Label.setToolTipText(""); + RBORNSTAT_Label.setHorizontalAlignment(SwingConstants.RIGHT); + RBORNSTAT_Label.setText(" RBORNSTAT: "); + RBORNSTAT_Label.addMouseListener(new + Sander9Frame_RBORNSTAT_Label_mouseAdapter(this)); + OFFSET_Label.setToolTipText(""); + OFFSET_Label.setHorizontalAlignment(SwingConstants.RIGHT); + OFFSET_Label.setText(" OFFSET: "); + OFFSET_Label.addMouseListener(new Sander9Frame_OFFSET_Label_mouseAdapter(this)); + OFFSET_TextField.setToolTipText(""); + OFFSET_TextField.setText(" "); + OFFSET_TextField.setColumns(6); + GBSA_Label.setToolTipText(""); + GBSA_Label.setHorizontalAlignment(SwingConstants.RIGHT); + GBSA_Label.setText(" GBSA: "); + GBSA_Label.addMouseListener(new Sander9Frame_GBSA_Label_mouseAdapter(this)); + RDT_Label.setToolTipText(""); + RDT_Label.setHorizontalAlignment(SwingConstants.RIGHT); + RDT_Label.setText(" RDT: "); + RDT_Label.addMouseListener(new Sander9Frame_RDT_Label_mouseAdapter(this)); + SURFTEN_Label.setToolTipText(""); + SURFTEN_Label.setHorizontalAlignment(SwingConstants.RIGHT); + SURFTEN_Label.setText(" SURFTEN: "); + SURFTEN_Label.addMouseListener(new + Sander9Frame_SURFTEN_Label_mouseAdapter(this)); + RDT_TextField.setToolTipText(""); + RDT_TextField.setText(" "); + RDT_TextField.setColumns(6); + SURFTEN_TextField.setToolTipText(""); + SURFTEN_TextField.setText(" "); + SURFTEN_TextField.setColumns(6); + GB_Dummy_Label.setToolTipText(""); + GB_Dummy_Label.setHorizontalAlignment(SwingConstants.RIGHT); + GB_Dummy_Label.setText(" "); + RBORNSTAT_ComboBox.addItemListener(new + Sander9Frame_RBORNSTAT_ComboBox_itemAdapter(this)); + GBSA_ComboBox.addItemListener(new Sander9Frame_GBSA_ComboBox_itemAdapter(this)); + NTXO_ComboBox.addItemListener(new Sander9Frame_NTXO_ComboBox_itemAdapter(this)); + IWRAP_ComboBox.addItemListener(new + Sander9Frame_IWRAP_ComboBox_itemAdapter(this)); + IOUTFM_ComboBox.addItemListener(new + Sander9Frame_IOUTFM_ComboBox_itemAdapter(this)); + IDECOMP_ComboBox.addItemListener(new + Sander9Frame_IDECOMP_ComboBox_itemAdapter(this)); + NTX_ComboBox.addItemListener(new Sander9Frame_NTX_ComboBox_itemAdapter(this)); + NTRX_ComboBox.addItemListener(new Sander9Frame_NTRX_ComboBox_itemAdapter(this)); + DIELC_Label.setToolTipText(""); + DIELC_Label.setHorizontalAlignment(SwingConstants.RIGHT); + DIELC_Label.setText("Dielectric Constant (dielc):"); + DIELC_Label.addMouseListener(new Sander9Frame_DIELC_Label_mouseAdapter(this)); + CUT_Label.setToolTipText(""); + CUT_Label.setHorizontalAlignment(SwingConstants.RIGHT); + CUT_Label.setText("Nonbonded Cutoff (cut):"); + CUT_Label.addMouseListener(new Sander9Frame_CUT_Label_mouseAdapter(this)); + SCNB_Label.setToolTipText(""); + SCNB_Label.setHorizontalAlignment(SwingConstants.RIGHT); + SCNB_Label.setText("SCNB:"); + SCNB_Label.addMouseListener(new Sander9Frame_SCNB_Label_mouseAdapter(this)); + Edit_MenuItem.setToolTipText("Edit Job Control File in text editor"); + Edit_MenuItem.setActionCommand("Edit"); + Edit_MenuItem.setText("Edit File"); + Edit_MenuItem.addActionListener(new + Sander9Frame_Edit_MenuItem_actionAdapter(this)); + flowLayout3.setAlignment(FlowLayout.LEFT); + NTR_Label.setToolTipText(""); + NTR_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTR_Label.setText("Position Restraints (ntr): "); + NTR_Label.addMouseListener(new Sander9Frame_NTR_Label_mouseAdapter(this)); + NTR_ComboBox.addItemListener(new Sander9Frame_NTR_ComboBox_itemAdapter(this)); + IBELLY_Label.setToolTipText(""); + IBELLY_Label.setHorizontalAlignment(SwingConstants.RIGHT); + IBELLY_Label.setText("Belly Run (ibelly): "); + IBELLY_Label.addMouseListener(new Sander9Frame_IBELLY_Label_mouseAdapter(this)); + IBELLY_ComboBox.addItemListener(new + Sander9Frame_IBELLY_ComboBox_itemAdapter(this)); + BELLYMASK_Label.setToolTipText(""); + BELLYMASK_Label.setHorizontalAlignment(SwingConstants.RIGHT); + BELLYMASK_Label.setText("BELLYMASK: "); + BELLYMASK_Label.addMouseListener(new + Sander9Frame_BELLYMASK_Label_mouseAdapter(this)); + RESTRAINTMASK_Label.setToolTipText(""); + RESTRAINTMASK_Label.setHorizontalAlignment(SwingConstants.RIGHT); + RESTRAINTMASK_Label.setText("RESTRAINTMASK: "); + RESTRAINTMASK_Label.addMouseListener(new + Sander9Frame_RESTRAINTMASK_Label_mouseAdapter(this)); + RESTRAINT_WT_Label.setToolTipText(""); + RESTRAINT_WT_Label.setHorizontalAlignment(SwingConstants.RIGHT); + RESTRAINT_WT_Label.setText("RESTRAINT_WT: "); + RESTRAINT_WT_Label.addMouseListener(new + Sander9Frame_RESTRAINT_WT_Label_mouseAdapter(this)); + BELLYMASK_TextField.setText(" "); + BELLYMASK_TextField.setColumns(6); + RESTRAINTMASK_TextField.setText(" "); + RESTRAINTMASK_TextField.setColumns(6); + RESTRAINT_WT_TextField.setText(" "); + RESTRAINT_WT_TextField.setColumns(6); + FCAP_Label.setToolTipText(""); + FCAP_Label.setHorizontalAlignment(SwingConstants.RIGHT); + FCAP_Label.setText("Force Constant (fcap): "); + FCAP_Label.addMouseListener(new Sander9Frame_FCAP_Label_mouseAdapter(this)); + IVCAP_Label.setToolTipText(""); + IVCAP_Label.setHorizontalAlignment(SwingConstants.RIGHT); + IVCAP_Label.setText("Water cap (ivcap): "); + IVCAP_Label.addMouseListener(new Sander9Frame_IVCAP_Label_mouseAdapter(this)); + FCAP_TextField.setText(" "); + FCAP_TextField.setColumns(6); + IVCAP_ComboBox.addItemListener(new + Sander9Frame_IVCAP_ComboBox_itemAdapter(this)); + HWTNM2_Label.setToolTipText(""); + HWTNM2_Label.setHorizontalAlignment(SwingConstants.RIGHT); + HWTNM2_Label.setText("HWTNM2: "); + HWTNM2_Label.addMouseListener(new Sander9Frame_HWTNM2_Label_mouseAdapter(this)); + HWTNM1_Label.setToolTipText(""); + HWTNM1_Label.setHorizontalAlignment(SwingConstants.RIGHT); + HWTNM1_Label.setText("HWTNM1: "); + HWTNM1_Label.addMouseListener(new Sander9Frame_HWTNM1_Label_mouseAdapter(this)); + OWTNM_Label.setToolTipText(""); + OWTNM_Label.setHorizontalAlignment(SwingConstants.RIGHT); + OWTNM_Label.setText("OWTNM: "); + OWTNM_Label.addMouseListener(new Sander9Frame_OWTNM_Label_mouseAdapter(this)); + WATNAM_Label.setToolTipText(""); + WATNAM_Label.setHorizontalAlignment(SwingConstants.RIGHT); + WATNAM_Label.setText("WATNAM: "); + WATNAM_Label.addMouseListener(new Sander9Frame_WATNAM_Label_mouseAdapter(this)); + TOL_Label.setToolTipText(""); + TOL_Label.setHorizontalAlignment(SwingConstants.RIGHT); + TOL_Label.setText("Tolerance (tol): "); + TOL_Label.addMouseListener(new Sander9Frame_TOL_Label_mouseAdapter(this)); + JFASTW_Label.setToolTipText(""); + JFASTW_Label.setHorizontalAlignment(SwingConstants.RIGHT); + JFASTW_Label.setText("Fast Water Flag (jfastw): "); + JFASTW_Label.addMouseListener(new Sander9Frame_JFASTW_Label_mouseAdapter(this)); + NTC_Label.setToolTipText(""); + NTC_Label.setHorizontalAlignment(SwingConstants.RIGHT); + NTC_Label.setText("Apply SHAKE (ntc): "); + NTC_Label.addMouseListener(new Sander9Frame_NTC_Label_mouseAdapter(this)); + shakePanel.setBorder(new TitledBorder(BorderFactory.createLineBorder( + Color. + lightGray, 1), "SHAKE bond length constraints")); + shakePanel.setLayout(gridBagLayout6); + HWTNM2_TextField.setText(" "); + HWTNM2_TextField.setColumns(6); + HWTNM1_TextField.setText(" "); + HWTNM1_TextField.setColumns(6); + WATNAM_TextField.setText(" "); + WATNAM_TextField.setColumns(6); + OWTNM_TextField.setText(" "); + OWTNM_TextField.setColumns(6); + TOL_TextField.setText(" "); + TOL_TextField.setColumns(6); + NTC_ComboBox.addItemListener(new Sander9Frame_NTC_ComboBox_itemAdapter(this)); + JFASTW_ComboBox.addItemListener(new + Sander9Frame_JFASTW_ComboBox_itemAdapter(this)); + jLabel6.setToolTipText(""); + jLabel6.setHorizontalAlignment(SwingConstants.RIGHT); + jLabel6.setText(" "); + Dummy_MD_Label.setToolTipText(""); + Dummy_MD_Label.setHorizontalAlignment(SwingConstants.RIGHT); + IREST_ComboBox.addMouseListener(new + Sander9Frame_IREST_ComboBox_mouseAdapter(this)); + NTMIN_ComboBox.addMouseListener(new + Sander9Frame_NTMIN_ComboBox_mouseAdapter(this)); + NTT_ComboBox.addMouseListener(new Sander9Frame_NTT_ComboBox_mouseAdapter(this)); + NTP_ComboBox.addMouseListener(new Sander9Frame_NTP_ComboBox_mouseAdapter(this)); + saveFile_Button.setToolTipText("Save File"); + saveFile_Button.setIcon(saveFileImage); + saveFile_Button.addActionListener(new + Sander9Frame_saveFile_Button_actionAdapter(this)); + NTF_ComboBox.addMouseListener(new Sander9Frame_NTF_ComboBox_mouseAdapter(this)); + IPOL_ComboBox.addMouseListener(new + Sander9Frame_IPOL_ComboBox_mouseAdapter(this)); + NTB_ComboBox.addMouseListener(new Sander9Frame_NTB_ComboBox_mouseAdapter(this)); + NTX_ComboBox.addMouseListener(new Sander9Frame_NTX_ComboBox_mouseAdapter(this)); + NTRX_ComboBox.addMouseListener(new + Sander9Frame_NTRX_ComboBox_mouseAdapter(this)); + NTXO_ComboBox.addMouseListener(new + Sander9Frame_NTXO_ComboBox_mouseAdapter(this)); + IWRAP_ComboBox.addMouseListener(new + Sander9Frame_IWRAP_ComboBox_mouseAdapter(this)); + IOUTFM_ComboBox.addMouseListener(new + Sander9Frame_IOUTFM_ComboBox_mouseAdapter(this)); + IDECOMP_ComboBox.addMouseListener(new + Sander9Frame_IDECOMP_ComboBox_mouseAdapter(this)); + NTR_ComboBox.addMouseListener(new Sander9Frame_NTR_ComboBox_mouseAdapter(this)); + IBELLY_ComboBox.addMouseListener(new + Sander9Frame_IBELLY_ComboBox_mouseAdapter(this)); + IVCAP_ComboBox.addMouseListener(new + Sander9Frame_IVCAP_ComboBox_mouseAdapter(this)); + NTC_ComboBox.addMouseListener(new Sander9Frame_NTC_ComboBox_mouseAdapter(this)); + JFASTW_ComboBox.addMouseListener(new + Sander9Frame_JFASTW_ComboBox_mouseAdapter(this)); + RBORNSTAT_ComboBox.addMouseListener(new + Sander9Frame_RBORNSTAT_ComboBox_mouseAdapter(this)); + GBSA_ComboBox.addMouseListener(new + Sander9Frame_GBSA_ComboBox_mouseAdapter(this)); + jMenuItem1.setText("Open Job Control File"); + jMenuItem1.addActionListener(new Sander9Frame_jMenuItem1_actionAdapter(this)); + jMenuItem2.setText("Save File"); + jMenuItem2.addActionListener(new Sander9Frame_jMenuItem2_actionAdapter(this)); + jMenuBar1.add(jMenuFile); + jMenuFile.add(jMenuItem1); + jMenuFile.add(jMenuItem2); + jMenuFile.add(Edit_MenuItem); + jMenuFile.addSeparator(); + jMenuFile.add(jMenuFileExit); + jMenuBar1.add(jMenuHelp); + jMenuHelp.add(jMenuHelpAbout); + setJMenuBar(jMenuBar1); + openFile_Button.setIcon(image1); + openFile_Button.setToolTipText("Open File"); + newFile_Button.setIcon(image2); + newFile_Button.setToolTipText( + "Reset the variables to their default values"); + help_Button.setIcon(image3); + help_Button.setToolTipText("Help"); + jToolBar.add(openFile_Button); + jToolBar.add(newFile_Button); + jToolBar.add(saveFile_Button); + jToolBar.add(help_Button); + descrPanel.add(descriptionPane); + jTabbedPane1.add(jobTypePanel, "Job Type"); + jTabbedPane1.add(potentialFuncPanel, "Potential Function"); + jTabbedPane1.add(MolDynPanel, "Molecular Dynamics"); + jTabbedPane1.add(ioPanel, "Input/Output"); + jTabbedPane1.add(restrainPanel, "Restrains"); + jTabbedPane1.add(GB_Panel, "GB/SA"); + jTabbedPane1.add(PME_Panel, "PME"); + ioPanel.add(inputPanel, BorderLayout.NORTH); + ioPanel.add(outputPanel, BorderLayout.CENTER); + jobTypePanel.add(jPanel1, BorderLayout.WEST); + jobTypePanel.add(cardsPanel, BorderLayout.CENTER); + cardsPanel.add(minCard, "minCard"); + cardsPanel.add(mdCard, "mdCard"); + + contentPane.add(jTabbedPane1, BorderLayout.CENTER); + MolDynPanel.add(PressureControlPanel, + new GridBagConstraints(0, 4, 8, 2, 1.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.BOTH, + new Insets(5, 5, 5, 5), 0, 0)); + MolDynPanel.add(TempControlPanel, + new GridBagConstraints(0, 1, 8, 3, 1.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.BOTH, + new Insets(5, 5, 5, 5), 0, 0)); + inputPanel.add(NTX_Label, null); + inputPanel.add(NTX_ComboBox, null); + inputPanel.add(NTRX_Label, null); + inputPanel.add(NTRX_ComboBox, null); + jPanel1.add(IMIN_ComboBox, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0 + , GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(IREST_ComboBox, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(IGB_ComboBox, new GridBagConstraints(0, 2, 1, 1, 0.0, 1.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + GB_Panel.add(INTDIEL_TextField, + new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(EXTDIEL_Label, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(EXTDIEL_TextField, + new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(SALTCON_Label, new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(SALTCON_TextField, + new GridBagConstraints(5, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(RGBMAX_Label, new GridBagConstraints(6, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(RDT_TextField, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(RBORNSTAT_ComboBox, + new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(OFFSET_Label, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(OFFSET_TextField, + new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(GBSA_Label, new GridBagConstraints(4, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(GBSA_ComboBox, new GridBagConstraints(5, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(SURFTEN_Label, new GridBagConstraints(6, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(SURFTEN_TextField, + new GridBagConstraints(7, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(RDT_Label, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(RBORNSTAT_Label, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + PressureControlPanel.add(COMP_Label, null); + PressureControlPanel.add(COMP_TextField, null); + restrainPanel.add(IBELLY_Label, + new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(shakePanel, + new GridBagConstraints(0, 3, 12, 1, 1.0, 1.0 + , GridBagConstraints.CENTER, + GridBagConstraints.BOTH, + new Insets(5, 0, 5, 0), 0, 0)); + shakePanel.add(OWTNM_Label, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + shakePanel.add(WATNAM_Label, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + shakePanel.add(NTC_Label, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 0), 0, 0)); + shakePanel.add(HWTNM1_Label, new GridBagConstraints(4, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(RESTRAINTMASK_Label, + new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + shakePanel.add(JFASTW_Label, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + shakePanel.add(TOL_Label, new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + shakePanel.add(HWTNM2_Label, new GridBagConstraints(6, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 5), 0, 0)); + GB_Panel.add(INTDIEL_Label, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(RGBMAX_TextField, + new GridBagConstraints(7, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + GB_Panel.add(GB_Dummy_Label, new GridBagConstraints(8, 3, 1, 1, 1.0, 1.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(0, 0, 0, 0), 0, 0)); + outputPanel.add(jLabel6, new GridBagConstraints(8, 3, 1, 1, 1.0, 1.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(0, 0, 0, 0), 0, 0)); + outputPanel.add(NTXO_Label, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 0, 0), 0, 0)); + outputPanel.add(NTXO_ComboBox, + new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTPR_Label, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTAVE_Label, new GridBagConstraints(4, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 0, 0), 0, 0)); + outputPanel.add(NTWR_Label, new GridBagConstraints(6, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(IWRAP_Label, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(IWRAP_ComboBox, + new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTWX_Label, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTWV_Label, new GridBagConstraints(4, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTWE_Label, new GridBagConstraints(6, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(NTF_Label, + new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(NTB_Label, + new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + potentialFuncPanel.add(NTF_ComboBox, + new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + minCard.add(covergLabel, new GridBagConstraints(0, 5, 1, 1, 0.0, 1.0 + , GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, + new Insets(0, 0, 0, 0), 1, 1)); + minCard.add(methodLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 1, 1)); + minCard.add(DRMS_TextField, new GridBagConstraints(1, 5, 4, 1, 1.0, 0.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, + new Insets(1, 0, 1, 0), 0, 0)); + mdCard.add(NSTLIM_Label, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(NSTLIM_TextField, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(DT_Label, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 1, 1)); + mdCard.add(DT_TextField, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 1, 1)); + mdCard.add(TEMP0_Label, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(TEMP0_TextField, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(PRES0_Label, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + mdCard.add(PRES0_TextField, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(NTT_Label, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(NTT_ComboBox, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 1, 0)); + mdCard.add(NTP_Label, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + mdCard.add(NTP_ComboBox, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(TAUTP_TextField, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(TAUTP_Label, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(TAUP_TextField, new GridBagConstraints(3, 3, 1, 1, 1.0, 0.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + mdCard.add(TAUP_Label, new GridBagConstraints(2, 3, 1, 1, 0.0, 1.0 + , GridBagConstraints.NORTH, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + restrainPanel.add(RESTRAINT_WT_TextField, + new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(BELLYMASK_TextField, + new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(RESTRAINTMASK_TextField, + new GridBagConstraints(5, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(NTR_Label, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 0), 0, 0)); + restrainPanel.add(NTR_ComboBox, + new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(IBELLY_ComboBox, + new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(IVCAP_Label, + new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(BELLYMASK_Label, + new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + restrainPanel.add(RESTRAINT_WT_Label, + new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + restrainPanel.add(IVCAP_ComboBox, + new GridBagConstraints(1, 2, 5, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(FCAP_TextField, + new GridBagConstraints(7, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + restrainPanel.add(FCAP_Label, new GridBagConstraints(6, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + shakePanel.add(NTC_ComboBox, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + shakePanel.add(JFASTW_ComboBox, + new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + shakePanel.add(WATNAM_TextField, + new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + shakePanel.add(OWTNM_TextField, + new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + shakePanel.add(HWTNM1_TextField, + new GridBagConstraints(5, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + shakePanel.add(HWTNM2_TextField, + new GridBagConstraints(7, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + shakePanel.add(TOL_TextField, new GridBagConstraints(5, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + TempControlPanel.add(VLIMIT_Label, + new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + TempControlPanel.add(VRAND_Label, + new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + TempControlPanel.add(VRAND_TextField, + new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 5), 0, 0)); + TempControlPanel.add(GAMMA_LN_Label, + new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + TempControlPanel.add(GAMMA_LN_TextField, + new GridBagConstraints(5, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 5), 0, 0)); + TempControlPanel.add(TEMPI_Label, + new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + TempControlPanel.add(TEMPI_TextField, + new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 5), 0, 0)); + TempControlPanel.add(TEMP0LES_Label, + new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 0), 0, 0)); + TempControlPanel.add(TEMP0LES_TextField, + new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + TempControlPanel.add(VLIMIT_TextField, + new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 5), 0, 0)); + TempControlPanel.add(Dummy_MD_Label, + new GridBagConstraints(6, 1, 1, 1, 1.0, 1.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(0, 0, 0, 0), 0, 0)); + MolDynPanel.add(NSCM_Label, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 15, 5, 0), 0, 0)); + MolDynPanel.add(NRESPA_Label, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 15, 5, 0), 0, 0)); + MolDynPanel.add(NRESPA_TextField, + new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 5), 0, 0)); + MolDynPanel.add(T_Label, new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 15, 5, 5), 0, 0)); + MolDynPanel.add(T_TextField, new GridBagConstraints(5, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + MolDynPanel.add(IG_Label, new GridBagConstraints(6, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 15, 5, 5), 0, 0)); + MolDynPanel.add(IG_TextField, new GridBagConstraints(7, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + MolDynPanel.add(NSCM_TextField, + new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 5), 0, 0)); + potentialFuncPanel.add(IPOL_Label, + new GridBagConstraints(0, 3, 1, 1, 0.0, 1.0 + , GridBagConstraints.NORTH, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(DIELC_Label, + new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(DIELC_TextField, + new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(SCEE_Label, + new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + potentialFuncPanel.add(SCEE_TextField, + new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(SCNB_Label, + new GridBagConstraints(4, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + potentialFuncPanel.add(NSNB_Label, + new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + potentialFuncPanel.add(CUT_Label, + new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 10, 5, 0), 0, 0)); + potentialFuncPanel.add(CUT_TextField, + new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(IPOL_ComboBox, + new GridBagConstraints(1, 3, 2, 1, 0.0, 0.0 + , + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(NTB_ComboBox, + new GridBagConstraints(3, 0, 3, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(NSNB_TextField, + new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + potentialFuncPanel.add(SCNB_TextField, + new GridBagConstraints(5, 2, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTWE_TextField, + new GridBagConstraints(7, 2, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTWR_TextField, + new GridBagConstraints(7, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(IOUTFM_Label, new GridBagConstraints(0, 3, 1, 1, 0.0, 1.0 + , GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(IOUTFM_ComboBox, + new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTWPRT_Label, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTWPRT_TextField, + new GridBagConstraints(3, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(IDECOMP_Label, + new GridBagConstraints(4, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTH, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(IDECOMP_ComboBox, + new GridBagConstraints(5, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTPR_TextField, + new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTWX_TextField, + new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTAVE_TextField, + new GridBagConstraints(5, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + outputPanel.add(NTWV_TextField, + new GridBagConstraints(5, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 0, 5, 0), 0, 0)); + minCard.add(NTMIN_ComboBox, new GridBagConstraints(0, 0, 2, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 2, 0), 1, 1)); + minCard.add(maxIterLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 2, 0), 1, 1)); + minCard.add(MAXCYC_TextField, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 2, 0), 1, 1)); + minCard.add(switchLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 2, 0), 1, 1)); + minCard.add(NCYC_TextField, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 2, 0), 0, 0)); + minCard.add(dxLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 2, 1), 1, 1)); + minCard.add(DX0_TextField, new GridBagConstraints(1, 4, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 0, 2, 0), 0, 0)); + contentPane.add(descrPanel, BorderLayout.SOUTH); + contentPane.add(jToolBar, BorderLayout.NORTH); + jTabbedPane1.setSelectedIndex(0); + + // --- setup all text fields, combo boxes etc... + setupControls(); + } + + public void setupControls() { + + Map allVars = s8jc.getAllVariablesInfo(); + SanderVariable var; + + setupList("NTF", NTF_ComboBox, true); + setupList("NTB", NTB_ComboBox, false); + setupValue("DIELC", DIELC_TextField); + setupValue("CUT", CUT_TextField); + setupValue("SCNB", SCNB_TextField); + setupValue("SCEE", SCEE_TextField); + setupValue("NSNB", NSNB_TextField); + setupValue("MAXCYC", MAXCYC_TextField); + setupValue("NCYC", NCYC_TextField); + setupValue("DX0", DX0_TextField); + setupValue("DRMS", DRMS_TextField); + setupList("IPOL", IPOL_ComboBox, false); + +// --- Setup mdCard Panel + + setupValue("NSTLIM", NSTLIM_TextField); + setupValue("TEMP0", TEMP0_TextField); + setupValue("DT", DT_TextField); + setupValue("TAUTP", TAUTP_TextField); + setupValue("PRES0", PRES0_TextField); + setupValue("TAUP", TAUP_TextField); + setupList("NTT", NTT_ComboBox, true); + setupList("NTP", NTP_ComboBox, true); + +// --- Setup Molecular Dynamics Panel + + setupValue("NSCM", NSCM_TextField); + setupValue("NRESPA", NRESPA_TextField); + setupValue("T", T_TextField); + setupValue("IG", IG_TextField); + setupValue("T", T_TextField); + setupValue("VLIMIT", VLIMIT_TextField); + setupValue("VRAND", VRAND_TextField); + setupValue("TEMPI", TEMPI_TextField); + setupValue("GAMMA_LN", GAMMA_LN_TextField); + setupValue("TEMP0LES", TEMP0LES_TextField); + setupValue("COMP", COMP_TextField); + +// --- Input panel + + setupList("NTRX", NTRX_ComboBox, true); + setupList("NTX", NTX_ComboBox, true); + +// --- Output panel + + setupList("NTXO", NTXO_ComboBox, true); + setupList("IWRAP", IWRAP_ComboBox, true); + setupList("IOUTFM", IOUTFM_ComboBox, true); + setupList("IDECOMP", IDECOMP_ComboBox, true); + + setupValue("NTPR", NTPR_TextField); + setupValue("NTAVE", NTAVE_TextField); + setupValue("NTWR", NTWR_TextField); + setupValue("NTWX", NTWX_TextField); + setupValue("NTWV", NTWV_TextField); + setupValue("NTWE", NTWE_TextField); + setupValue("NTWPRT", NTWPRT_TextField); + + // --- General Born + + setupList("IGB", IGB_ComboBox, false); + + setupList("RBORNSTAT", RBORNSTAT_ComboBox, true); + setupList("GBSA", GBSA_ComboBox, true); + + setupValue("INTDIEL", INTDIEL_TextField); + setupValue("EXTDIEL", EXTDIEL_TextField); + setupValue("SALTCON", SALTCON_TextField); + setupValue("RGBMAX", RGBMAX_TextField); + setupValue("OFFSET", OFFSET_TextField); + setupValue("SURFTEN", SURFTEN_TextField); + setupValue("RDT", RDT_TextField); + + // --- Frozen or restrained atoms. + + setupValue("RESTRAINT_WT", RESTRAINT_WT_TextField); + setupValue("RESTRAINTMASK", RESTRAINTMASK_TextField); + setupValue("BELLYMASK", BELLYMASK_TextField); + + // --- Water cap + + setupList("IVCAP", IVCAP_ComboBox, false); + setupValue("FCAP", FCAP_TextField); + + // -- SHAKE + + setupList("NTC", NTC_ComboBox, true); + setupList("JFASTW", JFASTW_ComboBox, true); + setupValue("TOL", TOL_TextField); + setupValue("WATNAM", WATNAM_TextField); + setupValue("OWTNM", OWTNM_TextField); + setupValue("HWTNM1", HWTNM1_TextField); + setupValue("HWTNM2", HWTNM2_TextField); + + // --- Special setup + + comboBoxAdjusting = true; + var = (SanderVariable) allVars.get("IMIN"); + IMIN_ComboBox.removeAllItems(); + IMIN_ComboBox.addItem("Molecular Dynamics"); + IMIN_ComboBox.addItem("Energy Minimization"); + IMIN_ComboBox.setSelectedIndex(var.getSelectedIndex()); + + var = (SanderVariable) allVars.get("IREST"); + IREST_ComboBox.removeAllItems(); + IREST_ComboBox.addItem("New Calculation"); + IREST_ComboBox.addItem("Restart"); + IREST_ComboBox.setSelectedIndex(var.getSelectedIndex()); + + var = (SanderVariable) allVars.get("NTMIN"); + NTMIN_ComboBox.removeAllItems(); + NTMIN_ComboBox.addItem("Conjugate Gradient"); + NTMIN_ComboBox.addItem("Steepest Descent + Conjugate Gradient"); + NTMIN_ComboBox.addItem("XMIN"); + NTMIN_ComboBox.addItem("LMOD"); + NTMIN_ComboBox.setSelectedIndex(var.getSelectedIndex()); + + var = (SanderVariable) allVars.get("NTR"); + NTR_ComboBox.removeAllItems(); + NTR_ComboBox.addItem("No"); + NTR_ComboBox.addItem("Yes"); + NTR_ComboBox.setSelectedIndex(var.getSelectedIndex()); + + var = (SanderVariable) allVars.get("IBELLY"); + IBELLY_ComboBox.removeAllItems(); + IBELLY_ComboBox.addItem("No"); + IBELLY_ComboBox.addItem("Yes"); + IBELLY_ComboBox.setSelectedIndex(var.getSelectedIndex()); + comboBoxAdjusting = false; + + // --- More of Special setup + + if (IGB_ComboBox.getSelectedIndex() == 0) { + jTabbedPane1.setEnabledAt(5, false); + } + else { + jTabbedPane1.setEnabledAt(5, true); + } + + if (IMIN_ComboBox.getSelectedIndex() == 0) { + jTabbedPane1.setEnabledAt(2, true); + } + else { + jTabbedPane1.setEnabledAt(2, false); + } + } + + /** + * + * @param amberVarName String + * @param jBox JComboBox + * @param use_values boolean - if "true" use variable's possible values, + * otherwise use values descriptions + */ + public void setupList(String amberVarName, JComboBox jBox, + boolean use_values) { + if (s8jc == null) { + JOptionPane.showMessageDialog(this, + "INTERNAL ERROR: setupList: s8jc == null", + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + comboBoxAdjusting = true; + jBox.removeAllItems(); + + Map allVars = s8jc.getAllVariablesInfo(); + SanderVariable var = (SanderVariable) allVars.get(amberVarName); + + if (var == null) { + JOptionPane.showMessageDialog(this, + "INTERNAL ERROR: setupList: var == null : var name: " + + amberVarName, + "Error", + JOptionPane.ERROR_MESSAGE); + comboBoxAdjusting = false; + return; + } + + String s_value; + for (int i = 0; i < var.getNumberOfValues(); i++) { + SanderVariableValue value = var.getValue(i); + + if (use_values) { + s_value = value.getValue(); + } + else { + s_value = value.getDescription(); + } + + if (value.isDefault()) { + s_value += " (default)"; + } + jBox.addItem(s_value); + } + + if (var.getSelectedIndex() == -1) { + JOptionPane.showMessageDialog(this, + "INTERNAL ERROR: setupList: var.getSelectedIndex() == -1 : var name: " + + amberVarName, + "Error", + JOptionPane.ERROR_MESSAGE); + + } + else { + jBox.setSelectedIndex(var.getSelectedIndex()); + } + comboBoxAdjusting = false; + //logger.info("Var: " + amberVarName + " selected: " + + // var.getSelectedIndex()); + controlsTable.put(amberVarName, jBox); + this.pack(); + } + + public void setupValue(String amberVarName, JTextField jText) { + if (s8jc == null) { + return; + } + jText.removeAll(); + + Map allVars = s8jc.getAllVariablesInfo(); + SanderVariable var = (SanderVariable) allVars.get(amberVarName); + + if (var == null || var.isEnumerated()) { + JOptionPane.showMessageDialog(this, + "INTERNAL ERROR: setupValue: var == null || var.isEnumerated(): var name: " + + amberVarName, + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + String s_value; + + //SanderVariableValue value = var.getValue(0); + //s_value = value.getValue(); + + s_value = var.getValue(); + + jText.setText(s_value); + jText.setToolTipText("Enter new Value and Press Enter"); + controlsTable.put(amberVarName, jText); + this.pack(); + } + + void showVarDescription(String var_name) { + Map allVars = s8jc.getAllVariablesInfo(); + SanderVariable var = (SanderVariable) allVars.get(var_name); + descriptionPane.removeAll(); + descriptionPane.setText(var.getDescription()); + } + + void setNewValue(String amberVarName, JTextField new_value) { + Map allVars = s8jc.getAllVariablesInfo(); + SanderVariable var = (SanderVariable) allVars.get(amberVarName); + String message = var.setValue(new_value.getText()); + if (message == null) { + descriptionPane.removeAll(); + descriptionPane.setText("Set " + amberVarName + " = " + + new_value.getText()); + } + else { + JOptionPane.showMessageDialog(this, + message, + "Error", + JOptionPane.ERROR_MESSAGE); + } + + } + + /** + * + * @param var_name String + * @param comboBox JComboBox + */ + void showValueDescription(String var_name, JComboBox comboBox) { + if (comboBoxAdjusting) { + return; + } + if (comboBox.getItemCount() == 0) { + return; + } + Map allVars = s8jc.getAllVariablesInfo(); + SanderVariable var = (SanderVariable) allVars.get(var_name); + SanderVariableValue value = var.getValue(comboBox.getSelectedIndex()); + descriptionPane.removeAll(); + descriptionPane.setText(value.getDescription()); + var.setSelectedIndex(comboBox.getSelectedIndex()); + } + + /** + * File | Exit action performed. + * + * @param actionEvent ActionEvent + */ + void jMenuFileExit_actionPerformed(ActionEvent actionEvent) { + System.exit(0); + } + + /** + * Help | About action performed. + * + * @param actionEvent ActionEvent + */ + void jMenuHelpAbout_actionPerformed(ActionEvent actionEvent) { + Sander9Frame_AboutBox dlg = new Sander9Frame_AboutBox(this); + Dimension dlgSize = dlg.getPreferredSize(); + Dimension frmSize = getSize(); + Point loc = getLocation(); + dlg.setLocation( (frmSize.width - dlgSize.width) / 2 + loc.x, + (frmSize.height - dlgSize.height) / 2 + loc.y); + dlg.setModal(true); + dlg.pack(); + dlg.setVisible(true); + } + + public void forceEvalButton_actionPerformed(ActionEvent e) { + showVarDescription("NTF"); + } + + public void NTF_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTF", NTF_ComboBox); + } + + public void NTB_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTB", NTB_ComboBox); + } + + public void DIELC_Button_actionPerformed(ActionEvent e) { + showVarDescription("DIELC"); + } + + public void CUT_Button_actionPerformed(ActionEvent e) { + showVarDescription("CUT"); + } + + public void SCNB_Button_actionPerformed(ActionEvent e) { + showVarDescription("SCNB"); + } + + public void NBListButton_actionPerformed(ActionEvent e) { + showVarDescription("NSNB"); + } + + public void SCEE_Button_actionPerformed(ActionEvent e) { + showVarDescription("SCEE"); + } + + public void jButton5_actionPerformed(ActionEvent e) { + showVarDescription("IPOL"); + } + + public void IPOL_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("IPOL", IPOL_ComboBox); + } + + public void IMIN_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("IMIN", IMIN_ComboBox); + + CardLayout cl = (CardLayout) cardsPanel.getLayout(); + if (IMIN_ComboBox.getSelectedIndex() == 0) { + cl.show(cardsPanel, "mdCard"); + jTabbedPane1.setEnabledAt(2, true); + } + else if (IMIN_ComboBox.getSelectedIndex() == 1) { + cl.show(cardsPanel, "minCard"); + jTabbedPane1.setEnabledAt(2, false); + } + } + + public void NTMIN_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTMIN", NTMIN_ComboBox); + } + + public void jLabel6_mouseEntered(MouseEvent e) { + showVarDescription("NTMIN"); + } + + public void maxIterLabel_mouseEntered(MouseEvent e) { + showVarDescription("MAXCYC"); + } + + public void switchLabel_mouseEntered(MouseEvent e) { + showVarDescription("NCYC"); + } + + public void dxLabel_mouseEntered(MouseEvent e) { + showVarDescription("DX0"); + } + + public void covergLabel_mouseEntered(MouseEvent e) { + showVarDescription("DRMS"); + } + + public void IREST_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("IREST", IREST_ComboBox); + } + + public void jLabel10_mouseEntered(MouseEvent e) { + showVarDescription("NSCM"); + } + + public void NRESPA_Label_mouseEntered(MouseEvent e) { + showVarDescription("NRESPA"); + } + + public void T_Label_mouseEntered(MouseEvent e) { + showVarDescription("T"); + } + + public void NTT_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTT"); + } + + public void TEMP0LES_Label_mouseEntered(MouseEvent e) { + showVarDescription("TEMP0LES"); + } + + public void IG_Label_mouseEntered(MouseEvent e) { + showVarDescription("IG"); + } + + public void TAUTP_Label_mouseEntered(MouseEvent e) { + showVarDescription("TAUTP"); + } + + public void GAMMA_LN_Label_mouseEntered(MouseEvent e) { + showVarDescription("GAMMA_LN"); + } + + public void VRAND_Label_mouseEntered(MouseEvent e) { + showVarDescription("VRAND"); + } + + public void NTP_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTP"); + } + + public void TEMP0_Label_mouseEntered(MouseEvent e) { + showVarDescription("TEMP0"); + } + + public void NSTLIM_Label_mouseEntered(MouseEvent e) { + showVarDescription("NSTLIM"); + } + + public void DT_Label_mouseEntered(MouseEvent e) { + showVarDescription("DT"); + } + + public void COMP_Label_mouseEntered(MouseEvent e) { + showVarDescription("COMP"); + } + + public void TAUP_Label_mouseEntered(MouseEvent e) { + showVarDescription("TAUP"); + } + + public void PRES0_Label_mouseEntered(MouseEvent e) { + showVarDescription("PRES0"); + } + + public void NTT_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTT", NTT_ComboBox); + } + + public void NTP_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTP", NTP_ComboBox); + } + + public void VLIMIT_Label_mouseEntered(MouseEvent e) { + showVarDescription("VLIMIT"); + } + + public void TEMPI_Label_mouseEntered(MouseEvent e) { + showVarDescription("TEMPI"); + } + + public void NSNB_Label_mouseEntered(MouseEvent e) { + showVarDescription("NSNB"); + } + + public void SCEE_Label_mouseEntered(MouseEvent e) { + showVarDescription("SCEE"); + } + + public void IPOL_Label_mouseEntered(MouseEvent e) { + showVarDescription("IPOL"); + } + + public void NTF_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTF"); + } + + public void NTB_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTB"); + } + + public void jButton1_actionPerformed(ActionEvent e) { + FileDialog fd = new FileDialog(this, "Open Sander 9 Job Control File", + FileDialog.LOAD); + fd.setFile("*.in;*.sh"); + fd.setVisible(true); + if (fd.getFile() != null) { + fileName = new String(fd.getFile()); + workingDirectory = new String(fd.getDirectory()); + s8jc = new Sander9JobControl(); + setupControls(); + parseInputData(IOUtils.loadFileIntoString(workingDirectory + fileName)); + } + } + + public Map parseInputData(String data) { + fileContent = data; + if (cntrl == null) { + cntrl = new FortranNamelist(); + } + Map vars = Sander8JobControl.getGeneralParameters(fileContent, 1, + cntrl, "cntrl"); + if (s8jc.setCntrlVariables(vars)) { + + } + else { + JOptionPane.showMessageDialog(this, + s8jc.getErrorMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + } + setupControls(); + return vars; + } + + public void jButton2_actionPerformed(ActionEvent e) { + s8jc = new Sander9JobControl(); + this.setupControls(); + fileContent = null; + JOptionPane.showMessageDialog(this, + "All variables are reset to their default values", + "Info", + JOptionPane.INFORMATION_MESSAGE); + + } + + public void jButton3_actionPerformed(ActionEvent e) { + JOptionPane.showMessageDialog(this, + "Program allows to edit \"cntrl\" namelist for Sander 9\n" + + "Select the tab corresponding to the desired component\n" + + "Set options using either text fields or combo boxes\n" + + "Toolbar provides access to commonly used features:\n" + + " Open Sander 9 job control file\n" + + " Reset the options to their default values\n" + + " Save File, and Help\n" + + "To see the description for a particular option point your cursor to an option\n" + + " and its description will be in the Option Description panel", + "Help", + JOptionPane.INFORMATION_MESSAGE); + } + + public void NTRX_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTRX"); + } + + public void NTX_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTX"); + } + + public void NTWR_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTWR"); + } + + public void NTAVE_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTAVE"); + } + + public void IWRAP_Label_mouseEntered(MouseEvent e) { + showVarDescription("IWRAP"); + } + + public void NTXO_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTXO"); + } + + public void NTPR_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTPR"); + } + + public void NTWX_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTWX"); + } + + public void NTWV_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTWV"); + } + + public void NTWE_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTWE"); + } + + public void IOUTFM_Label_mouseEntered(MouseEvent e) { + showVarDescription("IOUTFM"); + } + + public void NTWPRT_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTWPRT"); + } + + public void IDECOMP_Label_mouseEntered(MouseEvent e) { + showVarDescription("IDECOMP"); + } + + public void INTDIEL_Label_mouseEntered(MouseEvent e) { + showVarDescription("INTDIEL"); + } + + public void EXTDIEL_Label_mouseEntered(MouseEvent e) { + showVarDescription("EXTDIEL"); + } + + public void SALTCON_Label_mouseEntered(MouseEvent e) { + showVarDescription("SALTCON"); + } + + public void RGBMAX_Label_mouseEntered(MouseEvent e) { + showVarDescription("RGBMAX"); + } + + public void RBORNSTAT_Label_mouseEntered(MouseEvent e) { + showVarDescription("RBORNSTAT"); + } + + public void OFFSET_Label_mouseEntered(MouseEvent e) { + showVarDescription("OFFSET"); + } + + public void GBSA_Label_mouseEntered(MouseEvent e) { + showVarDescription("GBSA"); + } + + public void SURFTEN_Label_mouseEntered(MouseEvent e) { + showVarDescription("SURFTEN"); + } + + public void RDT_Label_mouseEntered(MouseEvent e) { + showVarDescription("RDT"); + } + + public void RBORNSTAT_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("RBORNSTAT", RBORNSTAT_ComboBox); + } + + public void GBSA_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("GBSA", GBSA_ComboBox); + } + + public void NTXO_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTXO", NTXO_ComboBox); + } + + public void IWRAP_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("IWRAP", IWRAP_ComboBox); + } + + public void IOUTFM_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("IOUTFM", IOUTFM_ComboBox); + } + + public void IDECOMP_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("IDECOMP", IDECOMP_ComboBox); + } + + public void NTX_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTX", NTX_ComboBox); + } + + public void NTRX_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTRX", NTRX_ComboBox); + } + + public void DIELC_Label_mouseEntered(MouseEvent e) { + showVarDescription("DIELC"); + } + + public void CUT_Label_mouseEntered(MouseEvent e) { + showVarDescription("CUT"); + } + + public void SCNB_Label_mouseEntered(MouseEvent e) { + showVarDescription("SCNB"); + } + + public void Edit_MenuItem_actionPerformed(ActionEvent e) { + if (inputEditor == null) { + inputEditor = new TextEditorFrame(this, "Text Editor", ""); + inputEditor.setSize(450, 300); + } + //this.setEnabled(false); + inputEditor.setVisible(true); + if (fileContent == null) { + fileContent = generateFileContents( + "This is automatically generated file"); + } + else { + fileContent = updateFileContents(fileContent, "cntrl"); + } + inputEditor.setTextToEdit(fileContent); + this.setEnabled(false); + } + + String updateFileContents(String data, String namelistName) { + Map vars = parseInputData(data); + if (vars.size() < 1) { + return data; // i.e. no cntrl namelist + } + + Map allVars = s8jc.getAllVariablesInfo(); + Map cntrlVars = cntrl.getVariables(); + String mess = Sander8JobControl.updateNamelistVariables(cntrlVars, + allVars); + if (mess != null) { + JOptionPane.showMessageDialog(this, + mess, "Warning", + JOptionPane.WARNING_MESSAGE); + } + + StringReader sReader = new StringReader(data); + StringWriter sWriter = new StringWriter(); + + try { + int character, count = 0; + char cbuf[] = new char[120]; + String line = null; + boolean skippingNamelist = false; + boolean theRest = false; + + while ( (character = sReader.read()) != -1) { + if (theRest) { + sWriter.write(character); + continue; + } + + if (character == '\n') { + if (line == null) { + line = String.copyValueOf(cbuf, 0, count); + } + else { + line += String.copyValueOf(cbuf, 0, count); + } + count = 0; + + if (skippingNamelist && + cct.tools.FortranNamelist.hasNamelistEnd(line)) { + theRest = true; + continue; + } + else if (skippingNamelist) { + continue; + } + + if (cct.tools.FortranNamelist.hasNamelistStart(line, "cntrl")) { + cct.tools.FortranNamelist.writeNamelistBody(sWriter, "cntrl", + cntrlVars); + skippingNamelist = true; + } + + if (cct.tools.FortranNamelist.hasNamelistEnd(line)) { + theRest = true; + continue; + } + + if (skippingNamelist) { + continue; + } + + sWriter.write(line + "\n"); + line = null; + + } + else if (count < 120) { + cbuf[count] = (char) character; + ++count; + } + else { + if (line == null) { + line = String.copyValueOf(cbuf, 0, count); + } + else { + line += String.copyValueOf(cbuf, 0, count); + } + count = 0; + } + } + } + catch (IOException er) { + + } + + return sWriter.toString(); + } + + /** + * + * @param title String + * @return String + */ + String generateFileContents(String title) { + + StringWriter sWriter = new StringWriter(); + sWriter.write(title + "\n &cntrl\n"); + + Map allVars = s8jc.getAllVariablesInfo(); + SanderVariable var; + + Set set = controlsTable.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String option = me.getKey().toString(); + var = (SanderVariable) allVars.get(option); + Object control = me.getValue(); + + if (control instanceof JComboBox) { + JComboBox jBox = (JComboBox) control; + if (var.isDefaultValue()) { + continue; + } + sWriter.write(" " + option + "=" + var.getValue() + "\n"); + } + else if (control instanceof JTextField) { + JTextField jText = (JTextField) control; + String value = jText.getText().trim(); + String reference = var.getValue(); + + if (!reference.equalsIgnoreCase(value)) { + String message = var.setValue(value); + if (message != null) { + JOptionPane.showMessageDialog(this, + option + ": " + message, + "Error", + JOptionPane.ERROR_MESSAGE); + setupValue(option, jText); + continue; + } + } + if (var.isDefaultValue()) { + continue; + } + sWriter.write(" " + option + "=" + var.getValue() + "\n"); + } + + } + + sWriter.write(" &end\n"); + return sWriter.toString(); + } + + public void IGB_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("IGB", IGB_ComboBox); + if (IGB_ComboBox.getSelectedIndex() == 0) { + jTabbedPane1.setEnabledAt(5, false); + } + else { + jTabbedPane1.setEnabledAt(5, true); + } + } + + public void NTR_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTR"); + } + + public void NTR_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTR", NTR_ComboBox); + } + + public void IBELLY_Label_mouseEntered(MouseEvent e) { + showVarDescription("IBELLY"); + } + + public void IBELLY_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("IBELLY", IBELLY_ComboBox); + } + + public void RESTRAINT_WT_Label_mouseEntered(MouseEvent e) { + showVarDescription("RESTRAINT_WT"); + } + + public void RESTRAINTMASK_Label_mouseEntered(MouseEvent e) { + showVarDescription("RESTRAINTMASK"); + } + + public void BELLYMASK_Label_mouseEntered(MouseEvent e) { + showVarDescription("BELLYMASK"); + } + + public void IVCAP_Label_mouseEntered(MouseEvent e) { + showVarDescription("IVCAP"); + } + + public void IVCAP_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("IVCAP", IVCAP_ComboBox); + } + + public void FCAP_Label_mouseEntered(MouseEvent e) { + showVarDescription("FCAP"); + } + + public void NTC_Label_mouseEntered(MouseEvent e) { + showVarDescription("NTC"); + } + + public void NTC_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("NTC", NTC_ComboBox); + } + + public void JFASTW_Label_mouseEntered(MouseEvent e) { + showVarDescription("JFASTW"); + } + + public void JFASTW_ComboBox_itemStateChanged(ItemEvent e) { + showValueDescription("JFASTW", JFASTW_ComboBox); + } + + public void TOL_Label_mouseEntered(MouseEvent e) { + showVarDescription("TOL"); + } + + public void WATNAM_Label_mouseEntered(MouseEvent e) { + showVarDescription("WATNAM"); + } + + public void OWTNM_Label_mouseEntered(MouseEvent e) { + showVarDescription("OWTNM"); + } + + public void HWTNM1_Label_mouseEntered(MouseEvent e) { + showVarDescription("HWTNM1"); + } + + public void HWTNM2_Label_mouseEntered(MouseEvent e) { + showVarDescription("HWTNM2"); + } + + public void NCYC_TextField_actionPerformed(ActionEvent e) { + setNewValue("NCYC", NCYC_TextField); + } + + public void DX0_TextField_actionPerformed(ActionEvent e) { + setNewValue("DX0", DX0_TextField); + } + + public void DRMS_TextField_actionPerformed(ActionEvent e) { + setNewValue("DRMS", DRMS_TextField); + } + + public void MAXCYC_TextField_actionPerformed(ActionEvent e) { + setNewValue("MAXCYC", MAXCYC_TextField); + } + + public void IMIN_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("IMIN", IMIN_ComboBox); + } + + public void IREST_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("IREST", IREST_ComboBox); + } + + public void IGB_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("IGB", IGB_ComboBox); + } + + public void NTMIN_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTMIN", NTMIN_ComboBox); + } + + public void NTT_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTT", NTT_ComboBox); + } + + public void NTP_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTP", NTP_ComboBox); + } + + public void NSTLIM_TextField_actionPerformed(ActionEvent e) { + setNewValue("NSTLIM", NSTLIM_TextField); + } + + public void saveFile_Button_actionPerformed(ActionEvent e) { + if (fileContent == null) { + fileContent = generateFileContents( + "This is automatically generated file"); + } + else { + fileContent = updateFileContents(fileContent, "cntrl"); + } + + FileDialog fd = new FileDialog(this, "Save Sander 9 Job Control File", + FileDialog.SAVE); + + if (fileName == null) { + fileName = "sander9.in"; + } + if (workingDirectory == null) { + workingDirectory = "./"; + } + + fd.setFile(fileName); + fd.setDirectory(workingDirectory); + fd.setVisible(true); + if (fd.getFile() != null) { + fileName = new String(fd.getFile()); + workingDirectory = new String(fd.getDirectory()); + try { + IOUtils.saveStringIntoFile(fileContent, workingDirectory + fileName); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + } + } + + } + + public void NTF_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTF", NTF_ComboBox); + } + + public void IPOL_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("IPOL", IPOL_ComboBox); + } + + public void NTB_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTB", NTB_ComboBox); + } + + public void NTX_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTX", NTX_ComboBox); + } + + public void NTRX_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTRX", NTRX_ComboBox); + } + + public void NTXO_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTXO", NTXO_ComboBox); + } + + public void IWRAP_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("IWRAP", IWRAP_ComboBox); + } + + public void IOUTFM_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("IOUTFM", IOUTFM_ComboBox); + } + + public void IDECOMP_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("IDECOMP", IDECOMP_ComboBox); + } + + public void NTR_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTR", NTR_ComboBox); + } + + public void IBELLY_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("IBELLY", IBELLY_ComboBox); + } + + public void IVCAP_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("IVCAP", IVCAP_ComboBox); + } + + public void NTC_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("NTC", NTC_ComboBox); + } + + public void JFASTW_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("JFASTW", JFASTW_ComboBox); + } + + public void RBORNSTAT_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("RBORNSTAT", RBORNSTAT_ComboBox); + } + + public void GBSA_ComboBox_mouseEntered(MouseEvent e) { + showValueDescription("GBSA", GBSA_ComboBox); + } + + public void jMenuItem1_actionPerformed(ActionEvent e) { + jButton1_actionPerformed(e); + } + + public void jMenuItem2_actionPerformed(ActionEvent e) { + saveFile_Button_actionPerformed(e); + } +} + +class Sander9Frame_jMenuItem2_actionAdapter + implements ActionListener { + private Sander9Frame adaptee; + Sander9Frame_jMenuItem2_actionAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.jMenuItem2_actionPerformed(e); + } +} + +class Sander9Frame_jMenuItem1_actionAdapter + implements ActionListener { + private Sander9Frame adaptee; + Sander9Frame_jMenuItem1_actionAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.jMenuItem1_actionPerformed(e); + } +} + +class Sander9Frame_NSTLIM_TextField_actionAdapter + implements ActionListener { + private Sander9Frame adaptee; + Sander9Frame_NSTLIM_TextField_actionAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.NSTLIM_TextField_actionPerformed(e); + } +} + +class Sander9Frame_HWTNM2_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_HWTNM2_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.HWTNM2_Label_mouseEntered(e); + } +} + +class Sander9Frame_HWTNM1_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_HWTNM1_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.HWTNM1_Label_mouseEntered(e); + } +} + +class Sander9Frame_OWTNM_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_OWTNM_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.OWTNM_Label_mouseEntered(e); + } +} + +class Sander9Frame_WATNAM_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_WATNAM_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.WATNAM_Label_mouseEntered(e); + } +} + +class Sander9Frame_TOL_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_TOL_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.TOL_Label_mouseEntered(e); + } +} + +class Sander9Frame_JFASTW_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_JFASTW_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.JFASTW_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_RBORNSTAT_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_RBORNSTAT_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.RBORNSTAT_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_JFASTW_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_JFASTW_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.JFASTW_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_JFASTW_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_JFASTW_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.JFASTW_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTC_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_NTC_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTC_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_FCAP_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_FCAP_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.FCAP_Label_mouseEntered(e); + } +} + +class Sander9Frame_IVCAP_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_IVCAP_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.IVCAP_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_NTC_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTC_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTC_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_NTC_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTC_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTC_Label_mouseEntered(e); + } +} + +class Sander9Frame_IVCAP_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_IVCAP_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IVCAP_Label_mouseEntered(e); + } +} + +class Sander9Frame_BELLYMASK_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_BELLYMASK_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.BELLYMASK_Label_mouseEntered(e); + } +} + +class Sander9Frame_RESTRAINTMASK_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_RESTRAINTMASK_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.RESTRAINTMASK_Label_mouseEntered(e); + } +} + +class Sander9Frame_IBELLY_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_IBELLY_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.IBELLY_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_IVCAP_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_IVCAP_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IVCAP_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_IBELLY_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_IBELLY_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IBELLY_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_IBELLY_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_IBELLY_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IBELLY_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTR_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_NTR_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTR_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_RESTRAINT_WT_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_RESTRAINT_WT_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.RESTRAINT_WT_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTR_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTR_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTR_Label_mouseEntered(e); + } +} + +class Sander9Frame_IGB_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_IGB_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.IGB_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_IGB_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_IGB_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IGB_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_SCNB_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_SCNB_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.SCNB_Label_mouseEntered(e); + } +} + +class Sander9Frame_CUT_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_CUT_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.CUT_Label_mouseEntered(e); + } +} + +class Sander9Frame_DIELC_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_DIELC_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.DIELC_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTRX_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_NTRX_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTRX_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_NTRX_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTRX_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTRX_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_IDECOMP_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_IDECOMP_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.IDECOMP_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_NTR_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTR_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTR_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_IDECOMP_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_IDECOMP_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IDECOMP_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_NTX_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_NTX_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTX_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_NTX_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTX_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTX_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_IOUTFM_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_IOUTFM_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.IOUTFM_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_IOUTFM_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_IOUTFM_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IOUTFM_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_IWRAP_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_IWRAP_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.IWRAP_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_NTXO_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_NTXO_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTXO_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_IWRAP_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_IWRAP_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IWRAP_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_NTXO_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTXO_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTXO_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_GBSA_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_GBSA_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.GBSA_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_RBORNSTAT_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_RBORNSTAT_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.RBORNSTAT_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_GBSA_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_GBSA_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.GBSA_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_RDT_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_RDT_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.RDT_Label_mouseEntered(e); + } +} + +class Sander9Frame_SURFTEN_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_SURFTEN_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.SURFTEN_Label_mouseEntered(e); + } +} + +class Sander9Frame_GBSA_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_GBSA_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.GBSA_Label_mouseEntered(e); + } +} + +class Sander9Frame_OFFSET_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_OFFSET_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.OFFSET_Label_mouseEntered(e); + } +} + +class Sander9Frame_RBORNSTAT_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_RBORNSTAT_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.RBORNSTAT_Label_mouseEntered(e); + } +} + +class Sander9Frame_RGBMAX_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_RGBMAX_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.RGBMAX_Label_mouseEntered(e); + } +} + +class Sander9Frame_SALTCON_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_SALTCON_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.SALTCON_Label_mouseEntered(e); + } +} + +class Sander9Frame_EXTDIEL_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_EXTDIEL_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.EXTDIEL_Label_mouseEntered(e); + } +} + +class Sander9Frame_INTDIEL_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_INTDIEL_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.INTDIEL_Label_mouseEntered(e); + } +} + +class Sander9Frame_IDECOMP_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_IDECOMP_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IDECOMP_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTWPRT_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTWPRT_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTWPRT_Label_mouseEntered(e); + } +} + +class Sander9Frame_IOUTFM_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_IOUTFM_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IOUTFM_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTWE_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTWE_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTWE_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTWV_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTWV_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTWV_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTPR_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTPR_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTPR_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTXO_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTXO_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTXO_Label_mouseEntered(e); + } +} + +class Sander9Frame_IWRAP_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_IWRAP_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IWRAP_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTWX_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTWX_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTWX_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTWR_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTWR_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTWR_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTAVE_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTAVE_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTAVE_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTX_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTX_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTX_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTRX_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTRX_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTRX_Label_mouseEntered(e); + } +} + +class Sander9Frame_jButton3_actionAdapter + implements ActionListener { + private Sander9Frame adaptee; + Sander9Frame_jButton3_actionAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.jButton3_actionPerformed(e); + } +} + +class Sander9Frame_jButton2_actionAdapter + implements ActionListener { + private Sander9Frame adaptee; + Sander9Frame_jButton2_actionAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.jButton2_actionPerformed(e); + } +} + +class Sander9Frame_jButton1_actionAdapter + implements ActionListener { + private Sander9Frame adaptee; + Sander9Frame_jButton1_actionAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.jButton1_actionPerformed(e); + } +} + +class Sander9Frame_TEMPI_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_TEMPI_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.TEMPI_Label_mouseEntered(e); + } +} + +class Sander9Frame_VLIMIT_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_VLIMIT_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.VLIMIT_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTP_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_NTP_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTP_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_NTP_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTP_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTP_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_NTT_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_NTT_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTT_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_NTT_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTT_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTT_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_PRES0_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_PRES0_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.PRES0_Label_mouseEntered(e); + } +} + +class Sander9Frame_TAUP_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_TAUP_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.TAUP_Label_mouseEntered(e); + } +} + +class Sander9Frame_COMP_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_COMP_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.COMP_Label_mouseEntered(e); + } +} + +class Sander9Frame_DT_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_DT_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.DT_Label_mouseEntered(e); + } +} + +class Sander9Frame_NSTLIM_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NSTLIM_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NSTLIM_Label_mouseEntered(e); + } +} + +class Sander9Frame_TEMP0_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_TEMP0_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.TEMP0_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTP_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTP_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTP_Label_mouseEntered(e); + } +} + +class Sander9Frame_VRAND_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_VRAND_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.VRAND_Label_mouseEntered(e); + } +} + +class Sander9Frame_GAMMA_LN_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_GAMMA_LN_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.GAMMA_LN_Label_mouseEntered(e); + } +} + +class Sander9Frame_TAUTP_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_TAUTP_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.TAUTP_Label_mouseEntered(e); + } +} + +class Sander9Frame_IG_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_IG_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IG_Label_mouseEntered(e); + } +} + +class Sander9Frame_TEMP0LES_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_TEMP0LES_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.TEMP0LES_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTT_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTT_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTT_Label_mouseEntered(e); + } +} + +class Sander9Frame_T_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_T_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.T_Label_mouseEntered(e); + } +} + +class Sander9Frame_NRESPA_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NRESPA_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NRESPA_Label_mouseEntered(e); + } +} + +class Sander9Frame_jLabel10_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_jLabel10_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.jLabel10_mouseEntered(e); + } +} + +class Sander9Frame_IREST_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_IREST_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.IREST_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_IREST_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_IREST_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IREST_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_covergLabel_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_covergLabel_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.covergLabel_mouseEntered(e); + } +} + +class Sander9Frame_dxLabel_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_dxLabel_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.dxLabel_mouseEntered(e); + } +} + +class Sander9Frame_switchLabel_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_switchLabel_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.switchLabel_mouseEntered(e); + } +} + +class Sander9Frame_maxIterLabel_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_maxIterLabel_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.maxIterLabel_mouseEntered(e); + } +} + +class Sander9Frame_NTMIN_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_NTMIN_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTMIN_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_NTMIN_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTMIN_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTMIN_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_saveFile_Button_actionAdapter + implements ActionListener { + private Sander9Frame adaptee; + Sander9Frame_saveFile_Button_actionAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.saveFile_Button_actionPerformed(e); + } +} + +class Sander9Frame_SCEE_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_SCEE_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.SCEE_Label_mouseEntered(e); + } +} + +class Sander9Frame_NSNB_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NSNB_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NSNB_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTF_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_NTF_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTF_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_IPOL_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_IPOL_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IPOL_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_NTF_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTF_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTF_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_NTF_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTF_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTF_Label_mouseEntered(e); + } +} + +class Sander9Frame_IPOL_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_IPOL_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IPOL_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTB_Label_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTB_Label_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTB_Label_mouseEntered(e); + } +} + +class Sander9Frame_NTB_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_NTB_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.NTB_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_IPOL_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_IPOL_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.IPOL_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_NTB_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_NTB_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.NTB_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_IMIN_ComboBox_itemAdapter + implements ItemListener { + private Sander9Frame adaptee; + Sander9Frame_IMIN_ComboBox_itemAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.IMIN_ComboBox_itemStateChanged(e); + } +} + +class Sander9Frame_IMIN_ComboBox_mouseAdapter + extends MouseAdapter { + private Sander9Frame adaptee; + Sander9Frame_IMIN_ComboBox_mouseAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void mouseEntered(MouseEvent e) { + adaptee.IMIN_ComboBox_mouseEntered(e); + } +} + +class Sander9Frame_jMenuFileExit_ActionAdapter + implements ActionListener { + Sander9Frame adaptee; + + Sander9Frame_jMenuFileExit_ActionAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent actionEvent) { + adaptee.jMenuFileExit_actionPerformed(actionEvent); + } +} + +class Sander9Frame_Edit_MenuItem_actionAdapter + implements ActionListener { + private Sander9Frame adaptee; + Sander9Frame_Edit_MenuItem_actionAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.Edit_MenuItem_actionPerformed(e); + } +} + +class Sander9Frame_NCYC_TextField_actionAdapter + implements ActionListener { + private Sander9Frame adaptee; + Sander9Frame_NCYC_TextField_actionAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.NCYC_TextField_actionPerformed(e); + } +} + +class Sander9Frame_DX0_TextField_actionAdapter + implements ActionListener { + private Sander9Frame adaptee; + Sander9Frame_DX0_TextField_actionAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.DX0_TextField_actionPerformed(e); + } +} + +class Sander9Frame_DRMS_TextField_actionAdapter + implements ActionListener { + private Sander9Frame adaptee; + Sander9Frame_DRMS_TextField_actionAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.DRMS_TextField_actionPerformed(e); + } +} + +class Sander9Frame_MAXCYC_TextField_actionAdapter + implements ActionListener { + private Sander9Frame adaptee; + Sander9Frame_MAXCYC_TextField_actionAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.MAXCYC_TextField_actionPerformed(e); + } +} + +class Sander9Frame_jMenuHelpAbout_ActionAdapter + implements ActionListener { + Sander9Frame adaptee; + + Sander9Frame_jMenuHelpAbout_ActionAdapter(Sander9Frame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent actionEvent) { + adaptee.jMenuHelpAbout_actionPerformed(actionEvent); + } +} diff --git a/src/main/java/cct/amber/Sander9Frame_AboutBox.java b/src/main/java/cct/amber/Sander9Frame_AboutBox.java new file mode 100644 index 0000000..f17dd3c --- /dev/null +++ b/src/main/java/cct/amber/Sander9Frame_AboutBox.java @@ -0,0 +1,154 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.amber; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; + +/** + *

Title: Preparation of input file for Sander 8 program

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Sander9Frame_AboutBox + extends JDialog implements ActionListener { + JPanel panel1 = new JPanel(); + JPanel panel2 = new JPanel(); + JPanel insetsPanel1 = new JPanel(); + JPanel insetsPanel2 = new JPanel(); + JPanel insetsPanel3 = new JPanel(); + JButton button1 = new JButton(); + JLabel imageLabel = new JLabel(); + JLabel label1 = new JLabel(); + JLabel label2 = new JLabel(); + JLabel label3 = new JLabel(); + JLabel label4 = new JLabel(); + ImageIcon image1 = new ImageIcon(); + BorderLayout borderLayout1 = new BorderLayout(); + BorderLayout borderLayout2 = new BorderLayout(); + FlowLayout flowLayout1 = new FlowLayout(); + GridLayout gridLayout1 = new GridLayout(); + String product = "Preparation of input file for Sander 8 program"; + String version = "1.0"; + String copyright = "Copyright (c) 2005"; + String comments = "Computational Chemistry Toolkit"; + + public Sander9Frame_AboutBox(Frame parent) { + super(parent); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public Sander9Frame_AboutBox() { + this(null); + } + + /** + * Component initialization. + * + * @throws Exception + */ + private void jbInit() throws Exception { + image1 = new ImageIcon(Sander8Frame.class.getResource("Amber-64x64.png")); + imageLabel.setIcon(image1); + setTitle("About"); + panel1.setLayout(borderLayout1); + panel2.setLayout(borderLayout2); + insetsPanel1.setLayout(flowLayout1); + insetsPanel2.setLayout(flowLayout1); + insetsPanel2.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + gridLayout1.setRows(4); + gridLayout1.setColumns(1); + label1.setText("Preparation of input file for Sander 8"); + label2.setText("Version 1.0 beta"); + label3.setText("Copyright (c) 2006 ANU"); + label4.setToolTipText(""); + label4.setText("Written by Dr. V. Vasilyev (vvv900@gmail.com)"); + insetsPanel3.setLayout(gridLayout1); + insetsPanel3.setBorder(BorderFactory.createEmptyBorder(10, 60, 10, 10)); + button1.setText("OK"); + button1.addActionListener(this); + insetsPanel2.add(imageLabel, null); + panel2.add(insetsPanel2, BorderLayout.WEST); + getContentPane().add(panel1, null); + insetsPanel3.add(label1, null); + insetsPanel3.add(label2, null); + insetsPanel3.add(label3, null); + insetsPanel3.add(label4, null); + panel2.add(insetsPanel3, BorderLayout.CENTER); + insetsPanel1.add(button1, null); + panel1.add(insetsPanel1, BorderLayout.SOUTH); + panel1.add(panel2, BorderLayout.NORTH); + setResizable(true); + } + + /** + * Close the dialog on a button event. + * + * @param actionEvent ActionEvent + */ + @Override + public void actionPerformed(ActionEvent actionEvent) { + if (actionEvent.getSource() == button1) { + dispose(); + } + } +} diff --git a/src/main/java/cct/amber/Sander9JobControl.java b/src/main/java/cct/amber/Sander9JobControl.java new file mode 100644 index 0000000..ba55a65 --- /dev/null +++ b/src/main/java/cct/amber/Sander9JobControl.java @@ -0,0 +1,1566 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.amber; + +import java.io.BufferedReader; +import java.io.StringReader; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.ResourceBundle; +import java.util.Set; +import java.util.logging.Logger; + +import cct.tools.FortranNamelist; + +/* +namelist /cntrl/ irest,ibelly, & +ntx,ntxo,ntcx,ig,tempi, & +ntb,ntt,temp0,tautp, & +ntp,pres0,comp,taup, & +nscm,nstlim,t,dt, & +ntc,ntcc,nconp,tol,ntf,ntn,nsnb, & +cut,scnb,scee,dielc, & +ntpr,ntwx,ntwv,ntwe,ntave,ntpp,ioutfm, & +ntr,nrc,ntrx,taur,nmropt, & +ivcap,fcap,imin,drms,dele,dx0, & +pencut,ipnlty,iscale,scalm,noeskp, & +maxcyc,ncyc,ntmin,vlimit, & +mxsub,ipol,jfastw,watnam,owtnm,hwtnm1,hwtnm2, iesp, & +skmin, skmax, vv,vfac, tmode, ips, & +isgld,isgsta,isgend,tsgavg,sgft,tempsg,& +jar, iamoeba, & +numexchg, repcrd, numwatkeep, & +ntwprt,tausw, & +ntwr,iyammp,imcdo, & +igb,alpb,Arad,rgbmax,saltcon,offset,gbsa,vrand, & +surften,iwrap,nrespa,nrespai,gamma_ln,extdiel,intdiel, & +cut_inner,icfe,clambda,klambda, rbornstat,lastrst,lastist, & +itgtmd,tgtrmsd,tgtmdfrc,tgtfitmask,tgtrmsmask, & +idecomp,temp0les,restraintmask,restraint_wt,bellymask, & +noshakemask, & +mmtsb_switch, mmtsb_iterations,rdt,icnstph,solvph,ntcnstph, & +ifqnt,ievb, & +#ifdef PIMD +pimd_runtype, pimd_use_original_mass, ineb, & +#endif +dtemp, dxm, heat, timlim !all retired + + */ +public class Sander9JobControl { + + FortranNamelist cntrl_namelist = new FortranNamelist(); + String ControlData = "mdin"; + String OutpusFile = "mdout"; + String LatestEnergyInfo = "mdinfo"; + String MolecularTopology = "prmtop"; + String InitialCoord = "inpcrd"; + String PositionRestraints = "refc"; + String CoordOverTrajectory = "mdcrd"; + String VelocitiesOverTrajectory = "mdvel"; + String EnergyOverTrajectory = "mden"; + String Restart = "restrt"; + String PolarDipoleInput = "inpdip"; + String PolarDipoleOutput = "rstdip"; + String ProtonationStateDefs = "cpin"; + String ProtonationStateDefsRestart = "cprestrt"; + String ProtonationStateOverTraj = "cpout"; + String MMTSB_Server = "mmtsb_setup.job"; + String Message = null; + static final Logger logger = Logger.getLogger(Sander9JobControl.class.getCanonicalName()); + static final public int TYPE_INTEGER = 0; + static final public int TYPE_FLOAT = 1; + static final public int TYPE_STRING = 2; + int numberOfAtoms = 0; + Map FileUsage = new HashMap(); + // --- Some most common options + // They set to their default values according to Sander-8 Manual + int IMIN = 0; // Flag to run minimization + int NTB = 1; // Periodic boundary. If NTB .EQ. 0 then a boundary is NOT applied + float CUT = 8.0f; // This is used to specify the nonbonded cutoff, in Angstroms. + float SCNB = 2.0f; // 1-4 vdw interactions are divided by SCNB. Default 2.0. + float SCEE = 1.2f; // 1-4 electrostatic interactions are divided by SCEE; + int NSNB = 25; // Determines the frequency of nonbonded list updates when igb=0 and nbflag=0; + int IPOL = 0; // Inclusion of polarizabilities in the force field + int IGB = 0; // generalized Born solvation model + int MAXCYC = 1; // The maximum number of cycles of minimization. + int NCYC = 10; // If NTMIN is 1 then the method of minimization will be switched from steepest + //descent to conjugate gradient after NCYC cycles. + int NTMIN = 1; // Flag for the method of minimization. + int NSTLIM = 1; // Number of MD-steps to be performed. Default 1. + float DT = 0.001f; // The time step (psec). + int NTT = 1; // Switch for temperature scaling + float TEMP0 = 300.0f; // Reference temperature at which the system is to be kept, if ntt > 0. + float TEMPI = 0.0f; // Initial temperature. For the initial dynamics run, + float TAUTP = 1.0f; // Time constant, in ps, for heat bath coupling for the system, if ntt = 1. + int NTP = 0; // Flag for constant pressure dynamics. + float PRES0 = 1.0f; // Reference pressure (in units of bars, where 1 bar � 1 atm) + float TAUP = 1.0f; // Pressure relaxation time (in ps), when NTP > 0. + int NTC = 1; // Flag for SHAKE to perform bond length constraints + Map ImportantVars = new HashMap(); + static Map allVars = new HashMap(); + static Map ewaldVars = new HashMap(); + + public Sander9JobControl() { + FileUsage.put("-i", ControlData); + FileUsage.put("-o", OutpusFile); + // --- Default values for the most important variables + ImportantVars.put("IMIN", new Integer(IMIN)); + ImportantVars.put("NTB", new Integer(NTB)); + ImportantVars.put("CUT", new Float(CUT)); + ImportantVars.put("SCNB", new Float(SCNB)); + ImportantVars.put("SCEE", new Float(SCEE)); + ImportantVars.put("NSNB", new Integer(NSNB)); + ImportantVars.put("IPOL", new Integer(IPOL)); + ImportantVars.put("IGB", new Integer(IGB)); + ImportantVars.put("MAXCYC", new Integer(MAXCYC)); + ImportantVars.put("NCYC", new Integer(NCYC)); + ImportantVars.put("NTMIN", new Integer(NTMIN)); + ImportantVars.put("NSTLIM", new Integer(NSTLIM)); + ImportantVars.put("DT", new Float(DT)); + ImportantVars.put("NTT", new Integer(NTT)); + ImportantVars.put("TEMP0", new Float(TEMP0)); + ImportantVars.put("TEMPI", new Float(TEMPI)); + ImportantVars.put("TAUTP", new Float(TAUTP)); + ImportantVars.put("NTP", new Integer(NTP)); + ImportantVars.put("PRES0", new Float(PRES0)); + ImportantVars.put("TAUP", new Float(TAUP)); + ImportantVars.put("NTC", new Integer(NTC)); + + SanderVariable var; + + // IMIN + var = new SanderVariable("Flag to run minimization", true); + var.addValue(new SanderVariableValue("0", + "No minimization (only do molecular dynamics)", true)); + var.addValue(new SanderVariableValue("1", + "Perform minimization (and no molecular dynamics)", false)); + var.addValue(new SanderVariableValue("5", + "Read in a trajectory for analysis", false)); + + allVars.put("IMIN", var); + + // IREST + var = new SanderVariable("Flag to restart the run.", true); + var.addValue(new SanderVariableValue("0", + "No effect", true)); + var.addValue(new SanderVariableValue("1", + "Restart calculation. Requires velocities in coordinate input file", false)); + allVars.put("IREST", var); + + // NMROPT + + var = new SanderVariable("", true); + var.addValue(new SanderVariableValue("0", + "No nmr-type analysis will be done", true)); + var.addValue(new SanderVariableValue("1", + "NOESY volume restraints or chemical shift restraints" + + " will be read as well", false)); + var.addValue(new SanderVariableValue("2", + "NOESY volume restraints or chemical shift restraints" + + " will be read as well", false)); + allVars.put("NMROPT", var); + + // --- Energy minimization. *********************** + + // MAXCYC + + var = new SanderVariable( + "The maximum number of cycles of minimization", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("1", + "", true)); + allVars.put("MAXCYC", var); + + // NCYC + + var = new SanderVariable( + "If NTMIN is 1 then the method of minimization will be switched from steepest " + + " descent to conjugate gradient after NCYC cycles", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("10", + "", true)); + allVars.put("NCYC", var); + + // NTMIN + + var = new SanderVariable( + "Flag for the method of minimization", true); + var.addValue(new SanderVariableValue("0", + "Full conjugate gradient minimization. The first 4 cycles are steepest" + + " descent at the start of the run and after every nonbonded pairlist" + + " update.", false)); + var.addValue(new SanderVariableValue("1", + "For NCYC cycles the steepest descent method is used then conjugate" + + " gradient is switched on", true)); + var.addValue(new SanderVariableValue("2", + "Only the steepest descent method is used", false)); + var.addValue(new SanderVariableValue("3", + "The XMIN method is used, see amber8/doc/lmod.pdf", false)); + var.addValue(new SanderVariableValue("4", + "The LMOD method is used, see amber8/doc/lmod.pdf", false)); + allVars.put("NTMIN", var); + + // DX0 + + var = new SanderVariable( + "The initial step length. If the initial step length is big then the minimizer will" + + " try to leap the energy surface and sometimes the first few cycles will give a" + + " huge energy, howev er the minimizer is smart enough to adjust itself", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.01", + "", true)); + allVars.put("DX0", var); + + // DRMS + + var = new SanderVariable( + "The convergence criterion for the energy gradient: minimization will halt" + + " when the root-mean-square of the Cartesian elements of the gradient is less" + + " than DRMS. Default 1.0E-4 kcal/mole A�", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("1.0E-4", + "", true)); + allVars.put("DRMS", var); + + // --- Potential function options ************************** + + // NTF + + var = new SanderVariable( + "Force evaluation. Note: If SHAKE is used (see NTC), it is not necessary to " + + "calculate forces for the constrained bonds", true); + var.addValue(new SanderVariableValue("1", + "Complete interaction is calculated", true)); + var.addValue(new SanderVariableValue("2", + "Bond interactions involving H-atoms omitted (use with NTC=2)", false)); + var.addValue(new SanderVariableValue("3", + "All the bond interactions are omitted (use with NTC=3)", false)); + var.addValue(new SanderVariableValue("4", + "Angle involving H-atoms and all bonds are omitted", false)); + var.addValue(new SanderVariableValue("5", + "All bond and angle interactions are omitted", false)); + var.addValue(new SanderVariableValue("6", + "Dihedrals involving H-atoms and all bonds and all angle interactions are omitted", false)); + var.addValue(new SanderVariableValue("7", + "All bond, angle and dihedral interactions are omitted", false)); + var.addValue(new SanderVariableValue("8", + "All bond, angle, dihedral and non-bonded interactions are omitted", false)); + + allVars.put("NTF", var); + + // NTB + + var = new SanderVariable( + "Periodic boundary. If NTB .EQ. 0 then a boundary is NOT applied regardless" + + " of any boundary condition information in the topology file. The value of NTB " + + "specifies whether constant volume or constant pressure dynamics will be used", true); + + var.addValue(new SanderVariableValue("0", + "No periodicity is applied and PME is off", false)); + var.addValue(new SanderVariableValue("1", + "Constant volume", true)); + var.addValue(new SanderVariableValue("2", + "Constant Pressure", false)); + + allVars.put("NTB", var); + + // DIELC + + var = new SanderVariable( + "Dielectric multiplicative constant for the electrostatic interactions. " + + "Please note this is NOT related to dielectric constants for generalized " + + "Born simulations.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("1.0", + "", true)); + allVars.put("DIELC", var); + + // CUT + + var = new SanderVariable( + "This is used to specify the nonbonded cutoff, in Angstroms. For PME, the " + + "cutoff is used to limit direct space sum, and the default value of 8.0 is usually " + + "a good value. When igb>0, the cutoff is used to truncate nonbonded pairs (on " + + "an atom-by-atom basis.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + + var.addValue(new SanderVariableValue("8.0", + "", true)); + allVars.put("CUT", var); + + // SCNB + + var = new SanderVariable( + "1-4 vdw interactions are divided by SCNB", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + + var.addValue(new SanderVariableValue("2.0", "", true)); + allVars.put("SCNB", var); + + // SCEE + + var = new SanderVariable( + "1-4 electrostatic interactions are divided by SCEE; the 1991 and previous " + + "force fields used 2.0, while the 1994 force field uses 1.2", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("1.2", "", true)); + allVars.put("SCEE", var); + + // NSNB + + var = new SanderVariable( + "Determines the frequency of nonbonded list updates when igb=0 and " + + "nbflag=0; see the description of nbflag for more information", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("25", "", true)); + allVars.put("NSNB", var); + + // IPOL + + var = new SanderVariable( + "When set to 1, use a polarizable force field. See Section 5.7.5 of Amber9 manual for more information." + + " Default is 0.", true); + + var.addValue(new SanderVariableValue("0", + "Nonpolar calc", true)); + var.addValue(new SanderVariableValue("1", + "Polar calc", false)); + allVars.put("IPOL", var); + + // IFQNT + + var = new SanderVariable("", true); + + var.addValue(new SanderVariableValue("0", + "No QM/MM", true)); + var.addValue(new SanderVariableValue("1", + "QM/MM", false)); + allVars.put("IFQNT", var); // !!! Add to dialog + + // IEVB + + var = new SanderVariable("", true); + + var.addValue(new SanderVariableValue("0", + "No VM Method", true)); + var.addValue(new SanderVariableValue("1", + "Use VM Method", false)); + allVars.put("IEVB", var); // !!! Add to dialog + + // IAMOEBA + + var = new SanderVariable("", true); + + var.addValue(new SanderVariableValue("0", + "Nonpolar calc", true)); + var.addValue(new SanderVariableValue("1", + "Polar calc", false)); + allVars.put("IAMOEBA", var); // !!! Add to dialog + + // --- General flags describing the calculation + + // NTX + + var = new SanderVariable( + "Option to read the initial coordinates, velocities and box size from the" + + " \"inpcrd\" file. The options 1-2 must be used when one is starting from minimized" + + " or model-built coordinates. If an MD restrt file is used as inpcrd, then" + + "options 4-7 may be used.", true); + + var.addValue(new SanderVariableValue("1", + "Formatted X", true)); + var.addValue(new SanderVariableValue("2", + "Unformatted X", false)); + var.addValue(new SanderVariableValue("4", + "Unformatted X and V", false)); + var.addValue(new SanderVariableValue("5", + "Formatted X and V", false)); + var.addValue(new SanderVariableValue("6", + "Unformatted X, V and BOX(1..3)", false)); + //var.addValue(new SanderVariableValue("7", + // "Unformatted X, V and BOX(1..3)", false)); + allVars.put("NTX", var); + + // NTRX + + var = new SanderVariable( + "Format of the Cartesian coordinates for restraint from file \"refc\". Note: the" + + " program expects file \"refc\" to contain coordinates for all the atoms in the system." + + " A subset for the actual restraints is selected by restraintmask in the control" + + "namelist.", true); + + var.addValue(new SanderVariableValue("0", + "Unformatted (binary) form)", false)); + var.addValue(new SanderVariableValue("1", + "Formatted (ascii) form", true)); + allVars.put("NTRX", var); + + // --- Nature and format of the output. + + // NTXO + + var = new SanderVariable( + "Format of the final coordinates, velocities, and box size (if constant volume or" + + " pressure run) written to file \"restrt\".", true); + + var.addValue(new SanderVariableValue("0", + "Unformatted)", false)); + var.addValue(new SanderVariableValue("1", + "Formatted", true)); + allVars.put("NTXO", var); + + // NTPR + + var = new SanderVariable( + "Every NTPR steps energy information will be printed in human-readable form" + + " to files \"mdout\" and \"mdinfo\". \"mdinfo\" is closed and reopened each time, so" + + " it always contains the most recent energy and temperature.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("50", + "", true)); + allVars.put("NTPR", var); + + // NTAVE + + var = new SanderVariable( + "Every NTAVE steps of dynamics, running averages of average energies and" + + " fluctuations over the last NTAVE steps will be printed out. Default value of 0" + + " disables this printout.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", + "", true)); + allVars.put("NTAVE", var); + + // NTWR + + var = new SanderVariable( + "Every NTWR steps during dynamics, the \"restrt\" file will be written, ensuring" + + " that recovery from a crash will not be so painful. If" + + " NTWR<0, a unique copy of the file, restrt_nstep, is written every abs(NTWR)" + + "steps. Default 500.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("500", + "", true)); + allVars.put("NTWR", var); + + // IWRAP + + var = new SanderVariable( + "If set to 1, the coordinates written to the restart and trajectory files will be" + + " \"wrapped\" into a primary box. This often makes the resulting structures" + + " look better visually, but has no effect on the energy or forces. Performing" + + " such wrapping, however, can mess up diffusion and other calculations. The" + + " default (when iwrap=0) is to not perform any such manipulations", true); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", + "No \"Wrapping\" coordinates into a primary box", true)); + var.addValue(new SanderVariableValue("1", + "\"Wrap\" coordinates into a primary box", false)); + allVars.put("IWRAP", var); + + // NTWX + + var = new SanderVariable( + "Every NTWX steps the coordinates will be written to file \"mdcrd\". NTWX=0" + + " inhibits all output. Default 0.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", + "", true)); + allVars.put("NTWX", var); + + // NTWV + + var = new SanderVariable( + "Every NTWV steps the velocities will be written to file \"mdvel\". NTWV=0" + + " inhibits all output. Default 0.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", + "", true)); + allVars.put("NTWV", var); + + // NTWE + + var = new SanderVariable( + "Every NTWE steps the energies and temperatures will be written to file" + + " \"mden\" in compact form. NTWE=0 inhibits all output. Default 0.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", + "", true)); + allVars.put("NTWE", var); + + // IOUTFM - obsolete + + var = new SanderVariable( + "Format of velocity, coordinate, and energy sets. Note: these values are \"backwards\"" + + " compared to NTRX and NTXO; this is an ancient mistake that we are" + + " reluctant to change, since it would break existing scripts.", true); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", + "Formatted (default)", true)); + var.addValue(new SanderVariableValue("1", + "Binary", false)); + allVars.put("IOUTFM", var); + + // NTWPRT + + var = new SanderVariable( + "Coordinate/velocity archive limit flag. This flag can be used to decrease the" + + " size of the coordinate / velocity archive files, by only including that portion of" + + " the system of greatest interest. The Coord/velocity archives will include:\n" + + "= 0 all atoms of the system (default)\n" + + "> 0 only atoms 1->NTWPRT", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", + "", true)); + allVars.put("NTWPRT", var); + + // IDECOMP + + var = new SanderVariable( + "This option is only really useful in conjunction with mm_pbsa, where it is" + + " turned on automatically if required.", true); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", + "Do nothing (default).", true)); + var.addValue(new SanderVariableValue("1", + "Decompose energies on a per-residue basis; 1-4 EEL + 1-4 VDW are" + + " added to internal (bond, angle, dihedral) energies.", false)); + var.addValue(new SanderVariableValue("2", + "Decompose energies on a per-residue basis; 1-4 EEL + 1-4 VDW are" + + " added to EEL and VDW.", false)); + var.addValue(new SanderVariableValue("3", + "Decompose energies on a pairwise per-residue basis; the rest is equal" + + " to \"1\".", false)); + var.addValue(new SanderVariableValue("4", + "Decompose energies on a pairwise per-residue basis; the rest is" + + " equal to \"2\".", false)); + allVars.put("IDECOMP", var); + + // --- Generalized Born/Surface Area options. + + // IGB + + var = new SanderVariable( + "The generalized Born solvation model can be used instead of explicit water for non-polarizable" + + " force fields such as ff94 or ff99. Users should understand that all" + + " (current) GB models have limitations and should proceed with caution. Generalized Born simulations" + + " can only be run for non-periodic systems The nonbonded cutoff for GB" + + " calculations should be greater than that for PME calculations, perhaps cut=16.", true); + + var.addValue(new SanderVariableValue("0", + "No GB", true)); + var.addValue(new SanderVariableValue("1", + "Hawkins et all model", false)); + var.addValue(new SanderVariableValue("2", + "Onufriev et all model", false)); + var.addValue(new SanderVariableValue("5", + "Onufriev et all model II", false)); + var.addValue(new SanderVariableValue("6", + "No solvent at all", false)); + var.addValue(new SanderVariableValue("7", + "The GBn Model", false)); + var.addValue(new SanderVariableValue("10", + "Poisson-Boltzmann solver", false)); + allVars.put("IGB", var); + + // INTDIEL + + var = new SanderVariable( + "Sets the interior dielectric constant of the molecule of interest. Default is 1.0." + + " Other values have not been extensively tested.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("1.0", + "", true)); + allVars.put("INTDIEL", var); + + // EXTDIEL + + var = new SanderVariable( + "Sets the exterior or solvent dielectric constant. Default is 78.5.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("78.5", + "", true)); + allVars.put("EXTDIEL", var); + + // SALTCON + + var = new SanderVariable( + "Sets the concentration (M) of 1-1 mobile counterions in solution, using a" + + " modified generalized Born theory based on the Debye-H�ckel limiting law for" + + " ion screening of interactions. Default is 0.0 M (i.e. no Debye-H�ckel" + + " screening.) Setting saltcon to a non-zero value does result in some increase in" + + "computation time.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.0", + "", true)); + allVars.put("SALTCON", var); + + // RGBMAX + + var = new SanderVariable( + "This parameter controls the maximum distance between atom pairs that will" + + " be considered in carrying out the pairwise summation involved in calculating" + + " the effective Born radii. Atoms whose associated spheres are farther way than" + + " rgbmax from given atom will not contribute to that atom�s effective Born" + + " radius. The default is 25 �, which is usually plenty for single-domain proteins of a few hundred residues.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("25.0", + "", true)); + allVars.put("RGBMAX", var); + + // RBORNSTAT + + var = new SanderVariable( + "If rbornstat = 1, the statistics of the effective Born radii for each atom of the" + + " molecule throughout the molecular dynamics simulation are reported in the" + + " output file. Default is 0.", true); + var.addValue(new SanderVariableValue("0", + "No output of the statistics of the effective Born radii for each atom", true)); + var.addValue(new SanderVariableValue("1", + "The statistics of the effective Born radii for each atom of the" + + " molecule throughout the molecular dynamics simulation are reported in the" + + " output file.", false)); + allVars.put("RBORNSTAT", var); + + // OFFSET + + var = new SanderVariable( + "The dielectric radii for generalized Born calculations are decreased by a uniform" + + " value \"offset\" to give the \"intrinsic radii\" used to obtain effective Born" + + " radii. Default 0.09 �.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.09", + "", true)); + allVars.put("OFFSET", var); + + // SURFTEN + + var = new SanderVariable( + "Surface tension used to calculate the nonpolar contribution to the free energy" + + " of solvation (when gbsa = 1), as Enp = surften*SA. The default is 0.005" + + " kcal/mol-�2", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.005", + "", true)); + allVars.put("SURFTEN", var); + + // RDT + + var = new SanderVariable( + "This parameter is only used for GB simulations with LES (Locally Enhanced" + + " Sampling). In GB+LES simulations, non-LES atoms require multiple effective" + + " Born radii due to alternate descreening effects of different LES copies." + + " Default 0.01 �.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.01", + "", true)); + allVars.put("RDT", var); + + // GBSA + + var = new SanderVariable( + "Option to carry out GB/SA (generalized Born/surface area) simulations. For" + + " the default value of 0, surface area will not be computed and included in the" + + " solvation term. If gbsa = 1, surface area will be computed using the LCPO" + + " model. If gbsa = 2, surface area will be computed by recursively approximating" + + " a sphere around an atom, starting from an icosahedra.", true); + + var.addValue(new SanderVariableValue("0", + "No surface area will not be computed and included in the solvation term.", true)); + var.addValue(new SanderVariableValue("1", + "Surface area will be computed using the LCPO model.", false)); + var.addValue(new SanderVariableValue("2", + "Surface area will be computed by recursively approximating a sphere around an atom, starting from an icosahedra.", false)); + allVars.put("GBSA", var); + + // --- Frozen or restrained atoms. + + // --- Molecular dynamics. + + // NSTLIM + + var = new SanderVariable( + "Number of MD-steps to be performed. Default 1.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("1", + "", true)); + allVars.put("NSTLIM", var); + + // NSCM + + var = new SanderVariable( + "Flag for the removal of translational and rotational center-of-mass (COM)" + + " motion at regular intervals. For non-periodic simulations, after every NSCM" + + " steps, translational and rotational motion will be removed. For periodic systems," + + " just the translational center-of-mass motion will be removed. This flag" + + " is ignored for belly simulations. Default 1000.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("1000", + "", true)); + allVars.put("NSCM", var); + + // T + + var = new SanderVariable( + "The time at the start (psec) this is for your own reference and is not critical." + + " Start time is taken from the coordinate input file if IREST=1. Default 0.0.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.0", + "", true)); + allVars.put("T", var); + + // DT + + var = new SanderVariable( + "The time step (psec). Recommended MAXIMUM is .002 if SHAKE is used," + + " or .001 if it isn�t. Note that for temperatures above 300K, the step size should" + + " be reduced since greater temperatures mean increased velocities and longer" + + " distance traveled between each force evaluation, which can lead to anomalously" + + " high energies and system blowup. Default 0.001.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.001", + "", true)); + allVars.put("DT", var); + + // NRESPA + + var = new SanderVariable( + "This variable allows the user to evaluate slowly-varying terms in the force" + + " field less frequently. If NRESPA>1 these slowly-varying forces are evaluated every nrespa steps." + + " The forces are adjusted appropriately, leading to an impulse at that step. If" + + " nrespa*dt is less than or equal to 4 fs the energy conservation is not seriously" + + " compromised. However if nrespa*dt > 4 fs the simulation becomes less stable.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("1", + "", true)); + allVars.put("NRESPA", var); + + // --- Temperature regulation + + // NTT + + var = new SanderVariable( + "Switch for temperature scaling. Note that setting ntt=0 corresponds to the" + + " microcanonical (NVE) ensemble (which should approach the canonical one" + + " for large numbers of degrees of freedom). Some aspects of the \"weak-coupling" + + " ensemble\" (ntt=1) have been examined, and roughly interpolate between" + + " the microcanonical and canonical ensembles. The ntt=2 and 3 options" + + " correspond to the canonical (constant T) ensemble. The ntt=4 option is" + + " included for historical reasons, but does not correspond to any of the traditional" + + " ensembles.", true); + + var.addValue(new SanderVariableValue("0", + "Constant total energy classical dynamics (assuming that ntb<2, as" + + " should probably always be the case when ntt=0).", true)); + var.addValue(new SanderVariableValue("1", + "Constant temperature, using the weak-coupling algorithm. A" + + " single scaling factor is used for all atoms.", false)); + var.addValue(new SanderVariableValue("2", + "Andersen temperature coupling scheme, in which imaginary" + + " \"collisions\" randomize the velocities to a distribution corresponding" + + " to temp0 every vrand steps.", false)); + var.addValue(new SanderVariableValue("3", + "Use Langevin dynamics with the collision frequency gamma given by" + + " gamma_ln. Note that when gamma has its default value" + + " of zero, this is the same as setting ntt = 0.", false)); + + allVars.put("NTT", var); + + // TEMP0 + + var = new SanderVariable( + "Reference temperature at which the system is to be kept, if ntt > 0. Note that" + + " for temperatures above 300K, the step size should be reduced since increased" + + " distance traveled between evaluations can lead to SHAKE and other problems." + + " Default 300.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("300", + "", true)); + allVars.put("TEMP0", var); + + // TEMP0LES + + var = new SanderVariable( + "This is the target temperature for all LES particles. If" + + " temp0les<0, a single temperature bath is used for all atoms, otherwise separate" + + " thermostats are used for LES and non-LES particles. Default is -1, corresponding" + + " to a single (weak-coupling) temperature bath.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("-1", + "", true)); + allVars.put("TEMP0LES", var); + + // TEMPI + + var = new SanderVariable( + "Initial temperature. For the initial dynamics run, (NTX .lt. 3) the velocities" + + " are assigned from a Maxwellian distribution at TEMPI K. If TEMPI = 0.0," + + " the velocities will be calculated from the forces instead. TEMPI has no effect" + + " if NTX .gt. 3. Default 0.0.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.0", + "", true)); + allVars.put("TEMPI", var); + + // IG + + var = new SanderVariable( + "The seed for the random number generator. The MD starting velocity is" + + " dependent on the random number generator seed if NTX .lt. 3 .and. TEMPI" + + " .ne. 0.0. Default 71277.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("71277", + "", true)); + allVars.put("IG", var); + + // TAUTP + + var = new SanderVariable( + "Time constant, in ps, for heat bath coupling for the system, if ntt = 1. Default" + + " is 1.0. Generally, values for TAUTP should be in the range of 0.5-5.0 ps, with" + + " a smaller value providing tighter coupling to the heat bath and, thus, faster" + + " heating and a less natural trajectory. Smaller values of TAUTP result in" + + " smaller fluctuations in kinetic energy, but larger fluctuations in the total" + + " energy. Values much larger than the length of the simulation result in a return" + + "to constant energy conditions.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("1.0", + "", true)); + allVars.put("TAUTP", var); + + // GAMMA_LN + + var = new SanderVariable( + "The collision frequency gamma , in ps-1, when ntt = 3. A simple Leapfrog integrator" + + " is used to propagate the dynamics, with the kinetic energy adjusted to be correct" + + " for the harmonic oscillator case. Note that it is not necessary that" + + " gamma approximate the physical collision frequency. In fact, it is often advantageous," + + " in terms of sampling or stability of integration, to use much smaller" + + " values. Default is 0", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0", + "", true)); + allVars.put("GAMMA_LN", var); + + // VRAND + + var = new SanderVariable( + "If vrand>0 and ntt=2, the velocities will be randomized to temperature" + + " TEMP0 every vrand steps.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", + "", true)); + allVars.put("VRAND", var); + + // VLIMIT + + var = new SanderVariable( + "If not equal to 0.0, then any component of the velocity that is greater than" + + " abs(VLIMIT) will be reduced to VLIMIT (preserving the sign). This can be" + + " used to avoid occasional instabilities in molecular dynamics runs. VLIMIT" + + " should generally be set to a value like 20 (the default), which is well above the" + + " most probable velocity in a Maxwell-Boltzmann distribution at room temperature.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("20", + "", true)); + allVars.put("VLIMIT", var); + + // --- Pressure regulation. + + // NTP + + var = new SanderVariable( + "Flag for constant pressure dynamics. This option should be set to 1 or 2 when" + + " Constant Pressure periodic boundary conditions are used (NTB = 2).", true); + + var.addValue(new SanderVariableValue("0", + "No pressure scaling", true)); + var.addValue(new SanderVariableValue("1", + "Isotropic scaling", false)); + var.addValue(new SanderVariableValue("2", + "MD with anisotropic (x-,y-,z-) pressure scaling: this should only be" + + " used with orthogonal boxes (i.e. with all angles set to 90 degrees)." + + " Anisotropic scaling is primarily intended for non-isotropic systems," + + " such as membrane simulations, where the surface tensions are different" + + " in different directions; it is generally not appropriate for solutes" + + " dissolved in water.", false)); + allVars.put("NTP", var); + + // PRES0 + + var = new SanderVariable( + "Reference pressure (in units of bars, where 1 bar � 1 atm) at which the system" + + " is maintained ( when NTP > 0). Default 1.0.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("1", + "", true)); + allVars.put("PRES0", var); + + // COMP + + var = new SanderVariable( + "Compressibility of the system when NTP > 0. The units are in 1.0E-06/bar; a" + + " value of 44.6 (default) is appropriate for water.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("44.6", + "", true)); + allVars.put("COMP", var); + + // TAUP + + var = new SanderVariable( + "Pressure relaxation time (in ps), when NTP > 0. The recommended value is" + + " between 1.0 and 5.0 psec. Default value is 1.0, but larger values may sometimes" + + " be necessary (if your trajectories seem unstable).", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("1.0", + "", true)); + allVars.put("TAUP", var); + + // --- Frozen or restrained atoms. + + // IBELLY + + var = new SanderVariable( + "Flag for belly type dynamics.", true); + + var.addValue(new SanderVariableValue("0", + "No belly run (default).", true)); + var.addValue(new SanderVariableValue("1", + "Belly run. A subset of the atoms in the system will be allowed to" + + " move, and the coordinates of the rest will be frozen. The moving" + + " atoms are specified bellymask. This option is not available when" + + " igb>0. Note also that this option does not provide any significant" + + " speed advantage, and is maintained primarily for backwards compatibility" + + " with older version of Amber. Most applications should use the" + + "ntr variable instead", false)); + allVars.put("IBELLY", var); + + // NTR + + var = new SanderVariable( + "Flag for restraining specified atoms in Cartesian space using a harmonic" + + " potential. The restrained atoms are determined by the restraintmask string." + + " The force constant is given by restraint_wt. The coordinates are read in" + + " \"restrt\" format from the \"refc\" file", true); + + var.addValue(new SanderVariableValue("0", + "No position restraints (default)", true)); + var.addValue(new SanderVariableValue("1", + "MD with restraint of specified atoms", false)); + allVars.put("NTR", var); + + // RESTRAINT_WT + + var = new SanderVariable( + "The weight (in kcal/mol \u2212 �2) for the positional restraints. The restraint is of" + + " the form k(\u0394x)2, where k is the value given by this variable, and \u0394x is the difference" + + " between one of the Cartesian coordinates of a restrained atom and its" + + " reference position. There is a term like this for each Cartesian coordinate of" + + " each restrainted atom.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("1.0", + "", true)); + allVars.put("RESTRAINT_WT", var); + + // RESTRAINTMASK + + var = new SanderVariable( + "String that specifies the restrained atoms when ntr=1.", false); + var.setVarType(Sander8JobControl.TYPE_STRING); + var.addValue(new SanderVariableValue(" ", + "", true)); + allVars.put("RESTRAINTMASK", var); + + // BELLYMASK + + var = new SanderVariable( + "String that specifies the moving atoms when ibelly=1. Note that these mask" + + " strings are limited to a maximum of 80 characters.", false); + var.setVarType(Sander8JobControl.TYPE_STRING); + var.addValue(new SanderVariableValue(" ", + "", true)); + allVars.put("BELLYMASK", var); + + // --- SHAKE bond length constraints. + + // NTC + + var = new SanderVariable( + "Flag for SHAKE to perform bond length constraints. (See also NTF in" + + " the Potential function section. In particular, typically NTF = NTC.) The" + + " SHAKE option should be used for most MD calculations. Since SHAKE is an " + + " algorithm based on dynamics, the minimizer is not aware of what SHAKE is doing;" + + " for this reason, minimizations generally should be carried out without SHAKE." + + " One exception is short minimizations whose purpose is to remove bad contacts" + + " before dynamics can begin.", true); + + var.addValue(new SanderVariableValue("1", + "SHAKE is not performed (default)", true)); + var.addValue(new SanderVariableValue("2", + "Bonds involving hydrogen are constrained", false)); + var.addValue(new SanderVariableValue("3", + "All bonds are constrained (not available for parallel runs in sander)", false)); + allVars.put("NTC", var); + + // TOL + + var = new SanderVariable( + "Relative geometrical tolerance for coordinate resetting in shake. Recommended" + + " maximum: <0.00005 Angstrom Default 0.00001.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.00001", + "", true)); + allVars.put("TOL", var); + + // JFASTW + + var = new SanderVariable( + "Fast water definition flag. By default, the system is searched for water" + + " residues, and special routines are used to SHAKE these systems", true); + + var.addValue(new SanderVariableValue("0", + "Normal operation. Waters are identified by the default names (given" + + " below), unless they are redefined, as described below.", true)); + var.addValue(new SanderVariableValue("4", + "Do not use the fast SHAKE routines for waters.", false)); + allVars.put("JFASTW", var); + + // WATNAM + + var = new SanderVariable( + "The residue name the program expects for water. Default �WAT �.", false); + var.setVarType(Sander8JobControl.TYPE_STRING); + var.addValue(new SanderVariableValue("WAT ", + "", true)); + allVars.put("WATNAM", var); + + // OWTNM + + var = new SanderVariable( + "The atom name the program expects for the oxygen of water. Default �O �.", false); + var.setVarType(Sander8JobControl.TYPE_STRING); + var.addValue(new SanderVariableValue("O ", + "", true)); + allVars.put("OWTNM", var); + + // HWTNM1 + + var = new SanderVariable( + "The atom name the program expects for the 1st H of water. Default �H1 �.", false); + var.setVarType(Sander8JobControl.TYPE_STRING); + var.addValue(new SanderVariableValue("H1 ", + "", true)); + allVars.put("HWTNM1", var); + + // HWTNM2 + + var = new SanderVariable( + "The atom name the program expects for the 2nd H of water. Default �H2 �.", false); + var.setVarType(Sander8JobControl.TYPE_STRING); + var.addValue(new SanderVariableValue("H2 ", + "", true)); + allVars.put("HWTNM2", var); + + // --- Water cap. + + // IVCAP + + var = new SanderVariable( + "Flag to control cap option. The \"cap\" refers to a spherical portion of water" + + " centered on a point in the solute and restrained by a soft half-harmonic potential." + + " For the best physical realism, this option should be combined with" + + " igb=10, in order to include the reaction field of waters that are beyond the cap" + + "radius.", true); + + var.addValue(new SanderVariableValue("0", + "Cap will be in effect if it is in the prmtop file (default).", true)); + var.addValue(new SanderVariableValue("2", + "Cap will be inactivated, even if parameters are present in the prmtop file.", false)); + allVars.put("IVCAP", var); + + // FCAP + + var = new SanderVariable( + "The force constant for the cap restraint potential.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("1", "", true)); + allVars.put("FCAP", var); + + // Variables WHICH ARE NOT PARSED !!! + + // ISCALE + + var = new SanderVariable( + "Number of additional variables to optimize beyond the 3N structural parameters." + + " (Default = 0). At present, this is only used with residual dipolar coupling" + + "restraints", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("0", "", true)); + allVars.put("ISCALE", var); + + // NOESKP --- !!! should be enumerated + var = new SanderVariable( + "The NOESY volumes will only be evaluated if mod(nstep, noeskp) = 0; otherwise" + + " the last computed values for intensities and derivatives will be used." + + " (default = 1, i.e. evaluate volumes at every step)", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("1", "", true)); + allVars.put("NOESKP", var); + + // IPNLTY --- !!! should be enumerated + var = new SanderVariable( + "", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("1", "", true)); + allVars.put("IPNLTY", var); + + // MXSUB + + var = new SanderVariable( + "Maximum number of submolecules that will be used. This is used to determine" + + " how much space to allocate for the NOESY calculations. Default 1.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("1", "", true)); + allVars.put("MXSUB", var); + + // SCALM + + var = new SanderVariable( + "\"Mass\" for the additional scaling parameters. Right now they are restricted to" + + " all have the same value. The larger this value, the slower these extra variables" + + " will respond to their environment. Default 100 amu.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("100", "", true)); + allVars.put("SCALM", var); + + // PENCUT + + var = new SanderVariable( + "In the summaries of the constraint deviations, entries will only be made if the" + + " penalty for that term is greater than PENCUT. Default 0.1.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.1", "", true)); + allVars.put("PENCUT", var); + + // TAUSW + + var = new SanderVariable( + "For noesy volume calculations (NMROPT = 2), intensities with mixing times" + + " less that TAUSW (in seconds) will be computed using perturbation theory," + + " whereas those greater than TAUSW will use a more exact theory." + + " To always use the \"exact\" intensities and" + + " derivatives, set TAUSW = 0.0; to always use perturbation theory, set TAUSW" + + " to a value larger than the largest mixing time in the input. Default is TAUSW" + + " of 0.1 second, which should work pretty well for most systems.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.1", "", true)); + allVars.put("TAUSW", var); + + // ---- Variables for ewald namelist + + // ORDER + + var = new SanderVariable( + "The order of the B-spline interpolation. The higher the order, the better the" + + " accuracy (unless the charge grid is too coarse). The minimum order is 3. An" + + " order of 4 (the default) implies a cubic spline approximation which is a good" + + " standard value. Note that the cost of the PME goes as roughly the order to the" + + " third power.", false); + var.setVarType(Sander8JobControl.TYPE_INTEGER); + var.addValue(new SanderVariableValue("4", "", true)); + ewaldVars.put("ORDER", var); + + // VERBOSE + + var = new SanderVariable( + "Standard use is to have VERBOSE = 0. Setting VERBOSE to higher values" + + " (up to a maximum of 3) leads to voluminous output of information about the" + + " PME run.", true); + + var.addValue(new SanderVariableValue("0", + "", true)); + var.addValue(new SanderVariableValue("1", + "", false)); + var.addValue(new SanderVariableValue("2", + "", false)); + var.addValue(new SanderVariableValue("3", + "", false)); + ewaldVars.put("VERBOSE", var); + + // EW_TYPE + + var = new SanderVariable( + "Standard use is to have EW_TYPE = 0 which turns on the particle mesh" + + " ewald (PME) method. When EW_TYPE = 1, instead of the approximate," + + " interpolated PME, a regular Ewald calculation is run. The number of reciprocal" + + " vectors used depends upon RSUM_TOL, or can be set by the user. The" + + " exact Ewald summation is present mainly to serve as an accuracy check" + + " allowing users to determine if the PME grid spacing, order and direct sum tolerance" + + " lead to acceptable results.", true); + + var.addValue(new SanderVariableValue("0", + "Turns on the particle mesh ewald (PME) method", true)); + var.addValue(new SanderVariableValue("1", + "A regular Ewald calculation is run.", false)); + ewaldVars.put("EW_TYPE", var); + + // DSUM_TOL + + var = new SanderVariable( + "This relates to the width of the direct sum part of the Ewald sum, requiring" + + " that the value of the direct sum at the Lennard-Jones cutoff value (specified in" + + " CUT as during standard dynamics) be less than DSUM_TOL. In practice it" + + " has been found that the relative error in the Ewald forces (RMS) due to cutting" + + " off the direct sum at CUT is between 10.0 and 50.0 times DSUM_TOL.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.00001", "", true)); + ewaldVars.put("DSUM_TOL", var); + + // RSUM_TOL + + var = new SanderVariable( + "This serves as a way to generate the number of reciprocal vectors used in an" + + " Ewald sum. Typically the relative RMS reciprocal sum error is about 5-10" + + " times RSUM_TOL. Default is 5 x 10\u22125.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + var.addValue(new SanderVariableValue("0.00005", "", true)); + ewaldVars.put("RSUM_TOL", var); + + // --- MLIMIT(1,2,3) - !!! not implemented yet + + // EW_COEFF + + var = new SanderVariable( + "Ewald coefficient, in �\u22121. Default is determined by dsum_tol and cutoff. If it" + + " is explicitly inputed then that value is used, and dsum_tol is computed from" + + " ew_coeff and cutoff.", false); + var.setVarType(Sander8JobControl.TYPE_FLOAT); + //var.addValue(new SanderVariableValue("0.00005", "", true)); + ewaldVars.put("EW_COEFF", var); + + logger.info("Number of hardwired variables in cntrl namelist: " + allVars.size()); + + // --- Check for all variable in cntrl namelist + + ResourceBundle cntrl_resources; + try { + cntrl_resources = ResourceBundle.getBundle("cct.amber.sander9cntrl"); + + Enumeration vars = cntrl_resources.getKeys(); + + while (vars.hasMoreElements()) { + String variable = vars.nextElement().toString().toUpperCase(); + if (allVars.containsKey(variable)) { + continue; + } + var = new SanderVariable("", false); + var.setVarType(Sander8JobControl.TYPE_UNDEFINED); + var.addValue(new SanderVariableValue("", "", true)); + allVars.put(variable, var); + } + + logger.info("Number of variables in cntrl namelist: " + allVars.size()); + } catch (Exception ex) { + System.err.println("Warning: No resource " + + "cct.amber.sander9cntrl"); + } + + // --- Check for resource bundle + + ResourceBundle resources; + try { + resources = ResourceBundle.getBundle("cct.amber.sander9VarDescr"); + + Set set = allVars.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String varName = me.getKey().toString(); + String description = null; + try { + description = resources.getString(varName); + var = (SanderVariable) me.getValue(); + var.setDescription(description); + } catch (Exception ex) { + // Just ignore it... + } + } + + } catch (Exception ex) { + System.err.println("Warning: No resource " + + "cct.amber.sander9VarDescr"); + } + + } + + public float getCutoff() { + Float f = (Float) ImportantVars.get("CUT"); + return f.floatValue(); + } + + public Map getAllVariablesInfo() { + return allVars; + } + + public int getNumberOfAtoms() { + return numberOfAtoms; + } + + public void setNumberOfAtoms(int n) { + numberOfAtoms = n; + } + + public int numberOfEnergySteps() { + Integer i = (Integer) ImportantVars.get("NSTLIM"); + //logger.info("NSTLIM: "+i.toString()); + return i.intValue(); + } + + public String getGeneralParameters(String filename, int fileType) { + String mess = null; + + if (fileType == 0) { // --- Read in from file + mess = cntrl_namelist.findAndParseFortranNamelist(filename, "cntrl"); + } else if (fileType == 1) { // --- Read in from string bufer + BufferedReader in = new BufferedReader(new StringReader(filename)); + //logger.info("Internal Text: "+filename); + mess = cntrl_namelist.findAndParseFortranNamelist(in, "cntrl"); + //in.close(); + //logger.info("After reading text bufer: "+mess); + } else { + return "getGeneralParameters: Internal Error: Unknown file type"; + } + + if (mess.compareTo("Ok") != 0) { + return mess; + } + Map vars = cntrl_namelist.getVariables(); + Set set = vars.entrySet(); + Iterator i = set.iterator(); + + // --- Debug print out + + while (i.hasNext()) { + Map.Entry me = (Map.Entry) i.next(); + String key = (String) me.getKey(); + System.out.print(key + " : "); + key = (String) me.getValue(); + logger.info(key); + } + + // --- End of debug + + // Get the most common options + + set = ImportantVars.entrySet(); + i = set.iterator(); + while (i.hasNext()) { + Map.Entry me = (Map.Entry) i.next(); + String key = (String) me.getKey(); + if (!vars.containsKey(key)) { + continue; + } + String value = (String) vars.get(key); + Number num = (Number) me.getValue(); + // --- Parse integer value + if (num instanceof Integer) { + try { + Integer ival = Integer.valueOf(value); + ImportantVars.put(key, ival); + logger.info("Key " + key + " is updated: " + + ival.toString()); + } catch (NumberFormatException e) { + logger.info("Not integer value for " + key + " : " + + value); + return "Not integer value for " + key + " : " + value; + } + } // Parse float value + else if (num instanceof Float) { + try { + Float fval = Float.valueOf(value); + ImportantVars.put(key, fval); + logger.info("Key " + key + " is updated: " + + fval.toString()); + } catch (NumberFormatException e) { + logger.info("Not float value for " + key + " : " + + value); + return "Not float value for " + key + " : " + value; + } + } + } + + return "Ok"; + } + + static public Map getGeneralParameters(String filename, int fileType, + FortranNamelist namelist, + String nm_name) { + String mess = null; + + if (fileType == 0) { // --- Read in from file + mess = namelist.findAndParseFortranNamelist(filename, nm_name); + } else if (fileType == 1) { // --- Read in from string bufer + BufferedReader in = new BufferedReader(new StringReader(filename)); + //logger.info("Internal Text: "+filename); + mess = namelist.findAndParseFortranNamelist(in, nm_name); + //in.close(); + //logger.info("After reading text bufer: "+mess); + } else { + logger.info( + "getGeneralParameters: Internal Error: Unknown file type"); + return null; + } + + if (mess.compareTo("Ok") != 0) { + return null; + } + Map vars = namelist.getVariables(); + Set set = vars.entrySet(); + Iterator i = set.iterator(); + + // --- Debug print out + + while (i.hasNext()) { + Map.Entry me = (Map.Entry) i.next(); + String key = (String) me.getKey(); + System.out.print(key + " : "); + key = (String) me.getValue(); + logger.info(key); + } + return vars; + } + + /** + * + * @param vars Map + * @return boolean + */ + public boolean setCntrlVariables(Map vars) { + Message = ""; + boolean no_errors = true; + + Set set = vars.entrySet(); + Iterator i = set.iterator(); + while (i.hasNext()) { + Map.Entry me = (Map.Entry) i.next(); + String key = me.getKey().toString(); + if (!allVars.containsKey(key)) { + no_errors = false; + Message += "Error: Unknown variable: " + key + + " in cntrl namelist\n"; + continue; + } + + String value = me.getValue().toString(); + + logger.info("Setting " + key + " = " + value); + + SanderVariable variable = (SanderVariable) allVars.get(key); + + String mess = variable.setValue(value); + if (mess != null) { + Message += "Error: " + key + " " + mess + "\n"; + no_errors = false; + } + + } + return no_errors; + } + + public String getErrorMessage() { + return Message; + } + + /** + * + * @param namelistVars Map + * @param s8jcVars Map + * @return String + */ + public static String updateNamelistVariables(Map namelistVars, Map s8jcVars) { + SanderVariable var; + String message = ""; + + Set set = s8jcVars.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String option = me.getKey().toString(); + var = (SanderVariable) me.getValue(); + + // If it's default value we remove it from the namelist + if (var.isDefaultValue()) { + if (namelistVars.containsKey(option)) { + namelistVars.remove(option); + } + } else { + namelistVars.put(option, var.getValue()); + } + } + + // -- Now check again all namelist variables and remove those which has + // no mapping + + Map newNamelistVars = new HashMap(); + + set = namelistVars.entrySet(); + iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String option = me.getKey().toString(); + + if (s8jcVars.containsKey(option)) { + newNamelistVars.put(option, me.getValue().toString()); + continue; + } + message += "Warning: No variable " + option + + " in Sander-8 job control list\n"; + //namelistVars.remove(option); + } + + namelistVars.clear(); + namelistVars.putAll(newNamelistVars); + + if (message.length() == 0) { + return null; + } + return message; + } +} diff --git a/src/main/java/cct/amber/Sander9JobPanel.java b/src/main/java/cct/amber/Sander9JobPanel.java new file mode 100644 index 0000000..e453886 --- /dev/null +++ b/src/main/java/cct/amber/Sander9JobPanel.java @@ -0,0 +1,575 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.amber; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTabbedPane; +import javax.swing.JTextField; +import javax.swing.border.BevelBorder; +import javax.swing.border.TitledBorder; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Sander9JobPanel + extends JPanel { + BorderLayout borderLayout1 = new BorderLayout(); + JPanel directoriesPanel = new JPanel(); + JPanel outputPanel = new JPanel(); + JPanel inputPanel = new JPanel(); + JLabel remoteDirLabel = new JLabel(); + JTextField remoteDirTextField = new JTextField(); + JButton scriptButton = new JButton(); + JLabel localDirLabel = new JLabel(); + JLabel jobNameLabel = new JLabel(); + JTextField jobNameTextField = new JTextField(); + JTextField localDirTextField = new JTextField(); + JLabel scriptLabel = new JLabel(); + JTextField scriptTextField = new JTextField(); + JButton jButton2 = new JButton(); + JButton localDirButton = new JButton(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + JLabel prmtopLabel = new JLabel(); + JTextField mdinTextField = new JTextField(); + JCheckBox mdinCheckBox = new JCheckBox(); + JButton mdinButton = new JButton(); + JLabel mdinLabel = new JLabel(); + JLabel evbinLabel = new JLabel(); + JLabel cpinLabel = new JLabel(); + JLabel inpdipLabel = new JLabel(); + JLabel inptrajLabel = new JLabel(); + JLabel refcLabel = new JLabel(); + JLabel inpcrdLabel = new JLabel(); + JTextField evbinTextField = new JTextField(); + JTextField cpinTextField = new JTextField(); + JTextField inpdipTextField = new JTextField(); + JTextField inptrajTextField = new JTextField(); + JTextField refcTextField = new JTextField(); + JTextField inpcrdTextField = new JTextField(); + JTextField prmtopTextField = new JTextField(); + JCheckBox evbinCheckBox = new JCheckBox(); + JCheckBox cpinCheckBox = new JCheckBox(); + JCheckBox inpdipCheckBox = new JCheckBox(); + JCheckBox inptrajCheckBox = new JCheckBox(); + JCheckBox refcCheckBox = new JCheckBox(); + JCheckBox inpcrdCheckBox = new JCheckBox(); + JCheckBox prmtopCheckBox = new JCheckBox(); + JButton evbinButton = new JButton(); + JButton cpinButton = new JButton(); + JButton inpdipButton = new JButton(); + JButton inptrajButton = new JButton(); + JButton refcButton = new JButton(); + JButton inpcrdButton = new JButton(); + JButton prmtopButton = new JButton(); + GridBagLayout gridBagLayout2 = new GridBagLayout(); + JLabel jLabel1 = new JLabel(); + JTextField jTextField1 = new JTextField(); + JCheckBox jCheckBox1 = new JCheckBox(); + JLabel jLabel2 = new JLabel(); + JLabel jLabel3 = new JLabel(); + JLabel jLabel4 = new JLabel(); + JLabel mdvelLabel = new JLabel(); + JLabel mdoutLabel = new JLabel(); + JLabel mdcrdLabel = new JLabel(); + JLabel mdinfoLabel = new JLabel(); + JTextField jTextField2 = new JTextField(); + JTextField jTextField3 = new JTextField(); + JTextField mdcrdTextField = new JTextField(); + JTextField jTextField5 = new JTextField(); + JTextField mdvelTextField = new JTextField(); + JTextField mdinfoTextField = new JTextField(); + JTextField mdoutTextField = new JTextField(); + JCheckBox jCheckBox2 = new JCheckBox(); + JCheckBox jCheckBox3 = new JCheckBox(); + JCheckBox jCheckBox4 = new JCheckBox(); + JCheckBox mdvelCheckBox = new JCheckBox(); + JCheckBox mdcrdCheckBox = new JCheckBox(); + JCheckBox mdinfoCheckBox = new JCheckBox(); + JCheckBox mdoutCheckBox = new JCheckBox(); + JPanel jPanel1 = new JPanel(); + BorderLayout borderLayout2 = new BorderLayout(); + GridBagLayout gridBagLayout3 = new GridBagLayout(); + JTabbedPane jTabbedPane1 = new JTabbedPane(); + public Sander9JobPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + directoriesPanel.setLayout(gridBagLayout1); + remoteDirLabel.setToolTipText(""); + remoteDirLabel.setText("Remote Directory: "); + remoteDirTextField.setToolTipText(""); + remoteDirTextField.setText("Remote Dir Here"); + scriptButton.setToolTipText(""); + scriptButton.setText("Edit"); + localDirLabel.setToolTipText(""); + localDirLabel.setText("Local Directory:"); + jobNameLabel.setToolTipText(""); + jobNameLabel.setText("Job Name: "); + jobNameTextField.setToolTipText(""); + jobNameTextField.setText("Job Name Here"); + localDirTextField.setToolTipText(""); + localDirTextField.setText("Local Dir Here"); + scriptLabel.setToolTipText(""); + scriptLabel.setText("Run Script: "); + scriptTextField.setToolTipText(""); + scriptTextField.setText("Script Here"); + jButton2.setToolTipText(""); + jButton2.setActionCommand("remoteDirButton"); + jButton2.setText("Browse"); + localDirButton.setToolTipText(""); + localDirButton.setText("Browse"); + directoriesPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder. + RAISED, Color.white, Color.white, new Color(115, 114, 105), + new Color(165, 163, 151))); + prmtopLabel.setToolTipText(""); + prmtopLabel.setText("Topology (prmtop): "); + mdinTextField.setToolTipText("Control data for the min/md run"); + mdinTextField.setText("Job Name Here"); + mdinCheckBox.setToolTipText(""); + mdinCheckBox.setText("Local File"); + mdinButton.setToolTipText(""); + mdinButton.setText("Browse"); + inputPanel.setLayout(gridBagLayout2); + mdinLabel.setToolTipText(""); + mdinLabel.setText("Control Data (mdin): "); + evbinLabel.setText("EVB Potentials (evbin): "); + evbinLabel.setToolTipText(""); + cpinLabel.setText("Protonation state defs (cpin): "); + cpinLabel.setToolTipText(""); + inpdipLabel.setText("Polarizable dipoles (inpdip): "); + inpdipLabel.setToolTipText(""); + inptrajLabel.setText("Input Coord Sets (inptraj): "); + inptrajLabel.setToolTipText(""); + refcLabel.setText("Reference Coords (refc): "); + refcLabel.setToolTipText(""); + inpcrdLabel.setText("Initial Coords (inpcrd): "); + inpcrdLabel.setToolTipText(""); + evbinTextField.setText("Job Name Here"); + evbinTextField.setToolTipText("Input for EVB potentials"); + cpinTextField.setText("Job Name Here"); + cpinTextField.setToolTipText("Protonation state definitions"); + inpdipTextField.setText("Job Name Here"); + inpdipTextField.setToolTipText("Polarizable dipole file, when indmeth=3"); + inptrajTextField.setText("Job Name Here"); + inptrajTextField.setToolTipText( + "Input coordinate sets in trajectory format, when imin=5"); + refcTextField.setText("Job Name Here"); + refcTextField.setToolTipText( + "(Optional) reference coords for position restraints; also used for " + + "targeted MD"); + inpcrdTextField.setText("Job Name Here"); + inpcrdTextField.setToolTipText( + "Initial coordinates and (optionally) velocities and periodic box " + + "size"); + prmtopTextField.setText("Job Name Here"); + prmtopTextField.setToolTipText( + "Molecular topology, force field, periodic box type, atom and residue " + + "names"); + evbinCheckBox.setToolTipText(""); + evbinCheckBox.setText("Local File"); + cpinCheckBox.setToolTipText(""); + cpinCheckBox.setText("Local File"); + inpdipCheckBox.setToolTipText(""); + inpdipCheckBox.setText("Local File"); + inptrajCheckBox.setToolTipText(""); + inptrajCheckBox.setText("Local File"); + refcCheckBox.setToolTipText(""); + refcCheckBox.setText("Local File"); + inpcrdCheckBox.setToolTipText(""); + inpcrdCheckBox.setText("Local File"); + prmtopCheckBox.setToolTipText(""); + prmtopCheckBox.setText("Local File"); + evbinButton.setToolTipText(""); + evbinButton.setText("Browse"); + cpinButton.setToolTipText(""); + cpinButton.setText("Browse"); + inpdipButton.setToolTipText(""); + inpdipButton.setText("Browse"); + inptrajButton.setToolTipText(""); + inptrajButton.setText("Browse"); + refcButton.setToolTipText(""); + refcButton.setText("Browse"); + inpcrdButton.setToolTipText(""); + inpcrdButton.setText("Browse"); + prmtopButton.setToolTipText(""); + prmtopButton.setText("Browse"); + inputPanel.setBorder(new TitledBorder(BorderFactory.createBevelBorder( + BevelBorder.LOWERED, Color.white, Color.white, + new Color(115, 114, 105), new Color(165, 163, 151)), "Input Files")); + jLabel1.setToolTipText(""); + jLabel1.setText("Protonation State (cpout): "); + outputPanel.setLayout(gridBagLayout3); + jTextField1.setToolTipText( + "final coordinates, velocity, and box dimensions if any - for restarting " + + "run"); + jTextField1.setText("Remote Dir Here"); + outputPanel.setBorder(new TitledBorder(BorderFactory.createBevelBorder( + BevelBorder.RAISED, Color.white, Color.white, new Color(115, 114, 105), + new Color(165, 163, 151)), "Output Files")); + jCheckBox1.setToolTipText(""); + jCheckBox1.setText("Copy to Local Filesystem"); + jLabel2.setToolTipText(""); + jLabel2.setText("Polarizable Dipoles (rstdip): "); + jLabel3.setToolTipText(""); + jLabel3.setText("Final Coords (restrt): "); + jLabel4.setToolTipText(""); + jLabel4.setText("MD Energy Data (mden): "); + mdvelLabel.setToolTipText(""); + mdvelLabel.setText("MD Velocities (mdvel): "); + mdoutLabel.setToolTipText(""); + mdoutLabel.setText("Program Info (mdout): "); + mdcrdLabel.setToolTipText(""); + mdcrdLabel.setText("MD Coordinates (mdcrd): "); + mdinfoLabel.setToolTipText(""); + mdinfoLabel.setText("Energy Info (mdinfo): "); + jTextField2.setToolTipText("protonation state data saved over trajectory"); + jTextField2.setText("Remote Dir Here"); + jTextField3.setToolTipText("polarizable dipole file, when indmeth=3"); + jTextField3.setText("Remote Dir Here"); + mdcrdTextField.setToolTipText("coordinate sets saved over trajectory"); + mdcrdTextField.setText("Remote Dir Here"); + jTextField5.setToolTipText("extensive energy data over trajectory"); + jTextField5.setText("Remote Dir Here"); + mdvelTextField.setToolTipText("velocity sets saved over trajectory"); + mdvelTextField.setText("Remote Dir Here"); + mdinfoTextField.setToolTipText("latest mdout-format energy info"); + mdinfoTextField.setText("Remote Dir Here"); + mdoutTextField.setToolTipText("User readable state info and diagnostics "); + mdoutTextField.setText("Remote Dir Here"); + jCheckBox2.setToolTipText(""); + jCheckBox2.setText("Copy to Local Filesystem"); + jCheckBox3.setToolTipText(""); + jCheckBox3.setText("Copy to Local Filesystem"); + jCheckBox4.setToolTipText(""); + jCheckBox4.setText("Copy to Local Filesystem"); + mdvelCheckBox.setToolTipText(""); + mdvelCheckBox.setText("Copy to Local Filesystem"); + mdcrdCheckBox.setToolTipText(""); + mdcrdCheckBox.setText("Copy to Local Filesystem"); + mdinfoCheckBox.setToolTipText(""); + mdinfoCheckBox.setText("Copy to Local Filesystem"); + mdoutCheckBox.setToolTipText(""); + mdoutCheckBox.setText("Copy to Local Filesystem"); + jPanel1.setLayout(borderLayout2); + directoriesPanel.add(jobNameTextField, + new GridBagConstraints(1, 0, 3, 1, 1.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + directoriesPanel.add(scriptTextField, + new GridBagConstraints(1, 1, 2, 1, 1.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + directoriesPanel.add(localDirTextField, + new GridBagConstraints(1, 2, 2, 1, 1.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + directoriesPanel.add(localDirButton, + new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + directoriesPanel.add(remoteDirTextField, + new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + directoriesPanel.add(jButton2, + new GridBagConstraints(3, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + directoriesPanel.add(scriptButton, + new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + directoriesPanel.add(jobNameLabel, + new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + directoriesPanel.add(scriptLabel, + new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + directoriesPanel.add(localDirLabel, + new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + directoriesPanel.add(remoteDirLabel, + new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(mdinTextField, new GridBagConstraints(1, 0, 2, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(mdinCheckBox, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(prmtopTextField, + new GridBagConstraints(1, 1, 2, 1, 1.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(prmtopCheckBox, + new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(prmtopButton, new GridBagConstraints(4, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(inpcrdTextField, + new GridBagConstraints(1, 2, 2, 1, 1.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(inpcrdCheckBox, + new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(inpcrdButton, new GridBagConstraints(4, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(refcTextField, new GridBagConstraints(1, 3, 2, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(refcCheckBox, new GridBagConstraints(3, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(inptrajTextField, + new GridBagConstraints(1, 4, 2, 1, 1.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(inptrajCheckBox, + new GridBagConstraints(3, 4, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(inptrajButton, new GridBagConstraints(4, 4, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(inpdipTextField, + new GridBagConstraints(1, 5, 2, 1, 1.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(inpdipCheckBox, + new GridBagConstraints(3, 5, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(inpdipButton, new GridBagConstraints(4, 5, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(cpinTextField, new GridBagConstraints(1, 6, 2, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(cpinCheckBox, new GridBagConstraints(3, 6, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(cpinButton, new GridBagConstraints(4, 6, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(mdinLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(prmtopLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(inpcrdLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(refcLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(inptrajLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(inpdipLabel, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(cpinLabel, new GridBagConstraints(0, 6, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(mdinButton, new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(refcButton, new GridBagConstraints(4, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + jPanel1.add(directoriesPanel, BorderLayout.NORTH); + outputPanel.add(mdoutLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(mdoutTextField, + new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(mdoutCheckBox, + new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(mdinfoLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(mdinfoTextField, + new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(mdinfoCheckBox, + new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(mdcrdLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(mdcrdTextField, + new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(mdcrdCheckBox, + new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(mdvelLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(mdvelTextField, + new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(mdvelCheckBox, + new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(jLabel4, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(jTextField5, new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(jCheckBox4, new GridBagConstraints(2, 4, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(jLabel3, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(jTextField1, new GridBagConstraints(1, 5, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(jCheckBox3, new GridBagConstraints(2, 5, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(jLabel2, new GridBagConstraints(0, 6, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(jTextField3, new GridBagConstraints(1, 6, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(jCheckBox2, new GridBagConstraints(2, 6, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(jTabbedPane1, BorderLayout.CENTER); + this.add(jPanel1, BorderLayout.NORTH); + jTabbedPane1.add(inputPanel, "Input Files"); + jTabbedPane1.add(outputPanel, "Output Files"); + inputPanel.add(evbinButton, new GridBagConstraints(4, 7, 1, 1, 0.0, 1.0 + , GridBagConstraints.NORTH, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(evbinCheckBox, new GridBagConstraints(3, 7, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTH, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(evbinTextField, + new GridBagConstraints(1, 7, 2, 1, 1.0, 0.0 + , GridBagConstraints.NORTHWEST, + GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + inputPanel.add(evbinLabel, new GridBagConstraints(0, 7, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(jCheckBox1, new GridBagConstraints(2, 7, 1, 1, 0.0, 1.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(jTextField2, new GridBagConstraints(1, 7, 1, 1, 1.0, 0.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + outputPanel.add(jLabel1, new GridBagConstraints(0, 7, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + jTabbedPane1.setSelectedComponent(inputPanel); + } +} diff --git a/src/main/java/cct/amber/SanderInputParserInterface.java b/src/main/java/cct/amber/SanderInputParserInterface.java new file mode 100644 index 0000000..43499d6 --- /dev/null +++ b/src/main/java/cct/amber/SanderInputParserInterface.java @@ -0,0 +1,22 @@ +package cct.amber; + +import java.util.Map; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface SanderInputParserInterface { + + Map parseInputData(String data); + + void setEnabled(boolean enable); +} diff --git a/src/main/java/cct/amber/SanderJobControlDialog.java b/src/main/java/cct/amber/SanderJobControlDialog.java new file mode 100644 index 0000000..b5e75fc --- /dev/null +++ b/src/main/java/cct/amber/SanderJobControlDialog.java @@ -0,0 +1,173 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.amber; + +import java.awt.Dialog; +import java.awt.FlowLayout; +import java.awt.GridLayout; +import java.awt.Label; +import java.awt.Panel; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class SanderJobControlDialog + extends Dialog implements ActionListener, ItemListener { + TextField natoms, nsteps, cutoff, memory_req, time_req; + AmberSubmitDialog daddy = null; + //BorderLayout borderLayout1 = new BorderLayout(); + + public SanderJobControlDialog(AmberSubmitDialog owner, String title, + boolean modal) { + super(owner, title, modal); + daddy = owner; + + GridLayout sizer = new GridLayout(0, 1, 3, 3); + setLayout(sizer); + + Panel P = new Panel(); + P.setLayout(new FlowLayout(FlowLayout.RIGHT)); + + Label nat = new Label("Number of Atoms:", Label.RIGHT); + natoms = new TextField(" 0"); + natoms.setEditable(false); + natoms.addActionListener(this); + + P.add(nat); + P.add(natoms); + add(P); + + P = new Panel(); + P.setLayout(new FlowLayout(FlowLayout.RIGHT)); + + Label nst = new Label("Number of Energy/Grad Evaluations:", Label.RIGHT); + nsteps = new TextField(" "); + nsteps.setEditable(false); + nsteps.addActionListener(this); + + P.add(nst); + P.add(nsteps); + add(P); + + P = new Panel(); + P.setLayout(new FlowLayout(FlowLayout.RIGHT)); + + Label cut = new Label("Nonbonded Cutoff", Label.RIGHT); + cutoff = new TextField(" "); + cutoff.setEditable(false); + cutoff.addActionListener(this); + + P.add(cut); + P.add(cutoff); + add(P); + + P = new Panel(); + P.setLayout(new FlowLayout(FlowLayout.RIGHT)); + + Label memory = new Label("Memory requirement (Mb):", Label.RIGHT); + memory_req = new TextField(" "); + memory_req.setEditable(false); + //memory_req.addActionListener(this); + + P.add(memory); + P.add(memory_req); + add(P); + + P = new Panel(); + P.setLayout(new FlowLayout(FlowLayout.RIGHT)); + + Label time = new Label("Time requirement (seconds):", Label.RIGHT); + time_req = new TextField(" "); + time_req.setEditable(false); + //time_req.addActionListener(this); + + P.add(time); + P.add(time_req); + add(P); + + setSize(350, 230); + } + + public void setCutoff(float cut) { + cutoff.setText(Float.toString(cut)); + } + + public void setMemoryRequirement(float m_req) { + memory_req.setText(Float.toString(m_req)); + } + + public void setNumberOfAtoms(int nat) { + natoms.setText(Integer.toString(nat)); + } + + public void setNumberOfSteps(int n) { + nsteps.setText(Integer.toString(n)); + } + + public void setTimeRequirement(float t_req) { + time_req.setText(Float.toString(t_req)); + } + + @Override + public void actionPerformed(ActionEvent ae) { + String arg = ae.getActionCommand(); + if (arg.equals("OK")) { + + } + } + + @Override + public void itemStateChanged(ItemEvent ie) { + repaint(); + } + +} diff --git a/src/main/java/cct/amber/SanderResourcesEval.java b/src/main/java/cct/amber/SanderResourcesEval.java new file mode 100644 index 0000000..df5b9b3 --- /dev/null +++ b/src/main/java/cct/amber/SanderResourcesEval.java @@ -0,0 +1,106 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.amber; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class SanderResourcesEval { + static final String platf_01 = "SGI Altix 3700 Bx2"; + + String currentPlatform = platf_01; + int numberOfAtoms = 20000; + List platform = new ArrayList(); + Map staticMemory = new HashMap(); // In Mb + + public SanderResourcesEval() { + platform.add(platf_01); + + staticMemory.put(platf_01, new Float(60.0)); + } + + public int getNumberOfAtoms() { + return numberOfAtoms; + } + + public float evaluateMemoryRequirement(Sander8JobControl sjc) { + float numAtoms; + if (sjc.getNumberOfAtoms() > 0) { + numberOfAtoms = sjc.getNumberOfAtoms(); + } + numAtoms = numberOfAtoms; + float cutoff = sjc.getCutoff(); + + // --- Static memory size for a given platform + Float f = (Float) staticMemory.get(currentPlatform); + float size = f.floatValue(); + + // ... plus size of dynamically allocated memory + float size_dyn = (1.677e-3f + cutoff * ( -7.196e-5f) + + cutoff * cutoff * 1.264e-5f + + cutoff * cutoff * cutoff * 1.174e-6f) * numAtoms; + if (size_dyn < 0) { + size_dyn = 0.0f; + } + return size + size_dyn; + } + + public float evaluateTimeRequirement(Sander8JobControl sjc) { + float numAtoms; + if (sjc.getNumberOfAtoms() > 0) { + numberOfAtoms = sjc.getNumberOfAtoms(); + } + numAtoms = numberOfAtoms; + float cutoff = sjc.getCutoff(); + if (cutoff < 1.0f) { + cutoff = 8.0f; + } + float steps = sjc.numberOfEnergySteps(); + + float time = (8.7266e-6f + cutoff * ( -9.2626e-7f) + + cutoff * cutoff * 4.5207e-8f + + cutoff * cutoff * cutoff * 1.2165e-8f) * numAtoms * steps; + if (time < 0) { + time = 0.0f; + } + return time; + } + +} diff --git a/src/main/java/cct/amber/SanderVariable.java b/src/main/java/cct/amber/SanderVariable.java new file mode 100644 index 0000000..8f0a225 --- /dev/null +++ b/src/main/java/cct/amber/SanderVariable.java @@ -0,0 +1,360 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.amber; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class SanderVariable { + boolean enumerated = false; + int varType = Sander8JobControl.TYPE_INTEGER; + String Description; + List Values = new ArrayList(); + int selectedValue = -1; // For enumerated variables + String newValue = null; // For non-enumerated variables + + boolean defaultIsSet = false; + boolean currentValueIsNotDefault = false; + Object nondefaultParsedValue = null; + String nondefaultValue = null; + static final Logger logger = Logger.getLogger(SanderVariable.class.getCanonicalName()); + + SanderVariable(String descr, boolean isEnum) { + Description = descr; + enumerated = isEnum; + if (enumerated) { + varType = Sander8JobControl.TYPE_INTEGER; + } + } + + public int getNumberOfValues() { + return Values.size(); + } + + public void addValue(SanderVariableValue value) { + if (!enumerated && Values.size() > 0) { + logger.info("INTERNAL ERROR: addValue: Only one value for non-enumerated variables is allowed!"); + return; + } + + if (defaultIsSet && value.isDefault()) { + logger.info( + "INTERNAL ERROR: addValue: Only one value can be default one!"); + return; + } + + if (value.isDefault()) { + defaultIsSet = true; + } + + if (enumerated) { + try { + Integer ival = Integer.valueOf(value.getValue()); + value.setParsedValue(ival); + } + catch (NumberFormatException e) { + logger.info( + "INTERNAL ERROR: addValue: Expected integer value for enumerated variable, got: " + + value); + return; + } + + if (value.isDefault()) { + selectedValue = Values.size(); + //logger.info("Selected changed: " + selectedValue); + } + } + + else if (varType == Sander8JobControl.TYPE_INTEGER) { + try { + Integer ival = Integer.valueOf(value.getValue()); + value.setParsedValue(ival); + } + catch (NumberFormatException e) { + logger.info( + "INTERNAL ERROR: addValue: Expected integer value, got: " + + value); + return; + } + } + + else if (varType == Sander8JobControl.TYPE_FLOAT) { + try { + Float fval = Float.valueOf(value.getValue()); + value.setParsedValue(fval); + } + catch (NumberFormatException e) { + logger.info( + "INTERNAL ERROR: addValue: Expected float value, got: " + + value); + return; + } + + } + + Values.add(value); + + } + + public int getSelectedIndex() { + return selectedValue; + } + + public String getDescription() { + return this.Description; + } + + public void setDescription(String newDescription) { + Description = null; + Description = newDescription; + } + + /** + * + * @return String + */ + public String getValue() { + if (enumerated) { + SanderVariableValue value = (SanderVariableValue) Values.get( + selectedValue); + return value.getValue(); + } + + if (currentValueIsNotDefault) { + return nondefaultValue; + } + SanderVariableValue value = (SanderVariableValue) Values.get(0); + return value.getValue(); + } + + /** + * + * @return Object + */ + public Object getParsedValue() { + if (enumerated) { + SanderVariableValue value = (SanderVariableValue) Values.get( + selectedValue); + return value.getParsedValue(); + } + + if (currentValueIsNotDefault) { + return nondefaultParsedValue; + } + SanderVariableValue value = (SanderVariableValue) Values.get(0); + return value.getParsedValue(); + } + + public SanderVariableValue getValue(int n) { + if (n < 0 || n >= getNumberOfValues()) { + return null; + } + return (SanderVariableValue) Values.get(n); + } + + public boolean isEnumerated() { + return enumerated; + } + + public boolean isDefaultValue() { + return!currentValueIsNotDefault; + } + + public void setNewValue(String new_value) { + if (enumerated) { + logger.info( + "INTERNAL ERROR: setNewValue: Attempt to set enumerated variable!"); + return; + } + newValue = new_value; + } + + /** + * + * @param index int + */ + public void setSelectedIndex(int index) { + if (!enumerated) { + logger.info( + "INTERNAL ERROR: setSelectedIndex: Attempt to set non-enumerated variable!"); + return; + } + + if (index < 0 || index >= Values.size()) { + logger.info( + "INTERNAL ERROR: setSelectedIndex: index < 0 || index >= Values.size()!"); + return; + } + + SanderVariableValue valid_value = (SanderVariableValue) Values. + get(index); + currentValueIsNotDefault = !valid_value.isDefault(); + + selectedValue = index; + //logger.info("Selected changed: setSelectedIndex" + selectedValue); + } + + void setVarType(int type) { + varType = type; + } + + /** + * + * @param value String + * @return String + */ + + public String setValue(String new_value) { + + if (new_value == null) { + return "INTERNAL ERROR: setValue: Attempt to set null value"; + } + String val = new_value.trim(); + logger.info("Parsing value: " + val); + + // --- Check enumerated variable + + if (enumerated) { + Integer ival; + try { + ival = Integer.valueOf(val); + } + catch (NumberFormatException e) { + return "Enumerated variable is not integer: " + val; + } + + for (int i = 0; i < Values.size(); i++) { + SanderVariableValue valid_value = (SanderVariableValue) Values. + get(i); + Integer proper_value = (Integer) valid_value.getParsedValue(); + if (ival.intValue() == proper_value.intValue()) { + selectedValue = i; + //logger.info("Selected changed: setValue: " + selectedValue); + if (valid_value.isDefault()) { + currentValueIsNotDefault = false; + logger.info("Value is a default one"); + } + else { + currentValueIsNotDefault = true; + logger.info("Value is not a default one"); + } + return null; + } + } + return val + " is not a valid enumerated value"; + + } + + // --- Check integer value + + else if (varType == Sander8JobControl.TYPE_INTEGER) { + try { + Integer ival = Integer.valueOf(val); + SanderVariableValue valid_value = (SanderVariableValue) Values. + get(0); + + // --- Is new value equal to default one? + + Integer default_value = (Integer) valid_value.getParsedValue(); + + if (default_value.intValue() == ival.intValue()) { + currentValueIsNotDefault = false; + logger.info("Value is a default one"); + } + else { + currentValueIsNotDefault = true; + nondefaultParsedValue = ival; + nondefaultValue = val; + logger.info("Value is not a default one"); + } + return null; + } + catch (NumberFormatException e) { + return "Expected integer value, got: " + val; + } + } + + // --- Check float value + + else if (varType == Sander8JobControl.TYPE_FLOAT) { + try { + Float fval = Float.valueOf(val); + SanderVariableValue valid_value = (SanderVariableValue) Values. + get(0); + // --- Is new value equal to default one? + + Float default_value = (Float) valid_value.getParsedValue(); + + if (default_value.floatValue() == fval.floatValue()) { + currentValueIsNotDefault = false; + logger.info("Value is a default one"); + } + else { + currentValueIsNotDefault = true; + nondefaultParsedValue = fval; + nondefaultValue = val; + logger.info("Value is not a default one"); + } + + return null; + } + catch (NumberFormatException e) { + return "Expected float value, got: " + val; + } + } + + return null; + } + + public int getType() { + return varType; + } +} diff --git a/src/main/java/cct/amber/SanderVariableValue.java b/src/main/java/cct/amber/SanderVariableValue.java new file mode 100644 index 0000000..35bdc61 --- /dev/null +++ b/src/main/java/cct/amber/SanderVariableValue.java @@ -0,0 +1,87 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.amber; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class SanderVariableValue { + boolean defaultValue = false; + String Description; + String Value; + Object parsedValue = null; + + public SanderVariableValue(String value, String description, boolean isDefault) { + defaultValue = isDefault; + Description = description; + Value = value; + } + + public boolean isDefault() { + return defaultValue; + } + + public String getDescription() { + return Description; + } + + public String getValue() { + return Value; + } + + public Object getParsedValue() { + return parsedValue; + } + + public void setParsedValue(Object value) { + parsedValue = value; + } + + public void setValue(String value) { + Value = value; + } +} diff --git a/src/main/java/cct/amber/Save-Icon-16x16.gif b/src/main/java/cct/amber/Save-Icon-16x16.gif new file mode 100644 index 0000000..46c7cdc Binary files /dev/null and b/src/main/java/cct/amber/Save-Icon-16x16.gif differ diff --git a/src/main/java/cct/amber/TextEditorFrame.java b/src/main/java/cct/amber/TextEditorFrame.java new file mode 100644 index 0000000..5d52800 --- /dev/null +++ b/src/main/java/cct/amber/TextEditorFrame.java @@ -0,0 +1,195 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.amber; + +import java.awt.BorderLayout; +import java.awt.FileDialog; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JEditorPane; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.WindowConstants; + +import cct.tools.IOUtils; + +/** + *

Title: Preparation of input file for Sander 8 program

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class TextEditorFrame + extends JFrame { + + JPanel contentPane; + JMenuBar jMenuBar1 = new JMenuBar(); + JEditorPane jEditorPane1 = new JEditorPane(); + JMenu jMenu1 = new JMenu(); + JMenuItem jMenuItem1 = new JMenuItem(); + JMenuItem jMenuItem2 = new JMenuItem(); + + String fileName = null; + String workingDirectory = null; + BorderLayout borderLayout1 = new BorderLayout(); + String editedText = null; + + SanderInputParserInterface Parent; + JScrollPane jScrollPane1 = new JScrollPane(); + + public TextEditorFrame() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public TextEditorFrame(SanderInputParserInterface parent, String Title, String Text) { + try { + Parent = parent; + jbInit(); + this.setTitle(Title); + jEditorPane1.setText(Text); + } + catch (Exception exception) { + exception.printStackTrace(); + } + + } + + private void jbInit() throws Exception { + contentPane = (JPanel) getContentPane(); + contentPane.setLayout(borderLayout1); + + jEditorPane1.setText("Text to edit..."); + jMenu1.setText("File"); + jMenuItem1.setText("Save"); + jMenuItem1.addActionListener(new TextEditorFrame_jMenuItem1_actionAdapter(this)); + jMenuItem2.setText("Return"); + jMenuItem2.addActionListener(new TextEditorFrame_jMenuItem2_actionAdapter(this)); + this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); + jMenuBar1.add(jMenu1); + jMenu1.add(jMenuItem1); + jMenu1.add(jMenuItem2); + contentPane.add(jScrollPane1, BorderLayout.CENTER); + jScrollPane1.getViewport().add(jEditorPane1); + setJMenuBar(jMenuBar1); + } + + public void jMenuItem1_actionPerformed(ActionEvent e) { + if (fileName == null) { + fileName = "sander8.in"; + } + if (workingDirectory == null) { + workingDirectory = "./"; + } + + FileDialog fd = new FileDialog(this, "Save Sander 8 Job Control File", + FileDialog.SAVE); + fd.setFile(fileName); + fd.setDirectory(workingDirectory); + fd.setVisible(true); + if (fd.getFile() != null) { + fileName = new String(fd.getFile()); + workingDirectory = new String(fd.getDirectory()); + try { + IOUtils.saveStringIntoFile(jEditorPane1.getText(), + workingDirectory + fileName); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + + } + } + + } + + public void jMenuItem2_actionPerformed(ActionEvent e) { + setVisible(false); + Parent.setEnabled(true); + Parent.parseInputData(jEditorPane1.getText()); + //jEditorPane1.is + } + + public void setTextToEdit(String text) { + editedText = text; + jEditorPane1.setText(text); + } +} + +class TextEditorFrame_jMenuItem2_actionAdapter + implements ActionListener { + private TextEditorFrame adaptee; + TextEditorFrame_jMenuItem2_actionAdapter(TextEditorFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.jMenuItem2_actionPerformed(e); + } +} + +class TextEditorFrame_jMenuItem1_actionAdapter + implements ActionListener { + private TextEditorFrame adaptee; + TextEditorFrame_jMenuItem1_actionAdapter(TextEditorFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.jMenuItem1_actionPerformed(e); + } +} diff --git a/src/main/java/cct/amber/about.png b/src/main/java/cct/amber/about.png new file mode 100644 index 0000000..754005c Binary files /dev/null and b/src/main/java/cct/amber/about.png differ diff --git a/src/main/java/cct/amber/amber-elements.properties b/src/main/java/cct/amber/amber-elements.properties new file mode 100644 index 0000000..e518dab --- /dev/null +++ b/src/main/java/cct/amber/amber-elements.properties @@ -0,0 +1,64 @@ +C= C +CA= C +CB= C +CC= C +CD= C +CK= C +CM= C +CN= C +CQ= C +CR= C +CT= C +CV= C +CW= C +C*= C +CY= C +CZ= C +C0= CA +H= H +HC= H +H1= H +H2= H +H3= H +HA= H +H4= H +H5= H +HO= H +HS= H +HW= H +HP= H +HZ= H +F= F +Cl= CL +Br= BR +I= I +IM= CL +IB= Na +MG= MG +N= N +NA= N +NB= N +NC= N +N2= N +N3= N +NT= N +N*= N +NY= N +O= O +O2= O +OW= O +OH= O +OS= O +P= P +S= S +SH= S +CU= CU +FE= FE +Li= LI +IP= Na +Na= Na +K = K +Rb= RB +Cs= CS +Zn= ZN +EP= DU diff --git a/src/main/java/cct/amber/closeFile.png b/src/main/java/cct/amber/closeFile.png new file mode 100644 index 0000000..81cc1a6 Binary files /dev/null and b/src/main/java/cct/amber/closeFile.png differ diff --git a/src/main/java/cct/amber/help.png b/src/main/java/cct/amber/help.png new file mode 100644 index 0000000..d7a33f8 Binary files /dev/null and b/src/main/java/cct/amber/help.png differ diff --git a/src/main/java/cct/amber/openFile.png b/src/main/java/cct/amber/openFile.png new file mode 100644 index 0000000..d4f742a Binary files /dev/null and b/src/main/java/cct/amber/openFile.png differ diff --git a/src/main/java/cct/amber/package.html b/src/main/java/cct/amber/package.html new file mode 100644 index 0000000..e205c41 --- /dev/null +++ b/src/main/java/cct/amber/package.html @@ -0,0 +1,24 @@ + + + + + + +

Package Specification

+Contains miscellaneous utility classes for work with Amber + + + +

Related Documentation

+ + + + + diff --git a/src/main/java/cct/amber/sander9VarDescr.properties b/src/main/java/cct/amber/sander9VarDescr.properties new file mode 100644 index 0000000..67950f5 --- /dev/null +++ b/src/main/java/cct/amber/sander9VarDescr.properties @@ -0,0 +1,7 @@ + + +IFQNT = Flag for QM/MM run; if set to 1, you must also include a &qmmm namelist. See Section 6.4 for details on this option. Default is 0. + +IEVB = If set to 1, use the empirical valence bond method to compute energies and forces. See Section 6.3 of Amber9 Manual for information about this option. Default is 0. + +IAMOEBA = Flag for using the amoeba polarizable potentials of Ren and Ponder. When this option is set to 1, you need to prepare an amoeba namelist with additional parameters. Also, the prmtop file is built in a special way. See Section 6.14 of Amber9 Manual for more information about this option. Default is 0. diff --git a/src/main/java/cct/amber/sander9cntrl.properties b/src/main/java/cct/amber/sander9cntrl.properties new file mode 100644 index 0000000..2b462b1 --- /dev/null +++ b/src/main/java/cct/amber/sander9cntrl.properties @@ -0,0 +1,139 @@ + +irest= +ibelly= +ntx= +ntxo= +ntcx= +ig= +tempi= +ntb= +ntt= +temp0= +tautp= +ntp= +pres0= +comp= +taup= +nscm= +nstlim= +t= +dt= +ntc= +ntcc= +nconp= +tol= +ntf= +ntn= +nsnb= +cut= +scnb= +scee= +dielc= +ntpr= +ntwx= +ntwv= +ntwe= +ntave= +ntpp= +ioutfm= +ntr= +nrc= +ntrx= +taur= +nmropt= +ivcap= +fcap= +imin= +drms= +dele= +dx0= +pencut= +ipnlty= +iscale= +scalm= +noeskp= +maxcyc= +ncyc= +ntmin= +vlimit= +mxsub= +ipol= +jfastw= +watnam= +owtnm= +hwtnm1= +hwtnm2= +iesp= +skmin= +skmax= +vv= +vfac= +tmode= +ips= +isgld= +isgsta= +isgend= +tsgavg= +sgft= +tempsg= +jar= +iamoeba= +numexchg= +repcrd= +numwatkeep= +ntwprt= +tausw= +ntwr= +iyammp= +imcdo= +igb= +alpb= +Arad= +rgbmax= +saltcon= +offset= +gbsa= +vrand= +surften= +iwrap= +nrespa= +nrespai= +gamma_ln= +extdiel= +intdiel= +cut_inner= +icfe= +clambda= +klambda= +rbornstat= +lastrst= +lastist= +itgtmd= +tgtrmsd= +tgtmdfrc= +tgtfitmask= +tgtrmsmask= +idecomp= +temp0les= +restraintmask= +restraint_wt= +bellymask= +noshakemask= +mmtsb_switch= +mmtsb_iterations= +rdt= +icnstph= +solvph= +ntcnstph= +ifqnt= +ievb= + + +pimd_runtype = pimd +pimd_use_original_mass = pimd +ineb = pimd + +dtemp = obsolete +dxm = obsolete +heat = obsolete +timlim = obsolete diff --git a/src/main/java/cct/applets/JamberooApplet.java b/src/main/java/cct/applets/JamberooApplet.java new file mode 100644 index 0000000..dcfc9bd --- /dev/null +++ b/src/main/java/cct/applets/JamberooApplet.java @@ -0,0 +1,397 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.applets; + +import java.applet.Applet; +import java.awt.BorderLayout; +import java.awt.Button; +import java.awt.Color; +import java.awt.FlowLayout; +import java.awt.Graphics; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.Panel; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import cct.dialogs.JamberooCore; +import cct.dialogs.MainPopupMenu; +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; +import cct.interfaces.MoleculeInterface; +import cct.j3d.Java3dUniverse; +import cct.modelling.MolecularDataWizard; +import cct.modelling.Molecule; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.URL; +import javax.swing.JOptionPane; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +//************************************************************** +public class JamberooApplet + extends Applet implements MouseListener, + MouseMotionListener, ActionListener { + + boolean isStandalone = false; + BorderLayout borderLayout1 = new BorderLayout(); + //SampleFrame f; + String msg = ""; + int mouseX = 0, mouseY = 10; + int movX = 0, movY = 0; + int tempInt; + Java3dUniverse Java3dUniverse; + Button Numbers = null; + static String labelAtomicNumbers = "Atomic Numbers"; + static String unlabelAtoms = "Unlabel Atoms"; + JamberooCore jamberooCore = new JamberooCore(); + static final Logger logger = Logger.getLogger(JamberooApplet.class.getCanonicalName()); + + //Get a parameter value + public String getParameter(String key, String def) { + return isStandalone ? System.getProperty(key, def) + : (getParameter(key) != null ? getParameter(key) : def); + } + + //Construct the applet + public JamberooApplet() { + } + + //Initialize the applet + @Override + public void init() { + try { + Init(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + //Component initialization + private void Init() throws Exception { + + + //f = new SampleFrame("Molecular Builder"); + //f.setSize(800, 600); + //f.setVisible(true); + + //repaint(); + + // register this object to receive its own mouse events + //addMouseListener(this); + //addMouseMotionListener(this); + + setBackground(Color.DARK_GRAY); + + GridBagLayout gridbag = new GridBagLayout(); + setLayout(gridbag); + + GridBagConstraints c = new GridBagConstraints(); + c.gridx = 0; + c.gridy = 0; + c.gridwidth = 10; + c.gridheight = 10; + c.weightx = 1; + c.weighty = 1; + c.fill = GridBagConstraints.BOTH; + c.insets = new Insets(1, 1, 1, 1); + + Java3dUniverse = jamberooCore.getJamberooRenderer(); + + MainPopupMenu mainPopup = new MainPopupMenu(jamberooCore); + mainPopup.createPopupMenu(); + + add(Java3dUniverse.getCanvas3D()); + + gridbag.setConstraints(Java3dUniverse.getCanvas3D(), c); + + c = new GridBagConstraints(); + c.gridx = 0; + c.gridy = 11; + c.gridwidth = 10; + c.gridheight = 1; + //c.weightx = 1; + //c.weighty = 1; + c.fill = GridBagConstraints.BOTH; + c.insets = new Insets(1, 1, 1, 1); + + Panel pControls = new Panel(new FlowLayout()); + pControls.setBackground(Color.BLACK); + pControls.setBackground(Color.DARK_GRAY); + add(pControls); + gridbag.setConstraints(pControls, c); + + /* + Numbers = new Button(labelAtomicNumbers); + Numbers.addActionListener(this); + pControls.add(Numbers); + + Button unLabel = new Button(unlabelAtoms); + unLabel.addActionListener(this); + pControls.add(unLabel); + * + */ + this.validate(); + + MoleculeInterface mol = new Molecule(); + mol.addMonomer("Molecule"); + + + // --- Parse input parameters + + String key, format, value = getParameter("natoms"); + if (value != null) { + logger.info("Natoms: " + value); + + AtomInterface atom = null; + StringTokenizer st; + float xyz[] = new float[3]; + + int nat = Integer.parseInt(value); + for (int i = 0; i < nat; i++) { + String param = "a" + i; + value = getParameter(param); + logger.info(param + ": " + value); + st = new StringTokenizer(value, ","); + int element = Integer.parseInt(st.nextToken()); + String name = st.nextToken(); // Skip for now + for (int j = 0; j < 3; j++) { + xyz[j] = Float.parseFloat(st.nextToken()); + } + + atom = mol.getNewAtomInstance(); + atom.setXYZ(xyz[0], xyz[1], xyz[2]); + atom.setAtomicNumber(element); + atom.setName(name); + + mol.addAtom(atom); + } + + value = getParameter("nbonds"); + if (value != null) { + logger.info("Nbonds: " + value); + nat = Integer.parseInt(value); + } else { + nat = 0; + } + + for (int i = 0; i < nat; i++) { + String param = "b" + i; + value = getParameter(param); + logger.info(param + ": " + value); + st = new StringTokenizer(value, ","); + int origin = Integer.parseInt(st.nextToken()); + int target = Integer.parseInt(st.nextToken()); + BondInterface bond = mol.getNewBondInstance(mol.getAtomInterface(origin), mol.getAtomInterface(target)); + //Bond b = mol.addBondBetweenAtoms(origin, target); + logger.info("Bond: " + (i + 1) + " origin: " + origin + " target: " + target); + mol.addBond(bond); + } + Java3dUniverse.setMolecule(mol); + + } else if ((value = getParameter("file")) != null) { + format = getParameter("format"); + URL baseURL; + try { + baseURL = new URL(this.getCodeBase(), value); + BufferedReader in = new BufferedReader(new InputStreamReader(baseURL.openStream())); + //CHEMISTRY_FILE_FORMAT form = CHEMISTRY_FILE_FORMAT.valueOf(format.toUpperCase()); + //if (form == null) { + // throw new Exception("Unknown format " + format); + //} + MolecularDataWizard wizard = new MolecularDataWizard(); + wizard.parseMolecularData(format, in); + if (wizard.getNumberMolecules() > 0) { + Java3dUniverse.setMolecule(wizard.getMolecule()); + } else { + throw new Exception("Din't find atoms in file " + value); + } + } catch (Exception ex) { + String error = "Error opening URL: " + getCodeBase().toString() + value + " : " + ex.getMessage(); + logger.severe(error); + JOptionPane.showMessageDialog(this, error, "Error", JOptionPane.ERROR_MESSAGE); + } + } + + + } + + //Start the applet + + /* + public void start() { + //f.setVisible(true); + repaint(); + } + + + //Stop the applet + public void stop() { + //f.setVisible(false); + } + */ + @Override + public void paint(Graphics g) { + //g.drawString(msg, mouseX, mouseY); + //g.drawString("Mouse at " + movX + ", " + movY, 0, 10); + //if (molec != null) { + // g.drawString("Number of atoms " + molec.getNumberOfAtoms(), 0, 20); + //} else { + // g.drawString("Molecule pointer is NULL", 0, 20); + //} + } + + // Handle mouse clicked. + @Override + public void mouseClicked(MouseEvent me) { + } + + // Handle mouse entered. + @Override + public void mouseEntered(MouseEvent me) { + // save coordinates + mouseX = 0; + mouseY = 24; + msg = "Mouse just entered applet window."; + //repaint(); + } + + // Handle mouse exited. + @Override + public void mouseExited(MouseEvent me) { + // save coordinates + mouseX = 0; + mouseY = 24; + msg = "Mouse just left applet window."; + //repaint(); + } + + // Handle button pressed. + @Override + public void mousePressed(MouseEvent me) { + // save coordinates + mouseX = me.getX(); + mouseY = me.getY(); + msg = "Down"; + //repaint(); + } + + // Handle button released. + @Override + public void mouseReleased(MouseEvent me) { + // save coordinates + mouseX = me.getX(); + mouseY = me.getY(); + msg = "Up"; + //repaint(); + } + + // Handle mouse dragged. + @Override + public void mouseDragged(MouseEvent me) { + // save coordinates + mouseX = me.getX(); + mouseY = me.getY(); + movX = me.getX(); + movY = me.getY(); + msg = "*"; + //repaint(); + } + + // Handle mouse moved. + @Override + public void mouseMoved(MouseEvent me) { + // save coordinates + movX = me.getX(); + movY = me.getY(); + //repaint(0, 0, 100, 20); + } + + //Destroy the applet + @Override + public void destroy() { + } + + //Get Applet information + @Override + public String getAppletInfo() { + return "Jamberoo Applet"; + } + + //Get parameter info + @Override + public String[][] getParameterInfo() { + return null; + } + + @Override + public void actionPerformed(ActionEvent ae) { + String controlName = ae.getSource().toString(); + controlName = controlName.substring(controlName.indexOf('[') + 1); + controlName = controlName.substring(0, controlName.indexOf(',')); + logger.info("controlName: " + controlName); + + // --- Molecule name is changed + if (ae.getActionCommand().toString().equals(labelAtomicNumbers)) { + Java3dUniverse.selectAllAtoms(true); + Java3dUniverse.labelSelectedAtoms("Atom number"); + Java3dUniverse.selectAllAtoms(false); + + } else if (ae.getActionCommand().toString().equals(unlabelAtoms)) { + Java3dUniverse.selectAllAtoms(true); + Java3dUniverse.unlabelSelectedAtoms(); + Java3dUniverse.selectAllAtoms(false); + } + } +} diff --git a/src/main/java/cct/awtdialogs/AddNewMethodDialog.java b/src/main/java/cct/awtdialogs/AddNewMethodDialog.java new file mode 100644 index 0000000..a3abf05 --- /dev/null +++ b/src/main/java/cct/awtdialogs/AddNewMethodDialog.java @@ -0,0 +1,416 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.awtdialogs; + +import java.awt.Button; +import java.awt.Checkbox; +import java.awt.Choice; +import java.awt.Dialog; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.Label; +import java.awt.Panel; +import java.awt.TextArea; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.util.logging.Logger; + +import cct.database.new_SQLChemistryDatabase; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class AddNewMethodDialog + extends Dialog implements ActionListener, + ItemListener, KeyListener { + + TextField final_name = null; + TextField name = null; + TextField custom_basis = null; + TextArea Notes = null; + static String bs_control = "Basis Set"; + Choice method = null, basisSets = null; + Checkbox Exp = null, fixedBasis = null, EffectiveCorepot = null; + Checkbox isDFT = null; + new_SQLChemistryDatabase database = null; + boolean OK_pressed = false; + boolean addedSuccessfully = false; + static final Logger logger = Logger.getLogger(AddNewMethodDialog.class.getCanonicalName()); + + public AddNewMethodDialog(String Title, boolean modal, + new_SQLChemistryDatabase db) { + super(new Frame(), Title, modal); + this.database = db; + //FlowLayout sizer = new FlowLayout( FlowLayout.CENTER); + //GridLayout sizer = new GridLayout(0, 2, 5, 5); + GridBagLayout sizer = new GridBagLayout(); + GridBagConstraints c = new GridBagConstraints(); + setLayout(sizer); + + c.gridx = 0; + c.gridy = 0; + c.gridwidth = 1; + c.gridheight = 1; + //c.weightx = 1; + //c.weighty = 1; + c.fill = GridBagConstraints.BOTH; + c.insets = new Insets(3, 3, 3, 3); + Label mol_name = new Label("Final Name: ", Label.LEFT); + sizer.setConstraints(mol_name, c); + add(mol_name); + + c.gridx += c.gridwidth; + c.gridwidth = 5; + c.weightx = 1; + final_name = new TextField(60); + final_name.setEditable(false); + sizer.setConstraints(final_name, c); + add(final_name); + + // Next row + + c.weightx = 0; + c.gridx = 0; // Reset + c.gridwidth = 1; + c.gridy += c.gridheight; + + Label m_name = new Label("Name: ", Label.LEFT); + sizer.setConstraints(m_name, c); + add(m_name); + + c.weightx = 1; + c.gridx += c.gridwidth; + //c.gridwidth = 5; + + name = new TextField(60); + name.addActionListener(this); + name.addKeyListener(this); + //name.setEditable(false); + sizer.setConstraints(name, c); + add(name); + + // Next row + + c.gridx = 0; + c.gridy += c.gridheight; + c.weightx = 0; + c.gridwidth = 2; + + Exp = new Checkbox("Experiment", true); + Exp.addItemListener(this); + sizer.setConstraints(Exp, c); + add(Exp); + + // Next row + + c.gridx = 0; + c.gridy += c.gridheight; + c.weightx = 0; + c.gridwidth = 2; + + isDFT = new Checkbox("Density Function", false); + if (Exp.getState()) { + isDFT.setEnabled(false); + } + isDFT.addItemListener(this); + sizer.setConstraints(isDFT, c); + add(isDFT); + + // Next row + + c.gridy += c.gridheight; + c.weightx = 0; + c.gridwidth = 2; + + fixedBasis = new Checkbox("Fixed Basis Set", false); + if (Exp.getState()) { + fixedBasis.setEnabled(false); + } + fixedBasis.addItemListener(this); + sizer.setConstraints(fixedBasis, c); + add(fixedBasis); + + // Next row + + c.gridy += c.gridheight; + c.weightx = 0; + c.gridwidth = 2; + + EffectiveCorepot = new Checkbox("Effective Core Potential", false); + if (Exp.getState()) { + EffectiveCorepot.setEnabled(false); + } + EffectiveCorepot.addItemListener(this); + sizer.setConstraints(EffectiveCorepot, c); + add(EffectiveCorepot); + + // Next row + + c.gridy += c.gridheight; + c.weightx = 0; + c.gridwidth = 1; + + Label bset = new Label("Basis Set:", Label.LEFT); + sizer.setConstraints(bset, c); + add(bset); + + c.gridx += c.gridwidth; + c.gridwidth = 1; + c.weightx = 0; + basisSets = new Choice(); + basisSets.setName(bs_control); + String[] available_bs = database.getAvailableBasisSets(); + if (available_bs != null) { + for (int i = 0; i < available_bs.length; i++) { + basisSets.add(available_bs[i]); + } + if (available_bs.length > 0) { + basisSets.select(0); + } + } + if (Exp.getState() || fixedBasis.getState()) { + basisSets.setEnabled(false); + } + basisSets.addItemListener(this); + sizer.setConstraints(basisSets, c); + add(basisSets); + + c.gridx += c.gridwidth; + Label custom_l = new Label("Custom:", Label.LEFT); + sizer.setConstraints(custom_l, c); + add(custom_l); + + c.gridx += c.gridwidth; + custom_basis = new TextField(" "); + custom_basis.addActionListener(this); + custom_basis.addKeyListener(this); + sizer.setConstraints(custom_basis, c); + add(custom_basis); + if (Exp.getState() || fixedBasis.getState()) { + custom_basis.setEnabled(false); + } + + // Next row + + c.weightx = 0; + c.gridx = 0; // Reset + c.gridwidth = 2; + c.gridy += c.gridheight; + + Label notes_l = new Label("Description: ", Label.LEFT); + sizer.setConstraints(notes_l, c); + add(notes_l); + + // Next row + + c.weightx = 1; + c.gridx = 0; + c.gridy += c.gridheight; + c.gridwidth = 6; + c.gridheight = 3; + + Notes = new TextArea(3, 60); + sizer.setConstraints(Notes, c); + add(Notes); + + // Next row + + c.gridx = 0; + c.gridy += c.gridheight; + c.gridwidth = 6; + c.gridheight = 1; + c.weightx = 0; + + Panel p = new Panel(); + p.setLayout(new FlowLayout()); + + Button OK = new Button("OK"); + p.add(OK); + OK.addActionListener(this); + + Button Cancel = new Button("Cancel"); + p.add(Cancel); + Cancel.addActionListener(this); + sizer.setConstraints(p, c); + add(p); + + setSize(500, 400); + + } + + /** Handle the key pressed event from the text field. */ + @Override + public void keyPressed(KeyEvent e) { + //displayInfo(e, "KEY PRESSED: "); + } + + /** Handle the key released event from the text field. */ + @Override + public void keyReleased(KeyEvent e) { + //displayInfo(e, "KEY RELEASED: "); + String temp = name.getText(); + if (basisSets.isEnabled()) { + //temp += "/" + basisSets.getSelectedItem(); + temp += "/" + custom_basis.getText(); + } + final_name.setText(temp); + + } + + @Override + public void keyTyped(KeyEvent e) { + } + + @Override + public void itemStateChanged(ItemEvent ie) { + String controlName = ie.getItemSelectable().toString(); + controlName = controlName.substring(controlName.indexOf('[') + 1); + controlName = controlName.substring(0, controlName.indexOf(',')); + + logger.info("Item: " + ie.getItem()); + logger.info("Item Selectable: " + ie.getItemSelectable()); + logger.info("ControlName: " + controlName); + + if (ie.getItem().equals("Experiment")) { + if (Exp.getState()) { // Enabled + fixedBasis.setEnabled(false); + basisSets.setEnabled(false); + custom_basis.setEnabled(false); + EffectiveCorepot.setEnabled(false); + isDFT.setEnabled(false); + final_name.setText(name.getText()); + } else { + processFixedBasisCheckbox(); + fixedBasis.setEnabled(true); + isDFT.setEnabled(true); + } + + } else if (ie.getItem().equals("Fixed Basis Set")) { + processFixedBasisCheckbox(); + } else if (controlName.equals(bs_control)) { + processBasisSetChoice(ie.getItem().toString()); + } + + } + + void processBasisSetChoice(String item) { + custom_basis.setText(item); + String f_name = name.getText(); + if (item.trim().length() == 0 || item.equals("No Basis Set")) { + final_name.setText(f_name); + } else { + f_name += "/" + custom_basis.getText(); + final_name.setText(f_name); + } + } + + void processFixedBasisCheckbox() { + if (fixedBasis.getState()) { + basisSets.setEnabled(false); + custom_basis.setEnabled(false); + EffectiveCorepot.setEnabled(false); + final_name.setText(name.getText()); + } else { + basisSets.setEnabled(true); + custom_basis.setEnabled(true); + EffectiveCorepot.setEnabled(true); + final_name.setText(name.getText() + "/" + custom_basis.getText()); + } + } + + /** + * + * @param ae ActionEvent + */ + @Override + public void actionPerformed(ActionEvent ae) { + String controlName = ae.getSource().toString(); + controlName = controlName.substring(controlName.indexOf('[') + 1); + controlName = controlName.substring(0, controlName.indexOf(',')); + logger.info("controlName: " + controlName); + + // --- Molecule name is changed + if (ae.getActionCommand().toString().equals("OK")) { + addedSuccessfully = database.addNewMethod( final_name.getText(), Notes.getText(), + Exp.getState(), + fixedBasis.getState(), isDFT.getState(), + EffectiveCorepot.getState() ); + OK_pressed = true; + setVisible(false); + } else if (ae.getActionCommand().toString().equals("Cancel")) { + OK_pressed = false; + setVisible(false); + } + } + + public boolean isOKPressed() { + return OK_pressed; + } + + public boolean isEddedSuccessfully() { + return addedSuccessfully; + } + + /** + * + * @return String + */ + public String getNewMethod() { + String str = final_name.getText(); + if (str.length() < 1) { + return null; + } + return str; + } +} diff --git a/src/main/java/cct/awtdialogs/AddNewMoleculeDialog.java b/src/main/java/cct/awtdialogs/AddNewMoleculeDialog.java new file mode 100644 index 0000000..49da9b6 --- /dev/null +++ b/src/main/java/cct/awtdialogs/AddNewMoleculeDialog.java @@ -0,0 +1,418 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.awtdialogs; + +import java.awt.Button; +import java.awt.Checkbox; +import java.awt.Choice; +import java.awt.Dialog; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.Label; +import java.awt.Panel; +import java.awt.TextArea; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.logging.Logger; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class AddNewMoleculeDialog + extends Dialog implements ActionListener, ItemListener { + TextArea aliases = null; + TextArea notes = null; + TextArea keywords = null; + Checkbox isModel = null; + Choice Charge = null, Mult = null; + Label name = null; + boolean OK_pressed = false; + static final Logger logger = Logger.getLogger(AddNewMoleculeDialog.class.getCanonicalName()); + + public AddNewMoleculeDialog(String Title, boolean modal, + String molName) { + super(new Frame(), Title, modal); + + //FlowLayout sizer = new FlowLayout( FlowLayout.CENTER); + //GridLayout sizer = new GridLayout(0, 1, 3, 3); + Panel p; + GridBagLayout sizer = new GridBagLayout(); + GridBagConstraints c = new GridBagConstraints(); + setLayout(sizer); + + c.gridx = 0; + c.gridy = 0; + c.gridwidth = 1; + c.gridheight = 1; + //c.weightx = 1; + //c.weighty = 1; + c.fill = GridBagConstraints.BOTH; + c.insets = new Insets(3, 3, 3, 3); + + name = new Label("Name: " + molName, Label.LEFT); + sizer.setConstraints(name, c); + add(name); + + // --- Charge, Multiplicity etc + + p = new Panel(); + p.setLayout(new FlowLayout(FlowLayout.LEADING)); + + isModel = new Checkbox("Model", false); + isModel.addItemListener(this); + p.add(isModel); + + p.add(new Label(" Charge: ", Label.LEFT)); + Charge = new Choice(); + Charge.setName("charge"); + for (int i = -10, j = 0; i <= 10; i++, j++) { + Charge.add(String.valueOf(i)); + if (i == 0) { + Charge.select(j); + } + } + Charge.addItemListener(this); + p.add(Charge); + + p.add(new Label(" Multiplicity: ", Label.LEFT)); + Mult = new Choice(); + Mult.setName("mult"); + for (int i = 1; i <= 5; i++) { + Mult.add(String.valueOf(i)); + } + Mult.select(0); + Mult.addItemListener(this); + p.add(Mult); + + if (isModel.getState()) { + Charge.setEnabled(false); + Mult.setEnabled(false); + } + + c.gridx = 0; + c.gridy += c.gridheight; + c.gridwidth = 6; + c.gridheight = 1; + sizer.setConstraints(p, c); + add(p); + + // --- Add aliases + + c.weightx = 0.0; //reset to the default + c.gridy += c.gridheight; + c.gridheight = 1; + Label alias = new Label("Aliases (max 255 chars):", Label.LEFT); + sizer.setConstraints(alias, c); + add(alias); + + c.gridx = 0; + c.gridy += c.gridheight; + c.gridwidth = 6; + c.gridheight = 3; + c.ipadx = 20; + aliases = new TextArea(3, 60); + sizer.setConstraints(aliases, c); + add(aliases); + //aliases.addActionListener(this); + + c.gridx = 0; + c.gridy += c.gridheight; + c.gridwidth = 1; + c.gridheight = 1; + c.weightx = 0.0; //reset to the default + Label keyw = new Label("Keywords (max 255 chars):", Label.LEFT); + sizer.setConstraints(keyw, c); + add(keyw); + + c.gridx = 0; + c.gridy += c.gridheight; + c.gridwidth = 6; + c.gridheight = 3; + aliases = new TextArea(3, 60); + sizer.setConstraints(aliases, c); + add(aliases); + //aliases.addActionListener(this); + + + c.gridx = 0; + c.gridy += c.gridheight; + c.gridwidth = 1; + c.gridheight = 1; + + Label note = new Label("Notes:", Label.LEFT); + sizer.setConstraints(note, c); + add(note); + + c.gridx = 0; + c.gridy += c.gridheight; + c.gridwidth = 6; + c.gridheight = 4; + notes = new TextArea(4, 60); + sizer.setConstraints(notes, c); + add(notes); + + p = new Panel(); + p.setLayout(new FlowLayout()); + + Button OK = new Button("OK"); + p.add(OK); + OK.addActionListener(this); + + Button Cancel = new Button("Cancel"); + p.add(Cancel); + Cancel.addActionListener(this); + + c.gridx = 0; + c.gridy += c.gridheight; + c.gridwidth = 6; + c.gridheight = 1; + sizer.setConstraints(p, c); + add(p); + + setSize(500, 450); + + } + + @Override + public void itemStateChanged(ItemEvent ie) { + String controlName = ie.getItemSelectable().toString(); + controlName = controlName.substring(controlName.indexOf('[') + 1); + controlName = controlName.substring(0, controlName.indexOf(',')); + + logger.info("Item: " + ie.getItem()); + logger.info("Item Selectable: " + ie.getItemSelectable()); + logger.info("ControlName: " + controlName); + + if (ie.getItem().equals("Model")) { + if (isModel.getState()) { + Charge.setEnabled(false); + Mult.setEnabled(false); + } + else { + Charge.setEnabled(true); + Mult.setEnabled(true); + } + } + /* + else if (controlName.equals(bs_control)) { + + } + */ + + } + + @Override + public void actionPerformed(ActionEvent ae) { + String controlName = ae.getSource().toString(); + controlName = controlName.substring(controlName.indexOf('[') + 1); + controlName = controlName.substring(0, controlName.indexOf(',')); + logger.info("controlName: " + controlName); + + // --- Molecule name is changed + if (controlName.equals("Enter molname")) { + + } + else if (ae.getActionCommand().toString().equals("OK")) { + OK_pressed = true; + setVisible(false); + //dispose(); + } + else if (ae.getActionCommand().toString().equals("Cancel")) { + OK_pressed = false; + setVisible(false); + //dispose(); + } + } + + public boolean isOKPressed() { + return OK_pressed; + } + + public boolean isModel() { + return isModel.getState(); + } + + public int getCharge() { + return Integer.parseInt(Charge.getSelectedItem()); + } + + public int getMultiplicity() { + return Integer.parseInt(Mult.getSelectedItem()); + } + + /** + * + * @return String + */ + public String getAliases() { + String str = aliases.getText(); + if (str.length() < 1) { + return null; + } + return str; + } + + /** + * + * @return String + */ + public String getNotes() { + String str = notes.getText(); + if (str.length() < 1) { + return null; + } + return str; + } + + /** + * + * @return String + */ + public String getKeywords() { + String str = keywords.getText(); + if (str.length() < 1) { + return null; + } + return str; + } + + /** + * + * @param value String + */ + public void setAliases(String value) { + if (value == null || value.length() < 1) { + return; + } + if (aliases == null) { + aliases = new TextArea(3, 60); + } + aliases.setText(value); + } + + /** + * + * @param value String + */ + public void setNotes(String value) { + if (value == null || value.length() < 1) { + return; + } + if (notes == null) { + notes = new TextArea(3, 60); + } + notes.setText(value); + } + + /** + * + * @param value String + */ + public void setKeywords(String value) { + if (value == null || value.length() < 1) { + return; + } + if (keywords == null) { + keywords = new TextArea(4, 60); + } + keywords.setText(value); + } + + @Override + public void setName(String value) { + if (value == null || value.length() < 1) { + return; + } + if (name == null) { + name = new Label("Name: " + value, Label.LEFT); + } + name.setText("Name: " + value); + } + + public void setCharge(int charge) { + int start_charge = Integer.parseInt(Charge.getItem(0)); + int end_charge = Integer.parseInt(Charge.getItem(Charge.getItemCount() - 1)); + String ch = String.valueOf(charge); + + //logger.info("Charge="+charge+" ch="+ch+" start: "+start_charge+" end: "+end_charge); + + if (charge < start_charge) { + Charge.insert(ch, 0); + } + else if (charge > end_charge) { + Charge.add(ch); + } + + Charge.select(ch); + + } + + public void setMultiplicity(int mult) { + + if (mult < 1) { + return; + } + + int start_mult = Integer.parseInt(Mult.getItem(0)); + int end_mult = Integer.parseInt(Mult.getItem(Mult.getItemCount() - 1)); + String m = String.valueOf(mult); + + if (mult < start_mult) { + Mult.insert(m, 0); + } + else if (mult > end_mult) { + Mult.add(m); + } + Mult.select(m); + } + +} diff --git a/src/main/java/cct/awtdialogs/AddNewStructureDialog.java b/src/main/java/cct/awtdialogs/AddNewStructureDialog.java new file mode 100644 index 0000000..45784f3 --- /dev/null +++ b/src/main/java/cct/awtdialogs/AddNewStructureDialog.java @@ -0,0 +1,288 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.awtdialogs; + +import java.awt.Button; +import java.awt.Choice; +import java.awt.Dialog; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.Label; +import java.awt.Panel; +import java.awt.TextArea; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.logging.Logger; + +import cct.database.new_SQLChemistryDatabase; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class AddNewStructureDialog + extends Dialog implements ActionListener { + TextField name = null; + TextArea notes = null; + Choice method = null; + new_SQLChemistryDatabase database = null; + AddNewMethodDialog addMethod = null; + boolean OK_pressed = false; + static final Logger logger = Logger.getLogger(AddNewStructureDialog.class.getCanonicalName()); + + public AddNewStructureDialog(String Title, boolean modal, + String molName, new_SQLChemistryDatabase db) { + super(new Frame(), Title, modal); + + this.database = db; + //FlowLayout sizer = new FlowLayout( FlowLayout.CENTER); + //GridLayout sizer = new GridLayout(0, 2, 5, 5); + GridBagLayout sizer = new GridBagLayout(); + GridBagConstraints c = new GridBagConstraints(); + setLayout(sizer); + + c.gridx = 0; + c.gridy = 0; + c.gridwidth = 1; + c.gridheight = 1; + //c.weightx = 1; + //c.weighty = 1; + c.fill = GridBagConstraints.BOTH; + c.insets = new Insets(3, 3, 3, 3); + Label mol_name = new Label("Molecule: " + molName, Label.LEFT); + sizer.setConstraints(mol_name, c); + add(mol_name); + + c.gridy += c.gridheight; + Label str_name = new Label("Structure Name:", Label.LEFT); + sizer.setConstraints(str_name, c); + add(str_name); + + c.gridy += c.gridheight; + c.gridwidth = 6; + name = new TextField(60); + sizer.setConstraints(name, c); + add(name); + + c.gridy += c.gridheight; + c.gridwidth = 1; + Label method_l = new Label("Method:", Label.LEFT); + sizer.setConstraints(method_l, c); + add(method_l); + + c.gridx += c.gridwidth; + c.gridwidth = 4; + c.weightx = 1.0; + method = new Choice(); + //method.add(" "); + String[] available_methods = database.getAvailableMethods(); + for (int i = 0; i < available_methods.length; i++) { + method.add(available_methods[i]); + } + if (available_methods.length > 0) { + method.select(0); + } + sizer.setConstraints(method, c); + add(method); + + c.gridx += c.gridwidth; + c.gridwidth = 1; + c.weightx = 0; + Button new_method = new Button("New Method"); + sizer.setConstraints(new_method, c); + add(new_method); + new_method.addActionListener(this); + + c.gridx = 0; // reset + c.gridy += c.gridheight; + c.gridwidth = 1; + Label note = new Label("Notes:", Label.LEFT); + sizer.setConstraints(note, c); + add(note); + + c.gridy += c.gridheight; + c.gridwidth = 6; + c.gridheight = 4; + notes = new TextArea(4, 60); + sizer.setConstraints(notes, c); + add(notes); + + c.gridy += c.gridheight; + c.gridwidth = 6; + c.gridheight = 1; + + Panel p = new Panel(); + p.setLayout(new FlowLayout()); + + Button OK = new Button("OK"); + p.add(OK); + OK.addActionListener(this); + + Button Cancel = new Button("Cancel"); + p.add(Cancel); + Cancel.addActionListener(this); + sizer.setConstraints(p, c); + add(p); + + setSize(500, 400); + + } + + @Override + public void actionPerformed(ActionEvent ae) { + String controlName = ae.getSource().toString(); + controlName = controlName.substring(controlName.indexOf('[') + 1); + controlName = controlName.substring(0, controlName.indexOf(',')); + logger.info("controlName: " + controlName); + + // --- Molecule name is changed + if (controlName.equals("Enter molname")) { + + } + else if (ae.getActionCommand().toString().equals("OK")) { + OK_pressed = true; + setVisible(false); + //dispose(); + } + else if (ae.getActionCommand().toString().equals("Cancel")) { + OK_pressed = false; + setVisible(false); + //dispose(); + } + else if (ae.getActionCommand().toString().equals("New Method")) { + if (addMethod == null) { + addMethod = new AddNewMethodDialog("Define New Method", true, + database); + } + addMethod.setVisible(true); + if (addMethod.isOKPressed() && addMethod.isEddedSuccessfully()) { + String new_method = addMethod.getNewMethod(); + method.removeAll(); + String[] available_methods = database.getAvailableMethods(); + for (int i = 0; i < available_methods.length; i++) { + method.add(available_methods[i]); + } + method.select(new_method); + } + + } + } + + public boolean isOKPressed() { + return OK_pressed; + } + + /** + * + * @return String + */ + @Override + public String getName() { + String str = name.getText(); + if (str.length() < 1) { + return null; + } + return str; + } + + /** + * + * @return String + */ + public String getMethod() { + String str = method.getSelectedItem(); + if (str.length() < 1) { + return null; + } + return str; + } + + /** + * + * @return String + */ + public String getNotes() { + String str = notes.getText(); + if (str.length() < 1) { + return null; + } + return str; + } + + /** + * + * @param value String + */ + @Override + public void setName(String value) { + if (value == null || value.length() < 1) { + return; + } + if (name == null) { + name = new TextField(); + } + name.setText(value); + } + + /** + * + * @param value String + */ + public void setNotes(String value) { + if (value == null || value.length() < 1) { + return; + } + if (notes == null) { + notes = new TextArea(3, 30); + } + notes.setText(value); + } + +} diff --git a/src/main/java/cct/awtdialogs/AtomLabelsDialog.java b/src/main/java/cct/awtdialogs/AtomLabelsDialog.java new file mode 100644 index 0000000..eff62af --- /dev/null +++ b/src/main/java/cct/awtdialogs/AtomLabelsDialog.java @@ -0,0 +1,165 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.awtdialogs; + +import java.awt.Button; +import java.awt.Dialog; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.Panel; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.logging.Logger; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class AtomLabelsDialog + extends Dialog implements ActionListener, ItemListener { + java.awt.List Properties = null; + Button OK, Cancel; + boolean OKpressed = false; + static final Logger logger = Logger.getLogger(AtomLabelsDialog.class.getCanonicalName()); + + public AtomLabelsDialog(Frame parent, String Title, java.util.List atomProperties, + boolean modal) { + super(parent, Title, modal); + + FlowLayout sizer = new FlowLayout(FlowLayout.CENTER); + //GridLayout sizer = new GridLayout( 0, 2, 5 ,5 ); + //GridLayout sizer = new GridLayout(0,1,3,3); + setLayout(sizer); + + Panel P = new Panel(); + P.setLayout(new FlowLayout()); + + Properties = new java.awt.List(5); + + for (int i = 0; i < atomProperties.size(); i++) { + Properties.add(atomProperties.get(i).toString()); + } + if (Properties.getItemCount() > 0) { + Properties.select(0); + } + P.add(Properties); + add(P); + + OK = new Button("OK"); + Cancel = new Button("Cancel"); + + P = new Panel(); + P.setLayout(new FlowLayout()); + P.add(OK); + //OK.setVisible(true); + P.add(Cancel); + add(P); + + OK.addActionListener(this); + Cancel.addActionListener(this); + + setSize(300, 200); + } + + public void setProperties(java.util.List atomProperties) { + + String selected = Properties.getSelectedItem(); + int newSelection = 0; + + Properties.removeAll(); + + for (int i = 0; i < atomProperties.size(); i++) { + Properties.add(atomProperties.get(i).toString()); + if (selected.equals(atomProperties.get(i).toString())) { + newSelection = i; + } + } + + if (Properties.getItemCount() > 0) { + Properties.select(newSelection); + } + + } + + @Override + public void actionPerformed(ActionEvent ae) { + String arg = ae.getActionCommand(); + if (arg.equals("OK")) { + OKpressed = true; + //dispose(); + setVisible(false); + } + else if (arg.equals("Cancel")) { + OKpressed = false; + //dispose(); + setVisible(false); + } + + else { + logger.info("Event: " + arg); + } + } + + @Override + public void itemStateChanged(ItemEvent ie) { + repaint(); + } + + public int getSelectedIndex() { + return Properties.getSelectedIndex(); + } + + public String getSelectedItem() { + return Properties.getSelectedItem(); + } + + public boolean pressedOK() { + return OKpressed; + } + +} diff --git a/src/main/java/cct/awtdialogs/AtomTypeDialog.java b/src/main/java/cct/awtdialogs/AtomTypeDialog.java new file mode 100644 index 0000000..66d84d2 --- /dev/null +++ b/src/main/java/cct/awtdialogs/AtomTypeDialog.java @@ -0,0 +1,256 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.awtdialogs; + +import java.awt.Button; +import java.awt.Checkbox; +import java.awt.Choice; +import java.awt.Dialog; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.Label; +import java.awt.Panel; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.logging.Logger; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class AtomTypeDialog + extends Dialog implements ActionListener, ItemListener { + TextField atomName, bLength; + Choice elements, hybrid, bondLength; + Checkbox drawBond, useBondLength; + Button OK, Cancel; + boolean OKpressed = false; + static final Logger logger = Logger.getLogger(AtomTypeDialog.class.getCanonicalName()); + public AtomTypeDialog(Frame parent, String Title, boolean modal) { + super(parent, Title, modal); + + //FlowLayout sizer = new FlowLayout( FlowLayout.CENTER); + //GridLayout sizer = new GridLayout( 0, 2, 5 ,5 ); + GridLayout sizer = new GridLayout(0, 1, 3, 3); + setLayout(sizer); + + Panel P = new Panel(); + P.setLayout(new FlowLayout()); + + Label elem = new Label("Element:", Label.RIGHT); + elements = new Choice(); + elements.addItemListener(this); + + Label elconf = new Label("Valency:", Label.RIGHT); + hybrid = new Choice(); + hybrid.addItemListener(this); + + Label aname = new Label("Atom Name:", Label.RIGHT); + atomName = new TextField(" "); //, host_str.length() > 100 ? host_str.length() : 100 ) ; + atomName.addActionListener(this); + + drawBond = new Checkbox("Draw Bond", true); + drawBond.addItemListener(this); + + OK = new Button("OK"); + Cancel = new Button("Cancel"); + + P.add(elem); + P.add(elements); + + P.add(elconf); + P.add(hybrid); + add(P); + + P = new Panel(); + P.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 0)); + + P.add(aname); + P.add(atomName); + + P.add(drawBond); + add(P); + + P = new Panel(); + P.setLayout(new FlowLayout()); + useBondLength = new Checkbox("Predefined Bond Length", true); + useBondLength.setState(false); + useBondLength.addItemListener(this); + P.add(useBondLength); + bondLength = new Choice(); + bondLength.add("0.9"); + bondLength.add("1.0"); + bondLength.add("1.1"); + bondLength.add("1.2"); + bondLength.add("1.3"); + bondLength.add("1.4"); + bondLength.add("1.5"); + bondLength.add("1.6"); + bondLength.add("1.7"); + bondLength.add("2.0"); + bondLength.add("2.5"); + bondLength.add("3.0"); + bondLength.add("3.5"); + bondLength.select(0); + bondLength.addItemListener(this); + P.add(bondLength); + bLength = new TextField(bondLength.getSelectedItem()); + bLength.addActionListener(this); + + if (!useBondLength.getState()) { + bondLength.setEnabled(false); + bLength.setEnabled(false); + } + P.add(bLength); + + add(P); + + P = new Panel(); + P.setLayout(new FlowLayout()); + P.add(OK); + //OK.setVisible(true); + P.add(Cancel); + add(P); + + OK.addActionListener(this); + Cancel.addActionListener(this); + + setSize(300, 200); + } + + @Override + public void actionPerformed(ActionEvent ae) { + String arg = ae.getActionCommand(); + if (arg.equals("OK")) { + OKpressed = true; + //dispose(); + setVisible(false); + } + else if (arg.equals("Cancel")) { + OKpressed = false; + //dispose(); + setVisible(false); + } + + else { + logger.info("Event: " + arg); + } + } + + @Override + public void itemStateChanged(ItemEvent ie) { + logger.info("Event: " + ie); + logger.info("Event: getItem" + ie.getItem()); + logger.info("Event: getItemSelectable" + ie.getItemSelectable()); + String item = (String) ie.getItem(); + + if (item.equals("Predefined Bond Length")) { + bondLength.setEnabled(useBondLength.getState()); + bLength.setEnabled(useBondLength.getState()); + } + + if (ie.getStateChange() == ItemEvent.SELECTED) { + bLength.setText(bondLength.getSelectedItem()); + } + + repaint(); + } + + public void addElement(String name) { + elements.add(name); + } + + public void addElements(String[] names) { + for (int i = 0; i < names.length; i++) { + elements.add(names[i]); + } + } + + public void clearElements() { + elements.removeAll(); + } + + public String getElement() { + return elements.getSelectedItem(); + } + + public int getElementNumber() { + return elements.getSelectedIndex(); + } + + public String getBondLength() { + return bLength.getText(); + } + + public boolean isDrawBond() { + return drawBond.getState(); + } + + public boolean isUseBondLength() { + return useBondLength.getState(); + } + + public boolean pressedOK() { + return OKpressed; + } + + public void setDrawBond(boolean draw) { + drawBond.setState(draw); + } + + public void setOKVisible(boolean enable) { + OK.setVisible(enable); + } + + public void setCancelVisible(boolean enable) { + Cancel.setVisible(enable); + } + +} diff --git a/src/main/java/cct/awtdialogs/ConnectSQLServer.java b/src/main/java/cct/awtdialogs/ConnectSQLServer.java new file mode 100644 index 0000000..9de870e --- /dev/null +++ b/src/main/java/cct/awtdialogs/ConnectSQLServer.java @@ -0,0 +1,233 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.awtdialogs; + +import java.awt.Button; +import java.awt.Dialog; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.Label; +import java.awt.Panel; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.logging.Logger; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class ConnectSQLServer + extends Dialog implements ActionListener { + TextField host, user, pass, port, database, db_type; + boolean OKpressed = false; + static final Logger logger = Logger.getLogger(ConnectSQLServer.class.getCanonicalName()); + public ConnectSQLServer(String Title, boolean modal) { + super(new Frame(), Title, modal); + + GridLayout sizer = new GridLayout(0, 1, 2, 2); + setLayout(sizer); + + Panel P = new Panel(); + P.setLayout(new FlowLayout(FlowLayout.RIGHT)); + + Label hostname = new Label("Hostname:", Label.RIGHT); + //String host_str = "jdbc:mysql://localhost/"; //parent.getSQLHostName(); + String host_str = "localhost"; //parent.getSQLHostName(); + host = new TextField(20); + host.setText(host_str); //, host_str.length() > 100 ? host_str.length() : 100 ) ; + + P.add(hostname); + P.add(host); + add(P); + + P = new Panel(); + P.setLayout(new FlowLayout(FlowLayout.RIGHT)); + + Label username = new Label("Username:", Label.RIGHT); + user = new TextField(20); + + P.add(username); + P.add(user); + add(P); + + P = new Panel(); + P.setLayout(new FlowLayout(FlowLayout.RIGHT)); + + Label password = new Label("Password:", Label.RIGHT); + pass = new TextField(20); + pass.setEchoChar('@'); + P.add(password); + P.add(pass); + add(P); + + P = new Panel(); + P.setLayout(new FlowLayout(FlowLayout.RIGHT)); + + database = new TextField(20); + + P.add(new Label("Database:", Label.RIGHT)); + P.add(database); + add(P); + + P = new Panel(); + P.setLayout(new FlowLayout(FlowLayout.RIGHT)); + + Label port_l = new Label("Port:", Label.RIGHT); + port = new TextField("3306", 10); + port.setEnabled(false); + P.add(port_l); + P.add(port); + add(P); + + P = new Panel(); + P.setLayout(new FlowLayout(FlowLayout.RIGHT)); + + Label type_l = new Label("Type:", Label.RIGHT); + db_type = new TextField("mySQL", 10); + db_type.setEnabled(false); + + P.add(type_l); + P.add(db_type); + add(P); + + P = new Panel(); + P.setLayout(new FlowLayout()); + + Button OK = new Button("OK"); + Button Cancel = new Button("Cancel"); + + P.add(OK); + P.add(Cancel); + add(P); + + /* + add( hostname ); + add(host); + + add( username ); + add(user); + + add(password); + add(pass); + + add( new Label( "Database:", Label.RIGHT )); + add( database); + + add( port_l); + add(port); + + add( type_l ); + + add( OK ); + */ + + host.addActionListener(this); + user.addActionListener(this); + pass.addActionListener(this); + port.addActionListener(this); + OK.addActionListener(this); + Cancel.addActionListener(this); + + setSize(300, 250); + } + + @Override + public void actionPerformed(ActionEvent ae) { + String arg = ae.getActionCommand(); + if (arg.equals("OK")) { + OKpressed = true; + setVisible(false); + //dispose(); + } + else if (arg.equals("Cancel")) { + OKpressed = false; + setVisible(false); + //dispose(); + } + else { + logger.info("Event: " + arg); + } + } + + public String getDatabase() { + return database.getText(); + } + + public String getHostname() { + return host.getText(); + } + + public String getUsername() { + return user.getText(); + } + + public String getPassword() { + return pass.getText(); + } + + public boolean pressedOK() { + return OKpressed; + } + + public void setDatabase(String dbase) { + database.setText(dbase); + } + + public void setHostname(String hname) { + host.setText(hname); + } + + public void setUsername(String usern) { + user.setText(usern); + } + + public void setPassword(String password) { + pass.setText(password); + } + +} diff --git a/src/main/java/cct/awtdialogs/GaussianCalcSetupDialog.java b/src/main/java/cct/awtdialogs/GaussianCalcSetupDialog.java new file mode 100644 index 0000000..743540e --- /dev/null +++ b/src/main/java/cct/awtdialogs/GaussianCalcSetupDialog.java @@ -0,0 +1,153 @@ + /* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.awtdialogs; + +import java.awt.Button; +import java.awt.Checkbox; +import java.awt.Choice; +import java.awt.Dialog; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.Label; +import java.awt.Panel; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.logging.Logger; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class GaussianCalcSetupDialog + extends Dialog implements ActionListener, ItemListener { + Choice JobType, Method, Charge, Spin, BasisSet; + Checkbox drawBond; + boolean OK = false; + static final Logger logger = Logger.getLogger(GaussianCalcSetupDialog.class.getCanonicalName()); + public GaussianCalcSetupDialog(Frame parent, String Title, boolean modal) { + super(parent, Title, modal); + + //FlowLayout sizer = new FlowLayout( FlowLayout.CENTER); + //GridLayout sizer = new GridLayout( 0, 2, 5 ,5 ); + GridLayout sizer = new GridLayout(0, 1, 3, 3); + setLayout(sizer); + + Panel P = new Panel(); + P.setLayout(new FlowLayout()); + + Label JobT = new Label("Job Type:", Label.RIGHT); + JobType = new Choice(); + JobType.addItemListener(this); + + Label method = new Label("Method:", Label.RIGHT); + Method = new Choice(); + Method.addItemListener(this); + + drawBond = new Checkbox("Draw Bond", true); + drawBond.addItemListener(this); + + Button OK = new Button("OK"); + Button Cancel = new Button("Cancel"); + + // --- Adding controls to a dialog + + P.add(JobT); + P.add(JobType); + + P.add(method); + P.add(Method); + add(P); + + P = new Panel(); + P.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 0)); + + P.add(drawBond); + add(P); + + P = new Panel(); + P.setLayout(new FlowLayout()); + P.add(OK); + P.add(Cancel); + add(P); + + OK.addActionListener(this); + Cancel.addActionListener(this); + + setSize(300, 200); + } + + @Override + public void actionPerformed(ActionEvent ae) { + String arg = ae.getActionCommand(); + if (arg.equals("OK")) { + OK = true; + //dispose(); + setVisible(false); + } + else if (arg.equals("Cancel")) { + OK = false; + //dispose(); + setVisible(false); + } + + else { + logger.info("Event: " + arg); + } + } + + @Override + public void itemStateChanged(ItemEvent ie) { + repaint(); + } + + public boolean pressedOK() { + return OK; + } + +} diff --git a/src/main/java/cct/awtdialogs/GeometrySelectDialog.java b/src/main/java/cct/awtdialogs/GeometrySelectDialog.java new file mode 100644 index 0000000..b083efa --- /dev/null +++ b/src/main/java/cct/awtdialogs/GeometrySelectDialog.java @@ -0,0 +1,167 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.awtdialogs; + +import java.awt.Button; +import java.awt.Dialog; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.List; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.logging.Logger; + +import cct.j3d.Java3dUniverse; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class GeometrySelectDialog + extends Dialog implements ActionListener, + ItemListener { + + List list; + Java3dUniverse daddy; + static final Logger logger = Logger.getLogger(GeometrySelectDialog.class.getCanonicalName()); + + public GeometrySelectDialog(Java3dUniverse parent, String Title, boolean modal) { + super(new Frame(), Title, modal); + daddy = parent; + + //GridLayout sizer = new GridLayout(0, 1, 3, 3); + //setLayout(sizer); + + GridBagLayout gridbag = new GridBagLayout(); + GridBagConstraints c = new GridBagConstraints(); + setLayout(gridbag); + + //c.fill = GridBagConstraints.HORIZONTAL; + c.fill = GridBagConstraints.BOTH; + c.weightx = 0.0; //reset to the default + c.gridwidth = GridBagConstraints.REMAINDER; + + //Panel P = new Panel(); + //P.setLayout(new FlowLayout()); + + list = new List(10, false); + //list.addActionListener(this); + list.addItemListener(this); + //P.add(list); + //add(P); + gridbag.setConstraints(list, c); + add(list); + + //P = new Panel(); + //P.setLayout(new FlowLayout()); + + //Button Hide = new Button("Hide"); + //Hide.addActionListener(this); + //P.add(Hide); + //add(P); + + c.weightx = 0.0; + c.fill = GridBagConstraints.CENTER; + Button Hide = new Button("Hide"); + Hide.addActionListener(this); + + gridbag.setConstraints(Hide, c); + add(Hide); + + setSize(170, 250); + } + + @Override + public void actionPerformed(ActionEvent ae) { + String arg = ae.getActionCommand(); + if (arg.equals("Hide")) { + setVisible(false); + } + else { + logger.info("Event: " + arg); + } + } + + @Override + public void itemStateChanged(ItemEvent ie) { + if (ie.getStateChange() == ItemEvent.SELECTED) { + int n = list.getSelectedIndex(); + daddy.setNewGeometry(n); + } + repaint(); + } + + public void addItem(String name) { + list.add(name); + } + + public void addItems(String[] names) { + for (int i = 0; i < names.length; i++) { + list.add(names[i]); + } + } + + public void clearItems() { + list.removeAll(); + } + + public String getSelectedItem() { + return list.getSelectedItem(); + } + + public int getSelectedIndex() { + return list.getSelectedIndex(); + } + + public void selectItem(int n) { + if (n >= 0 && n < list.getItemCount()) { + list.select(n); + } + } +} diff --git a/src/main/java/cct/awtdialogs/MessageWindow.java b/src/main/java/cct/awtdialogs/MessageWindow.java new file mode 100644 index 0000000..37f6972 --- /dev/null +++ b/src/main/java/cct/awtdialogs/MessageWindow.java @@ -0,0 +1,97 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.awtdialogs; + +import java.awt.Button; +import java.awt.Dialog; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.Label; +import java.awt.Panel; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class MessageWindow + extends Dialog implements ActionListener { + Button OK; + public MessageWindow(String Title, String Message, boolean modal) { + super(new Frame(), Title, modal); + + //FlowLayout sizer = new FlowLayout( FlowLayout.CENTER); + GridLayout sizer = new GridLayout(0, 1, 2, 2); + setLayout(sizer); + + Label text = new Label(Message, Label.CENTER); + add(text); + //Dimension dim = new Dimension( text.getPreferredSize() ); + //logger.info("Text: " + String.valueOf(dim.width) + " x " + dim.height ); + + Panel p = new Panel(); + p.setLayout(new FlowLayout()); + + OK = new Button("OK"); + //Dimension dimB = OK.getPreferredSize(); + //logger.info("OK Button: " + dimB.getWidth() + " x " + dimB.getHeight() ); + p.add(OK); + + add(p); + + OK.addActionListener(this); + + //setSize( dim.width + 100 , dim.height + dimB.height + 100 ); + setSize(400, 150); + } + + @Override + public void actionPerformed(ActionEvent ae) { + dispose(); + } +} diff --git a/src/main/java/cct/awtdialogs/SelectMethodDialog.java b/src/main/java/cct/awtdialogs/SelectMethodDialog.java new file mode 100644 index 0000000..7ce045a --- /dev/null +++ b/src/main/java/cct/awtdialogs/SelectMethodDialog.java @@ -0,0 +1,175 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.awtdialogs; + +import java.awt.Button; +import java.awt.Dialog; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.Label; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.Map; +import java.util.logging.Logger; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class SelectMethodDialog + extends Dialog implements ActionListener, ItemListener { + java.awt.List Methods = null; + java.awt.List basisSets = null; + int SelectedMethod = 0; + boolean OK_pressed = false; + static final Logger logger = Logger.getLogger(SelectMethodDialog.class.getCanonicalName()); + + public SelectMethodDialog(Frame parent, String Title, boolean modal, java.util.List allMethods, java.util.List allBasisSets) { + super(parent, Title, modal); + + FlowLayout sizer = new FlowLayout(FlowLayout.CENTER); + //GridLayout sizer = new GridLayout(0, 2, 5, 5); + setLayout(sizer); + + add(new Label("Select Method", Label.LEFT)); + + Methods = new java.awt.List(10, false); + + for (int i = 0; i < allMethods.size(); i++) { + Map row = (Map) allMethods.get(i); + Methods.add(row.get("MethodName").toString()); + } + add(Methods); + Methods.addActionListener(this); + Methods.addItemListener(this); + + Button OK = new Button("OK"); + add(OK); + OK.addActionListener(this); + + Button Cancel = new Button("Cancel"); + add(Cancel); + Cancel.addActionListener(this); + + setSize(300, 200); + + } + + @Override + public void actionPerformed(ActionEvent ae) { + String controlName = ae.getSource().toString(); + controlName = controlName.substring(controlName.indexOf('[') + 1); + controlName = controlName.substring(0, controlName.indexOf(',')); + logger.info("controlName: " + controlName); + + // --- Molecule name is changed + if (controlName.equals("Enter molname")) { + + } + else if (ae.getActionCommand().toString().equals("OK")) { + OK_pressed = true; + setVisible(false); + //dispose(); + } + else if (ae.getActionCommand().toString().equals("Cancel")) { + OK_pressed = false; + setVisible(false); + //dispose(); + } + } + + @Override + public void itemStateChanged(ItemEvent ie) { + String controlName = ie.getItemSelectable().toString(); + controlName = controlName.substring(controlName.indexOf('[') + 1); + controlName = controlName.substring(0, controlName.indexOf(',')); + + logger.info("Item: " + ie.getItem()); + logger.info("Item Selectable: " + ie.getItemSelectable()); + logger.info("ControlName: " + controlName); + + //if ( controlName.equals(controlMolList) ) { + SelectedMethod = Methods.getSelectedIndex(); + //selectMolecule(SelectedMolecule); + /* + } + else if ( controlName.equals(controlStrList)) { + + } + */ + } + + public boolean isOKPressed() { + return OK_pressed; + } + + /** + * + * @return String + */ + public String getSelectedMethod() { + String str = Methods.getSelectedItem(); + if (str.length() < 1) { + return null; + } + return str; + } + + public void updateMethods(java.util.List allMethods) { + if (Methods == null) { + return; + } + Methods.removeAll(); + for (int i = 0; i < allMethods.size(); i++) { + Map row = (Map) allMethods.get(i); + Methods.add(row.get("MethodName").toString()); + } + + } + +} diff --git a/src/main/java/cct/awtdialogs/SimpleAtomSelectionDialog.java b/src/main/java/cct/awtdialogs/SimpleAtomSelectionDialog.java new file mode 100644 index 0000000..a6e4b88 --- /dev/null +++ b/src/main/java/cct/awtdialogs/SimpleAtomSelectionDialog.java @@ -0,0 +1,154 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.awtdialogs; + +import java.awt.BorderLayout; +import java.awt.Button; +import java.awt.Dialog; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.Label; +import java.awt.Panel; +import java.awt.Rectangle; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.logging.Logger; + +import cct.j3d.Java3dUniverse; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class SimpleAtomSelectionDialog + extends Dialog implements ActionListener, ItemListener { + //SampleFrame daddy = null; + Java3dUniverse daddy = null; + Label message; + Button OK, Cancel; + boolean OKpressed = false; + static final Logger logger = Logger.getLogger(SimpleAtomSelectionDialog.class.getCanonicalName()); + + public SimpleAtomSelectionDialog(Java3dUniverse parent, String Title, boolean modal) { + super(new Frame(), Title, modal); + daddy = parent; + + //FlowLayout sizer = new FlowLayout( FlowLayout.CENTER, 5, 5 ); + //GridLayout sizer = new GridLayout( 0, 3, 5, 5 ); + //setLayout( sizer ); + + message = new Label("Your message is here ", Label.CENTER); + //add(message, FlowLayout.CENTER ); + add(message, BorderLayout.CENTER); + + Panel p = new Panel(); + p.setLayout(new FlowLayout()); + OK = new Button("OK"); + p.add(OK); + OK.addActionListener(this); + + Cancel = new Button("Cancel"); + p.add(Cancel); + Cancel.addActionListener(this); + + add(p, BorderLayout.SOUTH); + + daddy.enableMousePicking(true); + + validate(); + + Dimension dim; + + dim = message.getMinimumSize(); + logger.info("dim min: " + dim); + dim = message.getPreferredSize(); + logger.info("dim pref: " + dim); + Rectangle r = message.getBounds(); + logger.info("bounds: " + r); + setSize(400, 100); + //repaint(); + + } + + @Override + public void actionPerformed(ActionEvent ae) { + String arg = ae.getActionCommand(); + if (arg.equals("OK")) { + OKpressed = true; + daddy.enableMousePicking(false); + daddy.processSelectedAtoms(); + //dispose(); + } + else if (arg.equals("Cancel")) { + OKpressed = false; + daddy.selectAllAtoms(false); + daddy.enableMousePicking(false); + daddy.processSelectedAtoms(); + //dispose(); + } + } + + public boolean pressedOK() { + return OKpressed; + } // May be used in modal dialog + + @Override + public void itemStateChanged(ItemEvent ie) { + repaint(); + } + + public void setMessage(String mess) { + message.setText(mess); + } + + public void setOKVisible(boolean enable) { + OK.setVisible(enable); + } + +} diff --git a/src/main/java/cct/awtdialogs/SingleChoiceDialog.java b/src/main/java/cct/awtdialogs/SingleChoiceDialog.java new file mode 100644 index 0000000..9ff7bb5 --- /dev/null +++ b/src/main/java/cct/awtdialogs/SingleChoiceDialog.java @@ -0,0 +1,163 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.awtdialogs; + +import java.awt.Button; +import java.awt.Choice; +import java.awt.Dialog; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.Panel; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.logging.Logger; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class SingleChoiceDialog + extends Dialog implements ActionListener, ItemListener { + boolean OKpressed = false; + Choice choice; + Button OK, Cancel; + static final Logger logger = Logger.getLogger(SingleChoiceDialog.class.getCanonicalName()); + + public SingleChoiceDialog(Frame parent, String Title, boolean modal) { + super(parent, Title, modal); + + GridLayout sizer = new GridLayout(0, 1, 3, 3); + setLayout(sizer); + + Panel P = new Panel(); + P.setLayout(new FlowLayout()); + + choice = new Choice(); + choice.addItemListener(this); + + P.add(choice); + add(P); + + P = new Panel(); + P.setLayout(new FlowLayout()); + + OK = new Button("OK"); + Cancel = new Button("Cancel"); + OK.addActionListener(this); + Cancel.addActionListener(this); + + P.add(OK); + P.add(Cancel); + add(P); + + setSize(200, 150); + + } + + @Override + public void actionPerformed(ActionEvent ae) { + String arg = ae.getActionCommand(); + if (arg.equals("OK")) { + OKpressed = true; + //dispose(); + setVisible(false); + } + else if (arg.equals("Cancel")) { + OKpressed = false; + //dispose(); + setVisible(false); + } + + else { + logger.info("Event: " + arg); + } + } + + @Override + public void itemStateChanged(ItemEvent ie) { + repaint(); + } + + public void addChoice(String name) { + choice.add(name); + choice.select(choice.getItemCount() - 1); + } + + public void addChoices(String[] names) { + for (int i = 0; i < names.length; i++) { + choice.add(names[i]); + } + choice.select(names.length - 1); + } + + public void clearChoices() { + choice.removeAll(); + } + + public String getChoice() { + return choice.getSelectedItem(); + } + + public int getChoiceIndex() { + return choice.getSelectedIndex(); + } + + public boolean pressedOK() { + return OKpressed; + } + + public void setOKVisible(boolean enable) { + OK.setVisible(enable); + } + + public void setCancelVisible(boolean enable) { + Cancel.setVisible(enable); + } + +} diff --git a/src/main/java/cct/awtdialogs/TextEntryDialog.java b/src/main/java/cct/awtdialogs/TextEntryDialog.java new file mode 100644 index 0000000..fea58c6 --- /dev/null +++ b/src/main/java/cct/awtdialogs/TextEntryDialog.java @@ -0,0 +1,151 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.awtdialogs; + +import java.awt.Button; +import java.awt.Dialog; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.Label; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.logging.Logger; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class TextEntryDialog + extends Dialog implements ActionListener { + TextField name = null; + boolean nameEntered = false; + static final Logger logger = Logger.getLogger(TextEntryDialog.class.getCanonicalName()); + public TextEntryDialog(String Title, boolean modal) { + this(new Frame(), Title, modal); + } + + public TextEntryDialog(Frame parent, String Title, boolean modal) { + super(parent, Title, modal); + + FlowLayout sizer = new FlowLayout(FlowLayout.CENTER); + //GridLayout sizer = new GridLayout(0, 2, 5, 5); + setLayout(sizer); + + add(new Label(Title, Label.LEFT)); + name = new TextField(20); + name.setName("Enter molname"); + add(name); + name.addActionListener(this); + + Button OK = new Button("OK"); + add(OK); + OK.addActionListener(this); + + Button Cancel = new Button("Cancel"); + add(Cancel); + Cancel.addActionListener(this); + + setSize(300, 200); + + } + + @Override + public void actionPerformed(ActionEvent ae) { + String controlName = ae.getSource().toString(); + controlName = controlName.substring(controlName.indexOf('[') + 1); + controlName = controlName.substring(0, controlName.indexOf(',')); + logger.info("controlName: " + controlName); + + // --- Molecule name is changed + if (controlName.equals("Enter molname")) { + + } + else if (ae.getActionCommand().toString().equals("OK")) { + nameEntered = true; + dispose(); + } + else if (ae.getActionCommand().toString().equals("Cancel")) { + nameEntered = false; + dispose(); + } + } + + public boolean isTextEntered() { + return nameEntered; + } + + /** + * + * @return String + */ + public String getValue() { + if (nameEntered) { + String str = name.getText().trim(); + if (str.length() < 1) { + return null; + } + return str; + } + else { + return null; + } + } + + /** + * + * @param value String + */ + public void setValue(String value) { + if (value == null || value.length() < 1) { + return; + } + if (name == null) { + name = new TextField(20); + } + name.setText(value); + } +} diff --git a/src/main/java/cct/awtdialogs/YesNoDialog.java b/src/main/java/cct/awtdialogs/YesNoDialog.java new file mode 100644 index 0000000..4527c5f --- /dev/null +++ b/src/main/java/cct/awtdialogs/YesNoDialog.java @@ -0,0 +1,100 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.awtdialogs; + +import java.awt.Button; +import java.awt.Dialog; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.Label; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class YesNoDialog + extends Dialog implements ActionListener { + TextField name = null; + boolean pressedYes = false; + public YesNoDialog(Frame parent, String Title) { + super(parent, "Choose Yes or No", true); + + FlowLayout sizer = new FlowLayout(FlowLayout.CENTER); + //GridLayout sizer = new GridLayout(0, 2, 5, 5); + setLayout(sizer); + + add(new Label(Title, Label.CENTER)); + + Button OK = new Button("Yes"); + add(OK); + OK.addActionListener(this); + + Button Cancel = new Button("No"); + add(Cancel); + Cancel.addActionListener(this); + + setSize(300, 200); + + } + + @Override + public void actionPerformed(ActionEvent ae) { + if (ae.getActionCommand().toString().equals("Yes")) { + pressedYes = true; + } + else if (ae.getActionCommand().toString().equals("No")) { + pressedYes = false; + } + setVisible(false); + } + + public boolean isYes() { + return pressedYes; + } +} diff --git a/src/main/java/cct/beanshell/.DS_Store b/src/main/java/cct/beanshell/.DS_Store new file mode 100644 index 0000000..e11811a Binary files /dev/null and b/src/main/java/cct/beanshell/.DS_Store differ diff --git a/src/main/java/cct/beanshell/._.DS_Store b/src/main/java/cct/beanshell/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/cct/beanshell/._.DS_Store differ diff --git a/src/main/java/cct/beanshell/BeanShell.java b/src/main/java/cct/beanshell/BeanShell.java new file mode 100644 index 0000000..e96bc65 --- /dev/null +++ b/src/main/java/cct/beanshell/BeanShell.java @@ -0,0 +1,265 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.beanshell; + +import bsh.EvalError; +import bsh.Interpreter; +import bsh.util.JConsole; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; + +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.JFrame; +import javax.swing.JOptionPane; + +/** + * + * @author vvv900 + */ +public class BeanShell { + + public static void main(String args[]) throws IOException { + + if (args != null && args.length > 0 && args[0] != null && args[0].equals("testCommands")) { + try { + Interpreter i = new Interpreter(); // Construct an interpreter + i.eval("importCommands(\"cct.beanshell.commands\")"); + //i.eval("import cct.interfaces.*"); + //i.eval("import cct.interfaces.*"); + // --- Testing sin + i.eval("System.out.println(\"Testing sin:\")"); + i.eval("x = sin((double)20);"); + i.eval("System.out.println(\"Sin(double): \"+ x);"); + i.eval("x = sin((float)20);"); + i.eval("System.out.println(\"Sin(float): \"+ x);"); + i.eval("x = sin(20);"); + i.eval("System.out.println(\"Sin(int): \"+ x);"); + i.eval("x = sin(20l);"); + i.eval("System.out.println(\"Sin(long): \"+ x);"); + i.eval("x = sin(new Integer(20));"); + i.eval("System.out.println(\"Sin(Integer): \"+ x);"); + i.eval("x = sin(new Long(20));"); + i.eval("System.out.println(\"Sin(Long): \"+ x);"); + i.eval("x = sin(\"20 \");"); + i.eval("System.out.println(\"Sin(String): \"+ x);"); + // --- Testing cos + i.eval("System.out.println(\"Testing cos:\")"); + i.eval("x = cos((double)20);"); + i.eval("System.out.println(\"cos(double): \"+ x);"); + i.eval("x = cos((float)20);"); + i.eval("System.out.println(\"cos(float): \"+ x);"); + i.eval("x = cos(20);"); + i.eval("System.out.println(\"cos(int): \"+ x);"); + i.eval("x = cos(20l);"); + i.eval("System.out.println(\"cos(long): \"+ x);"); + i.eval("x = cos(new Integer(20));"); + i.eval("System.out.println(\"cos(Integer): \"+ x);"); + i.eval("x = cos(new Long(20));"); + i.eval("System.out.println(\"cos(Long): \"+ x);"); + i.eval("x = cos(\"20 \");"); + i.eval("System.out.println(\"cos(String): \"+ x);"); + // --- Testing acos + i.eval("System.out.println(\"Testing acos:\")"); + i.eval("x = acos((double)0.20);"); + i.eval("System.out.println(\"acos(double): \"+ x);"); + i.eval("x = acos((float)0.20);"); + i.eval("System.out.println(\"acos(float): \"+ x);"); + i.eval("x = acos(1);"); + i.eval("System.out.println(\"acos(int): \"+ x);"); + i.eval("x = acos(-1l);"); + i.eval("System.out.println(\"acos(long): \"+ x);"); + i.eval("x = acos(new Integer(1));"); + i.eval("System.out.println(\"acos(Integer): \"+ x);"); + i.eval("x = acos(new Long(-1));"); + i.eval("System.out.println(\"acos(Long): \"+ x);"); + i.eval("x = acos(\"0.999 \");"); + i.eval("System.out.println(\"acos(String): \"+ x+\" Ref: \"+Math.acos(0.999));"); + // --- Testing println + i.eval("println(\"String: \"+\"0.999 \");"); + i.eval("println(\"Real: \"+0.999+\" Math.cos: \"+ Math.cos(20.0));"); + } catch (Exception ex) { + Logger.getLogger(BeanShell.class.getName()).log(Level.SEVERE, null, ex); + } + System.exit(0); + } else if (args != null && args.length > 0 && args[0] != null && args[0].equals("console")) { + JConsole console = new JConsole(); + System.setIn(console.getInputStream()); + System.setOut(console.getOut()); + System.setErr(console.getErr()); + Interpreter interpreter = new Interpreter(console); + + try { + interpreter.eval("importCommands(\"cct.beanshell.commands\")"); + interpreter.eval("importCommands(\"cct.beanshell.commands.jamberoo\")"); + interpreter.eval("import cct.gaussian.*"); + interpreter.eval("import cct.interfaces.*"); + interpreter.eval("import cct.modelling.*;"); + // ---- + if (args.length >= 2 && args[1].equals("jamberoo")) { + interpreter.eval("global.jamberoo = new cct.JamberooMolecularEditor(null);"); + interpreter.eval("println(\"Variable jamberoo refers to the cct.JamberooMolecularEditor class\");"); + } + } catch (EvalError ex) { + Logger.getLogger(BeanShell.class.getName()).log(Level.SEVERE, null, ex); + } + new Thread(interpreter).start(); // start a thread to call the run() method + try { + Thread.sleep(1000); + } catch (Exception ex) { + } + //interpreter.getErr(); + //interpreter.getOut(); + JFrame frame = new JFrame("Scripting"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.getContentPane().add(console); + frame.pack(); + frame.setSize(800, 600); + frame.setVisible(true); + //try { + // Thread.sleep(1000000); + //} catch (InterruptedException ex) { + // Logger.getLogger(BeanShell.class.getName()).log(Level.SEVERE, null, ex); + //} + + } else if (args != null && args.length > 0 && args[0] != null && args[0].equals("gui")) { + try { + Interpreter i = new Interpreter(); // Construct an interpreter + i.eval("importCommands(\"cct.beanshell.commands\")"); + i.eval("desktop()"); + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + String line; + while (!(line = in.readLine()).equals("quit")) { + + line = line.trim(); + } + + } catch (Exception ex) { + Logger.getLogger(BeanShell.class.getName()).log(Level.SEVERE, null, ex); + } + + System.exit(0); + } else { + + try { + File f = new File(""); + f.getName().endsWith(null); + Interpreter i = new Interpreter(); // Construct an interpreter + //i.eval("import *;"); + i.eval("import cct.gaussian.*;"); + i.eval("import cct.interfaces.*;"); + i.eval("import cct.modelling.*;"); + i.eval("importCommands(\"cct.beanshell.commands\")"); + + i.eval("log = new FileWriter(\"statistics.txt\");"); + i.eval("gauss = new Gaussian();"); + i.eval("gauss.setLoggerLevel(java.util.logging.Level.WARNING);"); + i.eval("int n = gauss.parseGJF(\"ferrocene-admp-20c.com\", 0);"); + i.eval("System.out.println(\"Number of molecules: \"+ n);"); + i.eval("MoleculeInterface mol = Molecule.getNewInstance();"); + i.eval("mol = gauss.getMolecule(mol, 0);"); + i.eval("System.out.println(\"Number of atoms: \"+ mol.getNumberOfAtoms());"); + i.eval("StructureManager sm = new StructureManager(mol)"); + //i.eval("sm.parseTrajectoryFile(\"/home/vvv900/fuji1/Fc/ferrocene-admp-20c.log\", TRAJECTORY_FILE_FORMAT.G03_TRAJECTORY)"); + //i.eval("sm.parseTrajectoryFile(\"/home/vvv900/fuji1/Fc/ferrocene-admp-minus-50c.log\", TRAJECTORY_FILE_FORMAT.G03_TRAJECTORY)"); + //i.eval("sm.parseTrajectoryFile(\"E:/_SCIENCE-PROJECTS/ferrocene-admp-minus-50c.log\", TRAJECTORY_FILE_FORMAT.G03_TRAJECTORY)"); + i.eval("sm.parseTrajectoryFile(\"Q:/TEMP/ferrocene-admp-minus-50c.log\", TRAJECTORY_FILE_FORMAT.G03_TRAJECTORY)"); + //i.eval("sm.parseTrajectoryFile(\"g09-md.out\", TRAJECTORY_FILE_FORMAT.G03_TRAJECTORY)"); + i.eval("snaps = sm.getNumberOfSnapshots();"); + i.eval("System.out.println(\"Number of snapshots: \"+ snaps);"); + i.eval("List list1 = new ArrayList();"); + i.eval("List list2 = new ArrayList();"); + i.eval("List list3 = new ArrayList();"); + i.eval("List list4 = new ArrayList();"); + i.eval("a72rad = toRadians(72.0);"); + i.eval("a36rad = toRadians(36.0);"); + i.eval("int i = 0;\n"); + //i.eval("while (i a36rad ) dihed = a72rad - dihed;\n" + + " dihed = toDegrees(dihed);\n" + + " list3.add(dihed);\n" + + " plane_1 = new cct.vecmath.Plane( getAtom( mol, 1), getAtom( mol, 3), getAtom( mol, 5));\n" + + " plane_2 = new cct.vecmath.Plane( getAtom( mol, 6), getAtom( mol, 8), getAtom( mol, 10));\n" + + " pp_angle = toDegrees( plane_1.angle(plane_2) );\n" + + " list4.add(pp_angle);\n" + + " log.write(Fe_1+\",\"+Fe_2+\",\"+dihed+\",\"+pp_angle+\"\\n\");\n" + + "}\n" + + "log.close();\n" + + "data1 = list1.toArray();\n" + + "mean = mean(data1);\n" + + "System.out.println(\"Mean Fe - centroid_1 distance: \"+mean+\" Stn. dev: \"+cct.math.Statistics.standardDeviation(data1));" + + "data2 = list2.toArray();\n" + + "System.out.println(\"Mean Fe - centroid_2 distance: \"+mean(data2)+\" Stn. dev: \"+cct.math.Statistics.standardDeviation(data2));" + + "data3 = list3.toArray();\n" + + "data4 = list4.toArray();\n" + + "System.out.println(data1.length + \" & \"+data2.length);" + + "corr = cct.math.Statistics.linearCorrelationCoefficient(data1, data2);\n" + + "System.out.println(\"Linear correlation coeff (dist-dist): \"+corr);" + //+ "mean = mean(data3);\n" + + "mean = mean(list3);\n" + + "println(\"Mean dihedral value: \"+mean);" + + "println(\"Median dihedral value: \"+median(list3));" + + "println(\"Dihedral skew: \"+skew(list3));" + + "println(\"Dihedral kurtosis: \"+kurtosis(list3));" + + "mean = mean(data4);\n" + + "System.out.println(\"Mean plane-plane angle: \"+mean);" + + "System.out.println(\"Median plane-plane angle: \"+median(list4));" + + "corr = cct.math.Statistics.linearCorrelationCoefficient(data3, data4);\n" + + "System.out.println(\"Linear correlation coeff (twist-pp_angle): \"+corr);" + + "\n" + ); + + i.eval("tcf = cct.math.Statistics.timeCorrelationFunction(list3, list3);\n" + + "tcflog = new FileWriter(\"tcf.txt\");" + + "for(i=0; i frames = jamberoo.GetJamberooFrames();"); + //i.eval("Set frames = jamberoo.GetJamberooFrames();"); + } catch (EvalError ex) { + Logger.getLogger(BeanShell.class.getName()).log(Level.SEVERE, null, ex); + } + } + } +} diff --git a/src/main/java/cct/beanshell/BeanShellFrameTest.form b/src/main/java/cct/beanshell/BeanShellFrameTest.form new file mode 100644 index 0000000..a7082cf --- /dev/null +++ b/src/main/java/cct/beanshell/BeanShellFrameTest.form @@ -0,0 +1,57 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/src/main/java/cct/beanshell/BeanShellFrameTest.java b/src/main/java/cct/beanshell/BeanShellFrameTest.java new file mode 100644 index 0000000..6d87066 --- /dev/null +++ b/src/main/java/cct/beanshell/BeanShellFrameTest.java @@ -0,0 +1,139 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.beanshell; + +import bsh.Interpreter; +import bsh.util.JConsole; +import javax.swing.JMenuItem; + +/** + * + * @author vvv900 + */ +public class BeanShellFrameTest extends javax.swing.JFrame { + + /** + * Creates new form BeanShellFrameTest + */ + public BeanShellFrameTest() { + initComponents(); + } + + /** + * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The + * content of this method is always regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jMenuBar1 = new javax.swing.JMenuBar(); + jMenu1 = new javax.swing.JMenu(); + beanShellMenuItem = new JMenuItem(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + + jMenu1.setText("File"); + + beanShellMenuItem.setText("BeanShell"); + beanShellMenuItem.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + beanShellMenuItemActionPerformed(evt); + } + }); + jMenu1.add(beanShellMenuItem); + + jMenuBar1.add(jMenu1); + + setJMenuBar(jMenuBar1); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 400, Short.MAX_VALUE) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 279, Short.MAX_VALUE) + ); + + pack(); + }// //GEN-END:initComponents + + private void beanShellMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_beanShellMenuItemActionPerformed + // TODO add your handling code here: + System.out.println("MenuItem selected"); + }//GEN-LAST:event_beanShellMenuItemActionPerformed + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + /* Set the Nimbus look and feel */ + // + /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. + * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html + */ + try { + for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + javax.swing.UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (ClassNotFoundException ex) { + java.util.logging.Logger.getLogger(BeanShellFrameTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (InstantiationException ex) { + java.util.logging.Logger.getLogger(BeanShellFrameTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + java.util.logging.Logger.getLogger(BeanShellFrameTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (javax.swing.UnsupportedLookAndFeelException ex) { + java.util.logging.Logger.getLogger(BeanShellFrameTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + // + String comm = ""; + try { + //JConsole console = new JConsole(); + //System.setIn(console.getInputStream()); + //System.setOut(console.getOut()); + //System.setErr(console.getErr()); + //Interpreter i = new Interpreter(console); + Interpreter i = new Interpreter(); + i.eval("importCommands(\"cct.beanshell.commands\")"); + i.eval("import java.awt.event.*"); + //i.eval("bsh.util.JConsole con = new bsh.util.JConsole()"); + i.eval("frame = new cct.beanshell.BeanShellFrameTest();"); + i.eval("frame.setVisible(true);"); + //i.eval("public void actionPerformed( java.awt.event.ActionEvent event ) { println( event ); frame.getContentPane().add(this); frame.pack(); frame.setSize(800, 600);}"); + //i.eval("frame.getBeanShellMenuItem().addActionListener( this );"); + comm = "menuItemHandler = new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent event ) { System.out.println(event); } };"; + i.eval(comm); + i.eval("frame.getBeanShellMenuItem().addActionListener( menuItemHandler );"); + } catch (Exception ex) { + ex.printStackTrace(); + System.exit(1); + } + + /* Create and display the form + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + new BeanShellFrameTest().setVisible(true); + } + }); + */ + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private JMenuItem beanShellMenuItem; + private javax.swing.JMenu jMenu1; + private javax.swing.JMenuBar jMenuBar1; + // End of variables declaration//GEN-END:variables + + public JMenuItem getBeanShellMenuItem() { + return beanShellMenuItem; + } +} diff --git a/src/main/java/cct/beanshell/commands/.DS_Store b/src/main/java/cct/beanshell/commands/.DS_Store new file mode 100644 index 0000000..03ed2d1 Binary files /dev/null and b/src/main/java/cct/beanshell/commands/.DS_Store differ diff --git a/src/main/java/cct/beanshell/commands/._.DS_Store b/src/main/java/cct/beanshell/commands/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/cct/beanshell/commands/._.DS_Store differ diff --git a/src/main/java/cct/beanshell/commands/abs.bsh b/src/main/java/cct/beanshell/commands/abs.bsh new file mode 100644 index 0000000..478a09d --- /dev/null +++ b/src/main/java/cct/beanshell/commands/abs.bsh @@ -0,0 +1,45 @@ + +double abs(double value) { + return Math.abs(value); +} + +double abs(Double value) { + return Math.abs(value); +} + +double abs(float value) { + return Math.abs(value); +} + +double abs(Float value) { + return Math.abs(value); +} + +double abs(Number value) { + if ( value instanceof Integer ) + return Math.abs( (Integer)value) ); + if ( value instanceof Long ) + return Math.abs( (Long)value ); + + return Math.abs(((Number)value).doubleValue()); +} + +double abs(int value) { + return Math.abs(value); +} + +double abs(long value) { + return Math.abs(value); +} + +double abs(Integer value) { + return Math.abs(value); +} + +double abs(Long value) { + return Math.abs(value); +} + +double abs(String value) { + return Math.abs(Double.parseDouble(value.trim() ) ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/acos.bsh b/src/main/java/cct/beanshell/commands/acos.bsh new file mode 100644 index 0000000..748179e --- /dev/null +++ b/src/main/java/cct/beanshell/commands/acos.bsh @@ -0,0 +1,40 @@ + +double acos(double value) { + return Math.acos(value); +} + +double acos(Double value) { + return Math.acos(value); +} + +double acos(float value) { + return Math.acos(value); +} + +double acos(Float value) { + return Math.acos(value); +} + +double acos(Number value) { + return Math.acos(((Number)value).doubleValue()); +} + +double acos(int value) { + return Math.acos((double)value); +} + +double acos(long value) { + return Math.acos((double)value); +} + +double acos(Integer value) { + return Math.acos(value.doubleValue()); +} + +double acos(Long value) { + return Math.acos(value.doubleValue()); +} + +double acos(String value) { + return Math.acos(Double.parseDouble(value.trim() ) ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/angle.bsh b/src/main/java/cct/beanshell/commands/angle.bsh new file mode 100644 index 0000000..371a519 --- /dev/null +++ b/src/main/java/cct/beanshell/commands/angle.bsh @@ -0,0 +1,4 @@ + +double angle(cct.vecmath.Point3f p1, cct.vecmath.Point3f p2, cct.vecmath.Point3f p3) { + return cct.vecmath.Point3f.angle( p1, p2, p3 ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/asin.bsh b/src/main/java/cct/beanshell/commands/asin.bsh new file mode 100644 index 0000000..b9a9c3b --- /dev/null +++ b/src/main/java/cct/beanshell/commands/asin.bsh @@ -0,0 +1,40 @@ + +double asin(double value) { + return Math.asin(value); +} + +double asin(Double value) { + return Math.asin(value); +} + +double asin(float value) { + return Math.asin(value); +} + +double asin(Float value) { + return Math.asin(value); +} + +double asin(Number value) { + return Math.asin(((Number)value).doubleValue()); +} + +double asin(int value) { + return Math.asin((double)value); +} + +double asin(long value) { + return Math.asin((double)value); +} + +double asin(Integer value) { + return Math.asin(value.doubleValue()); +} + +double asin(Long value) { + return Math.asin(value.doubleValue()); +} + +double asin(String value) { + return Math.asin(Double.parseDouble(value.trim() ) ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/atan.bsh b/src/main/java/cct/beanshell/commands/atan.bsh new file mode 100644 index 0000000..843a1ee --- /dev/null +++ b/src/main/java/cct/beanshell/commands/atan.bsh @@ -0,0 +1,40 @@ + +double atan(double value) { + return Math.atan(value); +} + +double atan(Double value) { + return Math.atan(value); +} + +double atan(float value) { + return Math.atan(value); +} + +double atan(Float value) { + return Math.atan(value); +} + +double atan(Number value) { + return Math.atan(((Number)value).doubleValue()); +} + +double atan(int value) { + return Math.atan((double)value); +} + +double atan(long value) { + return Math.atan((double)value); +} + +double atan(Integer value) { + return Math.atan(value.doubleValue()); +} + +double atan(Long value) { + return Math.atan(value.doubleValue()); +} + +double atan(String value) { + return Math.atan(Double.parseDouble(value.trim() ) ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/cbrt.bsh b/src/main/java/cct/beanshell/commands/cbrt.bsh new file mode 100644 index 0000000..81c3900 --- /dev/null +++ b/src/main/java/cct/beanshell/commands/cbrt.bsh @@ -0,0 +1,40 @@ + +double cbrt(double value) { + return Math.cbrt(value); +} + +double cbrt(Double value) { + return Math.cbrt(value); +} + +double cbrt(float value) { + return Math.cbrt(value); +} + +double cbrt(Float value) { + return Math.cbrt(value); +} + +double cbrt(Number value) { + return Math.cbrt(((Number)value).doubleValue()); +} + +double cbrt(int value) { + return Math.cbrt((double)value); +} + +double cbrt(long value) { + return Math.cbrt((double)value); +} + +double cbrt(Integer value) { + return Math.cbrt(value.doubleValue()); +} + +double cbrt(Long value) { + return Math.cbrt(value.doubleValue()); +} + +double cbrt(String value) { + return Math.cbrt(Double.parseDouble(value.trim() ) ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/ceil.bsh b/src/main/java/cct/beanshell/commands/ceil.bsh new file mode 100644 index 0000000..3eaf5c2 --- /dev/null +++ b/src/main/java/cct/beanshell/commands/ceil.bsh @@ -0,0 +1,40 @@ + +double ceil(double value) { + return Math.ceil(value); +} + +double ceil(Double value) { + return Math.ceil(value); +} + +double ceil(float value) { + return Math.ceil(value); +} + +double ceil(Float value) { + return Math.ceil(value); +} + +double ceil(Number value) { + return Math.ceil(((Number)value).doubleValue()); +} + +double ceil(int value) { + return Math.ceil((double)value); +} + +double ceil(long value) { + return Math.ceil((double)value); +} + +double ceil(Integer value) { + return Math.ceil(value.doubleValue()); +} + +double ceil(Long value) { + return Math.ceil(value.doubleValue()); +} + +double ceil(String value) { + return Math.ceil(Double.parseDouble(value.trim() ) ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/cos.bsh b/src/main/java/cct/beanshell/commands/cos.bsh new file mode 100644 index 0000000..16e03dc --- /dev/null +++ b/src/main/java/cct/beanshell/commands/cos.bsh @@ -0,0 +1,40 @@ + +double cos(double value) { + return Math.cos(value); +} + +double cos(Double value) { + return Math.cos(value); +} + +double cos(float value) { + return Math.cos(value); +} + +double cos(Float value) { + return Math.cos(value); +} + +double cos(Number value) { + return Math.cos(((Number)value).doubleValue()); +} + +double cos(int value) { + return Math.cos((double)value); +} + +double cos(long value) { + return Math.cos((double)value); +} + +double cos(Integer value) { + return Math.cos(value.doubleValue()); +} + +double cos(Long value) { + return Math.cos(value.doubleValue()); +} + +double cos(String value) { + return Math.cos(Double.parseDouble(value.trim() ) ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/cosh.bsh b/src/main/java/cct/beanshell/commands/cosh.bsh new file mode 100644 index 0000000..6867d13 --- /dev/null +++ b/src/main/java/cct/beanshell/commands/cosh.bsh @@ -0,0 +1,40 @@ + +double cosh(double value) { + return Math.cosh(value); +} + +double cosh(Double value) { + return Math.cosh(value); +} + +double cosh(float value) { + return Math.cosh(value); +} + +double cosh(Float value) { + return Math.cosh(value); +} + +double cosh(Number value) { + return Math.cosh(((Number)value).doubleValue()); +} + +double cosh(int value) { + return Math.cosh((double)value); +} + +double cosh(long value) { + return Math.cosh((double)value); +} + +double cosh(Integer value) { + return Math.cosh(value.doubleValue()); +} + +double cosh(Long value) { + return Math.cosh(value.doubleValue()); +} + +double cosh(String value) { + return Math.cosh(Double.parseDouble(value.trim() ) ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/dihedral.bsh b/src/main/java/cct/beanshell/commands/dihedral.bsh new file mode 100644 index 0000000..e0e98a4 --- /dev/null +++ b/src/main/java/cct/beanshell/commands/dihedral.bsh @@ -0,0 +1,4 @@ + +double dihedral(cct.vecmath.Point3f p1, cct.vecmath.Point3f p2, cct.vecmath.Point3f p3, cct.vecmath.Point3f p4) { + return cct.vecmath.Point3f.dihedralAngle( p1, p2, p3, p4 ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/distance.bsh b/src/main/java/cct/beanshell/commands/distance.bsh new file mode 100644 index 0000000..eeacdc4 --- /dev/null +++ b/src/main/java/cct/beanshell/commands/distance.bsh @@ -0,0 +1,24 @@ + +double distance(cct.vecmath.Point3f p1, cct.vecmath.Point3f p2) { + return cct.vecmath.Point3f.distance( p1, p2 ); +} + +double distance(float [] p1, float [] p2) { + return cct.vecmath.Point3f.distance( p1, p2 ); +} + +double distance(Float [] p1, Float [] p2) { + return cct.vecmath.Point3f.distance( p1, p2 ); +} + +double distance(double [] p1, double [] p2) { + return cct.vecmath.Point3f.distance( p1, p2 ); +} + +double distance(Double [] p1, Double [] p2) { + return cct.vecmath.Point3f.distance( p1, p2 ); +} + +double distance(Number [] p1, Number [] p2) { + return cct.vecmath.Point3f.distance( p1, p2 ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/exp.bsh b/src/main/java/cct/beanshell/commands/exp.bsh new file mode 100644 index 0000000..1d07380 --- /dev/null +++ b/src/main/java/cct/beanshell/commands/exp.bsh @@ -0,0 +1,40 @@ + +double exp(double value) { + return Math.exp(value); +} + +double exp(Double value) { + return Math.exp(value); +} + +double exp(float value) { + return Math.exp(value); +} + +double exp(Float value) { + return Math.exp(value); +} + +double exp(Number value) { + return Math.exp( ((Number)value).doubleValue() ); +} + +double exp(int value) { + return Math.exp((double)value); +} + +double exp(long value) { + return Math.exp((double)value); +} + +double exp(Integer value) { + return Math.exp(value.doubleValue()); +} + +double exp(Long value) { + return Math.exp(value.doubleValue()); +} + +double exp(String value) { + return Math.exp(Double.parseDouble(value.trim() ) ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/expm1.bsh b/src/main/java/cct/beanshell/commands/expm1.bsh new file mode 100644 index 0000000..2a34807 --- /dev/null +++ b/src/main/java/cct/beanshell/commands/expm1.bsh @@ -0,0 +1,40 @@ + +double expm1(double value) { + return Math.expm1(value); +} + +double expm1(Double value) { + return Math.expm1(value); +} + +double expm1(float value) { + return Math.expm1(value); +} + +double expm1(Float value) { + return Math.expm1(value); +} + +double expm1(Number value) { + return Math.expm1(((Number)value).doubleValue()); +} + +double expm1(int value) { + return Math.expm1((double)value); +} + +double expm1(long value) { + return Math.expm1((double)value); +} + +double expm1(Integer value) { + return Math.expm1(value.doubleValue()); +} + +double expm1(Long value) { + return Math.expm1(value.doubleValue()); +} + +double expm1(String value) { + return Math.expm1(Double.parseDouble(value.trim() ) ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/floor.bsh b/src/main/java/cct/beanshell/commands/floor.bsh new file mode 100644 index 0000000..af22bb5 --- /dev/null +++ b/src/main/java/cct/beanshell/commands/floor.bsh @@ -0,0 +1,40 @@ + +double floor(double value) { + return Math.floor(value); +} + +double floor(Double value) { + return Math.floor(value); +} + +double floor(float value) { + return Math.floor(value); +} + +double floor(Float value) { + return Math.floor(value); +} + +double floor(Number value) { + return Math.floor(((Number)value).doubleValue()); +} + +double floor(int value) { + return Math.floor((double)value); +} + +double floor(long value) { + return Math.floor((double)value); +} + +double floor(Integer value) { + return Math.floor(value.doubleValue()); +} + +double floor(Long value) { + return Math.floor(value.doubleValue()); +} + +double floor(String value) { + return Math.floor(Double.parseDouble(value.trim() ) ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/getAtom.bsh b/src/main/java/cct/beanshell/commands/getAtom.bsh new file mode 100644 index 0000000..99f1b9a --- /dev/null +++ b/src/main/java/cct/beanshell/commands/getAtom.bsh @@ -0,0 +1,4 @@ + +cct.interfaces.AtomInterface getAtom( cct.interfaces.MoleculeInterface mol, int nAtom) { + return mol.getAtomInterface( nAtom-1 );; +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/getExponent.bsh b/src/main/java/cct/beanshell/commands/getExponent.bsh new file mode 100644 index 0000000..78b6adf --- /dev/null +++ b/src/main/java/cct/beanshell/commands/getExponent.bsh @@ -0,0 +1,40 @@ + +double getExponent(double value) { + return Math.getExponent(value); +} + +double getExponent(Double value) { + return Math.getExponent(value); +} + +double getExponent(float value) { + return Math.getExponent(value); +} + +double getExponent(Float value) { + return Math.getExponent(value); +} + +double getExponent(Number value) { + return Math.getExponent(((Number)value).doubleValue()); +} + +double getExponent(int value) { + return Math.getExponent((double)value); +} + +double getExponent(long value) { + return Math.getExponent((double)value); +} + +double getExponent(Integer value) { + return Math.getExponent(value.doubleValue()); +} + +double getExponent(Long value) { + return Math.getExponent(value.doubleValue()); +} + +double getExponent(String value) { + return Math.getExponent(Double.parseDouble(value.trim() ) ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/jamberoo.bsh b/src/main/java/cct/beanshell/commands/jamberoo.bsh new file mode 100644 index 0000000..da0ffca --- /dev/null +++ b/src/main/java/cct/beanshell/commands/jamberoo.bsh @@ -0,0 +1,4 @@ + +cct.JamberooMolecularEditor jamberoo() { + return new cct.JamberooMolecularEditor(null); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/jamberoo/loadMolecule.bsh b/src/main/java/cct/beanshell/commands/jamberoo/loadMolecule.bsh new file mode 100644 index 0000000..b74d4a1 --- /dev/null +++ b/src/main/java/cct/beanshell/commands/jamberoo/loadMolecule.bsh @@ -0,0 +1,3 @@ +Molecule loadMolecule(String fileName ) { + return cct.math.Statistics.variance( data ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/jamberoo/parseGaussianOutput.bsh b/src/main/java/cct/beanshell/commands/jamberoo/parseGaussianOutput.bsh new file mode 100644 index 0000000..80eecb6 --- /dev/null +++ b/src/main/java/cct/beanshell/commands/jamberoo/parseGaussianOutput.bsh @@ -0,0 +1,37 @@ +import cct.gaussian.*; + +GaussianJob parseGaussianOutput(String fileName, Molecule mol, java.util.logging.Level level) { + GaussianJob gaussianJob = null; + try { + GaussianOutput gaussianOutput = new GaussianOutput(); + gaussianOutput.setLoggerLevel(level); + gaussianJob = gaussianOutput.parseFile(mol, fileName, false); + } catch (Exception ex) { + System.err.println("Error Loading Gaussian Output file : " + ex.getMessage()); + return null; + } + + if (gaussianJob.countSteps() < 1) { + System.err.println("Didn't find gaussian steps in output file..."); + return null; + } + + return gaussianJob; +} + +GaussianJob parseGaussianOutput(String fileName, Molecule mol) { + return parseGaussianOutput(fileName, mol, java.util.logging.Level.WARNING); +} + +GaussianJob parseGaussianOutput(String fileName) { + Molecule mol = new Molecule(); + GaussianJob gaussianJob = parseGaussianOutput(fileName, mol, java.util.logging.Level.WARNING); + return gaussianJob; +} + +GaussianJob parseGaussianOutput(String fileName, java.util.logging.Level level) { + Molecule mol = new Molecule(); + GaussianJob gaussianJob = parseGaussianOutput(fileName, mol, level); + return gaussianJob; +} + diff --git a/src/main/java/cct/beanshell/commands/kurtosis.bsh b/src/main/java/cct/beanshell/commands/kurtosis.bsh new file mode 100644 index 0000000..f06954c --- /dev/null +++ b/src/main/java/cct/beanshell/commands/kurtosis.bsh @@ -0,0 +1,32 @@ + +double kurtosis(float [] data ) { + return cct.math.Statistics.kurtosis( data ); +} + +double kurtosis(Float [] data ) { + return cct.math.Statistics.kurtosis( data ); +} + +double kurtosis(double [] data ) { + return cct.math.Statistics.kurtosis( data ); +} + +double kurtosis(Double [] data ) { + return cct.math.Statistics.kurtosis( data ); +} + +double kurtosis(java.util.List data ) { + return cct.math.Statistics.kurtosis( data ); +} + +double kurtosis(java.util.ArrayList data ) { + return cct.math.Statistics.kurtosis( data ); +} + +double kurtosis(Number [] data ) { + return cct.math.Statistics.kurtosis( data ); +} + +double kurtosis(Object [] data ) { + return cct.math.Statistics.kurtosis( data ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/log.bsh b/src/main/java/cct/beanshell/commands/log.bsh new file mode 100644 index 0000000..d9b913b --- /dev/null +++ b/src/main/java/cct/beanshell/commands/log.bsh @@ -0,0 +1,40 @@ + +double log(double value) { + return Math.log(value); +} + +double log(Double value) { + return Math.log(value); +} + +double log(float value) { + return Math.log(value); +} + +double log(Float value) { + return Math.log(value); +} + +double log(Number value) { + return Math.log( ((Number)value).doubleValue() ); +} + +double log(int value) { + return Math.log((double)value); +} + +double log(long value) { + return Math.log((double)value); +} + +double log(Integer value) { + return Math.log(value.doubleValue()); +} + +double log(Long value) { + return Math.log(value.doubleValue()); +} + +double log(String value) { + return Math.log(Double.parseDouble(value.trim() ) ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/log10.bsh b/src/main/java/cct/beanshell/commands/log10.bsh new file mode 100644 index 0000000..72de6cf --- /dev/null +++ b/src/main/java/cct/beanshell/commands/log10.bsh @@ -0,0 +1,40 @@ + +double log10(double value) { + return Math.log10(value); +} + +double log10(Double value) { + return Math.log10(value); +} + +double log10(float value) { + return Math.log10(value); +} + +double log10(Float value) { + return Math.log10(value); +} + +double log10(Number value) { + return Math.log10( ((Number)value).doubleValue() ); +} + +double log10(int value) { + return Math.log10((double)value); +} + +double log10(long value) { + return Math.log10((double)value); +} + +double log10(Integer value) { + return Math.log10(value.doubleValue()); +} + +double log10(Long value) { + return Math.log10(value.doubleValue()); +} + +double log10(String value) { + return Math.log10(Double.parseDouble(value.trim() ) ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/log1p.bsh b/src/main/java/cct/beanshell/commands/log1p.bsh new file mode 100644 index 0000000..7f0a6cf --- /dev/null +++ b/src/main/java/cct/beanshell/commands/log1p.bsh @@ -0,0 +1,40 @@ + +double log1p(double value) { + return Math.log1p(value); +} + +double log1p(Double value) { + return Math.log1p(value); +} + +double log1p(float value) { + return Math.log1p(value); +} + +double log1p(Float value) { + return Math.log1p(value); +} + +double log1p(Number value) { + return Math.log1p( ((Number)value).doubleValue() ); +} + +double log1p(int value) { + return Math.log1p((double)value); +} + +double log1p(long value) { + return Math.log1p((double)value); +} + +double log1p(Integer value) { + return Math.log1p(value.doubleValue()); +} + +double log1p(Long value) { + return Math.log1p(value.doubleValue()); +} + +double log1p(String value) { + return Math.log1p(Double.parseDouble(value.trim() ) ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/maxOfTwo.bsh b/src/main/java/cct/beanshell/commands/maxOfTwo.bsh new file mode 100644 index 0000000..e787a3c --- /dev/null +++ b/src/main/java/cct/beanshell/commands/maxOfTwo.bsh @@ -0,0 +1,4 @@ + +double maxOfTwo(double a1, double a2) { + return a1 > a2 ? a1 : a2; +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/mean.bsh b/src/main/java/cct/beanshell/commands/mean.bsh new file mode 100644 index 0000000..0233c06 --- /dev/null +++ b/src/main/java/cct/beanshell/commands/mean.bsh @@ -0,0 +1,33 @@ + +double mean(float [] data ) { + return cct.math.Statistics.mean( data ); +} + +double mean(Float [] data ) { + return cct.math.Statistics.mean( data ); +} + +double mean(double [] data ) { + return cct.math.Statistics.mean( data ); +} + +double mean(Double [] data ) { + return cct.math.Statistics.mean( data ); +} + +double mean(java.util.List data ) { + return cct.math.Statistics.mean( data ); +} + +double mean(java.util.ArrayList data ) { + return cct.math.Statistics.mean( data ); +} + + +double mean(Number [] data ) { + return cct.math.Statistics.mean( data ); +} + +double mean(Object [] data ) { + return cct.math.Statistics.mean( data ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/median.bsh b/src/main/java/cct/beanshell/commands/median.bsh new file mode 100644 index 0000000..b8d3b4f --- /dev/null +++ b/src/main/java/cct/beanshell/commands/median.bsh @@ -0,0 +1,33 @@ + +double median(float [] data ) { + return cct.math.Statistics.median( data ); +} + +double median(Float [] data ) { + return cct.math.Statistics.median( data ); +} + +double median(double [] data ) { + return cct.math.Statistics.median( data ); +} + +double mean(Double [] data ) { + return cct.math.Statistics.median( data ); +} + +double median(java.util.List data ) { + return cct.math.Statistics.median( data ); +} + +double median(java.util.ArrayList data ) { + return cct.math.Statistics.median( data ); +} + + +double median(Number [] data ) { + return cct.math.Statistics.median( data ); +} + +double median(Object [] data ) { + return cct.math.Statistics.median( data ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/minOfTwo.bsh b/src/main/java/cct/beanshell/commands/minOfTwo.bsh new file mode 100644 index 0000000..025f164 --- /dev/null +++ b/src/main/java/cct/beanshell/commands/minOfTwo.bsh @@ -0,0 +1,4 @@ + +double minOfTwo(double a1, double a2) { +return a1 > a2 ? a2 : a1; +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/println.bsh b/src/main/java/cct/beanshell/commands/println.bsh new file mode 100644 index 0000000..bab2f8c --- /dev/null +++ b/src/main/java/cct/beanshell/commands/println.bsh @@ -0,0 +1,4 @@ + +println(Object obj) { + System.out.println(obj.toString()); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/random.bsh b/src/main/java/cct/beanshell/commands/random.bsh new file mode 100644 index 0000000..728c7c6 --- /dev/null +++ b/src/main/java/cct/beanshell/commands/random.bsh @@ -0,0 +1,4 @@ + +double random() { + return Math.random(); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/selectFile.bsh b/src/main/java/cct/beanshell/commands/selectFile.bsh new file mode 100644 index 0000000..27b629c --- /dev/null +++ b/src/main/java/cct/beanshell/commands/selectFile.bsh @@ -0,0 +1,19 @@ +/** + Opens dialog to select directory. Returns null is dialog was cancelled +*/ + +String selectFile(String dialogTitle) { + JFileChooser fc = new JFileChooser(); + fc.setDialogTitle(dialogTitle); + fc.setFileSelectionMode(JFileChooser.FILES_ONLY); + fc.setAcceptAllFileFilterUsed(false); + int returnVal = fc.showOpenDialog(new Frame()); + if (returnVal != JFileChooser.APPROVE_OPTION ) { + return null; + } + return fc.getSelectedFile().toString(); +} + +String selectFile() { + return selectDirectory("Select Directory"); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/sin.bsh b/src/main/java/cct/beanshell/commands/sin.bsh new file mode 100644 index 0000000..edd40d7 --- /dev/null +++ b/src/main/java/cct/beanshell/commands/sin.bsh @@ -0,0 +1,40 @@ + +double sin(double value) { + return Math.sin(value); +} + +double sin(Double value) { + return Math.sin(value); +} + +double sin(float value) { + return Math.sin(value); +} + +double sin(Float value) { + return Math.sin(value); +} + +double sin(Number value) { + return Math.sin(((Number)value).doubleValue()); +} + +double sin(int value) { + return Math.sin((double)value); +} + +double sin(long value) { + return Math.sin((double)value); +} + +double sin(Integer value) { + return Math.sin(value.doubleValue()); +} + +double sin(Long value) { + return Math.sin(value.doubleValue()); +} + +double sin(String value) { + return Math.sin(Double.parseDouble(value.trim() ) ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/skew.bsh b/src/main/java/cct/beanshell/commands/skew.bsh new file mode 100644 index 0000000..df64efe --- /dev/null +++ b/src/main/java/cct/beanshell/commands/skew.bsh @@ -0,0 +1,32 @@ + +double skew(float [] data ) { + return cct.math.Statistics.skew( data ); +} + +double skew(Float [] data ) { + return cct.math.Statistics.skew( data ); +} + +double skew(double [] data ) { + return cct.math.Statistics.skew( data ); +} + +double skew(Double [] data ) { + return cct.math.Statistics.skew( data ); +} + +double skew(java.util.List data ) { + return cct.math.Statistics.skew( data ); +} + +double skew(java.util.ArrayList data ) { + return cct.math.Statistics.skew( data ); +} + +double skew(Number [] data ) { + return cct.math.Statistics.skew( data ); +} + +double skew(Object [] data ) { + return cct.math.Statistics.skew( data ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/sqrt.bsh b/src/main/java/cct/beanshell/commands/sqrt.bsh new file mode 100644 index 0000000..3761279 --- /dev/null +++ b/src/main/java/cct/beanshell/commands/sqrt.bsh @@ -0,0 +1,40 @@ + +double sqrt(double value) { + return Math.sqrt(value); +} + +double sqrt(Double value) { + return Math.sqrt(value); +} + +double sqrt(float value) { + return Math.sqrt(value); +} + +double sqrt(Float value) { + return Math.sqrt(value); +} + +double sqrt(Number value) { + return Math.sqrt(((Number)value).doubleValue()); +} + +double sqrt(int value) { + return Math.sqrt((double)value); +} + +double sqrt(long value) { + return Math.sqrt((double)value); +} + +double sqrt(Integer value) { + return Math.sqrt(value.doubleValue()); +} + +double sqrt(Long value) { + return Math.sqrt(value.doubleValue()); +} + +double sqrt(String value) { + return Math.sqrt(Double.parseDouble(value.trim() ) ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/toDegrees.bsh b/src/main/java/cct/beanshell/commands/toDegrees.bsh new file mode 100644 index 0000000..b7124fc --- /dev/null +++ b/src/main/java/cct/beanshell/commands/toDegrees.bsh @@ -0,0 +1,40 @@ + +double toDegrees(double value) { + return Math.toDegrees(value); +} + +double toDegrees(Double value) { + return Math.toDegrees(value); +} + +double toDegrees(float value) { + return Math.toDegrees(value); +} + +double toDegrees(Float value) { + return Math.toDegrees(value); +} + +double toDegrees(Number value) { + return Math.toDegrees(((Number)value).doubleValue()); +} + +double toDegrees(int value) { + return Math.toDegrees((double)value); +} + +double toDegrees(long value) { + return Math.toDegrees((double)value); +} + +double toDegrees(Integer value) { + return Math.toDegrees(value.doubleValue()); +} + +double toDegrees(Long value) { + return Math.toDegrees(value.doubleValue()); +} + +double toDegrees(String value) { + return Math.toDegrees(Double.parseDouble(value.trim() ) ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/toRadians.bsh b/src/main/java/cct/beanshell/commands/toRadians.bsh new file mode 100644 index 0000000..1b023d4 --- /dev/null +++ b/src/main/java/cct/beanshell/commands/toRadians.bsh @@ -0,0 +1,40 @@ + +double toRadians(double value) { + return Math.toRadians(value); +} + +double toRadians(Double value) { + return Math.toRadians(value); +} + +double toRadians(float value) { + return Math.toRadians(value); +} + +double toRadians(Float value) { + return Math.toRadians(value); +} + +double toRadians(Number value) { + return Math.toRadians(((Number)value).doubleValue()); +} + +double toRadians(int value) { + return Math.toRadians((double)value); +} + +double toRadians(long value) { + return Math.toRadians((double)value); +} + +double toRadians(Integer value) { + return Math.toRadians(value.doubleValue()); +} + +double toRadians(Long value) { + return Math.toRadians(value.doubleValue()); +} + +double toRadians(String value) { + return Math.toRadians(Double.parseDouble(value.trim() ) ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/commands/variance.bsh b/src/main/java/cct/beanshell/commands/variance.bsh new file mode 100644 index 0000000..87034d3 --- /dev/null +++ b/src/main/java/cct/beanshell/commands/variance.bsh @@ -0,0 +1,32 @@ + +double variance(float [] data ) { + return cct.math.Statistics.variance( data ); +} + +double variance(Float [] data ) { + return cct.math.Statistics.variance( data ); +} + +double variance(double [] data ) { + return cct.math.Statistics.variance( data ); +} + +double variance(Double [] data ) { + return cct.math.Statistics.variance( data ); +} + +double variance(java.util.List data ) { + return cct.math.Statistics.variance( data ); +} + +double variance(java.util.ArrayList data ) { + return cct.math.Statistics.variance( data ); +} + +double variance(Number [] data ) { + return cct.math.Statistics.variance( data ); +} + +double variance(Object [] data ) { + return cct.math.Statistics.variance( data ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/dialogs/inputIntegerDialog.bsh b/src/main/java/cct/beanshell/dialogs/inputIntegerDialog.bsh new file mode 100644 index 0000000..330cc35 --- /dev/null +++ b/src/main/java/cct/beanshell/dialogs/inputIntegerDialog.bsh @@ -0,0 +1,70 @@ + +Integer inputIntegerDialog(String title) { + while(true) { + String inputValue = javax.swing.JOptionPane.showInputDialog(title); + if ( inputValue == null ) return null; + inputValue = inputValue.trim(); + if ( inputValue.length() == 0 ) { + return null; + } else { + try { + Integer maxToProcess = Integer.parseInt(inputValue); + return maxToProcess; + } catch (Exception ex ) { + System.err.println("Error parsing "+inputValue+" : "+ex.getMessage()+" Try again"); + } + } + } + + return null; +} + +Integer inputIntegerDialog(String title, Integer defaultValue) { + while(true) { + String inputValue = javax.swing.JOptionPane.showInputDialog(null, title, defaultValue ); + if ( inputValue == null ) return null; + inputValue = inputValue.trim(); + if ( inputValue.length() == 0 ) { + return null; + } else { + try { + Integer maxToProcess = Integer.parseInt(inputValue); + return maxToProcess; + } catch (Exception ex ) { + System.err.println("Error parsing "+inputValue+" : "+ex.getMessage()+" Try again"); + } + } + } + + return null; +} + +Integer inputIntegerDialog(String title, int defaultValue) { + return inputIntegerDialog(title, new Integer(defaultValue)); +} + +Integer inputIntegerDialog(String title, Integer defaultValue, Integer minValue, Integer maxValue) { + Integer value=null; + while(true) { + value = inputIntegerDialog(title, defaultValue); + if (value == null ) { + javax.swing.JOptionPane.showMessageDialog(null, "Input value cannot be empty", + "Error", javax.swing.JOptionPane.ERROR_MESSAGE); + continue; + } + if ( minValue != null && value < minValue ) { + javax.swing.JOptionPane.showMessageDialog(null, "Input value cannot be less than " + minValue.toString(), + "Error", javax.swing.JOptionPane.ERROR_MESSAGE); + continue; + } else if ( maxValue != null && value > maxValue ) { + javax.swing.JOptionPane.showMessageDialog(null, "Input value cannot be larger than " + maxValue.toString(), + "Error", javax.swing.JOptionPane.ERROR_MESSAGE); + continue; + } + return value; + } +} + +Integer inputIntegerDialog(String title, int defaultValue, Integer minValue, Integer maxValue) { + return inputIntegerDialog(title, new Integer(defaultValue), minValue, maxValue); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/dialogs/inputStringDialog.bsh b/src/main/java/cct/beanshell/dialogs/inputStringDialog.bsh new file mode 100644 index 0000000..d261131 --- /dev/null +++ b/src/main/java/cct/beanshell/dialogs/inputStringDialog.bsh @@ -0,0 +1,9 @@ + +String inputStringDialog(String title) { + return javax.swing.JOptionPane.showInputDialog(title); +} + +String inputStringDialog(String title, String defaultValue) { + + return javax.swing.JOptionPane.showInputDialog(null, title, defaultValue ); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/dialogs/radioButtonsDialog.bsh b/src/main/java/cct/beanshell/dialogs/radioButtonsDialog.bsh new file mode 100644 index 0000000..d658ae5 --- /dev/null +++ b/src/main/java/cct/beanshell/dialogs/radioButtonsDialog.bsh @@ -0,0 +1,19 @@ + +String radioButtonsDialog(String title, String [] options) { + javax.swing.JPanel panel = new javax.swing.JPanel(); + panel.setLayout(new java.awt.GridLayout(options.length, 1)); + javax.swing.ButtonGroup buttonGroup = new javax.swing.ButtonGroup(); + for(String opt:options) { + javax.swing.JRadioButton button = new javax.swing.JRadioButton(opt); + button.setActionCommand(opt); + buttonGroup.add(button); + panel.add(button); + } + + javax.swing.JOptionPane.showMessageDialog(null, panel, title, + javax.swing.JOptionPane.QUESTION_MESSAGE); + if (buttonGroup.getSelection() != null) { + return buttonGroup.getSelection().getActionCommand(); + } + return null; +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/dialogs/selectDirectory.bsh b/src/main/java/cct/beanshell/dialogs/selectDirectory.bsh new file mode 100644 index 0000000..548ccfb --- /dev/null +++ b/src/main/java/cct/beanshell/dialogs/selectDirectory.bsh @@ -0,0 +1,47 @@ +/** + Opens dialog to select directory. Returns null is dialog was cancelled +*/ + +String selectDirectory(String dialogTitle, String saveLabel ) { + java.util.prefs.Preferences prefs = null; + JFileChooser fc = new JFileChooser(); + fc.setDialogTitle(dialogTitle); + fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + fc.setAcceptAllFileFilterUsed(false); + + if ( saveLabel != null && saveLabel.trim().length() > 0 ) { + prefs = java.util.prefs.Preferences.userNodeForPackage(this.getClass()); + String lastPWD = prefs.get(saveLabel, ""); + if (lastPWD.length() > 0) { + File pwd = new File(lastPWD); + if (pwd.isDirectory() && pwd.exists()) { + fc.setCurrentDirectory(pwd); + } + } + } + + int returnVal = fc.showOpenDialog(new Frame()); + if (returnVal != JFileChooser.APPROVE_OPTION ) { + return null; + } + + if (prefs != null ) { + pwd = fc.getSelectedFile(); + try { + prefs.put(saveLabel, pwd.getAbsolutePath()); + } catch (Exception ex) { + System.err.println("Cannot save cwd: " + ex.getMessage() + + " Ignored..."); + } + } + + return fc.getSelectedFile().toString(); +} + +String selectDirectory(String dialogTitle ) { + return selectDirectory(dialogTitle, null ); +} + +String selectDirectory() { + return selectDirectory("Select Directory", null); +} \ No newline at end of file diff --git a/src/main/java/cct/beanshell/dialogs/selectFile.bsh b/src/main/java/cct/beanshell/dialogs/selectFile.bsh new file mode 100644 index 0000000..926435b --- /dev/null +++ b/src/main/java/cct/beanshell/dialogs/selectFile.bsh @@ -0,0 +1,59 @@ +/** + Opens dialog to select directory. Returns null is dialog was cancelled +*/ + +String selectFile(String dialogTitle, javax.swing.filechooser.FileFilter [] fileFilters, String saveLabel) { + java.util.prefs.Preferences prefs = null; + JFileChooser fc = new JFileChooser(); + fc.setDialogTitle(dialogTitle); + fc.setFileSelectionMode(JFileChooser.FILES_ONLY); + if ( fileFilters != null ) { + for(int i=0; i 0 ) { + prefs = java.util.prefs.Preferences.userNodeForPackage(this.getClass()); + String lastPWD = prefs.get(saveLabel, ""); + if (lastPWD.length() > 0) { + File cwd = new File(lastPWD); + if (cwd.isDirectory() && cwd.exists()) { + fc.setCurrentDirectory(cwd); + } + } + } + + int returnVal = fc.showOpenDialog(new Frame()); + if (returnVal != JFileChooser.APPROVE_OPTION ) { + return null; + } + + if (prefs != null ) { + cwd = fc.getCurrentDirectory(); + try { + prefs.put(saveLabel, cwd.getAbsolutePath()); + } catch (Exception ex) { + System.err.println("Cannot save cwd: " + ex.getMessage() + + " Ignored..."); + } + } + + return fc.getSelectedFile().toString(); +} + +String selectFile(String dialogTitle, javax.swing.filechooser.FileFilter fileFilter, String saveLabel) { + return selectFile(dialogTitle, new javax.swing.filechooser.FileFilter [] {fileFilter}, saveLabel); +} + +String selectFile(String dialogTitle, String saveLabel) { + return selectFile(dialogTitle, null, saveLabel); +} + +String selectFile(String dialogTitle) { + return selectFile(dialogTitle, null, null); +} + +String selectFile() { + return selectFile("Select a File", null, null); +} \ No newline at end of file diff --git a/src/main/java/cct/chart/.DS_Store b/src/main/java/cct/chart/.DS_Store new file mode 100644 index 0000000..ecb07bc Binary files /dev/null and b/src/main/java/cct/chart/.DS_Store differ diff --git a/src/main/java/cct/chart/._.DS_Store b/src/main/java/cct/chart/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/cct/chart/._.DS_Store differ diff --git a/src/main/java/cct/chart/ChartFrame.java b/src/main/java/cct/chart/ChartFrame.java new file mode 100644 index 0000000..9c4f000 --- /dev/null +++ b/src/main/java/cct/chart/ChartFrame.java @@ -0,0 +1,409 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.chart; + +import java.awt.BorderLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.util.HashSet; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import javax.swing.JButton; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.ListSelectionModel; + +import org.jfree.data.xy.XYSeries; + +import cct.chart.jfreechart.JFreeChartPanel; +import cct.dialogs.SelectListDialog; +import cct.interfaces.MoleculeInterface; +import cct.j3d.Java3dUniverse; +import cct.modelling.StructureManagerInterface; +import cct.tools.DXData; + +/** + *

Title: Computational Chemistry Toolkit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2008 Dr. V. Vasilyev

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class ChartFrame + extends JFrame implements ChartInterface, StructureManagerInterface, ActionListener { + private BorderLayout borderLayout1 = new BorderLayout(); + private JPanel buttonPanel = new JPanel(); + private JButton ok = new JButton("Hide"); + private JButton cancel = new JButton("Cancel"); + private JFreeChartPanel jFreeChartPanel1 = new JFreeChartPanel(); + private Java3dUniverse java3dUniverse = null; + private StructureManagerInterface structureManagerInterface = null; + private JMenuBar jMenuBar = new JMenuBar(); + private JMenu jMenuFile = new JMenu("File"); + private JMenu jFileSaveAsSubmenu = new JMenu("Save As"); + private JMenu jFileAddSeriesSubmenu = new JMenu("Add Data Serie As"); + private JMenuItem jFileSaveAsCSV = new JMenuItem("CSV"); + private JMenuItem addAsDX = new JMenuItem("DX"); + private JMenuItem exitChart = new JMenuItem("Exit"); + private JFileChooser CSVchooser = null; + private JFileChooser DXchooser = null; + static final Logger logger = Logger.getLogger(ChartFrame.class.getCanonicalName()); + + public ChartFrame() throws Exception { + try { + jbInit(); + } + catch (Exception exception) { + throw exception; + } + } + + private void jbInit() throws Exception { + try { + this.getClass().getClassLoader().loadClass("org.jfree.chart.JFreeChart"); + } + catch (Exception ex) { + System.err.println(ex.getMessage()); + throw new Exception("JFreeChart is not found in CLASSPATH: "); + } + + ok.addActionListener(this); + cancel.addActionListener(this); + buttonPanel.add(ok); + buttonPanel.add(cancel); + + cancel.setVisible(false); // !!! + + jMenuFile.setMnemonic(KeyEvent.VK_F); + jMenuFile.add(jFileSaveAsSubmenu); + + jFileSaveAsSubmenu.add(jFileSaveAsCSV); + jFileSaveAsCSV.addActionListener(this); + + jMenuFile.add(jFileAddSeriesSubmenu); + jFileAddSeriesSubmenu.add(addAsDX); + addAsDX.addActionListener(this); + + jMenuFile.add(exitChart); + exitChart.addActionListener(this); + + jMenuBar.add(jMenuFile); + + setJMenuBar(jMenuBar); + + getContentPane().setLayout(borderLayout1); + this.getContentPane().add(jFreeChartPanel1, BorderLayout.CENTER); + this.getContentPane().add(buttonPanel, BorderLayout.SOUTH); + this.setSize(800, 600); + } + + public void setChartTitle(String title) { + jFreeChartPanel1.setChartTitle(title); + } + + public void enableAnimationPanel(boolean enable) { + jFreeChartPanel1.enableAnimationPanel(enable); + } + + public void setXAxisTitle(String title) { + jFreeChartPanel1.setXAxisTitle(title); + } + + public void setYAxisTitle(String title) { + jFreeChartPanel1.setYAxisTitle(title); + } + + public void enableChartPanel(boolean enable) { + jFreeChartPanel1.enableChartPanel(enable); + } + + public void enableTablePanel(boolean enable) { + jFreeChartPanel1.enableTablePanel(enable); + } + + public static void main(String[] args) { + try { + ChartFrame jchartframe = new ChartFrame(); + int n_test = 100; + double x[] = new double[n_test]; + double y[] = new double[n_test]; + for (int i = 0; i < n_test; i++) { + x[i] = i; + y[i] = Math.random(); + } + jchartframe.addDataSeries(x, y, "My test plot"); + jchartframe.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + jchartframe.showChart(true); + } + catch (Exception ex) {} + } + + @Override + public void addDataSeries(double x[], double y[], String name) throws Exception { + jFreeChartPanel1.addDataSeries(x, y, name); + } + + @Override + public void addDataSeries(double x[], double y[], int n, String name) throws Exception { + jFreeChartPanel1.addDataSeries(x, y, n, name); + } + + @Override + public void showChart(boolean enable) { + if (enable) { + jFreeChartPanel1.setSize(this.getSize()); + jFreeChartPanel1.showChart(true); + this.pack(); + setVisible(true); + } + else { + setVisible(false); + } + } + + public void setStructureManagerInterface(StructureManagerInterface smi) { + structureManagerInterface = smi; + jFreeChartPanel1.setStructureManagerInterface(this); + } + + @Override + public void selectStructure(int number) throws Exception { + throw new Exception(this.getClass().getCanonicalName() + ": selectStructure(int number) is not implemented yet"); + } + + @Override + public void selectStructure(int number, String term) throws Exception { + MoleculeInterface referenceStructure = java3dUniverse.getMoleculeInterface(); + + float[][] coords = structureManagerInterface.getStructure(number, term); + if (coords == null) { + throw new Exception("No coordinates for structure " + number); + } + for (int i = 0; i < referenceStructure.getNumberOfAtoms(); i++) { + referenceStructure.getAtomInterface(i).setXYZ(coords[i][0], coords[i][1], coords[i][2]); + } + long start = System.currentTimeMillis(); + java3dUniverse.updateMolecularGeometry(); + float secs = (System.currentTimeMillis() - start) / 1000.0f; + logger.info("Elapsed time for java3d update: " + secs); + } + + @Override + public float[][] getStructure(int n) { + return null; + } + + @Override + public float[][] getStructure(int n, String term) { + return null; + } + + public void setRenderer(Java3dUniverse j3d) { + java3dUniverse = j3d; + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == cancel) { + this.setVisible(false); + } + else if (e.getSource() == ok) { + this.setVisible(false); + } + else if (e.getSource() == this.exitChart) { + this.setVisible(false); + } + + else if (e.getSource() == this.addAsDX) { + if (DXchooser == null) { + DXchooser = new JFileChooser(); + ChartFileFilter chartFileFilter = new ChartFileFilter("dx DX", "DX Files"); + DXchooser.setFileFilter(chartFileFilter); + DXchooser.setDialogTitle("Open As DX File"); + } + int returnVal = DXchooser.showOpenDialog(this); + if (returnVal != JFileChooser.APPROVE_OPTION) { + return; + } + + DXData dxData = new DXData(); + try { + dxData.parseDXFile(DXchooser.getSelectedFile().getAbsolutePath()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Error parsing file " + DXchooser.getSelectedFile().getAbsolutePath() + " : " + ex.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + //ArrayList dataSets = jFreeChartPanel1.getDataSets(); + //dataSets.clear(); + //this.getContentPane().remove(jFreeChartPanel1); + //jFreeChartPanel1 = new JFreeChartPanel(); + //this.getContentPane().add(jFreeChartPanel1, java.awt.BorderLayout.CENTER); + + //jFreeChartPanel1.addDataSets(dataSets); + + try { + jFreeChartPanel1.addDataSeries(dxData.getXData(), dxData.getYData(), dxData.countItems(), ""); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Error adding data serie: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + + jFreeChartPanel1.showChart(true); + pack(); + } + + // ************************************************************************* + else if (e.getSource() == jFileSaveAsCSV) { + if (CSVchooser == null) { + CSVchooser = new JFileChooser(); + ChartFileFilter chartFileFilter = new ChartFileFilter("csv CSV", "CSV Files"); + CSVchooser.setFileFilter(chartFileFilter); + CSVchooser.setDialogTitle("Save As CSV File"); + } + int returnVal = CSVchooser.showSaveDialog(this); + if (returnVal != JFileChooser.APPROVE_OPTION) { + return; + } + + String file_name = CSVchooser.getSelectedFile().getAbsolutePath(); + if (!file_name.endsWith(".csv") && !file_name.endsWith(".CSV")) { + file_name += ".csv"; + } + + java.util.List dataSets = jFreeChartPanel1.getDataSets(); + if (dataSets.size() < 1) { + JOptionPane.showMessageDialog(this, "No data set(s)", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + int index = 0; + if (dataSets.size() > 1) { + SelectListDialog selectListDialog = new SelectListDialog(this, "Select dataset to save"); + selectListDialog.setLocationRelativeTo(this); + Object[] list = new Object[dataSets.size()]; + for (int i = 0; i < dataSets.size(); i++) { + list[i] = dataSets.get(0).getDataCollection().getSeries(0).getDescription(); + } + selectListDialog.setList(list); + selectListDialog.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + boolean ok = selectListDialog.showDialog(); + if (!ok) { + return; + } + index = selectListDialog.getSelectedIndex(); + dataSets.get(0).getDataCollection().getSeries(0).getDescription(); + } + + XYSeries series = dataSets.get(index).getDataCollection().getSeries(0); + try { + saveDataSerie(file_name, series); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Cannot save dataset to file " + file_name + " : " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + } + } + } + + public void saveDataSerie(String file, XYSeries series) throws Exception { + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("X,Y\n"); + for (int i = 0; i < series.getItemCount(); i++) { + writer.write(String.format("%f,%f\n", series.getX(i), series.getY(i))); + } + writer.close(); + } + + class ChartFileFilter + extends javax.swing.filechooser.FileFilter { + private String description = ""; + private Set ext = new HashSet (); + + public ChartFileFilter(String extentions, String description) { + this.description = description; + StringTokenizer st = new StringTokenizer(extentions, " "); + while (st.hasMoreTokens()) { + ext.add(st.nextToken()); + } + } + + @Override + public boolean accept(File f) { + if (!f.isFile()) { + return true; + } + + String path = f.getAbsolutePath(); + int index = path.lastIndexOf("."); + if (index == -1) { + return false; + } + path = path.substring(index + 1); + return ext.contains(path); + } + + @Override + public String getDescription() { + return description; + } + } + +} diff --git a/src/main/java/cct/chart/ChartInterface.java b/src/main/java/cct/chart/ChartInterface.java new file mode 100644 index 0000000..3eed638 --- /dev/null +++ b/src/main/java/cct/chart/ChartInterface.java @@ -0,0 +1,56 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.chart; + +/** + *

Title: Computational Chemistry Toolkit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2008 Dr. V. Vasilyev

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface ChartInterface { + void addDataSeries(double x[], double y[], String name) throws Exception; + void addDataSeries(double x[], double y[], int n, String name) throws Exception; + void showChart(boolean enable); +} diff --git a/src/main/java/cct/chart/ChartReference.java b/src/main/java/cct/chart/ChartReference.java new file mode 100644 index 0000000..ec80675 --- /dev/null +++ b/src/main/java/cct/chart/ChartReference.java @@ -0,0 +1,108 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.chart; + +import java.util.HashMap; +import java.util.Map; + +import cct.modelling.VIBRATIONAL_SPECTRUM; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class ChartReference { + + static final Map spectrumTitleReference = new HashMap (); + static final Map spectrumXAxisReference = new HashMap (); + static final Map spectrumYAxisReference = new HashMap (); + + static { + spectrumTitleReference.put(VIBRATIONAL_SPECTRUM.INFRARED_SPECTRUM, "Infrared Spectrum"); + spectrumTitleReference.put(VIBRATIONAL_SPECTRUM.RAMAN_SPECTRUM, "Raman Spectrum"); + spectrumTitleReference.put(VIBRATIONAL_SPECTRUM.P_DEPOLARIZATION_SPECTRUM, "P-Depolarization Spectrum"); + spectrumTitleReference.put(VIBRATIONAL_SPECTRUM.U_DEPOLARIZATION_SPECTRUM, "U-Depolarization Spectrum"); + spectrumTitleReference.put(VIBRATIONAL_SPECTRUM.VCD_ROTATIONAL_STRENGTH_SPECTRUM, "VCD Rotational Strength Spectrum"); + + spectrumXAxisReference.put(VIBRATIONAL_SPECTRUM.INFRARED_SPECTRUM, "Frequency"); + spectrumXAxisReference.put(VIBRATIONAL_SPECTRUM.RAMAN_SPECTRUM, "Frequency"); + spectrumXAxisReference.put(VIBRATIONAL_SPECTRUM.P_DEPOLARIZATION_SPECTRUM, "Frequency"); + spectrumXAxisReference.put(VIBRATIONAL_SPECTRUM.U_DEPOLARIZATION_SPECTRUM, "Frequency"); + spectrumXAxisReference.put(VIBRATIONAL_SPECTRUM.VCD_ROTATIONAL_STRENGTH_SPECTRUM, "Frequency"); + + spectrumYAxisReference.put(VIBRATIONAL_SPECTRUM.INFRARED_SPECTRUM, "Intensity"); + spectrumYAxisReference.put(VIBRATIONAL_SPECTRUM.RAMAN_SPECTRUM, "Activity"); + spectrumYAxisReference.put(VIBRATIONAL_SPECTRUM.P_DEPOLARIZATION_SPECTRUM, "Depolarization"); + spectrumYAxisReference.put(VIBRATIONAL_SPECTRUM.U_DEPOLARIZATION_SPECTRUM, "Depolarization"); + spectrumYAxisReference.put(VIBRATIONAL_SPECTRUM.VCD_ROTATIONAL_STRENGTH_SPECTRUM, "Strength"); + + } + + private ChartReference() { + } + + public static String getTitle(VIBRATIONAL_SPECTRUM spectrum) { + if (spectrumTitleReference.get(spectrum) == null) { + return "Vibrational Spectrum"; + } + return spectrumTitleReference.get(spectrum); + } + + public static String getXAxisTitle(VIBRATIONAL_SPECTRUM spectrum) { + if (spectrumXAxisReference.get(spectrum) == null) { + return "Frequency"; + } + return spectrumXAxisReference.get(spectrum); + } + + public static String getYAxisTitle(VIBRATIONAL_SPECTRUM spectrum) { + if (spectrumYAxisReference.get(spectrum) == null) { + return "Value"; + } + return spectrumYAxisReference.get(spectrum); + } + +} diff --git a/src/main/java/cct/chart/DataRangePanel.form b/src/main/java/cct/chart/DataRangePanel.form new file mode 100644 index 0000000..c3532d2 --- /dev/null +++ b/src/main/java/cct/chart/DataRangePanel.form @@ -0,0 +1,107 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/cct/chart/DataRangePanel.java b/src/main/java/cct/chart/DataRangePanel.java new file mode 100644 index 0000000..7a3c81a --- /dev/null +++ b/src/main/java/cct/chart/DataRangePanel.java @@ -0,0 +1,169 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.chart; + +import cct.modelling.StructureManager; +import java.util.HashSet; +import java.util.Set; +import javax.swing.JDialog; +import javax.swing.JOptionPane; + +/** + * + * @author vvv900 + */ +public class DataRangePanel extends javax.swing.JPanel { + + private Set startFrameValues = new HashSet(); + private StructureManager structureManager; + + /** + * Creates new form DataRangePanel + */ + public DataRangePanel() { + initComponents(); + for (int i = 0; i < startFrameComboBox.getItemCount(); i++) { + startFrameValues.add((Integer) startFrameComboBox.getItemAt(i)); + } + if (startFrameComboBox.getItemCount() > 0) { + startFrameComboBox.setSelectedIndex(0); + } + } + + public static void main(String[] args) { + JDialog dialog = new JDialog(); + dialog.add(new DataRangePanel()); + dialog.validate(); + dialog.setSize(640, 480); + dialog.setModal(true); + dialog.setVisible(true); + System.exit(0); + } + + /** + * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The + * content of this method is always regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + java.awt.GridBagConstraints gridBagConstraints; + + jLabel1 = new javax.swing.JLabel(); + startFrameComboBox = new javax.swing.JComboBox(); + jLabel2 = new javax.swing.JLabel(); + jComboBox2 = new javax.swing.JComboBox(); + jLabel3 = new javax.swing.JLabel(); + jComboBox3 = new javax.swing.JComboBox(); + + setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Data Range", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); + setLayout(new java.awt.GridBagLayout()); + + jLabel1.setText("Frame to begin reading at:"); + jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.gridx = 0; + gridBagConstraints.gridy = 0; + gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; + gridBagConstraints.weightx = 1.0; + add(jLabel1, gridBagConstraints); + + startFrameComboBox.setEditable(true); + startFrameComboBox.setModel(new javax.swing.DefaultComboBoxModel(new Integer[] { 1})); + startFrameComboBox.setToolTipText("Select Item or Enter a New One and Press Enter"); + startFrameComboBox.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + startFrameComboBoxActionPerformed(evt); + } + }); + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.gridx = 1; + gridBagConstraints.gridy = 0; + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; + gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; + gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); + add(startFrameComboBox, gridBagConstraints); + + jLabel2.setText("Frame to stop reading at:"); + jLabel2.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.gridx = 0; + gridBagConstraints.gridy = 1; + gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; + add(jLabel2, gridBagConstraints); + + jComboBox2.setEditable(true); + jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Last" })); + jComboBox2.setToolTipText("Select Item or Enter a New One and Press Enter"); + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.gridy = 1; + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; + gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; + gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); + add(jComboBox2, gridBagConstraints); + + jLabel3.setText("Data read step:"); + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.gridx = 0; + gridBagConstraints.gridy = 2; + gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; + add(jLabel3, gridBagConstraints); + + jComboBox3.setEditable(true); + jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new Integer[] { 1, 5, 10, 15, 20, 25, 30, 35, 40, 50, 100 })); + jComboBox3.setToolTipText("Select Item or Enter a New One and Press Enter"); + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.gridx = 1; + gridBagConstraints.gridy = 2; + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; + gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_END; + gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); + add(jComboBox3, gridBagConstraints); + jComboBox3.getAccessibleContext().setAccessibleName(""); + }// //GEN-END:initComponents + + public void setStructureManager(StructureManager structureManager) { + this.structureManager = structureManager; + } + + private void startFrameComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startFrameComboBoxActionPerformed + Object obj = startFrameComboBox.getSelectedItem(); + if (obj instanceof Integer) { + if (startFrameValues.contains( obj )) { + return; + } + } + try { + Integer value = Integer.parseInt(obj.toString().trim()); + if (value < 0) { + value = 0; + } + if (structureManager != null) { + if (value > structureManager.getSnapshotsCount()) { + value = structureManager.getSnapshotsCount(); + } + } + startFrameValues.add(value); + startFrameComboBox.addItem(value); + startFrameComboBox.setSelectedItem(value); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, obj.toString() + " is not a valid integer value!", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + System.out.println("Selected: " + obj.toString()); + }//GEN-LAST:event_startFrameComboBoxActionPerformed + + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JComboBox jComboBox2; + private javax.swing.JComboBox jComboBox3; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel3; + private javax.swing.JComboBox startFrameComboBox; + // End of variables declaration//GEN-END:variables +} diff --git a/src/main/java/cct/chart/DataSet.java b/src/main/java/cct/chart/DataSet.java new file mode 100644 index 0000000..3d15efb --- /dev/null +++ b/src/main/java/cct/chart/DataSet.java @@ -0,0 +1,38 @@ +package cct.chart; + +import org.jfree.data.xy.XYSeriesCollection; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2009 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class DataSet { + private double y_Min, y_Max; + private XYSeriesCollection xySC; + + public DataSet(double y_min, double y_max, XYSeriesCollection xySeries) { + this.y_Min = y_min; + this.y_Max = y_max; + xySC = xySeries; + } + + public XYSeriesCollection getDataCollection() { + return xySC; + } + + public double getYMin() { + return this.y_Min; + } + + public double getYMax() { + return this.y_Max; + } +} diff --git a/src/main/java/cct/chart/PropsToChartDialog.form b/src/main/java/cct/chart/PropsToChartDialog.form new file mode 100644 index 0000000..51b49b9 --- /dev/null +++ b/src/main/java/cct/chart/PropsToChartDialog.form @@ -0,0 +1,148 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/cct/chart/PropsToChartDialog.java b/src/main/java/cct/chart/PropsToChartDialog.java new file mode 100644 index 0000000..1905daf --- /dev/null +++ b/src/main/java/cct/chart/PropsToChartDialog.java @@ -0,0 +1,240 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.chart; + +import cct.modelling.StructureManager; +import cct.tools.DataSets; +import java.awt.Component; +import java.awt.Frame; +import javax.swing.JOptionPane; + +/** + * + * @author vvv900 + */ +public class PropsToChartDialog extends javax.swing.JDialog { + + private boolean okPressed = false; + + /** + * Creates new form PropsToChartDialog + */ + public PropsToChartDialog(Frame parent, boolean modal) { + super(parent, modal); + initComponents(); + } + + public PropsToChartDialog(boolean modal) { + super(new Frame(), modal); + initComponents(); + } + + public void setXAxisValues(Object[] possibleValues) { + xAxisList.setListData(possibleValues); + } + + public void setYAxisValues(Object[] possibleValues) { + yAxisList.setListData(possibleValues); + } + + public void setStructureManager(StructureManager structureManager) { + dataRangePanel1.setStructureManager(structureManager); + Object[] values = structureManager.getAllProperties(); + setXAxisValues(values); + setYAxisValues(values); + } + + public boolean isOkPressed() { + return okPressed; + } + + public Object getXAxisValue() { + Object obj = xAxisList.getSelectedValue(); + if (obj == null && xAxisList.getModel().getSize() == 1) { + return xAxisList.getModel().getElementAt(0); + } + return obj; + } + + public Object[] getYAxisValues() { + if (yAxisList.getSelectedValues() != null) { + return yAxisList.getSelectedValues(); + } else if (yAxisList.getSelectedValues() == null && yAxisList.getModel().getSize() == 1) { + return new Object[]{yAxisList.getModel().getElementAt(0)}; + } + return null; + } + + public void setDataRangePanelVisible(boolean enable) { + if (enable) { + for (Component c : getContentPane().getComponents()) { + if (c == dataRangePanel1) { + return; + } + } + getContentPane().add(dataRangePanel1, java.awt.BorderLayout.CENTER); + + } else { + getContentPane().remove(dataRangePanel1); + } + validate(); + } + + /** + * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The + * content of this method is always regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jPanel1 = new javax.swing.JPanel(); + jScrollPane1 = new javax.swing.JScrollPane(); + xAxisList = new javax.swing.JList(); + jScrollPane2 = new javax.swing.JScrollPane(); + yAxisList = new javax.swing.JList(); + jPanel2 = new javax.swing.JPanel(); + okButton = new javax.swing.JButton(); + cancelButton = new javax.swing.JButton(); + dataRangePanel1 = new DataRangePanel(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + setAlwaysOnTop(true); + setMinimumSize(new java.awt.Dimension(200, 100)); + setModal(true); + + jPanel1.setLayout(new java.awt.GridLayout(1, 2)); + + jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder("X-Axis Data")); + + xAxisList.setModel(new javax.swing.AbstractListModel() { + String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; + public int getSize() { return strings.length; } + public Object getElementAt(int i) { return strings[i]; } + }); + xAxisList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); + xAxisList.setToolTipText("Select One Property"); + xAxisList.setPreferredSize(new java.awt.Dimension(100, 120)); + xAxisList.setSelectedIndex(0); + xAxisList.setVisibleRowCount(10); + jScrollPane1.setViewportView(xAxisList); + xAxisList.getAccessibleContext().setAccessibleName(""); + + jPanel1.add(jScrollPane1); + + jScrollPane2.setBorder(javax.swing.BorderFactory.createTitledBorder("Y-Axis Data")); + + yAxisList.setModel(new javax.swing.AbstractListModel() { + String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9", "Item 10", "Item 11", "Item 12", "Item 13" }; + public int getSize() { return strings.length; } + public Object getElementAt(int i) { return strings[i]; } + }); + yAxisList.setToolTipText("You can select multiple items"); + yAxisList.setLayoutOrientation(javax.swing.JList.VERTICAL_WRAP); + yAxisList.setPreferredSize(new java.awt.Dimension(100, 120)); + yAxisList.setVisibleRowCount(-1); + jScrollPane2.setViewportView(yAxisList); + + jPanel1.add(jScrollPane2); + + getContentPane().add(jPanel1, java.awt.BorderLayout.NORTH); + + okButton.setText("OK"); + okButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + okButtonActionPerformed(evt); + } + }); + jPanel2.add(okButton); + + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + cancelButtonActionPerformed(evt); + } + }); + jPanel2.add(cancelButton); + + getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH); + getContentPane().add(dataRangePanel1, java.awt.BorderLayout.CENTER); + + pack(); + }// //GEN-END:initComponents + + private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed + if (xAxisList.getSelectedValue() == null && xAxisList.getModel().getSize() > 1) { + JOptionPane.showMessageDialog(this, "Select Item to Plot for the X-Axis", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + if (yAxisList.getSelectedValues() == null && yAxisList.getModel().getSize() > 1) { + JOptionPane.showMessageDialog(this, "Select Item to Plot for the Y-Axis", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + this.okPressed = true; + this.setVisible(false); + }//GEN-LAST:event_okButtonActionPerformed + + private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed + this.okPressed = false; + this.setVisible(false); + }//GEN-LAST:event_cancelButtonActionPerformed + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + /* Set the Nimbus look and feel */ + // + /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. + * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html + */ + try { + for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + javax.swing.UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (ClassNotFoundException ex) { + java.util.logging.Logger.getLogger(PropsToChartDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (InstantiationException ex) { + java.util.logging.Logger.getLogger(PropsToChartDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + java.util.logging.Logger.getLogger(PropsToChartDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (javax.swing.UnsupportedLookAndFeelException ex) { + java.util.logging.Logger.getLogger(PropsToChartDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + // + + /* Create and display the dialog */ + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + PropsToChartDialog dialog = new PropsToChartDialog(new javax.swing.JFrame(), true); + dialog.addWindowListener(new java.awt.event.WindowAdapter() { + @Override + public void windowClosing(java.awt.event.WindowEvent e) { + System.exit(0); + } + }); + dialog.setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton cancelButton; + private DataRangePanel dataRangePanel1; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JScrollPane jScrollPane2; + private javax.swing.JButton okButton; + private javax.swing.JList xAxisList; + private javax.swing.JList yAxisList; + // End of variables declaration//GEN-END:variables +} diff --git a/src/main/java/cct/chart/QuickChart.java b/src/main/java/cct/chart/QuickChart.java new file mode 100644 index 0000000..6f6c3ef --- /dev/null +++ b/src/main/java/cct/chart/QuickChart.java @@ -0,0 +1,439 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.chart; + +import cct.interfaces.ChartDataProvider; +import cct.amber.AmberMden; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.JFileChooser; +import javax.swing.JOptionPane; + +/** + * + * @author Vlad + */ +public class QuickChart { + + public static final String CHART_PROPERTY_FILE = "cct/chart/chart.properties"; + private static Properties chartProperties = null; + private static URL cctPropsURL = null; + private static Map dataProviders = new HashMap(); + private String fileName = null; + private boolean showAllDescriptors = false; + private ChartDataProvider dataProvider = null; + private Map> graphs = new LinkedHashMap>(); + static final Logger logger = Logger.getLogger(QuickChart.class.getCanonicalName()); + + public QuickChart() { + + logger.setLevel(Level.WARNING); + + if (chartProperties == null) { + chartProperties = getProperties(); + for (Map.Entry entry : chartProperties.entrySet()) { + String name = entry.getKey().toString(); + String className = entry.getValue().toString(); + + Class builderClass = null; + ClassLoader loader = null; + try { + // Get the Class object associated with builder + builderClass = Class.forName(className); + + // Get the ClassLoader object associated with this Class. + loader = builderClass.getClassLoader(); + + if (loader == null) { + logger.severe("loader == null while attempting to load class " + className + " Ignored..."); + continue; + } else { + // Verify that this ClassLoader is associated with the builder class. + Class loaderClass = loader.getClass(); + + if (logger.isLoggable(Level.INFO)) { + logger.info("Class associated with ClassLoader: " + loaderClass.getName()); + } + } + } catch (ClassNotFoundException ex) { + logger.severe("Cannot load class " + className + " : " + ex.getMessage() + " Ignored..."); + continue; + } + + try { + Class cl = loader.loadClass(className); + Object obj = cl.newInstance(); + if (logger.isLoggable(Level.INFO)) { + logger.info("Classr " + className + " was loaded"); + } + // ---- + if (!(obj instanceof ChartDataProvider)) { + logger.severe("Class " + className + " does not implement " + ChartDataProvider.class.getName() + + " interface. Ignored..."); + continue; + } + // ---- + + dataProviders.put(name, (ChartDataProvider) obj); + } catch (Exception ex) { + logger.severe("Error while loading Class " + className + ex.getMessage() + " Ignored..."); + continue; + } + + } + + } + } + + public void execute(String[] args) throws Exception { + + boolean interactiveMode = false; + + if (args.length < 1) { + printUsage(); + System.exit(0); + } + + int count = 0; + while (count < args.length) { + if (args[count].equals("-f")) { + ++count; + if (count >= args.length) { + throw new Exception("Expected file format after -f option"); + } + dataProvider = dataProviders.get(args[count]); + if (dataProvider == null) { + throw new Exception("File format " + args[count] + " is not supported"); + } + } else if (args[count].equals("-s")) { + showAllDescriptors = true; + } else if (args[count].equals("-gui")) { + interactiveMode = true; + break; + } else if (args[count].equals("-i")) { + ++count; + if (count >= args.length) { + throw new Exception("Expected file name after -i option"); + } + fileName = args[count]; + } else if (args[count].startsWith("-x")) { + ++count; + if (count >= args.length) { + throw new Exception("Expected descriptor label after " + args[count - 1] + " option"); + } + String graphLabel = args[count - 1].length() == 2 ? "" : args[count - 1].substring(2); + List graphList = graphs.get(graphLabel); + if (graphList != null && graphList.get(0) != null && graphList.get(0).equals(args[count])) { + throw new Exception("May be only one dataset for X-ccordinate " + graphLabel); + } else if (graphList != null && graphList.get(0) == null) { + graphList.set(0, args[count]); + } else { + graphList = new ArrayList(); + graphList.add(args[count]); + graphs.put(graphLabel, graphList); + } + } // *********************************************** + else if (args[count].startsWith("-y")) { + ++count; + if (count >= args.length) { + throw new Exception("Expected descriptor label after " + args[count - 1] + " option"); + } + String graphLabel = args[count - 1].length() == 2 ? "" : args[count - 1].substring(2); + List graphList = graphs.get(graphLabel); + if (graphList == null) { + graphList = new ArrayList(); + graphList.add(null); + graphs.put(graphLabel, graphList); + } + graphList.add(args[count]); + } else if (args[count].equals("-v")) { + logger.setLevel(Level.INFO); + } else { + throw new Exception("Uknown option " + args[count]); + } + // + ++count; + } + + // --- + if (interactiveMode) { + interactiveFileSelection(); + } + + // --- Final Error check for the input options + if (fileName == null) { + throw new Exception("File name is not set"); + } + + if (dataProvider == null) { + throw new Exception("File format is not specified"); + } + + //AmberMden amberMden = new AmberMden(); + //amberMden.parseData(fileName); + dataProvider.cdpParseData(fileName); + Set descriptors = dataProvider.cdpGetDescriptors(); + + if (interactiveMode) { + interactiveDescriptorSelection(descriptors); + } else if (showAllDescriptors) { + printDescriptors(descriptors); + System.exit(0); + } + + // -- check that we have all descriptors in file + StringBuilder sb = new StringBuilder(); + for (String key : graphs.keySet()) { + List graphList = graphs.get(key); + for (String desc : graphList) { + if (!descriptors.contains(desc)) { + sb.append("Data does not contain descriptor " + desc + "\n"); + } + } + } + if (sb.length() > 0) { + throw new Exception(sb.toString()); + } + + // --- Finally, show chart + try { + ChartFrame jchartframe = new ChartFrame(); + jchartframe.setSize(1024, 600); + jchartframe.enableAnimationPanel(false); + + String xSeriesName = "X"; + String ySeriesName = "Y"; + double x[] = null, y[] = null; + count = 0; + for (String key : graphs.keySet()) { + List graphList = graphs.get(key); + xSeriesName = "X"; + ySeriesName = "Y"; + for (String desc : graphList) { + if (count == 0) { + x = dataProvider.cdpGetDataAsDouble(desc); + xSeriesName = desc; + ++count; + continue; + } else { + y = dataProvider.cdpGetDataAsDouble(desc); + ySeriesName = desc; + } + jchartframe.addDataSeries(x, y, xSeriesName + " vs " + ySeriesName); + } + break; + } + + //int n_test = 100; + //double x[] = new double[n_test]; + //double y[] = new double[n_test]; + //for (int i = 0; i < n_test; i++) { + // x[i] = i; + // y[i] = Math.random(); + //} + // + //jchartframe.addDataSeries(x, y, xSeriesName + " vs " + ySeriesName); + jchartframe.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + jchartframe.showChart(true); + + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public void printUsage() { + System.out.println("program -i input-file-name -f format [-s] [-v]"); + System.out.println(" -s - Show properties/descriptors in input file. Programs exits after showing."); + System.out.println(" -v - Verbose mode"); + System.out.println("Available formats:"); + for (Map.Entry entry : dataProviders.entrySet()) { + ChartDataProvider cdp = entry.getValue(); + System.out.println(" " + entry.getKey() + " - " + cdp.cdpGetDescription()); + } + } + + public void printDescriptors(Set descriptors) { + if (descriptors == null || descriptors.size() < 1) { + System.err.println("No descriptors were found"); + return; + } + + System.out.println("Number of descriptors: " + descriptors.size()); + for (String key : descriptors) { + System.out.print(key + " "); + } + System.out.println(); + } + + public static void main(String[] args) { + QuickChart quickChart = new QuickChart(); + try { + //quickChart.execute(args); + + //quickChart.execute(args); + // --- + //args = new String[]{"-i", "01_min.out", "-s", "-f", "mdout"}; + //quickChart.execute(args); + // --- + //args = new String[]{"-i", "01_min.out", "-f", "mdout", "-x", "NSTEP", "-y", "ENERGY"}; + //quickChart.execute(args); + // --- + //args = new String[]{"-i", "mden", "-s", "-f", "mden"}; + //quickChart.execute(args); + // --- + //args = new String[]{"-i", "mden", "-f", "mden", "-x", "time(ps)", "-y", "Etot"}; + args = new String[]{"-gui"}; + quickChart.execute(args); + } catch (Exception ex) { + Logger.getLogger(QuickChart.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public static Properties getProperties() { + if (chartProperties != null) { + return chartProperties; + } + + chartProperties = getProperties(CHART_PROPERTY_FILE); + return chartProperties; + } + + public static Properties getProperties(String propertiesFile) { + + String file = propertiesFile; + if (file == null || file.trim().length() < 1) { + file = CHART_PROPERTY_FILE; + } + chartProperties = null; + cctPropsURL = null; + try { + cctPropsURL = QuickChart.class.getClassLoader().getResource(QuickChart.CHART_PROPERTY_FILE); + chartProperties = new Properties(); + chartProperties.load(cctPropsURL.openStream()); + logger.info("Loaded chart properties file " + file); + } catch (Exception ex) { + logger.warning("Cannot open chart properties file " + file + ": " + ex.getMessage()); + } + return chartProperties; + } + + public void interactiveFileSelection() throws Exception { + //Create a file chooser + final JFileChooser fc = new JFileChooser(); + fc.setCurrentDirectory(new java.io.File(".")); + int returnVal = fc.showOpenDialog(null); + if (returnVal != JFileChooser.APPROVE_OPTION) { + throw new Exception("No file was selected"); + } + + fileName = fc.getSelectedFile().getAbsolutePath(); + + float highestScore = 0; + ChartDataProvider mostProbableCDP = null; + for (Map.Entry entry : dataProviders.entrySet()) { + ChartDataProvider cdp = entry.getValue(); + float score = cdp.cdpIsThisFormat(fileName); + if (score > highestScore) { + highestScore = score; + mostProbableCDP = cdp; + } + } + + dataProvider = mostProbableCDP; + + // --- Cannot determine. Ask user about that.. + if (dataProvider == null) { + Object[] possibleValues = dataProviders.keySet().toArray(); + Object selectedValue = JOptionPane.showInputDialog(null, + "Program was unable to determine format of input file\nSelect from available ones:", "Select input format", + JOptionPane.INFORMATION_MESSAGE, null, + possibleValues, possibleValues[0]); + if (selectedValue == null) { + throw new Exception("Unknown input format"); + } + + dataProvider = dataProviders.get(selectedValue); + } + } + + public void interactiveDescriptorSelection(Set descriptors) throws Exception { + + Object[] possibleValues = descriptors.toArray(); + + if (possibleValues == null || possibleValues.length < 1) { + throw new Exception("possibleValues == null || possibleValues.length < 1"); + } + + PropsToChartDialog propsToChartDialog = new PropsToChartDialog(true); + propsToChartDialog.setXAxisValues(possibleValues); + propsToChartDialog.setYAxisValues(possibleValues); + propsToChartDialog.doLayout(); + propsToChartDialog.validate(); + propsToChartDialog.setLocationByPlatform(true); + propsToChartDialog.setVisible(true); + if (!propsToChartDialog.isOkPressed()) { + throw new Exception("User cancelled selection"); + } + + Object selectedValue = propsToChartDialog.getXAxisValue(); + + // --- Old stuff... + if (false) { + selectedValue = JOptionPane.showInputDialog(null, + "Select descriptor for X-axis", "Select X-axis data", JOptionPane.INFORMATION_MESSAGE, null, + possibleValues, possibleValues[0]); + if (selectedValue == null) { + throw new Exception("User cancelled selection"); + } + } + // --- End of old stuff + + String graphLabel = ""; + List graphList = graphs.get(graphLabel); + if (graphList != null && graphList.get(0) != null && graphList.get(0).equals(selectedValue.toString())) { + throw new Exception("May be only one dataset for X-ccordinate " + graphLabel); + } else if (graphList != null && graphList.get(0) == null) { + graphList.set(0, selectedValue.toString()); + } else { + graphList = new ArrayList(); + graphList.add(selectedValue.toString()); + graphs.put(graphLabel, graphList); + } + + // ---- Select Y-axis + Object[] yaxisItems = propsToChartDialog.getYAxisValues(); + + if (false) { + selectedValue = JOptionPane.showInputDialog(null, + "Select descriptor for Y-axis", "Select Y-axis data", JOptionPane.INFORMATION_MESSAGE, null, + possibleValues, possibleValues[0]); + if (selectedValue == null) { + throw new Exception("User cancelled selection"); + } + } + + for (Object obj : yaxisItems) { + graphLabel = ""; + graphList = graphs.get(graphLabel); + if (graphList == null) { + graphList = new ArrayList(); + graphList.add(null); + graphs.put(graphLabel, graphList); + } + //graphList.add(selectedValue.toString()); + graphList.add(obj.toString()); + } + } +} diff --git a/src/main/java/cct/chart/VibrationSpectrumChart.java b/src/main/java/cct/chart/VibrationSpectrumChart.java new file mode 100644 index 0000000..436fca2 --- /dev/null +++ b/src/main/java/cct/chart/VibrationSpectrumChart.java @@ -0,0 +1,95 @@ +package cct.chart; + +import cct.interfaces.OutputResultsInterface; +import cct.modelling.VIBRATIONAL_SPECTRUM; + +/** + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class VibrationSpectrumChart { + + private OutputResultsInterface outputResultsInterface = null; + private int dimension = 5000; + + public VibrationSpectrumChart() { + } + + public VibrationSpectrumChart(OutputResultsInterface output) { + outputResultsInterface = output; + } + + public void setOutputResultsInterface(OutputResultsInterface output) { + outputResultsInterface = output; + } + + public static void main(String[] args) { + VibrationSpectrumChart vibrationspectrumchart = new VibrationSpectrumChart(); + } + + public ChartFrame createChart(VIBRATIONAL_SPECTRUM spectrum) throws Exception { + + if (outputResultsInterface == null) { + throw new Exception("createChart: OutputResultsInterface is not set"); + } + + double x[] = new double[dimension]; + double y[] = new double[dimension]; + + try { + outputResultsInterface.getSpectrum(x, y, dimension, spectrum); + } catch (Exception ex) { + throw ex; + } + + return createChart(x, y, spectrum); + + //ChartFrame chart = new ChartFrame(); + //chart.enableAnimationPanel(false); + //chart.setTitle(ChartReference.getTitle(spectrum)); + //chart.setChartTitle(ChartReference.getTitle(spectrum)); + //chart.setYAxisTitle(ChartReference.getYAxisTitle(spectrum)); + //chart.setXAxisTitle(ChartReference.getXAxisTitle(spectrum)); + //chart.addDataSeries(x, y, ChartReference.getYAxisTitle(spectrum)); + //return chart; + } + + public ChartFrame createChart(double[] x, double[] y, VIBRATIONAL_SPECTRUM spectrum) throws Exception { + ChartFrame chart = new ChartFrame(); + chart.enableAnimationPanel(false); + chart.setTitle(ChartReference.getTitle(spectrum)); + chart.setChartTitle(ChartReference.getTitle(spectrum)); + chart.setYAxisTitle(ChartReference.getYAxisTitle(spectrum)); + chart.setXAxisTitle(ChartReference.getXAxisTitle(spectrum)); + + chart.addDataSeries(x, y, ChartReference.getYAxisTitle(spectrum)); + + return createChart(x, y, ChartReference.getTitle(spectrum), ChartReference.getTitle(spectrum), + ChartReference.getXAxisTitle(spectrum), ChartReference.getYAxisTitle(spectrum)); + } + + public ChartFrame createChart(double[] x, double[] y, String winTitle, String title, String xAxis, String yAxis) throws Exception { + ChartFrame chart = new ChartFrame(); + chart.enableAnimationPanel(false); + chart.setTitle(winTitle); + chart.setChartTitle(title); + chart.setYAxisTitle(yAxis); + chart.setXAxisTitle(xAxis); + + chart.addDataSeries(x, y, yAxis); + + return chart; + } +} diff --git a/src/main/java/cct/chart/chart.properties b/src/main/java/cct/chart/chart.properties new file mode 100644 index 0000000..17c9ab5 --- /dev/null +++ b/src/main/java/cct/chart/chart.properties @@ -0,0 +1,6 @@ +# To change this license header, choose License Headers in Project Properties. +# + +mden = cct.amber.AmberMden +mdout = cct.amber.AmberMdout +g09md = cct.gaussian.G03MDTrajectory \ No newline at end of file diff --git a/src/main/java/cct/chart/images/media_beginning.png b/src/main/java/cct/chart/images/media_beginning.png new file mode 100644 index 0000000..60a0323 Binary files /dev/null and b/src/main/java/cct/chart/images/media_beginning.png differ diff --git a/src/main/java/cct/chart/images/media_end.png b/src/main/java/cct/chart/images/media_end.png new file mode 100644 index 0000000..2de17cf Binary files /dev/null and b/src/main/java/cct/chart/images/media_end.png differ diff --git a/src/main/java/cct/chart/images/media_pause.png b/src/main/java/cct/chart/images/media_pause.png new file mode 100644 index 0000000..0557de6 Binary files /dev/null and b/src/main/java/cct/chart/images/media_pause.png differ diff --git a/src/main/java/cct/chart/images/media_play.png b/src/main/java/cct/chart/images/media_play.png new file mode 100644 index 0000000..abeef45 Binary files /dev/null and b/src/main/java/cct/chart/images/media_play.png differ diff --git a/src/main/java/cct/chart/images/media_play_back.png b/src/main/java/cct/chart/images/media_play_back.png new file mode 100644 index 0000000..9516856 Binary files /dev/null and b/src/main/java/cct/chart/images/media_play_back.png differ diff --git a/src/main/java/cct/chart/images/media_step_back.png b/src/main/java/cct/chart/images/media_step_back.png new file mode 100644 index 0000000..7185171 Binary files /dev/null and b/src/main/java/cct/chart/images/media_step_back.png differ diff --git a/src/main/java/cct/chart/images/media_step_forward.png b/src/main/java/cct/chart/images/media_step_forward.png new file mode 100644 index 0000000..350c45f Binary files /dev/null and b/src/main/java/cct/chart/images/media_step_forward.png differ diff --git a/src/main/java/cct/chart/jfreechart/JFreeChartPanel.java b/src/main/java/cct/chart/jfreechart/JFreeChartPanel.java new file mode 100644 index 0000000..0ae5731 --- /dev/null +++ b/src/main/java/cct/chart/jfreechart/JFreeChartPanel.java @@ -0,0 +1,1340 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.chart.jfreechart; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.ArrayList; +import java.util.logging.Logger; + +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSlider; +import javax.swing.JSpinner; +import javax.swing.JTable; +import javax.swing.SpinnerModel; +import javax.swing.SpinnerNumberModel; +import javax.swing.Timer; +import javax.swing.border.Border; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.TableCellRenderer; +import javax.swing.table.TableModel; + +import org.jfree.chart.ChartFactory; +import org.jfree.chart.ChartPanel; +import org.jfree.chart.JFreeChart; +import org.jfree.chart.axis.AxisLocation; +import org.jfree.chart.axis.NumberAxis; +import org.jfree.chart.axis.ValueAxis; +import org.jfree.chart.event.ChartChangeEvent; +import org.jfree.chart.event.ChartChangeListener; +import org.jfree.chart.event.ChartProgressEvent; +import org.jfree.chart.event.ChartProgressListener; +import org.jfree.chart.plot.PlotOrientation; +import org.jfree.chart.plot.XYPlot; +import org.jfree.chart.renderer.xy.StandardXYItemRenderer; +import org.jfree.chart.renderer.xy.XYItemRenderer; +import org.jfree.data.Range; +import org.jfree.data.xy.XYDataItem; +import org.jfree.data.xy.XYSeries; +import org.jfree.data.xy.XYSeriesCollection; +import org.jfree.ui.NumberCellRenderer; +import org.jfree.ui.RectangleInsets; + +import cct.chart.DataSet; +import cct.modelling.StructureManagerInterface; + +/** + *

Title: Computational Chemistry Toolkit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2008 Dr. V. Vasilyev

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class JFreeChartPanel + extends JPanel implements ChartChangeListener, ChartProgressListener, ActionListener { + + public static int MAX_SLIDER_VALUE = 1000; + public Color colors[] = { + Color.black, Color.red, Color.blue, Color.green, Color.cyan, Color.magenta, Color.orange, Color.pink, Color.yellow}; + public static boolean debug = false; + private int minStep = 1, maxStep = 100, stepStep = 1; + private int Step = 1; + private static final String[] MOVIE_MODES = { + "Once", "Loop", "Rock"}; + + private BorderLayout borderLayout1 = new BorderLayout(); + + private String chartTitle = "XY Chart", xAxisTitle = "X", yAxisTitle = "Y"; + private ChartPanel chartPanel; + private XYSeriesCollection xySeriesCollection = new XYSeriesCollection(); + private java.util.List dataSets = new ArrayList (); + private double yMin, yMax, span = 0.05; + private double xMin, xMax; + private JPanel tablePanel = new JPanel(); + private JScrollPane jScrollPane1 = new JScrollPane(); + private ChartTableModel chartTableModel = null; + private BorderLayout borderLayout2 = new BorderLayout(); + //private JSplitPane jSplitPane = new JSplitPane(); + + private java.util.List indexFind = new ArrayList (); + private JPanel mainChartPanel = new JPanel(); + private BorderLayout borderLayout3 = new BorderLayout(); + private JPanel animationChartPanel = new JPanel(); + private JSlider chartSlider = new JSlider(); + private BorderLayout borderLayout4 = new BorderLayout(); + + private JFreeChart chart = null; + private JPanel animationControlPanel = new JPanel(); + private JPanel jPanel1 = new JPanel(); + private JButton stepBackButton = new JButton(); + private JButton playBackButton = new JButton(); + private JButton pauseButton = new JButton(); + private JButton playButton = new JButton(); + private JButton stepForwardButton = new JButton(); + private BorderLayout borderLayout5 = new BorderLayout(); + + private ImageIcon mediaBeginningImage = new ImageIcon(cct.chart.ChartFrame.class.getResource("images/media_beginning.png")); + private ImageIcon mediaEndImage = new ImageIcon(cct.chart.ChartFrame.class.getResource("images/media_end.png")); + private ImageIcon mediaPauseImage = new ImageIcon(cct.chart.ChartFrame.class.getResource("images/media_pause.png")); + private ImageIcon mediaPlayImage = new ImageIcon(cct.chart.ChartFrame.class.getResource("images/media_play.png")); + private ImageIcon mediaPlayBackImage = new ImageIcon(cct.chart.ChartFrame.class.getResource("images/media_play_back.png")); + private ImageIcon mediaStepBackImage = new ImageIcon(cct.chart.ChartFrame.class.getResource("images/media_step_back.png")); + private ImageIcon mediaStepForwardImage = new ImageIcon(cct.chart.ChartFrame.class.getResource("images/media_step_forward.png")); + private JButton goToEndButton = new JButton(); + private JButton goToBeginningButton = new JButton(); + + private int delay; + private int framesPerSeconds = 25; + private SpinnerModel stepModel = new SpinnerNumberModel(Step, minStep, maxStep, stepStep); + private SpinnerModel fpsModel = new SpinnerNumberModel(framesPerSeconds, 1, 100, 1); + + private int currentIndex = 0; + private int selectedStructure = 0; + private boolean animationInProgress = false; + private int animDirection = 1; + private Timer timer; + private int animationMode; + + private StructureManagerInterface structureManagerInterface = null; + + private JPanel jPanel2 = new JPanel(); + private JLabel jLabel1 = new JLabel(); + private JSpinner stepSpinner = new JSpinner(stepModel); + private JLabel jLabel2 = new JLabel(); + private JSpinner fpsSpinner = new JSpinner(fpsModel); + private JComboBox animationComboBox = new JComboBox(); + + private boolean showChartPanel = true; + private boolean showTablePanel = true; + static final Logger logger = Logger.getLogger(JFreeChartPanel.class.getCanonicalName()); + + public JFreeChartPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public java.util.List getDataSets() { + return dataSets; + } + + public void addDataSets(java.util.List dataS) { + dataSets.addAll(dataS); + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + chart = createDefaultChart(); + chartPanel = new ChartPanel(chart); + setDefaultChartOptions(); + tablePanel.setLayout(borderLayout2); + //jSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); + chartPanel.setMinimumSize(new Dimension(800, 600)); + chartPanel.setPreferredSize(new Dimension(800, 600)); + chartPanel.setZoomOutFactor(1.0); + mainChartPanel.setLayout(borderLayout3); + animationChartPanel.setLayout(borderLayout4); + chartSlider.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + chartSlider_stateChanged(e); + } + }); + stepBackButton.setMaximumSize(new Dimension(24, 24)); + stepBackButton.setMinimumSize(new Dimension(24, 24)); + stepBackButton.setPreferredSize(new Dimension(24, 24)); + stepBackButton.setToolTipText("Step Back"); + stepBackButton.setIcon(mediaStepBackImage); + stepBackButton.setMargin(new Insets(0, 0, 0, 0)); + stepBackButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + stepBackButton_actionPerformed(e); + } + }); + playBackButton.setMaximumSize(new Dimension(24, 24)); + playBackButton.setMinimumSize(new Dimension(24, 24)); + playBackButton.setPreferredSize(new Dimension(24, 24)); + playBackButton.setToolTipText("Play Back"); + playBackButton.setIcon(mediaPlayBackImage); + playBackButton.setMargin(new Insets(0, 0, 0, 0)); + playBackButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + playBackButton_actionPerformed(e); + } + }); + pauseButton.setMaximumSize(new Dimension(24, 24)); + pauseButton.setMinimumSize(new Dimension(24, 24)); + pauseButton.setPreferredSize(new Dimension(24, 24)); + pauseButton.setToolTipText("Stop/Pause Animation"); + pauseButton.setIcon(mediaPauseImage); + pauseButton.setMargin(new Insets(0, 0, 0, 0)); + pauseButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + pauseButton_actionPerformed(e); + } + }); + playButton.setMaximumSize(new Dimension(24, 24)); + playButton.setMinimumSize(new Dimension(24, 24)); + playButton.setPreferredSize(new Dimension(24, 24)); + playButton.setToolTipText("Play Forward"); + playButton.setIcon(mediaPlayImage); + playButton.setMargin(new Insets(0, 0, 0, 0)); + playButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + playButton_actionPerformed(e); + } + }); + stepForwardButton.setMaximumSize(new Dimension(24, 24)); + stepForwardButton.setMinimumSize(new Dimension(24, 24)); + stepForwardButton.setPreferredSize(new Dimension(24, 24)); + stepForwardButton.setToolTipText("Step Forward"); + stepForwardButton.setIcon(mediaStepForwardImage); + stepForwardButton.setMargin(new Insets(0, 0, 0, 0)); + stepForwardButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + stepForwardButton_actionPerformed(e); + } + }); + animationControlPanel.setLayout(borderLayout5); + goToEndButton.setMaximumSize(new Dimension(24, 24)); + goToEndButton.setMinimumSize(new Dimension(24, 24)); + goToEndButton.setPreferredSize(new Dimension(24, 24)); + goToEndButton.setToolTipText("Go to Beginning"); + goToEndButton.setIcon(mediaBeginningImage); + goToEndButton.setMargin(new Insets(0, 0, 0, 0)); + goToEndButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + goToEndButton_actionPerformed(e); + } + }); + goToBeginningButton.setMaximumSize(new Dimension(24, 24)); + goToBeginningButton.setMinimumSize(new Dimension(24, 24)); + goToBeginningButton.setPreferredSize(new Dimension(24, 24)); + goToBeginningButton.setToolTipText("Go to End"); + goToBeginningButton.setIcon(mediaEndImage); + goToBeginningButton.setMargin(new Insets(0, 0, 0, 0)); + goToBeginningButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + goToBeginningButton_actionPerformed(e); + } + }); + jLabel1.setText("Step: "); + jLabel2.setToolTipText(""); + jLabel2.setText("Frames per second: "); + stepSpinner.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + stepSpinner_stateChanged(e); + } + }); + fpsSpinner.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + fpsSpinner_stateChanged(e); + } + }); + animationComboBox.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + animationComboBox_itemStateChanged(e); + } + }); + mainChartPanel.setMinimumSize(new Dimension(500, 300)); + mainChartPanel.setPreferredSize(new Dimension(500, 300)); + mainChartPanel.setToolTipText(""); + tablePanel.setMinimumSize(new Dimension(500, 70)); + tablePanel.setPreferredSize(new Dimension(500, 70)); + tablePanel.setToolTipText(""); + this.setMinimumSize(new Dimension(500, 400)); + this.setPreferredSize(new Dimension(500, 400)); + this.setToolTipText(""); + jScrollPane1.setMinimumSize(new Dimension(500, 100)); + jScrollPane1.setPreferredSize(new Dimension(500, 100)); + tablePanel.add(jScrollPane1, BorderLayout.CENTER); //this.add(jSplitPane, java.awt.BorderLayout.CENTER); + //jSplitPane.add(tablePanel, JSplitPane.BOTTOM); + add(tablePanel, BorderLayout.SOUTH); + mainChartPanel.add(chartPanel, BorderLayout.CENTER); + mainChartPanel.add(animationChartPanel, BorderLayout.SOUTH); + animationChartPanel.add(animationControlPanel, BorderLayout.SOUTH); + jPanel1.add(goToEndButton); + jPanel1.add(stepBackButton); + jPanel1.add(playBackButton); + jPanel1.add(pauseButton); + jPanel1.add(playButton); + jPanel1.add(stepForwardButton); + jPanel1.add(goToBeginningButton); + jPanel2.add(jLabel1); + jPanel2.add(stepSpinner); + jPanel2.add(jLabel2); + jPanel2.add(fpsSpinner); + jPanel2.add(animationComboBox); + animationChartPanel.add(chartSlider, BorderLayout.NORTH); + animationControlPanel.add(jPanel2, BorderLayout.SOUTH); + animationControlPanel.add(jPanel1, BorderLayout.NORTH); + this.add(mainChartPanel, BorderLayout.CENTER); //Set up a timer that calls this object's action handler. + delay = 1000 / framesPerSeconds; + //timer.setDelay(delay); + //timer.setInitialDelay(delay * 10); + + timer = new Timer(delay, this); + //timer.setInitialDelay(delay * 7); //We pause animation twice per cycle by restarting the timer + timer.setCoalesce(true); + + for (int i = 0; i < MOVIE_MODES.length; i++) { + animationComboBox.addItem(MOVIE_MODES[i]); + } + animationComboBox.setSelectedIndex(0); + animationMode = animationComboBox.getSelectedIndex(); + + this.validate(); + } + + public void enableAnimationPanel(boolean enable) { + animationControlPanel.setVisible(enable); + } + + private void setDefaultChartOptions() { + chartPanel.setPreferredSize(new Dimension(640, 480)); + chartPanel.setDomainZoomable(true); + chartPanel.setRangeZoomable(true); + Border border = BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4), + BorderFactory.createEtchedBorder()); + this.chartPanel.setBorder(border); + } + + public void startAnimation() { + //Start (or restart) animating! + timer.start(); + } + + private JFreeChart createDefaultChart() { + + XYSeries series1 = new XYSeries("First"); + series1.add(1.0, 1.0); + series1.add(2.0, 4.0); + series1.add(3.0, 3.0); + series1.add(4.0, 5.0); + series1.add(5.0, 5.0); + series1.add(6.0, 7.0); + series1.add(7.0, 7.0); + series1.add(8.0, 8.0); + XYSeries series2 = new XYSeries("Second"); + series2.add(1.0, 5.0); + series2.add(2.0, 7.0); + series2.add(3.0, 6.0); + series2.add(4.0, 8.0); + series2.add(5.0, 4.0); + series2.add(6.0, 4.0); + series2.add(7.0, 2.0); + series2.add(8.0, 1.0); + XYSeries series3 = new XYSeries("Third"); + series3.add(3.0, 4.0); + series3.add(4.0, 3.0); + series3.add(5.0, 2.0); + series3.add(6.0, 3.0); + series3.add(7.0, 6.0); + series3.add(8.0, 3.0); + series3.add(9.0, 4.0); + series3.add(10.0, 3.0); + XYSeriesCollection dataset = new XYSeriesCollection(); + dataset.addSeries(series1); + //dataset.addSeries(series2); + //dataset.addSeries(series3); + + chart = ChartFactory.createXYLineChart( + chartTitle, // chart title + xAxisTitle, // x axis label + yAxisTitle, // y axis label + null, // data + PlotOrientation.VERTICAL, + true, // include legend + true, // tooltips + false // urls + ); + + XYPlot plot = (XYPlot) chart.getPlot(); + + // AXIS 1 + NumberAxis axis1 = new NumberAxis("Range Axis 1"); + axis1.setFixedDimension(10.0); + axis1.setAutoRangeIncludesZero(false); + axis1.setLabelPaint(Color.black); + axis1.setTickLabelPaint(Color.black); + plot.setRangeAxis(0, axis1); + plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_LEFT); + + XYSeriesCollection dataset1 = new XYSeriesCollection(); + dataset1.addSeries(series1); + plot.setDataset(0, dataset1); + plot.mapDatasetToRangeAxis(0, 0); + XYItemRenderer renderer1 = new StandardXYItemRenderer(); + renderer1.setSeriesPaint(0, Color.BLACK); + plot.setRenderer(0, renderer1); + + // AXIS 2 + NumberAxis axis2 = new NumberAxis("Range Axis 2"); + axis2.setFixedDimension(10.0); + axis2.setAutoRangeIncludesZero(false); + axis2.setLabelPaint(Color.red); + axis2.setTickLabelPaint(Color.red); + plot.setRangeAxis(1, axis2); + plot.setRangeAxisLocation(1, AxisLocation.BOTTOM_OR_LEFT); + + XYSeriesCollection dataset2 = new XYSeriesCollection(); + dataset2.addSeries(series2); + plot.setDataset(1, dataset2); + plot.mapDatasetToRangeAxis(1, 1); + XYItemRenderer renderer2 = new StandardXYItemRenderer(); + renderer2.setSeriesPaint(0, Color.red); + plot.setRenderer(1, renderer2); + + // AXIS 3 + NumberAxis axis3 = new NumberAxis("Range Axis 3"); + axis3.setLabelPaint(Color.blue); + axis3.setTickLabelPaint(Color.blue); + plot.setRangeAxis(2, axis3); + + XYSeriesCollection dataset3 = new XYSeriesCollection(series3); + plot.setDataset(2, dataset3); + plot.mapDatasetToRangeAxis(2, 2); + XYItemRenderer renderer3 = new StandardXYItemRenderer(); + renderer3.setSeriesPaint(0, Color.blue); + plot.setRenderer(2, renderer3); + + int n = 7; + chartTableModel = new ChartTableModel(3); + + for (int row = 0; row < 3; row++) { + + //chartTableModel.setValueAt(plot.getDataset(row).getSeriesKey(0), row, 0); + chartTableModel.setValueAt(new Double("0.00"), row, 0); + chartTableModel.setValueAt(new Double("0.00"), row, 1); + chartTableModel.setValueAt(new Double("0.00"), row, 2); + chartTableModel.setValueAt(new Double("0.00"), row, 3); + chartTableModel.setValueAt(new Double("0.00"), row, 4); + chartTableModel.setValueAt(new Double("0.00"), row, 5); + chartTableModel.setValueAt(new Double("0.00"), row, 6); + } + + JTable table = new JTable(chartTableModel); + //TableCellRenderer renderer2 = new NumberCellRenderer(); + /* + table.getColumnModel().getColumn(1).setCellRenderer(renderer2); + table.getColumnModel().getColumn(2).setCellRenderer(renderer2); + table.getColumnModel().getColumn(3).setCellRenderer(renderer2); + table.getColumnModel().getColumn(4).setCellRenderer(renderer2); + table.getColumnModel().getColumn(5).setCellRenderer(renderer2); + table.getColumnModel().getColumn(6).setCellRenderer(renderer2); + + */ + jScrollPane1.getViewport().add(table); + return chart; + } + + private JFreeChart createChart() { + + if (dataSets.size() < 1) { + chart = ChartFactory.createXYLineChart( + "Empty Chart (no dataset supplied)", // chart title + "X", // x axis label + "Y", // y axis label + null, // + //dataSets.get(0).getDataCollection(), // + PlotOrientation.VERTICAL, + true, // include legend + true, // tooltips + false // urls + ); + + return chart; + } + + if (dataSets.size() == 1) { + chart = ChartFactory.createXYLineChart( + chartTitle, // chart title + xAxisTitle, // x axis label + dataSets.get(0).getDataCollection().getSeries(0).getDescription(), // y axis label + dataSets.get(0).getDataCollection(), // + PlotOrientation.VERTICAL, + true, // include legend + true, // tooltips + false // urls + ); + XYPlot plot = (XYPlot) chart.getPlot(); + ValueAxis rangeAxis = plot.getRangeAxis(); + if (rangeAxis instanceof NumberAxis) { + ( (NumberAxis) rangeAxis).setAutoRangeIncludesZero(false); + } + } + else { + chart = ChartFactory.createXYLineChart( + chartTitle, // chart title + xAxisTitle, // x axis label + dataSets.get(0).getDataCollection().getSeries(0).getDescription(), // y axis label + null, // + //dataSets.get(0).getDataCollection(), // + PlotOrientation.VERTICAL, + true, // include legend + true, // tooltips + false // urls + ); + + XYPlot plot = (XYPlot) chart.getPlot(); + /* + NumberAxis axis1 = new NumberAxis(dataSets.get(0).getDataCollection().getSeries(0).getDescription()); + axis1.setAutoRangeIncludesZero(false); + axis1.setLabelPaint(Color.black); + axis1.setTickLabelPaint(Color.black); + plot.setRangeAxis(0, axis1); + + XYItemRenderer renderer1 = new StandardXYItemRenderer(); + renderer1.setSeriesPaint(0, Color.black); + plot.setRenderer(0, renderer1); + */ + for (int i = 0; i < dataSets.size(); i++) { + Color color = colors[i % colors.length]; + DataSet data_set = dataSets.get(i); + XYSeriesCollection dataset2 = data_set.getDataCollection(); + NumberAxis axis2 = new NumberAxis(dataset2.getSeries(0).getDescription()); + //axis2.setFixedDimension(10.0); + axis2.setAutoRangeIncludesZero(false); + axis2.setLabelPaint(color); + axis2.setTickLabelPaint(color); + + plot.setRangeAxis(i, axis2); + if (i % 2 == 0) { + plot.setRangeAxisLocation(i, AxisLocation.BOTTOM_OR_LEFT); + } + else { + plot.setRangeAxisLocation(i, AxisLocation.BOTTOM_OR_RIGHT); + } + //plot.setRangeAxisLocation(i, AxisLocation.BOTTOM_OR_LEFT); + plot.setDataset(i, dataset2); + plot.mapDatasetToRangeAxis(i, i); + XYItemRenderer renderer2 = new StandardXYItemRenderer(); + renderer2.setSeriesPaint(0, color); + plot.setRenderer(i, renderer2); + + } + /* + ValueAxis rangeAxis = plot.getRangeAxis(); + double range = yMax - yMin; + rangeAxis.setRange(yMin - range * span, yMax + range * span); + plot.setRangeAxis(rangeAxis); + + logger.info("Low: " + rangeAxis.getRange().getLowerBound() + " High: " + rangeAxis.getRange().getUpperBound()); + */ + + } + + chart.addChangeListener(this); + chart.addProgressListener(this); + chart.setBackgroundPaint(Color.white); + + XYPlot plot = (XYPlot) chart.getPlot(); + + plot.setOrientation(PlotOrientation.VERTICAL); + plot.setBackgroundPaint(Color.lightGray); + plot.setDomainGridlinePaint(Color.white); + plot.setRangeGridlinePaint(Color.white); + plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); + + plot.setDomainCrosshairVisible(true); + plot.setDomainCrosshairLockedOnData(true); + plot.setRangeCrosshairVisible(false); + + //XYItemRenderer renderer = plot.getRenderer(); + //renderer.setSeriesPaint(0, Color.black); + + return chart; + } + + public void setChartTitle(String title) { + chartTitle = title; + } + + public void setXAxisTitle(String title) { + xAxisTitle = title; + } + + public void setYAxisTitle(String title) { + yAxisTitle = title; + } + + @Override + public void chartChanged(ChartChangeEvent event) { + + /* + if (this.chartPanel != null) { + JFreeChart chart = this.chartPanel.getChart(); + if (chart != null) { + XYPlot plot = (XYPlot) chart.getPlot(); + double xx = plot.getDomainCrosshairValue(); + logger.info("Domain Crosshair Value: " + xx); + } + } + */ + /* + if (this.chartPanel != null) { + JFreeChart chart = this.chartPanel.getChart(); + if (chart != null) { + XYPlot plot = (XYPlot) chart.getPlot(); + XYDataset dataset = plot.getDataset(); + Comparable seriesKey = dataset.getSeriesKey(0); + double xx = plot.getDomainCrosshairValue(); + this.model.setValueAt(seriesKey, 0, 0); + long millis = (long) xx; + for (int row = 0; row < SERIES_COUNT; row++) { + this.model.setValueAt(new Long(millis), row, 1); + int[] bounds + = this.datasets[row].getSurroundingItems(0, millis); + long prevX = 0; + long nextX = 0; + double prevY = 0.0; + double nextY = 0.0; + if (bounds[0] >= 0) { + TimeSeriesDataItem prevItem + = this.series[row].getDataItem(bounds[0]); + prevX = prevItem.getPeriod().getMiddleMillisecond(); + Number y = prevItem.getValue(); + if (y != null) { + prevY = y.doubleValue(); + this.model.setValueAt(new Double(prevY), row, + 4); + } + else { + this.model.setValueAt(null, row, 4); + } + this.model.setValueAt(new Long(prevX), row, 3); + } + else { + this.model.setValueAt(new Double(0.00), row, 4); + this.model.setValueAt(new Double(plot.getDomainAxis().getRange().getLowerBound()), row, 3); + } + if (bounds[1] >= 0) { + TimeSeriesDataItem nextItem + = this.series[row].getDataItem(bounds[1]); + nextX = nextItem.getPeriod().getMiddleMillisecond(); + Number y = nextItem.getValue(); + if (y != null) { + nextY = y.doubleValue(); + this.model.setValueAt(new Double(nextY), row, + 6); + } + else { + this.model.setValueAt(null, row, 6); + } + this.model.setValueAt(new Long(nextX), row, 5); + } + else { + this.model.setValueAt(new Double(0.00), row, 6); + this.model.setValueAt(new Double(plot.getDomainAxis().getRange().getUpperBound()), row, 5); + } + double interpolatedY = 0.0; + if ( (nextX - prevX) > 0) { + interpolatedY = prevY + ( ( (double) millis + - (double) prevX) / ( (double) nextX - (double) prevX)) * (nextY - prevY); + } + else { + interpolatedY = prevY; + } + this.model.setValueAt(new Double(interpolatedY), row, 2); + } + } + } + */ + } + + @Override + public void chartProgress(ChartProgressEvent event) { + + if (event.getType() != ChartProgressEvent.DRAWING_FINISHED) { + return; + } + if (this.chartPanel != null) { + JFreeChart c = this.chartPanel.getChart(); + if (c != null) { + XYPlot plot = (XYPlot) c.getPlot(); + Double xx = plot.getDomainCrosshairValue(); + if (debug) { + logger.info("Crosshair Value: " + xx); + } + + ValueAxis domainAxis = plot.getDomainAxis(); + Range range = domainAxis.getRange(); + if (debug) { + logger.info("Domain axis range: " + range.toString()); + } + + double step = range.getLength() / chartSlider.getMaximum(); + // --- Assume that minimum value of slider is zero !!! + int slider_value = (int) ( (xx - domainAxis.getLowerBound()) / step); + chartSlider.setEnabled(false); + chartSlider.setValue(slider_value); + chartSlider.setEnabled(true); + + //for (int i = 0; i < xySeriesCollection.getSeriesCount(); i++) { + for (int i = 0; i < dataSets.size(); i++) { + XYSeries series = dataSets.get(i).getDataCollection().getSeries(0); + //XYSeries series = xySeriesCollection.getSeries(i); + java.util.List toIndex = indexFind.get(i); + int index = toIndex.indexOf(xx); + if (index == -1) { + index = calculateIndex(xx, toIndex); + } + currentIndex = index; + XYDataItem yxItem = series.getDataItem(index); + chartTableModel.setValueAt(new Double(yxItem.getXValue()), i, 1); + chartTableModel.setValueAt(new Double(yxItem.getYValue()), i, 2); + + // --- Set previous values + if (index > 0) { + yxItem = series.getDataItem(index - 1); + chartTableModel.setValueAt(new Double(yxItem.getXValue()), i, 3); + chartTableModel.setValueAt(new Double(yxItem.getYValue()), i, 4); + } + else { + chartTableModel.setValueAt(new Double(yxItem.getXValue()), i, 3); + chartTableModel.setValueAt(new Double(yxItem.getYValue()), i, 4); + } + + // --- Set next values + if (index < toIndex.size() - 1) { + yxItem = series.getDataItem(index + 1); + chartTableModel.setValueAt(new Double(yxItem.getXValue()), i, 5); + chartTableModel.setValueAt(new Double(yxItem.getYValue()), i, 6); + } + else { + yxItem = series.getDataItem(index); + chartTableModel.setValueAt(new Double(yxItem.getXValue()), i, 5); + chartTableModel.setValueAt(new Double(yxItem.getYValue()), i, 6); + } + + if (selectedStructure == currentIndex) { + continue; + } + + if (structureManagerInterface != null) { + try { + structureManagerInterface.selectStructure(currentIndex, + dataSets.get(0).getDataCollection().getSeries(0).getDescription()); // We use the first plot + selectedStructure = currentIndex; + } + catch (Exception ex) { + System.err.println("Cannot select structure " + currentIndex + " : " + ex.getMessage()); + } + } + } + } + } + + /* + if (this.chartPanel != null) { + JFreeChart c = this.chartPanel.getChart(); + if (c != null) { + XYPlot plot = (XYPlot) c.getPlot(); + XYDataset dataset = plot.getDataset(); + Comparable seriesKey = dataset.getSeriesKey(0); + double xx = plot.getDomainCrosshairValue(); + // update the table... + this.model.setValueAt(seriesKey, 0, 0); + long millis = (long) xx; + this.model.setValueAt(new Long(millis), 0, 1); + for (int i = 0; i < SERIES_COUNT; i++) { + int itemIndex = this.series[i].getIndex(new Minute(new Date(millis))); + if (itemIndex >= 0) { + TimeSeriesDataItem item = this.series[i].getDataItem(Math.min(199, Math.max(0, itemIndex))); + TimeSeriesDataItem prevItem = this.series[i].getDataItem(Math.max(0, itemIndex - 1)); + TimeSeriesDataItem nextItem = this.series[i].getDataItem(Math.min(199, itemIndex + 1)); + long x = item.getPeriod().getMiddleMillisecond(); + double y = item.getValue().doubleValue(); + long prevX = prevItem.getPeriod().getMiddleMillisecond(); + double prevY = prevItem.getValue().doubleValue(); + long nextX = nextItem.getPeriod().getMiddleMillisecond(); + double nextY = nextItem.getValue().doubleValue(); + this.model.setValueAt(new Long(x), i, 1); + this.model.setValueAt(new Double(y), i, 2); + this.model.setValueAt(new Long(prevX), i, 3); + this.model.setValueAt(new Double(prevY), i, 4); + this.model.setValueAt(new Long(nextX), i, 5); + this.model.setValueAt(new Double(nextY), i, 6); + } + } + } + } + */ + } + +// --- ChartInterface functions + + public void addDataSeries(double x[], double y[], String name) throws Exception { + addDataSeries(x, y, x.length, name); + } + + public void addDataSeries(double x[], double y[], int n, String name) throws Exception { + if (n > Math.min(x.length, y.length)) { + throw new Exception("n(" + n + ") > Math.min(x.length, y.length)(" + Math.min(x.length, y.length) + ")"); + } + + double yMin = y[0], yMax = y[0]; + if (dataSets.size() < 1) { + //yMin = yMax = y[0]; + xMin = xMax = x[0]; + } + + java.util.List toIndex = new ArrayList (x.length); + XYSeries series = new XYSeries(name); + series.setDescription(name); + + for (int i = 0; i < n; i++) { + series.add(x[i], y[i]); + toIndex.add(new Double(x[i])); + if (yMin > y[i]) { + yMin = y[i]; + } + else if (yMax < y[i]) { + yMax = y[i]; + } + if (xMin > x[i]) { + xMin = x[i]; + } + else if (xMax < x[i]) { + xMax = x[i]; + } + + } + + if (chartSlider.getMaximum() < x.length && chartSlider.getMaximum() < MAX_SLIDER_VALUE) { + chartSlider.setMaximum(x.length); + } + + XYSeriesCollection xySC = new XYSeriesCollection(); + xySC.addSeries(series); + indexFind.add(toIndex); + + DataSet dataSet = new DataSet(yMin, yMax, xySC); + dataSets.add(dataSet); + + /* + if (xySeriesCollection.getSeriesCount() == 0) { + //jSplitPane.removeAll(); + } + + if (xySeriesCollection.getSeriesCount() < 1) { + yMin = yMax = y[0]; + xMin = xMax = x[0]; + } + + ArrayList toIndex = new ArrayList (x.length); + XYSeries series = new XYSeries(name); + series.setDescription(name); + + for (int i = 0; i < n; i++) { + series.add(x[i], y[i]); + toIndex.add(new Double(x[i])); + if (yMin > y[i]) { + yMin = y[i]; + } + else if (yMax < y[i]) { + yMax = y[i]; + } + if (xMin > x[i]) { + xMin = x[i]; + } + else if (xMax < x[i]) { + xMax = x[i]; + } + + } + + if (chartSlider.getMaximum() < x.length && chartSlider.getMaximum() < MAX_SLIDER_VALUE) { + chartSlider.setMaximum(x.length); + } + + xySeriesCollection.addSeries(series); + this.indexFind.add(toIndex); + */ + } + + public void showChart(boolean enable) { + //if ( true) return; + mainChartPanel.remove(chartPanel); + + if (showChartPanel) { + + JFreeChart chart = createChart(); + chartPanel = new ChartPanel(chart); + setDefaultChartOptions(); + mainChartPanel.add(chartPanel, BorderLayout.CENTER); + + //chartTableModel = new ChartTableModel(xySeriesCollection.getSeriesCount()); + chartTableModel = new ChartTableModel(dataSets.size()); + + for (int row = 0; row < dataSets.size(); row++) { + DataSet data_set = dataSets.get(row); + chartTableModel.setValueAt(data_set.getDataCollection().getSeries(0).getDescription(), row, 0); + chartTableModel.setValueAt(new Double("0.00"), row, 1); + chartTableModel.setValueAt(new Double("0.00"), row, 2); + chartTableModel.setValueAt(new Double("0.00"), row, 3); + chartTableModel.setValueAt(new Double("0.00"), row, 4); + chartTableModel.setValueAt(new Double("0.00"), row, 5); + chartTableModel.setValueAt(new Double("0.00"), row, 6); + } + } + /* + for (int row = 0; row < xySeriesCollection.getSeriesCount(); row++) { + XYPlot plot = (XYPlot) chart.getPlot(); + XYSeries series = xySeriesCollection.getSeries(row); + chartTableModel.setValueAt(series.getDescription(), row, 0); + chartTableModel.setValueAt(new Double("0.00"), row, 1); + chartTableModel.setValueAt(new Double("0.00"), row, 2); + chartTableModel.setValueAt(new Double("0.00"), row, 3); + chartTableModel.setValueAt(new Double("0.00"), row, 4); + chartTableModel.setValueAt(new Double("0.00"), row, 5); + chartTableModel.setValueAt(new Double("0.00"), row, 6); + } + */ + + jScrollPane1.getViewport().removeAll(); + if (showTablePanel) { + JTable table = new JTable(chartTableModel); + TableCellRenderer renderer2 = new NumberCellRenderer(); + table.getColumnModel().getColumn(1).setCellRenderer(renderer2); + table.getColumnModel().getColumn(2).setCellRenderer(renderer2); + table.getColumnModel().getColumn(3).setCellRenderer(renderer2); + table.getColumnModel().getColumn(4).setCellRenderer(renderer2); + table.getColumnModel().getColumn(5).setCellRenderer(renderer2); + table.getColumnModel().getColumn(6).setCellRenderer(renderer2); + jScrollPane1.getViewport().add(table); + } + + //jSplitPane.add(tablePanel, JSplitPane.BOTTOM); + + chartSlider.setEnabled(false); + chartSlider.setValue(0); + chartSlider.setEnabled(true); + + this.validate(); + } + + static class ChartTableModel + extends AbstractTableModel implements TableModel { + + private Object[][] data; + + /** + * Creates a new table model + * + * @param rows the row count. + */ + public ChartTableModel(int rows) { + this.data = new Object[rows][7]; + } + + /** + * Returns the column count. + * + * @return 7. + */ + @Override + public int getColumnCount() { + return 7; + } + + /** + * Returns the row count. + * + * @return The row count. + */ + @Override + public int getRowCount() { + return this.data.length; + } + + /** + * Returns the value at the specified cell in the table. + * + * @param row the row index. + * @param column the column index. + * + * @return The value. + */ + @Override + public Object getValueAt(int row, int column) { + return this.data[row][column]; + } + + /** + * Sets the value at the specified cell. + * + * @param value the value. + * @param row the row index. + * @param column the column index. + */ + @Override + public void setValueAt(Object value, int row, int column) { + this.data[row][column] = value; + fireTableDataChanged(); + } + + /** + * Returns the column name. + * + * @param column the column index. + * + * @return The column name. + */ + @Override + public String getColumnName(int column) { + switch (column) { + case 0: + return "Series Name:"; + case 1: + return "X:"; + case 2: + return "Y:"; + case 3: + return "X (prev)"; + case 4: + return "Y (prev):"; + case 5: + return "X (next):"; + case 6: + return "Y (next):"; + } + return null; + } + + } + + public void chartSlider_stateChanged(ChangeEvent e) { + if (!chartSlider.isEnabled()) { + return; + } + int value = chartSlider.getValue(); + XYPlot plot = (XYPlot)this.chartPanel.getChart().getPlot(); + ValueAxis domainAxis = plot.getDomainAxis(); + Range range = domainAxis.getRange(); + double c = domainAxis.getLowerBound() + (value / (double) chartSlider.getMaximum()) * range.getLength(); + plot.setDomainCrosshairValue(c); + } + + private int calculateIndex(double value, java.util.List toIndex) { + int index = 0; + double x_min = toIndex.get(0); + if (value <= x_min) { + return 0; + } + double x_max = toIndex.get(toIndex.size() - 1); + if (value >= x_max) { + return toIndex.size() - 1; + } + + double step = (x_max - x_min) / (toIndex.size() - 1); + double real_ind = (value - x_min) / step; + int lower_ind = (int) Math.floor(real_ind); + if (lower_ind == toIndex.size() - 1) { + return lower_ind; + } + + double low = toIndex.get(lower_ind); + double high = toIndex.get(lower_ind + 1); + + if (value >= low && value <= high) { // Simple case (uniform distribution) + if ( (value - low) < (high - value)) { + return lower_ind; + } + return lower_ind + 1; + } + + else if (value < low) { + for (index = lower_ind - 1; index >= 0; index--) { + low = toIndex.get(index); + high = toIndex.get(index + 1); + if (value >= low && value <= high) { // Simple case + if ( (value - low) < (high - value)) { + return index; + } + return index + 1; + } + } + } + else if (value > high) { + for (index = lower_ind + 1; index < toIndex.size(); index++) { + low = toIndex.get(index); + high = toIndex.get(index + 1); + if (value >= low && value <= high) { // Simple case + if ( (value - low) < (high - value)) { + return index; + } + return index + 1; + } + } + + } + + return index; + } + + public void goToEndButton_actionPerformed(ActionEvent e) { + XYPlot plot = (XYPlot)this.chartPanel.getChart().getPlot(); + plot.setDomainCrosshairValue(xMin); + } + + public void goToBeginningButton_actionPerformed(ActionEvent e) { + XYPlot plot = (XYPlot)this.chartPanel.getChart().getPlot(); + plot.setDomainCrosshairValue(xMax); + + } + + public void stepBackButton_actionPerformed(ActionEvent e) { + if (currentIndex <= 0) { + return; + } + --currentIndex; + java.util.List toIndex = indexFind.get(0); + XYPlot plot = (XYPlot)this.chartPanel.getChart().getPlot(); + plot.setDomainCrosshairValue(toIndex.get(currentIndex)); + } + + public void stepForwardButton_actionPerformed(ActionEvent e) { + java.util.List toIndex = indexFind.get(0); + if (currentIndex >= toIndex.size() - 1) { + return; + } + ++currentIndex; + XYPlot plot = (XYPlot)this.chartPanel.getChart().getPlot(); + plot.setDomainCrosshairValue(toIndex.get(currentIndex)); + + } + + public void playButton_actionPerformed(ActionEvent e) { + if (animationInProgress && animDirection == 1) { + return; + } + + animDirection = 1; + + startAnimation(); + } + + public void stepSpinner_stateChanged(ChangeEvent e) { + Integer value = (Integer) stepSpinner.getValue(); + stepStep = value; + } + + public void fpsSpinner_stateChanged(ChangeEvent e) { + Integer value = (Integer) fpsSpinner.getValue(); + framesPerSeconds = value; + delay = 1000 / framesPerSeconds; + timer.setDelay(delay); + } + + /** + * Called when the Timer fires. + * @param e ActionEvent + */ + @Override + public void actionPerformed(ActionEvent e) { + + if (animationInProgress) { + logger.info("Lost frame..."); + return; + } + animationInProgress = true; + + java.util.List toIndex = indexFind.get(0); + + int value = Step + stepStep * animDirection; + if (value < 1) { + value = 1; + } + else if (value > toIndex.size()) { + value = toIndex.size() - 1; + } + + Step = value; + + try { + long start = System.currentTimeMillis(); + XYPlot plot = (XYPlot)this.chartPanel.getChart().getPlot(); + currentIndex = Step - 1; + plot.setDomainCrosshairValue(toIndex.get(currentIndex)); + //selectStructure(Step); + //structureManagerInterface.selectStructure(currentIndex); + float secs = (System.currentTimeMillis() - start) / 1000.0f; + logger.info("Elapsed time: " + secs); + //setSnapshotValue(Step); + } + catch (Exception ex) { + animationInProgress = false; + timer.stop(); + JOptionPane.showMessageDialog(this, "Error during animation: " + ex.getMessage() + "\nAnimation stopped", "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + if (animationMode == 0) { // Animate once + if (Step == 1 && animDirection == -1) { + stopAnimation(); + } + else if (Step == toIndex.size() && animDirection == 1) { + stopAnimation(); + } + } + + else if (animationMode == 1) { // Animate in loop + if (Step == 1 && animDirection == -1) { + Step = toIndex.size(); + } + else if (Step == toIndex.size() && animDirection == 1) { + Step = 1; + } + } + + else if (animationMode == 2) { // Animate back & forth + if (Step == 1 && animDirection == -1) { + if (toIndex.size() > 1) { + Step = 1; + animDirection = 1; + } + } + else if (Step == toIndex.size() && animDirection == 1) { + if (toIndex.size() > 1) { + Step = toIndex.size() - 1; + animDirection = -1; + } + } + } + + animationInProgress = false; + } + + public void stopAnimation() { + //Stop animation + timer.stop(); + animationInProgress = false; + } + + public void playBackButton_actionPerformed(ActionEvent e) { + if (animationInProgress && animDirection == -1) { + return; + } + + animDirection = -1; + startAnimation(); + } + + public void pauseButton_actionPerformed(ActionEvent e) { + stopAnimation(); + } + + public void animationComboBox_itemStateChanged(ItemEvent e) { + if (!animationComboBox.isEnabled()) { + return; + } + if (e.getStateChange() == ItemEvent.DESELECTED) { + return; + } + else if (e.getStateChange() == ItemEvent.SELECTED) { + animationMode = animationComboBox.getSelectedIndex(); + } + } + + public void setStructureManagerInterface(StructureManagerInterface smi) { + structureManagerInterface = smi; + } + + public void enableChartPanel(boolean enable) { + showChartPanel = enable; + } + + public void enableTablePanel(boolean enable) { + showTablePanel = enable; + } +} diff --git a/src/main/java/cct/config/FormatObject.java b/src/main/java/cct/config/FormatObject.java new file mode 100644 index 0000000..eead2b1 --- /dev/null +++ b/src/main/java/cct/config/FormatObject.java @@ -0,0 +1,231 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.config; + +import cct.modelling.AbstractDataParser; +import cct.tools.Utils; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Logger; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpression; +import javax.xml.xpath.XPathFactory; +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * + * @author vvv900 + */ +public class FormatObject { + + static final String NAME = "name"; + static final String DESCRIPTION = "desc"; + static final String EXTENSIONS = "ext"; + static final String PARSER = "parser"; + public static final String FORMATS_TAG = "formats"; + public static final String FORMAT_TAG = "format"; + static final String FORMAT_NODES_PATH = FORMATS_TAG + "/" + FORMAT_TAG; + static final Logger logger = Logger.getLogger(FormatObject.class.getCanonicalName()); + private String name, description, extensions; + private Object parser; + private static final String formatsPathExpr = "//" + FORMATS_TAG + "/" + FORMAT_TAG; + private static final String nameXPath = "@" + NAME; + private static final String descXPath = "@" + DESCRIPTION; + private static final String extXPath = "@" + EXTENSIONS; + private static final String parserXPath = "@" + PARSER; + private static XPath xPath; + private static XPathExpression formatsPath, namePath, descPath, extPath, parserPath; + + public FormatObject(String name, String description, String extensions, String parserClass) { + this.name = name; + this.description = description; + this.extensions = extensions; + if (parserClass != null && parserClass.length() > 0) { + try { + logger.info("Loading class " + parserClass + "..."); + parser = Utils.loadClass(parserClass); + logger.info("Loaded class " + parserClass + "..."); + if (parser instanceof AbstractDataParser) { + if (name != null && name.trim().length() > 0) { + ((AbstractDataParser) parser).setName(name); + } + if (description != null && description.trim().length() > 0) { + ((AbstractDataParser) parser).setDescription(description); + } + if (extensions != null && extensions.trim().length() > 0) { + ((AbstractDataParser) parser).setExtensions(extensions); + } + } + } catch (Exception ex) { + logger.severe("Cannot load class " + parserClass + " : " + ex.getMessage()); + } + } + } + + public AbstractDataParser newParserInstance() throws Exception { + AbstractDataParser prsr = (AbstractDataParser) parser.getClass().newInstance(); + prsr.setDescription(((AbstractDataParser) parser).getDescription()); + prsr.setExtensions(((AbstractDataParser) parser).getExtensions()); + prsr.setName(((AbstractDataParser) parser).getName()); + prsr.setUseDialog(((AbstractDataParser) parser).isUseDialog()); + return prsr; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getExtensions() { + return extensions; + } + + public void setExtensions(String extensions) { + this.extensions = extensions; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Object getParser() { + return parser; + } + + public void setParser(Object parser) { + this.parser = parser; + } + + public static Map getFormatObjects(Document doc) throws Exception { + if (doc == null) { + throw new Exception("doc == null"); + } + + if (xPath == null) { + xPath = XPathFactory.newInstance().newXPath(); + formatsPath = xPath.compile(formatsPathExpr); + namePath = xPath.compile(nameXPath); + descPath = xPath.compile(descXPath); + extPath = xPath.compile(extXPath); + parserPath = xPath.compile(parserXPath); + } + + NodeList list = (NodeList) formatsPath.evaluate(doc, XPathConstants.NODESET); + //doc.getElementsByTagName("./" + FORMAT_NODES_PATH); + if (list.getLength() < 1) { + throw new Exception("Document does not contain path " + formatsPathExpr); + } + + Map forms = new HashMap(); + + for (int i = 0; i < list.getLength(); i++) { + + // Get element + Node node = list.item(i); + + logger.info(node.getNodeName() + " : " + node.getNodeValue()); + + NamedNodeMap attr = node.getAttributes(); + + if (attr == null || attr.getLength() < 1) { + continue; + } + + // --- Get Name + + Node nameN = attr.getNamedItem(NAME); + + if (nameN == null) { + logger.warning("No name for format. Ignored..."); + continue; + } + + if (nameN.getNodeType() != Node.ATTRIBUTE_NODE) { + logger.warning("Name is not an attribute. Ignored..."); + continue; + } + + String name = ""; + try { + name = nameN.getNodeValue(); + } catch (Exception ex) { + logger.warning("Error getting name: " + ex.getMessage() + " Ignored..."); + continue; + } + + if (forms.containsKey(name.toUpperCase())) { + logger.warning("Coordinate Builder " + name + " is already in Table. Ignored..."); + continue; + } + + // --- Get Description + + String desc = ""; + Node descN = attr.getNamedItem(DESCRIPTION); + + if (descN != null) { + if (descN.getNodeType() != Node.ATTRIBUTE_NODE) { + logger.warning("Description is not an attribute. Ignored..."); + } else { + try { + desc = descN.getNodeValue(); + } catch (Exception ex) { + logger.warning("Error getting description: " + ex.getMessage() + " Ignored..."); + } + } + } + + // --- Get Extensions + + String exts = ""; + Node extN = attr.getNamedItem(EXTENSIONS); + + if (extN != null) { + if (extN.getNodeType() != Node.ATTRIBUTE_NODE) { + logger.warning("Extensions is not an attribute. Ignored..."); + } else { + try { + exts = extN.getNodeValue(); + } catch (Exception ex) { + logger.warning("Error getting extenstion: " + ex.getMessage() + " Ignored..."); + } + } + } + + // --- Get parser + + String parser = ""; + Node parN = attr.getNamedItem(PARSER); + + if (parN != null) { + if (parN.getNodeType() != Node.ATTRIBUTE_NODE) { + logger.warning("Parser is not an attribute. Ignored..."); + } else { + try { + parser = parN.getNodeValue(); + } catch (Exception ex) { + logger.warning("Error getting parser: " + ex.getMessage() + " Ignored..."); + } + } + } + + FormatObject fo = new FormatObject(name, desc, exts, parser); + forms.put(name.toUpperCase(), fo); + } + + return forms; + } +} diff --git a/src/main/java/cct/cpmd/CPMD.java b/src/main/java/cct/cpmd/CPMD.java new file mode 100644 index 0000000..32491dd --- /dev/null +++ b/src/main/java/cct/cpmd/CPMD.java @@ -0,0 +1,703 @@ +package cct.cpmd; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import cct.GlobalConstants; +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.interfaces.OutputResultsInterface; +import cct.modelling.ChemicalElements; +import cct.modelling.StructureManagerInterface; +import cct.modelling.VIBRATIONAL_SPECTRUM; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ + +enum CPMD_JOB_TYPE { + MOLECULAR_DYNAMICS, VIBRATIONAL_ANALYSIS} + +public class CPMD + implements GlobalConstants, StructureManagerInterface, OutputResultsInterface { + + private CPMD_JOB_TYPE jobType = null; + private StringWriter outputResume = null; + private StringWriter warnings = null; + private String trajFile = null, outputFile = null; + private int netCharge = 0; + private List atoms = new ArrayList (); + private List snapshots = null; + private Map nfiProperties = new HashMap (); + private boolean normalTermination = true; + static final Logger logger = Logger.getLogger(CPMD.class.getCanonicalName()); + + public CPMD() { + } + + public int countAtoms() { + return atoms.size(); + } + + public int getNumberOfAtoms() { + return countAtoms(); + } + + public int countSnapshots() { + return snapshots.size(); + } + + @Override + public boolean isNormalTermination() { + return normalTermination; + } + + @Override + public void setNormalTermination(boolean yes) { + normalTermination = yes; + } + + @Override + public String getOutputResume() { + if (outputResume == null) { + return "No Output Resume"; + } + return outputResume.toString(); + } + + @Override + public String[] getAvailPropToChart() { + if (nfiProperties.size() < 1) { + return null; + } + String[] sa = new String[nfiProperties.size()]; + nfiProperties.keySet().toArray(sa); + return sa; + } + + public double[] getAllTerms(String term) { + if (!nfiProperties.containsKey(term)) { + return null; + } + + List values = nfiProperties.get(term); + double[] energies = new double[values.size()]; + for (int i = 0; i < values.size(); i++) { + energies[i] = values.get(i); + } + return energies; + } + + public void getMolecule(MoleculeInterface molec) throws + Exception { + if (molec == null) { + throw new Exception(this.getClass().getCanonicalName() + " : molec == null"); + } + if (atoms.size() < 1) { + throw new Exception(this.getClass().getCanonicalName() + " : no CPMD atoms"); + } + + molec.addProperty(MoleculeInterface.ChargeProperty, new Integer(netCharge)); + //molec.addProperty(MoleculeInterface.MultiplicityProperty, new Integer(spinMultiplicity)); + + molec.addMonomer("CPMD"); + + for (int i = 0; i < atoms.size(); i++) { + CPMDAtom ga = atoms.get(i); + AtomInterface atom = molec.getNewAtomInstance(); + atom.setName(ga.name); + atom.setAtomicNumber(ga.element); + atom.setXYZ( (float) ga.x, (float) ga.y, (float) ga.z); + molec.addAtom(atom); + } + } + + public void parseOutputFile(String filename) throws Exception { + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(filename)); + } + catch (Exception ex) { + throw new Exception("Error opening CPMD output: " + ex.getMessage()); + } + + outputFile = filename; + parseOutputFile(in); + } + + public void parseOutputFile(BufferedReader in) throws Exception { + String line; + outputResume = new StringWriter(1024); + try { + while ( (line = in.readLine()) != null) { + if (line.contains("VERSION ")) { + outputResume.write(line + "\n"); + } + + else if (line.contains("PERFORM A VIBRATIONAL ANALYSIS ")) { + outputResume.write(line + "\n"); + jobType = CPMD_JOB_TYPE.VIBRATIONAL_ANALYSIS; + } + else if (line.contains("CAR-PARRINELLO MOLECULAR DYNAMICS")) { + outputResume.write(line + "\n"); + jobType = CPMD_JOB_TYPE.MOLECULAR_DYNAMICS; + } + + else if (line.contains("CHARGE:")) { + outputResume.write(line + "\n"); + try { + float ch = Float.parseFloat(line.substring(line.indexOf(":") + 1).trim()); + netCharge = (int) ch; + } + catch (Exception ex) { + addWarning("Encountered Error while parsing total charge: " + ex.getMessage() + " got: " + line); + } + } + + else if (line.contains("PROGRAM CPMD ")) { + outputResume.write(line + "\n"); + } + else if (line.contains("THE INPUT FILE IS:")) { + outputResume.write(line + "\n"); + } + else if (line.contains("THIS JOB RUNS ON:")) { + outputResume.write(line + "\n"); + } + else if (line.contains("CPU TIME :")) { + outputResume.write(line + "\n"); + } + else if (line.contains("ELAPSED TIME :")) { + outputResume.write(line + "\n"); + } + + else if (line.contains("THE CURRENT DIRECTORY IS:")) { + outputResume.write(line + "\n"); + if ( (line = in.readLine()) == null) { + break; + } + outputResume.write(line + "\n"); + } + else if (line.contains("THE JOB WAS SUBMITTED BY:")) { + outputResume.write(line + "\n"); + } + else if (line.contains(" FINAL RESULTS ")) { + outputResume.write(line + "\n"); + } + + else if (line.contains("TRAJECTORIES ARE SAVED ON FILE")) { + if ( (line = in.readLine()) == null) { + break; + } + if (!line.contains("IS SAVED ON FILE")) { + continue; + } + line = line.trim(); + trajFile = line.trim().substring(0, line.indexOf(" ")); + } + + else if (line.contains("***** ATOMS *****")) { + readAtoms(in); + } + else if (line.contains("ATOMIC COORDINATES")) { + readAtomCoordinates(in); + } + + else if (line.contains(" NFI ")) { + readFiniteIterations(in, line); + } + else if (line.contains("TOTAL ENERGY =")) { + outputResume.write("\n" + line + "\n"); + while ( (line = in.readLine()) != null && line.trim().length() > 0) { + outputResume.write(line + "\n"); + } + outputResume.write("\n"); + } + + } + } + catch (Exception ex) { + throw new Exception("Error reading CPMD output: " + ex.getMessage()); + } + + // --- Postprocessing + + if (trajFile != null) { + try { + String trajPath = getPath(outputFile) + trajFile; + logger.info("Built a path to the trajectory file: " + trajPath); + File tfile = new File(trajPath); + if (tfile.exists() && tfile.canRead()) { + this.parseTrajectoryFile(trajPath); + } + } + catch (Exception ex) { + System.err.println("CPMD Output file has a reference to the trajectory file. Error reading it: " + ex.getMessage() + + " Ignored..."); + } + } + + } + + private void readFiniteIterations(BufferedReader in, String line) throws Exception { + // --- parse properties + // NFI EKINC TEMPP EKS ECLASSIC EHAM DIS TCPU + + StringTokenizer st = new StringTokenizer(line, " \t"); + if (st.countTokens() < 2) { + return; + } + String[] keys = new String[st.countTokens() - 1]; + st.nextToken(); // Skip the first token - NFI + + int count = 0; + while (st.hasMoreTokens()) { + keys[count] = st.nextToken(); + nfiProperties.put(keys[count], new ArrayList ()); + ++count; + } + + try { + while ( (line = in.readLine()) != null) { + if (line.trim().length() < 1) { + return; + } + + if (nfiProperties.size() == 7) { // MD Info + try { + nfiProperties.get(keys[0]).add(Double.parseDouble(line.substring(10, 19).trim())); // EKINC + nfiProperties.get(keys[1]).add(Double.parseDouble(line.substring(19, 27).trim())); // TEMPP + nfiProperties.get(keys[2]).add(Double.parseDouble(line.substring(27, 41).trim())); // EKS + nfiProperties.get(keys[3]).add(Double.parseDouble(line.substring(41, 55).trim())); // ECLASSIC + nfiProperties.get(keys[4]).add(Double.parseDouble(line.substring(55, 69).trim())); // EHAM + nfiProperties.get(keys[5]).add(Double.parseDouble(line.substring(69, 81).trim())); // DIS + nfiProperties.get(keys[6]).add(Double.parseDouble(line.substring(81, 89).trim())); // TCPU + } + catch (Exception ex) { + throw ex; + } + } + } + } + catch (Exception ex) { + throw new Exception("Error reading header finite itereations info: " + ex.getMessage()); + } + } + + private void readAtomCoordinates(BufferedReader in) throws Exception { + String line; + double factor = ONE_BOHR; + try { + // Skipping the first line + //************************************************************** + + if ( (line = in.readLine()) == null) { + throw new Exception("Unexpected end-of-file while reading header ATOMIC COORDINATES in CPMD output"); + } + + if (atoms.size() > 0) { // So, we need just to update atomic coordinates + CPMDAtom[] atom_array = new CPMDAtom[atoms.size()]; + for (int i = 0; i < atoms.size(); i++) { + if ( (line = in.readLine()) == null) { + addWarning("Encountered an unxpected end-of-file while reading ATOMIC COORDINATES section..."); + break; + } + if (line.contains("*****************")) { + addWarning("Encountered an unxpected end-of-data while reading ATOMIC COORDINATES section..."); + break; + } + + try { + atom_array[i] = readAtom(line, factor); + } + catch (Exception ex) { + addWarning("Encountered Error(s) while parsing ATOMIC COORDINATES section: " + ex.getMessage()); + break; + } + } + + for (int i = 0; i < atoms.size(); i++) { + CPMDAtom atom = atoms.get(i); + atom.x = atom_array[i].x; + atom.y = atom_array[i].y; + atom.z = atom_array[i].z; + } + } + + // --- Read atoms' info for the first time + else { + while ( (line = in.readLine()) != null && !line.contains("**********")) { + try { + CPMDAtom atom = readAtom(line, factor); + atoms.add(atom); + } + catch (Exception ex) { + throw new Exception("Error while parsing ATOMIC COORDINATES section: " + ex.getMessage()); + } + } + } + + } + catch (Exception ex) { + throw new Exception("Error reading ATOMIC COORDINATES in CPMD output: " + ex.getMessage()); + } + + } + + public static CPMDAtom readAtom(String line, double factor) throws Exception { + StringTokenizer st = new StringTokenizer(line, " \t"); + if (st.countTokens() < 5) { + throw new Exception("Expecting at least 5 tokens while reading atom info, got " + line); + } + st.nextToken(); // Skip the first + String type = st.nextToken(); + int element = ChemicalElements.getAtomicNumber(type); + double x = 0, y = 0, z = 0; + try { + x = Double.parseDouble(st.nextToken()) * factor; + y = Double.parseDouble(st.nextToken()) * factor; + z = Double.parseDouble(st.nextToken()) * factor; + } + catch (Exception ex) { + throw new Exception("Error parsing atom coordinate, got " + line); + } + + CPMDAtom atom = new CPMDAtom(); + atom.name = type; + atom.element = element; + atom.x = x; + atom.y = y; + atom.z = z; + + return atom; + } + + void readAtoms(BufferedReader in) throws Exception { + String line; + double factor = 1.0; + try { + // Reading the header + // NR TYPE X(bohr) Y(bohr) Z(bohr) MBL + + if ( (line = in.readLine()) == null) { + throw new Exception("Unxpected end-of-file while reading header ATOMS in CPMD output"); + } + if (line.contains("X(bohr)")) { + factor = ONE_BOHR; + } + + // --- Reading atoms + // 1 H 8.800000 8.000000 8.000000 3 + + while ( (line = in.readLine()) != null && !line.contains("**********")) { + CPMDAtom atom = readAtom(line, factor); + atoms.add(atom); + } + } + catch (Exception ex) { + throw new Exception("Error reading ATOMS in CPMD output: " + ex.getMessage()); + } + } + + public boolean hasWarningMessages() { + return warnings != null; + } + + public String getWarnings() { + if (hasWarningMessages()) { + return warnings.toString(); + } + return "No Warning Messages"; + } + + private void addWarning(String message) { + if (warnings == null) { + warnings = new StringWriter(512); + } + warnings.write(message + "\n"); + } + + public void parseTrajectoryFile(String filename) throws Exception { + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(filename)); + } + catch (Exception ex) { + throw new Exception("Error opening CPMD trajectory: " + ex.getMessage()); + } + + parseTrajectoryFile(in); + } + + public void parseTrajectoryFile(BufferedReader in) throws Exception { + int natoms = 0; + String line, type; + double x, y, z; + List temp_atoms = null; + + try { + while ( (line = in.readLine()) != null) { + + // --- Read number of atoms + + StringTokenizer st = new StringTokenizer(line, " \t"); + if (!st.hasMoreTokens()) { + logger.info("Warning: expected number of atoms, got empty line..."); + break; + } + + try { + natoms = Integer.parseInt(st.nextToken()); + } + catch (Exception ex) { + logger.info("Warning: cannot parse number of atoms..."); + break; + } + + if (atoms.size() > 0 && atoms.size() != natoms) { + logger.info("Warning: expected " + atoms.size() + " atoms, trajectory is for " + natoms + " atoms..."); + break; + } + + // --- Read STEP number + + if ( (line = in.readLine()) == null) { + logger.info("Warning: unexpected end-of-file while reading in STEP number..."); + break; + } + + if (!line.contains("STEP")) { + logger.info("Warning: expected a line with a \"STEP\" word, got " + line); + break; + } + + st = new StringTokenizer(line, " \t"); + + if (st.countTokens() < 2) { + logger.info("Warning: expected at least two tokens for a \"STEP\" line, got " + line); + break; + } + + int snapshot = 0; + st.nextToken(); + try { + snapshot = Integer.parseInt(st.nextToken()); + } + catch (Exception ex) { + logger.info("Warning: cannot parse STEP number, got " + line); + break; + } + + // --- Reading atoms + + CPMDSnapshot snap = new CPMDSnapshot(natoms); + boolean need_mol = atoms.size() < 1; + if (need_mol) { + temp_atoms = new ArrayList (natoms); + } + int i = 0; + for (; i < natoms; i++) { + if ( (line = in.readLine()) == null) { + logger.info("Warning: unexpected end-of-file while reading " + (i + 1) + " atom..."); + break; + } + st = new StringTokenizer(line, " \t"); + if (st.countTokens() < 4) { + logger.info("Warning: expected at least 4 tokens while reading " + (i + 1) + " atom, got " + line); + break; + } + + type = st.nextToken(); + + try { + x = Double.parseDouble(st.nextToken()); + y = Double.parseDouble(st.nextToken()); + z = Double.parseDouble(st.nextToken()); + } + catch (Exception ex) { + logger.info("Warning: error parsing atom coordinate(s) of " + (i + 1) + " atom, got " + line); + break; + } + + snap.setCoordinates(x, y, z, i); + + if (need_mol) { + CPMDAtom atom = new CPMDAtom(); + atom.name = type; + atom.element = ChemicalElements.getAtomicNumber(type); + atom.x = x; + atom.y = y; + atom.z = z; + temp_atoms.add(atom); + } + + } + + if (i < natoms) { + break; + } + + if (snapshots == null) { + snapshots = new ArrayList (); + } + snapshots.add(snap); + if (need_mol) { + atoms.addAll(temp_atoms); + } + + } + } + catch (Exception ex) { + throw new Exception("Error reading CPMD trajectory: " + ex.getMessage()); + } + } + + private String getPath(String abs_path) { + int index = 0; + if ( (index = abs_path.lastIndexOf("/")) != -1) { + return abs_path.substring(0, index + 1); + } + else if ( (index = abs_path.lastIndexOf("\\")) != -1) { + return abs_path.substring(0, index + 1); + } + return ""; + } + + public float[][] getStructure(int n) { + return getStructure(n, null); + } + + public float[][] getStructure(int n, String term) { + if (snapshots == null || snapshots.size() < 1 || n >= snapshots.size()) { + System.err.println(this.getClass().getCanonicalName() + + ": snapshots == null || snapshots.size() < 1 || n >= snapshots.size()"); + return null; + } + + CPMDSnapshot snap = snapshots.get(n); + return snap.getCoordinates(); + } + + public void selectStructure(int number) throws Exception { + throw new Exception(this.getClass().getCanonicalName() + ": selectStructure(int number) is not implemented yet"); + } + + public void selectStructure(int number, String term) throws Exception { + throw new Exception(this.getClass().getCanonicalName() + ": selectStructure(int number, String term) is not implemented yet"); + } + + public VIBRATIONAL_SPECTRUM[] availableVibrationalSpectra() { + return null; + } + + public int countFrequencies() { + return 0; + } + + public int countSpectra() { + return 0; + } + + public boolean hasJobSummary() { + return outputResume != null; + } + + public boolean hasDisplacementVectors() { + return false; + } + + public boolean hasInteractiveChart() { + return false; + } + + public boolean hasVCDSpectrum() { + return false; + } + + public boolean hasUDepolSpectrum() { + return false; + } + + public boolean hasPDepolSpectrum() { + return false; + } + + public boolean hasRamanSpectrum() { + return false; + } + + public boolean hasInfraredSpectrum() { + return false; + } + + public float[][] getDisplacementVectors(int n) { + return null; + } + + public double getFrequency(int n) { + return 0; + } + + public double getSpectrumValue(int n, VIBRATIONAL_SPECTRUM spectrum) { + return 0; + } + + public void getSpectrum(double[] x, double[] y, int dim, VIBRATIONAL_SPECTRUM type) throws Exception { + + } + + } + +// ***************************************************************************** + class CPMDAtom { + String name; + int element; + double x, y, z; + } + + class CPMDSnapshot { + private float[][] coord; + + public CPMDSnapshot(int n_atoms) { + coord = new float[n_atoms][3]; + } + + public void setCoordinates(double[] xyz, int n) throws Exception { + if (n < 0 || n >= coord.length) { + throw new Exception(this.getClass().getCanonicalName() + ": setCoordinates: index out of range"); + } + coord[n][0] = (float) xyz[0]; + coord[n][1] = (float) xyz[1]; + coord[n][2] = (float) xyz[2]; + } + + public void setCoordinates(double x, double y, double z, int n) throws Exception { + if (n < 0 || n >= coord.length) { + throw new Exception(this.getClass().getCanonicalName() + ": setCoordinates: index out of range"); + } + coord[n][0] = (float) x; + coord[n][1] = (float) y; + coord[n][2] = (float) z; + } + + public float[][] getCoordinates() { + return coord; + } + + } diff --git a/src/main/java/cct/cpmd/CPMDOutput.java b/src/main/java/cct/cpmd/CPMDOutput.java new file mode 100644 index 0000000..9928f83 --- /dev/null +++ b/src/main/java/cct/cpmd/CPMDOutput.java @@ -0,0 +1,124 @@ +package cct.cpmd; + +import java.io.BufferedReader; +import java.util.StringTokenizer; + +import cct.GlobalConstants; +import cct.interfaces.AtomInterface; +import cct.interfaces.CoordinateParserInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.ChemicalElements; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class CPMDOutput + implements GlobalConstants, CoordinateParserInterface { + + //private ArrayList atoms = new ArrayList (); + + public CPMDOutput() { + } + + @Override + public void parseCoordinates(BufferedReader in, MoleculeInterface molecule) throws Exception { + + try { + // --- Reading atoms + String line; + molecule.addMonomer("CPMD"); + while ( (line = in.readLine()) != null) { + line = line.trim(); + if (line.length() < 1) { + continue; // Empty line + } + + CPMDAtom atom = CPMD.readAtom(line, ONE_BOHR); + AtomInterface at = molecule.getNewAtomInstance(); + at.setName(atom.name); + at.setAtomicNumber(ChemicalElements.getAtomicNumber(atom.name)); + at.setXYZ((float)atom.x,(float)atom.y,(float)atom.z); + molecule.addAtom(at); + } + + } + catch (Exception ex) { + throw ex; + } + + //Molecule.guessCovalentBonds(molecule); + //Molecule.guessAtomTypes(molecule, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } + + @Override + public double evaluateCompliance(BufferedReader in) throws Exception { + double score = 0; + try { + // --- Reading atoms + String line; + while ( (line = in.readLine()) != null) { + + line = line.trim(); + if (line.length() < 1) { + continue; // Empty line + } + + score = 1.0; + // For ATOMS section + // 1 C 16.586049 16.342961 20.770901 3 + // For ATOMIC COORDINATES + // 1 C 6.219888 7.668818 9.317632 + + StringTokenizer st = new StringTokenizer(line, " \t", false); + if (st.countTokens() < 5) { + return 0; + } + else if (st.countTokens() > 6) { + score -= 0.25; + } + + // --- The first token should be integer number + + try { + Integer.parseInt(st.nextToken()); + } + catch (Exception ex) { + score -= 0.25; + } + + // --- Element symbol. Skipping... + + String token = st.nextToken(); + + // --- Getting x,y,z + + try { + Float.parseFloat(st.nextToken()); + Float.parseFloat(st.nextToken()); + Float.parseFloat(st.nextToken()); + } + catch (Exception ex) { + return 0; + } + + return score; // i.e. we check only the first line + } + + } + catch (Exception ex) { + throw ex; + } + return score; + + } + +} diff --git a/src/main/java/cct/cprocessor/AddCommandObjects.java b/src/main/java/cct/cprocessor/AddCommandObjects.java new file mode 100644 index 0000000..d9bd0b5 --- /dev/null +++ b/src/main/java/cct/cprocessor/AddCommandObjects.java @@ -0,0 +1,59 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.cprocessor; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +enum AddCommandObjects { + ATOM("atom"), BOND("bond"); + + String comObject; + AddCommandObjects(String obj) { + comObject = obj; + } +} diff --git a/src/main/java/cct/cprocessor/AssignmentOperator.java b/src/main/java/cct/cprocessor/AssignmentOperator.java new file mode 100644 index 0000000..0ae7cf3 --- /dev/null +++ b/src/main/java/cct/cprocessor/AssignmentOperator.java @@ -0,0 +1,45 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.cprocessor; + +import java.util.logging.Logger; + +/** + * + * @author vvv900 + */ +public class AssignmentOperator implements CommandInterface { + + static final Logger logger = Logger.getLogger(AssignmentOperator.class.getCanonicalName()); + + public CommandInterface ciInstance() { + return new AssignmentOperator(); + } + + /** + * Assumes variable as the first argument and its value as the second one + * + * @param args + * @return + * @throws Exception + */ + public Object ciExecuteCommand(Object[] args) throws Exception { + if (args == null || args.length != 2) { + throw new Exception("Assignment operator expects for two arguments"); + } + if (!(args[0] instanceof Variable)) { + throw new Exception("Assignment operator: first argument should be of type " + + Variable.class.getCanonicalName() + " Got: " + args[0].getClass().getCanonicalName()); + } + Variable var = (Variable) args[0]; + var.setValue(args[1]); + return new Boolean(true); + } + + public Object[] ciParseCommand(String[] tokens) throws Exception { + throw new Exception("Not implemented yet"); + } +} diff --git a/src/main/java/cct/cprocessor/AtomicCommand.java b/src/main/java/cct/cprocessor/AtomicCommand.java new file mode 100644 index 0000000..1b99927 --- /dev/null +++ b/src/main/java/cct/cprocessor/AtomicCommand.java @@ -0,0 +1,61 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.cprocessor; + +/** + * + * @author vvv900 + */ +public class AtomicCommand { + + private CommandInterface command; + private Object[] parsedArguments; + private boolean[] setPrevResult; + private boolean needPreviousResult = false; + + public AtomicCommand(CommandInterface command, Object[] parsedArguments) { + this.command = command; + this.parsedArguments = parsedArguments; + if (parsedArguments != null) { + setPrevResult = new boolean[parsedArguments.length]; + int i = 0; + for (Object obj : parsedArguments) { + if (obj instanceof CommandProcessor.CONSTANTS + && obj == CommandProcessor.CONSTANTS.PREVIOUS_RESULT) { + needPreviousResult = true; + setPrevResult[i] = true; + } else { + setPrevResult[i] = false; + } + ++i; + } + } + } + + public Object executeCommand() throws Exception { + return command.ciExecuteCommand(parsedArguments); + } + + public Object[] getParsedArguments() { + return parsedArguments; + } + + public boolean isNeedPreviousResult() { + return needPreviousResult; + } + + public void setPreviousResult(Object result) { + for (int i = 0; i < parsedArguments.length; i++) { + if (setPrevResult[i]) { + parsedArguments[i] = result; + } + } + } + + public CommandInterface getCommand() { + return command; + } +} diff --git a/src/main/java/cct/cprocessor/CommandInterface.java b/src/main/java/cct/cprocessor/CommandInterface.java new file mode 100644 index 0000000..7d3de34 --- /dev/null +++ b/src/main/java/cct/cprocessor/CommandInterface.java @@ -0,0 +1,26 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.cprocessor; + +/** + * + * @author vvv900 + */ +public interface CommandInterface { + + CommandInterface ciInstance(); + + Object ciExecuteCommand(Object[] args) throws Exception; + + /** + * Parses command parameters. + * + * @param tokens - arguments. The first argument is a command name, so it's ignored + * @return parsed and parameters + * @throws Exception + */ + Object[] ciParseCommand(String[] tokens) throws Exception; +} diff --git a/src/main/java/cct/cprocessor/CommandObject.java b/src/main/java/cct/cprocessor/CommandObject.java new file mode 100644 index 0000000..55eb47e --- /dev/null +++ b/src/main/java/cct/cprocessor/CommandObject.java @@ -0,0 +1,73 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.cprocessor; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public enum CommandObject { + ATOMS("atoms"), BONDS("bonds"); + private String objectName; + CommandObject(String object) { + objectName = object; + } + + public boolean isValidCommandObject(String command) { + for (CommandObject c: CommandObject.values()) { + if (command.equalsIgnoreCase(c.objectName)) return true; + } + return false; + } + + public CommandObject getCommandObject(String command) { + for (CommandObject c: CommandObject.values()) { + if (command.equalsIgnoreCase(c.objectName)) return c; + } + return null; + } + +} diff --git a/src/main/java/cct/cprocessor/CommandProcessor.java b/src/main/java/cct/cprocessor/CommandProcessor.java new file mode 100644 index 0000000..08f4d0f --- /dev/null +++ b/src/main/java/cct/cprocessor/CommandProcessor.java @@ -0,0 +1,847 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.cprocessor; + +import cct.j3d.Java3dUniverse; +import cct.math.MathExpressionParser; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.StringReader; +import java.io.StringWriter; +import java.math.BigInteger; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.StringTokenizer; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + *

+ * Title: Molecular Structure Viewer/Editor

+ * + *

+ * Description: Computational Chemistry Toolkit

+ * + *

+ * Copyright: Copyright (c) 2007

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class CommandProcessor { + + public enum CONSTANTS { + + PREVIOUS_RESULT + } + + public static final String COMMANDS_PROPERTY_FILE = "cct/cprocessor/commands.properties"; + private Properties commandsProperties = null; + private URL cctCommandsURL = null; + private Map commandProviders = new HashMap(); + private Map variables = new HashMap(); + private boolean oneVariableInstanceOnly = true; + private AssignmentOperator assignmentOperator = new AssignmentOperator(); + private Java3dUniverse renderer = null; + private boolean allowVariableRedifination = true; + + private List compiledCommands = new ArrayList(); + private List forLoopTracker = new ArrayList(); + + Commands currentCommand = null; + Object commandObject = null; + Object commandArguments = null; + + static final Logger logger = Logger.getLogger(CommandProcessor.class.getCanonicalName()); + + public CommandProcessor() throws Exception { + commandsProperties = getProperties(); + + for (Map.Entry entry : commandsProperties.entrySet()) { + String name = entry.getKey().toString(); + String className = entry.getValue().toString(); + + Class builderClass = null; + ClassLoader loader = null; + try { + // Get the Class object associated with builder + builderClass = Class.forName(className); + + // Get the ClassLoader object associated with this Class. + loader = builderClass.getClassLoader(); + + if (loader == null) { + logger.severe("loader == null while attempting to load class " + className + " Ignored..."); + continue; + } else { + // Verify that this ClassLoader is associated with the builder class. + Class loaderClass = loader.getClass(); + + if (logger.isLoggable(Level.INFO)) { + logger.info("Class associated with ClassLoader: " + loaderClass.getName()); + } + } + } catch (ClassNotFoundException ex) { + logger.severe("Cannot load class " + className + " : " + ex.getMessage() + " Ignored..."); + continue; + } + + try { + Class cl = loader.loadClass(className); + Object obj = cl.newInstance(); + if (logger.isLoggable(Level.INFO)) { + logger.info("Classr " + className + " was loaded"); + } + // ---- + if (!(obj instanceof CommandInterface)) { + logger.severe("Class " + className + " does not implement " + CommandInterface.class.getName() + + " interface. Ignored..."); + continue; + } + // ---- + + commandProviders.put(name, (CommandInterface) obj); + } catch (Exception ex) { + logger.severe("Error while loading Class " + className + ex.getMessage() + " Ignored..."); + continue; + } + + } + // Setup "inbuilt" commands + for (String cmd : GUIWrapperCommand.supportedCommands()) { + commandProviders.put(cmd, new GUIWrapperCommand(renderer)); + } + ForLoopCommand forLoop = new ForLoopCommand(); + forLoop.setCommandProcessor(this); + commandProviders.put("for", forLoop); + + EndForLoopCommand endforLoop = new EndForLoopCommand(); + endforLoop.setCommandProcessor(this); + commandProviders.put("endfor", endforLoop); + + PrintCommand print = new PrintCommand(); + print.setCommandProcessor(this); + commandProviders.put("print", print); + + print = new PrintCommand(); + print.setCommandProcessor(this); + commandProviders.put("CreateLog", print); + } + + public void setLoggerLevel(Level level) { + logger.setLevel(level); + } + + public Properties getProperties() throws Exception { + + commandsProperties = getProperties(COMMANDS_PROPERTY_FILE); + return commandsProperties; + } + + public Properties getProperties(String propertiesFile) throws Exception { + + commandsProperties = null; + cctCommandsURL = null; + try { + cctCommandsURL = CommandProcessor.class.getClassLoader().getResource(propertiesFile); + commandsProperties = new Properties(); + commandsProperties.load(cctCommandsURL.openStream()); + logger.info("Loaded commands properties file " + propertiesFile); + } catch (Exception ex) { + logger.warning("Cannot open commands properties file " + propertiesFile + ": " + ex.getMessage()); + } + return commandsProperties; + } + + static public Number getNumber(String numStr) throws Exception { + try { + Integer inum = Integer.parseInt(numStr); + return inum; + } catch (Exception ex) { + + } + + Double dnum = null; + try { + dnum = Double.parseDouble(numStr); + return dnum; + } catch (Exception ex) { + throw new Exception(numStr + " is not a valid number"); + } + } + + /** + * Use this function to add a new variable. DO not use a direct add + * + * @param variable + */ + public void addVariable(Variable variable) throws Exception { + if (!this.allowVariableRedifination && variables.containsKey(variable.getName())) { + throw new Exception("Variable " + variable.getName() + " was already defined. Allow Variable Redifinition to avoid this error"); + } + variables.put(variable.getName(), variable); + } + + public boolean isHasVariable(String variableName) { + return variables.containsKey(variableName); + } + + public Variable getVariable(String variableName) { + return variables.get(variableName); + } + + public int numberForLoopsInProcessing() { + if (forLoopTracker == null) { + return 0; + } + return forLoopTracker.size(); + } + + public void addForLoopForProcessing(int number) { + forLoopTracker.add(0, number); + } + + public int extractForLoopStart() { + if (forLoopTracker == null) { + return -1; + } + int n = forLoopTracker.get(0); + forLoopTracker.remove(0); // Remove for entry from the stack queue + return n; + } + + public AtomicCommand getCompiledCommand(int n) { + return compiledCommands.get(n); + } + + public void addCompiledCommand(AtomicCommand command) { + compiledCommands.add(command); + } + + public int numberOfCompiledCommands() { + return compiledCommands.size(); + } + + public Java3dUniverse getRenderer() { + return renderer; + } + + public void setRenderer(Java3dUniverse renderer) { + this.renderer = renderer; + for (String cmd : GUIWrapperCommand.supportedCommands()) { + ((GUIWrapperCommand) commandProviders.get(cmd)).setRenderer(renderer); + } + } + + public static void main(String[] args) { + try { + CommandProcessor commandprocessor = new CommandProcessor(); + Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).setLevel(Level.WARNING); + commandprocessor.setLoggerLevel(Level.WARNING); + commandprocessor.parseScript("x=1\n" + + "gjh = 1.68765\n" + + "log = CreateLog\n" + + "log setLog analysis.log\n" + + "mol = loadGJF ferrocene-admp-20c.com\n" + + "traj = TrajectoryManager\n" + + "traj set mol\n" + //+ "traj load g09-md.out g09\n" + + "traj load /home/vvv900/fuji1/Fc/ferrocene-admp-20c.log g09\n" + + "snaps = traj getNumSnaps\n" + + "print Number of snapshots: snaps\n" + + "snaps = snaps - 1 \n" + + "print Stop value for loop over trajectories: snaps\n" + + "list1 = List\n" + + "list2 = List\n" + + "list3 = List\n" + + "for iter 0 snaps 2\n" + + " print Snapshot: iter\n" + + " coords = traj getXYZ iter\n" + + " print Coordinates: coords\n" + + " Molecule setXYZ mol coords\n" + + " centroid_1 = Molecule centroid mol 1-5\n" + + " print Centroid 1: centroid_1\n" + + " centroid_2 = Molecule centroid mol 6-10\n" + + " print Centroid 2: centroid_2\n" + + " Fe = Molecule getAtom mol 21\n" + + " C_1 = Molecule getAtom mol 1\n" + + " C_2 = Molecule getAtom mol 6\n" + + " Fe_1 = Geometry distance Fe centroid_1\n" + + " print Fe-Centroid 1 distance: Fe_1\n" + + " Fe_2 = Geometry distance Fe centroid_2\n" + + " C_C = Geometry distance centroid_1 centroid_2\n" + + " print Fe-Centroid 2 distance: Fe_2\n" + + " dihed = Geometry dihedral C_1 centroid_1 centroid_2 C_2\n" + + " log Fe_1 Fe_2 C_C dihed\n" + + " list1 add Fe_1\n" + + " list2 add Fe_2\n" + + "endfor\n" + + "log close\n" + + "data1 = list1 toArray\n" + + "data2 = list2 toArray\n" + + "corr = Stat linearCorrelationCoefficient data1 data2\n" + + "print Linear correlation coeff for Fe-C_1 and Fe-C_2 distances: corr\n", 1); + commandprocessor.printCompiledCommands(); + commandprocessor.executeScript(); + } catch (Exception ex) { + Logger.getLogger(CommandProcessor.class.getName()).log(Level.SEVERE, null, ex); + } + System.exit(0); + } + + public void executeScript() throws Exception { + executeScript(compiledCommands); + } + + public void executeScript(List compiled_commands) throws Exception { + boolean printExecution = false; + Object previousResult = null; + //if (false) { + // for (int i = 0; i < compiled_commands.size(); i++) { + // AtomicCommand command = compiled_commands.get(i); + // if (command.isNeedPreviousResult()) { + // command.setPreviousResult(previousResult); + // } + // Object result = command.executeCommand(); + // previousResult = result; + // } + //} + + int commandCounter = 0; + while (commandCounter < compiled_commands.size()) { + AtomicCommand command = compiled_commands.get(commandCounter); + if (command.isNeedPreviousResult()) { + command.setPreviousResult(previousResult); + } + if (printExecution) { + System.out.println("\nExecuting command: " + commandCounter + " : " + + command.getCommand().getClass().getSimpleName() + + "\nArguments:"); + if (command.getParsedArguments() != null) { + for (int i = 0; i < command.getParsedArguments().length; i++) { + System.out.print(i + ": "); + printArgument(command.getParsedArguments()[i]); + } + } + } + Object result = command.executeCommand(); + if (printExecution) { + System.out.println("Result: "); + printArgument(result); + } + previousResult = result; + if (command.getCommand() instanceof InbuiltCommandInterface) { + int newCounter = ((InbuiltCommandInterface) command.getCommand()).getNewCommandCounter(); + if (newCounter != -1) { + commandCounter = newCounter; + continue; + } + } + ++commandCounter; + } + } + + public void printCompiledCommands() { + printCompiledCommands(compiledCommands); + } + + public void printCompiledCommands(List compiled_commands) { + System.out.println("\nCompiled commands: "); + for (int i = 0; i < compiled_commands.size(); i++) { + AtomicCommand command = compiled_commands.get(i); + System.out.printf("%3d %-30s ", i, command.getCommand().getClass().getSimpleName()); + Object[] args = command.getParsedArguments(); + if (args == null) { + System.out.println(args); + } else { + for (Object obj : args) { + if (obj == null) { + System.out.print(" " + obj); + } else { + System.out.print(" " + obj.toString()); + } + + } + System.out.print("\n"); + } + } + } + + public void parseScript(String filename, int fileType) throws Exception { + + String line; + BufferedReader in = null; + StringWriter sWriter = new StringWriter(); + int lineNumber = 0; + + if (fileType == 0) { // Read from file + try { + in = new BufferedReader(new FileReader(filename)); + } catch (Exception ex) { + throw ex; + } + } else if (fileType == 1) { // Read from String + in = new BufferedReader(new StringReader(filename)); + } else { + throw new Exception( + "parseScript: INTERNAL ERROR: Unknown file type"); + } + + try { + //BufferedReader in = new BufferedReader(new FileReader(filename)); + + Variable variable = null; + boolean setValue = false; + String variableName = "", subLine = ""; + + while ((line = in.readLine()) != null) { + setValue = false; + subLine = line.trim(); + ++lineNumber; + + if (subLine.length() < 1) { // Blank line + continue; + } + + if (subLine.startsWith("!") || subLine.startsWith("#") || subLine.startsWith(";")) { + continue; + } + + logger.info("Parsing line " + lineNumber + ": " + line); + + // variable = value(s): assignment operator + if (subLine.matches("\\w+\\s*=\\s*\\w+.*")) { + + setValue = true; + variableName = subLine.substring(0, subLine.indexOf("=")).trim(); + if (!this.isHasVariable(variableName)) { + variable = new Variable(variableName, null); + this.addVariable(variable); + } + + logger.info("Found variable: " + variableName + " in line: " + line); + + subLine = subLine.substring(subLine.indexOf("=") + 1).trim(); + } + + String[] tokens = subLine.split("\\s+"); + + // --- Now we assume that the first token is a command name or a number + if (tokens.length == 1 && setValue && !isItCommand(tokens[0])) { + try { + Integer iNum = Integer.parseInt(tokens[0]); + if (!this.isHasVariable(variableName)) { + variable = new Variable(variableName, iNum); + this.addVariable(variable); + } else { + variable = this.getVariable(variableName); + variable.setValue(iNum); + } + + logger.info("Line: " + line + " is an integer number assignment: " + variableName + "=" + iNum); + continue; + } catch (Exception ex) { + // --- Is is a real number?... + try { + Double dNum = Double.parseDouble(tokens[0]); + if (!this.isHasVariable(variableName)) { + variable = new Variable(variableName, dNum); + this.addVariable(variable); + } else { + variable = this.getVariable(variableName); + variable.setValue(dNum); + } + logger.info("Line: " + line + " is a real number assignment: " + variableName + "=" + dNum); + continue; + } catch (Exception e) { + logger.info("Line: " + line + " is not a number assignment..."); + } + } + // --- Check for object + CommandInterface command = commandProviders.get(tokens[0]); + if (command != null) { + if (!this.isHasVariable(variableName)) { + variable = new Variable(variableName, command); + this.addVariable(variable); + logger.info("Line: " + line + " this is variable of type " + variable.getValue().getClass().getCanonicalName()); + continue; + } + + } + } // End "if" for ONE token after a "=" + + // --- if it's initialization statement + if (tokens.length == 1 && setValue && isItCommand(tokens[0])) { + CommandInterface command = this.getCommand(tokens[0]); + variable = this.getVariable(variableName); + variable.setValue(command.ciInstance()); + continue; + } + + // --- Now check for math expression + if (setValue) { + CommandInterface command = commandProviders.get(tokens[0]); + if (isItCommand(tokens[0]) || this.isItVariableCommand(tokens[0])) { + + } else { + if (isMathExpression(subLine)) { + // -- Add expression operator + Object[] args = {subLine}; + this.addCompiledCommand(new AtomicCommand(new MathExpressionOperator(this), args)); + // -- Add assinment operator + variable = this.getVariable(variableName); + args = new Object[]{variable, CONSTANTS.PREVIOUS_RESULT}; + this.addCompiledCommand(new AtomicCommand(assignmentOperator, args)); + continue; + } + } + } + + CommandInterface command = commandProviders.get(tokens[0]); + if (command == null) { + // --- Check for variable-command + if (this.isHasVariable(tokens[0])) { + Variable var = this.getVariable(tokens[0]); + if (var.getValue() instanceof CommandInterface) { + command = (CommandInterface) var.getValue(); + + } else { + throw new Exception("Variable-command should be of type " + CommandInterface.class + .getCanonicalName() + + " Got: " + var.getValue().getClass().getCanonicalName()); + } + } else { + throw new Exception("Unknown command " + tokens[0] + " in line " + lineNumber); + } + } + + Object[] commandArguments = command.ciParseCommand(tokens); + if (commandArguments == null) { + + } else { + for (int i = 0; i < commandArguments.length; i++) { + Object item = commandArguments[i]; + if (item instanceof String && variables.containsKey(item.toString())) { + commandArguments[i] = variables.get(item.toString()); + logger.info("Substituting variable " + item.toString()); + } else if (item instanceof Variable) { + Variable var = (Variable) item; + if (variables.containsKey(var.getName()) && !(command instanceof InbuiltCommandInterface)) { + throw new Exception("Variable " + var.getName() + " is already defined"); + } else { + variables.put(var.getName(), var); + } + } + } + // --- Record a compiled command + AtomicCommand atomicCommand = new AtomicCommand(command, commandArguments); + compiledCommands.add(atomicCommand); + } + + // --- Extra step in the case of assignment operator + if (setValue) { + variable = this.getVariable(variableName); + Object[] args = {variable, CONSTANTS.PREVIOUS_RESULT}; + + AtomicCommand assignCommand = new AtomicCommand(assignmentOperator, args); + this.addCompiledCommand(assignCommand); + } + } + + in.close(); + + } catch (Exception e) { + throw e; + } + + if (forLoopTracker.size() > 0) { + sWriter.append("Unmatched for loop\n"); + } + + String errors = sWriter.toString(); + if (errors != null && errors.length() > 0) { + throw new Exception(errors); + } + + StringBuilder sb = new StringBuilder(); + sb.append("Parsed " + lineNumber + " lines\n"); + sb.append("Number of variables: " + this.variables.size() + "\n"); + if (variables.size() > 0) { + sb.append("Variables: \n"); + for (String key : variables.keySet()) { + sb.append(key + " = " + variables.get(key).getValue() + "\n"); + } + } + logger.info(sb.toString()); + } + + public boolean isItVariableCommand(String variable) { + if (this.isHasVariable(variable)) { + Variable var = this.getVariable(variable); + if (var.getValue() instanceof CommandInterface) { + return true; + } + } + return false; + } + + public boolean isItCommand(String token) { + return commandProviders.containsKey(token); + } + + public CommandInterface getCommand(String commName) { + return commandProviders.get(commName); + } + + public boolean isMathExpression(String line) throws Exception { + MathExpressionParser mathExpressionParser = new MathExpressionParser(); + mathExpressionParser.setCaseSensitive(true); + for (String varName : variables.keySet()) { + if (this.isItVariableCommand(varName)) { + continue; + } + mathExpressionParser.addVariable(varName, 0); + } + try { + mathExpressionParser.addLine("x$$$=" + line); + return true; + } catch (Exception ex) { + throw new Exception(line + " : " + ex.getMessage()); + } + } + + public double evaluateMathExpression(String line) throws Exception { + MathExpressionParser mathExpressionParser = new MathExpressionParser(); + mathExpressionParser.setCaseSensitive(true); + + for (String varName : variables.keySet()) { + if (this.isItVariableCommand(varName)) { // Skip variable commands + continue; + } + // --- Some variables is not defined yet at this point + Variable var = this.getVariable(varName); + if (var.getValue() == null) { + continue; + //throw new Exception("Evaluating \"" + line + "\" : variable " + varName + " is not defined"); + } + + if (isObjectArray(var.getValue())) { + continue; + //throw new Exception("Evaluating \"" + line + "\" : variable " + varName + " is not a scalar"); + } + + if (var.getValue() instanceof Number) { + mathExpressionParser.addVariable(varName, ((Number) var.getValue()).doubleValue()); + continue; + } + + if (var.getValue() instanceof String) { + try { + double value = Double.parseDouble(var.getValue().toString()); + mathExpressionParser.addVariable(varName, value); + } catch (Exception ex) { + throw new Exception("Evaluating \"" + line + "\" : cannot convert " + varName + "=" + var.getValue().toString() + + " to double value"); + } + // --- Desperate attempt to conver variable into double + + try { + double value = Double.parseDouble(var.getValue().toString()); + mathExpressionParser.addVariable(varName, value); + System.err.println("Warning: converted Object value into double..."); + } catch (Exception ex) { + throw new Exception("Evaluating \"" + line + "\" : cannot convert " + varName + "=" + var.getValue().toString() + + " to double value"); + } + + } + + } + // --- Evaluate + try { + return mathExpressionParser.resolveExpression(line); + } catch (Exception ex) { + throw new Exception(line + " : " + ex.getMessage()); + } + } + + public static boolean isObjectArray(Object obj) { + return obj.getClass().isArray(); + } + + public boolean isOneVariableInstanceOnly() { + return oneVariableInstanceOnly; + } + + public void setOneVariableInstanceOnly(boolean oneVariableInstanceOnly) { + this.oneVariableInstanceOnly = oneVariableInstanceOnly; + } + + public boolean isAllowVariableRedifination() { + return allowVariableRedifination; + } + + public void setAllowVariableRedifination(boolean allowVariableRedifination) { + this.allowVariableRedifination = allowVariableRedifination; + } + + public static void printArgument(Object arg) { + if (arg == null) { + + System.out.print(arg); + } else if (arg.getClass().isPrimitive()) { + if (arg instanceof float[]) { + for (int i = 0; i < ((float[]) arg).length; i++) { + System.out.print(i + ": " + arg + "\n"); + } + } else if (arg instanceof float[][]) { + for (int i = 0; i < ((float[]) arg).length; i++) { + System.out.print(i + ": "); + for (int j = 0; j < ((float[][]) arg).length; j++) { + System.out.print(i + ": " + ((float[][]) arg)[i][j]); + } + System.out.print("\n"); + } + } else if (isObjectArray(arg)) { + + } else { + Object[] array = (Object[]) arg; + for (int i = 0; i < array.length; i++) { + if (array[i] != null) { + System.out.print(i + ": " + array[i].toString() + "\n"); + } else { + System.out.print(i + ": " + array[i] + "\n"); + } + } + } + } else { + System.out.print(arg.toString() + "\n"); + } + } + + public static Integer getIntValue(Object obj) throws Exception { + if (obj == null) { + throw new Exception("Cannot convert null into Integer value"); + } + if (obj instanceof Number) { + return ((Number) obj).intValue(); + } + + if (obj instanceof Variable) { + Variable var = (Variable) obj; + return var.getIntValue(); + } + + if (obj instanceof String) { + return getIntValue((String) obj); + } + throw new Exception("Cannot convert object " + obj.getClass().getCanonicalName() + " into the scalar Integer value"); + } + + public static Integer getIntValue(String str) throws Exception { + return Integer.parseInt(str.trim()); + } + + public static boolean isNumber(Object obj) { + if (obj == null) { + return false; + } + if (obj instanceof Number) { + return true; + } + try { + Double.parseDouble(obj.toString().trim()); + return true; + } catch (Exception ex) { + return false; + } + } + + public static boolean isIntegerNumber(Object obj) { + if (obj == null) { + return false; + } + if (obj instanceof Integer || obj instanceof Long || obj instanceof Short + || obj instanceof BigInteger || obj instanceof AtomicInteger) { + return true; + } + try { + Integer.parseInt(obj.toString().trim()); + return true; + } catch (Exception ex) { + return false; + } + } + + public static Double getDoubleValue(Object obj) throws Exception { + if (obj == null) { + throw new Exception("Cannot convert null into double value"); + } + if (obj instanceof Number) { + return ((Number) obj).doubleValue(); + } + + if (obj instanceof Variable) { + Variable var = (Variable) obj; + if (var.getValue() instanceof Number) { + return ((Number) var.getValue()).doubleValue(); + } + if (var.getValue() instanceof String) { + return getDoubleValue((String) var.getValue()); + } + throw new Exception("Cannot convert object " + var.getValue().getClass().getCanonicalName() + " of variable " + + var.getName() + " into the scalar double value"); + } + + if (obj instanceof String) { + return getDoubleValue((String) obj); + } + throw new Exception("Cannot convert object " + obj.getClass().getCanonicalName() + " into the scalar double value"); + } + + public static Double getDoubleValue(String str) throws Exception { + return Double.parseDouble(str.trim()); + } +} diff --git a/src/main/java/cct/cprocessor/CommandProcessorDeprecated.java b/src/main/java/cct/cprocessor/CommandProcessorDeprecated.java new file mode 100644 index 0000000..087ef53 --- /dev/null +++ b/src/main/java/cct/cprocessor/CommandProcessorDeprecated.java @@ -0,0 +1,614 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.cprocessor; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + * @Deprecated + */ + + +enum EraseCommandObject { + A, ATOM, ATOMS, B, BOND, MOLECULE +} + +enum SelectCommandObjects { + ATOM("atom"), ATOMS("atoms"); + + String comObject; + SelectCommandObjects(String obj) { + comObject = obj; + } +} + +/** + * + * @author vvv900 + * @Deprecated + */ +public class CommandProcessorDeprecated { + + List compiledCommands = new ArrayList (); + MolProcessorInterface molProcessor = null; + + Commands currentCommand = null; + Object commandObject = null; + Object commandArguments = null; + + public CommandProcessorDeprecated(MolProcessorInterface mp) { + molProcessor = mp; + } + + public static void main(String[] args) { + CommandProcessorDeprecated commandprocessor = new CommandProcessorDeprecated(null); + } + + public void executeScript() throws Exception { + executeScript(compiledCommands); + } + + public void executeScript(List < Object[] > compiled_commands) throws Exception { + for (int i = 0; i < compiled_commands.size(); i++) { + Object[] commLine = compiled_commands.get(i); + if (! (commLine[0] instanceof Commands)) { + throw new Exception("Runtime Error: expecting command, got " + + commLine[0].getClass().getCanonicalName()); + } + Commands command = (Commands) commLine[0]; + try { + switch (command) { + case A: + case ADD: + AddCommandObjects obj = (AddCommandObjects) commLine[1]; + executeAddCommand(obj, commLine[2]); + break; + case S: + case SEL: + case SELECT: + + //parseSelectCommand(st); + break; + case D: + case DEL: + case DELETE: + case E: + case ERASE: + EraseCommandObject obj2 = (EraseCommandObject) commLine[1]; + executeEraseCommand(obj2, commLine[2]); + break; + case C: + case CENTER: + executeCenterCommand(commLine[1], commLine[2]); + break; + case SLEEP: + Long millis = (Long) commLine[2]; + Thread.sleep(millis); + break; + case RENDER: + RenderCommandObject obj3 = (RenderCommandObject) commLine[1]; + executeRenderCommand(obj3, commLine[2]); + break; + } + } + catch (Exception ex) { + throw new Exception("Runtime Error: " + ex.getMessage()); + } + } + } + + void executeAddCommand(AddCommandObjects command_object, Object args) throws + Exception { + switch (command_object) { + case ATOM: + molProcessor.addAtom(args); + break; + case BOND: + molProcessor.addBond(args); + break; + } + } + + void executeEraseCommand(EraseCommandObject command_object, Object args) throws + Exception { + switch (command_object) { + case A: + case ATOM: + case ATOMS: + molProcessor.eraseAtoms(args); + break; + case BOND: + case B: + throw new Exception("Runtime Error: ERASE BOND is not implemented yet"); + //break; + case MOLECULE: + + break; + } + } + + void executeCenterCommand(Object command_object, Object args) throws + Exception { + molProcessor.centerMolecule(args); + } + + void executeRenderCommand(RenderCommandObject command_object, Object args) throws + Exception { + switch (command_object) { + case WIREFRAME: + molProcessor.setRenderingStyle("Wireframe"); + break; + case STICKS: + molProcessor.setRenderingStyle("Sticks"); + break; + case BALLS: + molProcessor.setRenderingStyle("Ball & Sticks"); + break; + case SPACEFILL: + molProcessor.setRenderingStyle("Spacefill"); + break; + default: + molProcessor.setRenderingStyle(command_object.toString()); + } + } + + public void parseScript(String filename, int fileType) throws Exception { + + String line; + BufferedReader in = null; + StringWriter sWriter = new StringWriter(); + + if (fileType == 0) { // Read from file + try { + in = new BufferedReader(new FileReader(filename)); + } + catch (Exception ex) { + throw ex; + } + } + else if (fileType == 1) { // Read from String + in = new BufferedReader(new StringReader(filename)); + } + else { + throw new Exception( + "parseScript: INTERNAL ERROR: Unknown file type"); + } + + try { + //BufferedReader in = new BufferedReader(new FileReader(filename)); + + int lineNumber = 0; + while ( (line = in.readLine()) != null) { + line = line.trim(); + ++lineNumber; + + if (line.length() < 1) { // Blank line + continue; + } + + if (line.startsWith("!") || line.startsWith("#") || + line.startsWith(";")) { + continue; + } + + StringTokenizer st = new StringTokenizer(line, " \t,"); + + // --- First token - command + + String com = st.nextToken().toUpperCase(); + Commands command; + /* + try { + //command = Commands.valueOf(com); + command = this.getCommand(com); + } + catch (Exception ex) { + sWriter.write("ERROR: line " + lineNumber + + ": Unrecognizable command: " + com + "\n"); + continue; + } + */ + + command = this.getCommand(com); + if (command == null) { + sWriter.write("ERROR: line " + lineNumber + + ": Unrecognizable command: " + com + "\n"); + continue; + } + currentCommand = command; + + try { + parseCommand(command, st); + } + catch (Exception ex) { + sWriter.write("ERROR: line " + lineNumber + ": " + ex.getMessage() + + "\n"); + continue; + } + + // --- Record a compiled command + + Object[] commLine = { + currentCommand, commandObject, commandArguments}; + compiledCommands.add(commLine); + } + + in.close(); + + } + catch (Exception e) { + throw e; + } + + String errors = sWriter.toString(); + if (errors != null && errors.length() > 0) { + throw new Exception(errors); + } + + } + + void parseCommand(Commands command, StringTokenizer st) throws Exception { + switch (command) { + case A: + case ADD: + parseAddCommand(st); + break; + case S: + case SEL: + case SELECT: + parseSelectCommand(st); + break; + case D: + case DEL: + case DELETE: + case E: + case ERASE: + parseEraseCommand(st); + break; + case C: + case CENTER: + commandObject = null; + commandArguments = null; + break; + case SLEEP: + parseSleepCommand(st); + break; + case RENDER: + parseRenderCommand(st); + break; + + } + + } + + void parseAddCommand(StringTokenizer st) throws Exception { + if (st.countTokens() < 1) { + throw new Exception( + "add command has to have an object to be applied to..."); + } + + String cobj = st.nextToken().toUpperCase(); + + AddCommandObjects command_object = this.getAddCommandObject(cobj); + + if (command_object == null) { + throw new Exception("add command has no object " + cobj); + } + /* + try { + command_object = AddCommandObjects.valueOf(cobj); + } + catch (Exception ex) { + throw new Exception("add command has no object " + cobj); + } + */ + commandObject = command_object; + + switch (command_object) { + case ATOM: + parseAddAtomArg(st); + break; + case BOND: + parseAddBondArg(st); + break; + + } + } + + void parseAddAtomArg(StringTokenizer st) throws Exception { + if (st.countTokens() < 3) { + throw new Exception( + "add atom command has to have at least 3 arguments"); + } + + String token = ""; + float x, y, z; + try { + token = st.nextToken(); + x = Float.parseFloat(token); + token = st.nextToken(); + y = Float.parseFloat(token); + token = st.nextToken(); + z = Float.parseFloat(token); + } + catch (Exception ex) { + throw new Exception( + "add atom command: cannot parse coordinate " + token); + } + + int element = 0; + if (st.hasMoreTokens()) { + try { + token = st.nextToken(); + element = Integer.parseInt(token); + } + catch (Exception ex) { + throw new Exception( + "add atom command: cannot parse atomic element " + token); + } + } + + String name = ""; + if (st.hasMoreTokens()) { + name = st.nextToken(); + } + + GenericAtom atom = new GenericAtom(x, y, z, element, name); + commandArguments = atom; + } + + void parseAddBondArg(StringTokenizer st) throws Exception { + if (st.countTokens() < 2) { + throw new Exception( + "add bond command has to have 2 arguments"); + } + + String token = ""; + int i, j; + try { + token = st.nextToken(); + i = Integer.parseInt(token) - 1; + token = st.nextToken(); + j = Integer.parseInt(token) - 1; + } + catch (Exception ex) { + throw new Exception( + "add bond command: cannot parse atom number " + token); + } + + GenericBond bond = new GenericBond(i, j); + commandArguments = bond; + } + + void parseSelectCommand(StringTokenizer st) throws Exception { + if (st.countTokens() < 1) { + throw new Exception( + "select command has to have an object to be applied to..."); + } + + String cobj = st.nextToken(); + + SelectCommandObjects command_object; + try { + command_object = SelectCommandObjects.valueOf(cobj); + } + catch (Exception ex) { + throw new Exception("select command has no object " + cobj); + } + + commandObject = command_object; + + switch (command_object) { + case ATOM: + case ATOMS: + parseSelectAtomArg(st); + break; + } + } + + void parseSelectAtomArg(StringTokenizer st) throws Exception { + if (st.countTokens() < 1) { + return; + } + + int[] atom_numbers = new int[st.countTokens()]; + + String token = ""; + int count = 0; + while (st.hasMoreTokens()) { + try { + token = st.nextToken(); + atom_numbers[count] = Integer.parseInt(token) - 1; + ++count; + } + catch (Exception ex) { + throw new Exception( + "select atoms command: cannot parse atom number " + token); + } + + } + + commandArguments = atom_numbers; + } + + void parseEraseCommand(StringTokenizer st) throws Exception { + if (st.countTokens() < 1) { + throw new Exception( + "erase command has to have an object to be applied to..."); + } + + String cobj = st.nextToken().toUpperCase(); + + EraseCommandObject command_object = this.getEraseCommandObject(cobj); + + if (command_object == null) { + throw new Exception("erase command has no object " + cobj); + } + commandObject = command_object; + + switch (command_object) { + case A: + case ATOM: + case ATOMS: + parseEraseAtomsArg(st); + break; + case BOND: + case B: + parseAddBondArg(st); + break; + case MOLECULE: + parseAddBondArg(st); + break; + + } + } + + void parseEraseAtomsArg(StringTokenizer st) throws Exception { + if (st.countTokens() < 1) { + throw new Exception( + "erase atom(s) command has to have at least 1 argument"); + } + + String token = ""; + int[] atom_numbers = new int[st.countTokens()]; + int count = 0; + while (st.hasMoreTokens()) { + try { + token = st.nextToken(); + atom_numbers[count] = Integer.parseInt(token) - 1; + ++count; + } + catch (Exception ex) { + throw new Exception( + "erase atom(s) command: cannot parse atom number " + token); + } + + } + + commandArguments = atom_numbers; + } + + void parseSleepCommand(StringTokenizer st) throws Exception { + if (st.countTokens() < 1) { + throw new Exception( + "sleep command has to have an argument..."); + } + + commandObject = null; + + String token = st.nextToken(); + Long millis = 0L; + try { + millis = Long.parseLong(token); + } + catch (Exception ex) { + throw new Exception("Error parsing milliseconds for sleep command: expecting integer number, got: " + token); + } + commandArguments = millis; + } + + void parseRenderCommand(StringTokenizer st) throws Exception { + if (st.countTokens() < 1) { + throw new Exception( + "render command has to have an object to be applied to..."); + } + + String cobj = st.nextToken().toUpperCase(); + + RenderCommandObject command_object = this.getRenderCommandObject(cobj); + + if (command_object == null) { + throw new Exception("render command has no object " + cobj); + } + commandObject = command_object; + commandArguments = null; + } + + Commands getCommand(String command) throws Exception { + for (Commands c : Commands.values()) { + if (command.equalsIgnoreCase(c.toString())) { + return c; + } + } + throw new Exception("No such command " + command); + } + + AddCommandObjects getAddCommandObject(String command) throws Exception { + for (AddCommandObjects c : AddCommandObjects.values()) { + if (command.equalsIgnoreCase(c.toString())) { + return c; + } + } + throw new Exception("No such add command object " + command); + } + + EraseCommandObject getEraseCommandObject(String command) throws Exception { + for (EraseCommandObject c : EraseCommandObject.values()) { + if (command.equalsIgnoreCase(c.toString())) { + return c; + } + } + throw new Exception("No such erase command object " + command); + } + + RenderCommandObject getRenderCommandObject(String command) throws Exception { + for (RenderCommandObject c : RenderCommandObject.values()) { + if (command.equalsIgnoreCase(c.toString())) { + return c; + } + } + throw new Exception("No such render command object " + command); + } + +} diff --git a/src/main/java/cct/cprocessor/Commands.java b/src/main/java/cct/cprocessor/Commands.java new file mode 100644 index 0000000..1bcab1d --- /dev/null +++ b/src/main/java/cct/cprocessor/Commands.java @@ -0,0 +1,74 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.cprocessor; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +enum Commands { + A("a"), ADD("add"), S("s"), SEL("sel"), SELECT("select"), D("d"), DEL("del"), + DELETE("delete"), E("e"), ERASE("erase"), C("c"), CENTER("center"), SLEEP("sleep"), RENDER("render"); + private String Command; + Commands(String command) { + Command = command; + } + + public boolean isValidCommand(String command) { + for (Commands c: Commands.values()) { + if (command.equalsIgnoreCase(c.Command)) return true; + } + return false; + } + + public Commands getCommand(String command) { + for (Commands c: Commands.values()) { + if (command.equalsIgnoreCase(c.Command)) return c; + } + return null; + + } +} diff --git a/src/main/java/cct/cprocessor/EmptyCommand.java b/src/main/java/cct/cprocessor/EmptyCommand.java new file mode 100644 index 0000000..11aba4f --- /dev/null +++ b/src/main/java/cct/cprocessor/EmptyCommand.java @@ -0,0 +1,25 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.cprocessor; + +/** + * + * @author vvv900 + */ +public class EmptyCommand implements CommandInterface { + + public CommandInterface ciInstance() { + return new EmptyCommand(); + } + + public Object ciExecuteCommand(Object[] args) throws Exception { + return null; + } + + public Object[] ciParseCommand(String[] tokens) throws Exception { + return null; + } +} diff --git a/src/main/java/cct/cprocessor/EndForLoopCommand.java b/src/main/java/cct/cprocessor/EndForLoopCommand.java new file mode 100644 index 0000000..7dc7bcf --- /dev/null +++ b/src/main/java/cct/cprocessor/EndForLoopCommand.java @@ -0,0 +1,106 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.cprocessor; + +import java.util.List; +import java.util.Map; + +/** + * + * @author vvv900 + */ +public class EndForLoopCommand implements InbuiltCommandInterface { + + private int switchToCommand = -1; + private CommandProcessor commandProcessor; + + public EndForLoopCommand() { + } + + public EndForLoopCommand(CommandProcessor commandProcessor) { + this.commandProcessor = commandProcessor; + } + + public CommandInterface ciInstance() { + return new EndForLoopCommand(commandProcessor); + } + + public Object ciExecuteCommand(Object[] args) throws Exception { + int forStart = (Integer) args[0]; + AtomicCommand atomicCommand = commandProcessor.getCompiledCommand(forStart); // Get for loop parameters + + Object[] forArgs = atomicCommand.getParsedArguments(); + Variable controlLoopVar = (Variable) forArgs[0]; + Number clv = (Number) controlLoopVar.getValue(); + if (controlLoopVar.getValue() instanceof Double || controlLoopVar.getValue() instanceof Float) { + Double i = ((Number) controlLoopVar.getValue()).doubleValue(); + Double step = 1.0; + //if (forArgs[2] != null) { + step = CommandProcessor.getDoubleValue(forArgs[2]); + //} + double newi = i.doubleValue() + step.doubleValue(); + if (clv instanceof Double) { + controlLoopVar.setValue(new Double(newi)); + } else { + controlLoopVar.setValue(new Float(newi)); + } + } else { + Integer i = ((Number) controlLoopVar.getValue()).intValue(); + Integer step = 1; + //if (forArgs[2] != null) { + step = CommandProcessor.getIntValue(forArgs[2]); + //} + int newi = i.intValue() + step.intValue(); + controlLoopVar.setValue(new Integer(newi)); + } + + switchToCommand = forStart; + return null; + } + + public int getNewCommandCounter() { + return switchToCommand; + } + + public Object[] ciParseCommand(String[] tokens) throws Exception { + if (tokens == null || tokens.length == 0) { + throw new Exception(this.getClass().getCanonicalName() + ": for loop command: parameters are not set"); + } + + if (!tokens[0].equals("endfor")) { + throw new Exception(this.getClass().getCanonicalName() + + ": expected endfor loop command, got: " + tokens[0]); + } + // for i start stop [step] + if (tokens.length > 1) { + throw new Exception(this.getClass().getCanonicalName() + ": endfor loop command does not require any arguments"); + } + + if (commandProcessor.numberForLoopsInProcessing() == 0) { + throw new Exception(this.getClass().getCanonicalName() + ": endfor loop command: matching \"for\" loop operator is missing"); + } + // --- at the endfor we need to make increment of loop control variable ("i") using a "step" variable + Integer forStart = commandProcessor.extractForLoopStart(); + AtomicCommand forCommand = commandProcessor.getCompiledCommand(forStart); // Get for loop parameters + + AtomicCommand endforCommand = new AtomicCommand(this, new Object[]{forStart}); + commandProcessor.addCompiledCommand(endforCommand); + + // --- Update the last argument for for command + Object[] args = forCommand.getParsedArguments(); + args[args.length - 1] + = new Integer(commandProcessor.numberOfCompiledCommands()); // i.e. point to the next command after endfor + + commandProcessor.addCompiledCommand(new AtomicCommand(new EmptyCommand(), null)); + + return null; + } + + public void setCommandProcessor(CommandProcessor commandProcessor) { + this.commandProcessor = commandProcessor; + } + +} diff --git a/src/main/java/cct/cprocessor/ForLoopCommand.java b/src/main/java/cct/cprocessor/ForLoopCommand.java new file mode 100644 index 0000000..5af5391 --- /dev/null +++ b/src/main/java/cct/cprocessor/ForLoopCommand.java @@ -0,0 +1,153 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.cprocessor; + +import java.util.List; +import java.util.Map; + +/** + * + * @author vvv900 + */ +public class ForLoopCommand implements InbuiltCommandInterface { + + private CommandProcessor commandProcessor; + private int switchToCommand = -1; + + public ForLoopCommand() { + } + + public ForLoopCommand(CommandProcessor commandProcessor) { + this.commandProcessor = commandProcessor; + } + + public CommandInterface ciInstance() { + return new ForLoopCommand(commandProcessor); + } + + public Object ciExecuteCommand(Object[] args) throws Exception { + if (args.length != 4) { + throw new Exception(this.getClass().getCanonicalName() + ": for loop execution command requires 4 arguments"); + } + // --- Get Control loop variable + Variable iVar = (Variable) args[0]; + Number i = (Number) iVar.getValue(); + // --- Get "stop variable + Number stop; + if (args[1] instanceof Variable) { + Variable stopVar = (Variable) args[1]; + stop = (Number) stopVar.getValue(); + } else { + stop = (Number) args[1]; + } + + // --- Get "step" + Number step; + if (args[2] instanceof Variable) { + Variable stepVar = (Variable) args[2]; + step = (Number) stepVar.getValue(); + } else { + step = (Number) args[2]; + } + + // -- Get jump value + Number jump = (Number) args[3]; + // --- + if (step.doubleValue() == 0) { + throw new Exception(this.getClass().getCanonicalName() + ": for loop execution command: step cannot be 0"); + } else if (step.doubleValue() > 0) { + if (i.doubleValue() <= stop.doubleValue()) { + switchToCommand = -1; + } else { + switchToCommand = jump.intValue(); + } + } else { + if (i.doubleValue() >= stop.doubleValue()) { + switchToCommand = -1; + } else { + switchToCommand = jump.intValue(); + } + } + return null; + } + + public Object[] ciParseCommand(String[] tokens) throws Exception { + if (tokens == null || tokens.length == 0) { + throw new Exception(this.getClass().getCanonicalName() + ": for loop command: parameters are not set"); + } + + if (!tokens[0].equals("for")) { + throw new Exception(this.getClass().getCanonicalName() + + ": expected for loop command, got: " + tokens[0]); + } + // for i start stop [step] + if (tokens.length < 4) { + throw new Exception(this.getClass().getCanonicalName() + ": for loop command requires at least three arguments"); + } else if (tokens.length > 5) { + throw new Exception(this.getClass().getCanonicalName() + ": for loop command does not require more than 4 arguments"); + } + // --- Process variable "i" + Variable var = null; + if (commandProcessor.isHasVariable(tokens[1])) { + var = commandProcessor.getVariable(tokens[1]); + } else { + var = new Variable(tokens[1], null); + commandProcessor.addVariable(var); + } + + // --- Now decide what is a type of a "start" variable and add an assignment command + if (commandProcessor.isHasVariable(tokens[2])) { + Variable var2 = commandProcessor.getVariable(tokens[2]); + AtomicCommand atomicCommand = new AtomicCommand(new AssignmentOperator(), new Object[]{var, var2}); + commandProcessor.addCompiledCommand(atomicCommand); + } else { // It's not an existing variable + Number num = CommandProcessor.getNumber(tokens[2]); + AtomicCommand atomicCommand = new AtomicCommand(new AssignmentOperator(), new Object[]{var, num}); + commandProcessor.addCompiledCommand(atomicCommand); + } + + // --- Now decide what is a type of a "stop" variable + Object stop; + if (commandProcessor.isHasVariable(tokens[3])) { + stop = commandProcessor.getVariable(tokens[3]); + } else { // It's not an existing variable + Number num = CommandProcessor.getNumber(tokens[3]); + stop = num; + } + + Object[] compiledArgs = null; + AtomicCommand atomicCommand = null; + if (tokens.length == 4) { + compiledArgs = new Object[]{var, stop, new Integer(1), null}; + atomicCommand = new AtomicCommand(this, compiledArgs); // reserve last value to be filled in by endfor + } else if (tokens.length == 5) { + // --- Now decide what is a type of a "step" variable + Object step; + if (commandProcessor.isHasVariable(tokens[4])) { + step = commandProcessor.getVariable(tokens[4]); + } else { // It's not an existing variable + Number num = CommandProcessor.getNumber(tokens[4]); + step = num; + } + compiledArgs = new Object[]{var, stop, step, null}; + atomicCommand = new AtomicCommand(this, compiledArgs); // reserve last value to be filled in by endfor + } + // --- + + //compiledCommands.add(atomicCommand); + commandProcessor.addForLoopForProcessing(commandProcessor.numberOfCompiledCommands()); // i.e. adds at the top of the list + + return compiledArgs; + } + + public int getNewCommandCounter() { + return switchToCommand; + } + + public void setCommandProcessor(CommandProcessor commandProcessor) { + this.commandProcessor = commandProcessor; + } +} diff --git a/src/main/java/cct/cprocessor/GUIWrapperCommand.java b/src/main/java/cct/cprocessor/GUIWrapperCommand.java new file mode 100644 index 0000000..3acc880 --- /dev/null +++ b/src/main/java/cct/cprocessor/GUIWrapperCommand.java @@ -0,0 +1,116 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.cprocessor; + +import cct.GlobalSettings; +import cct.interfaces.MoleculeInterface; +import cct.j3d.Java3dUniverse; +import java.util.HashSet; +import java.util.Set; + +/** + * + * @author vvv900 + */ +public class GUIWrapperCommand implements CommandInterface { + + public static final Set supportedCommands = new HashSet(); + + static { + supportedCommands.add("show"); + } + private String command; + private Java3dUniverse renderer; + + public GUIWrapperCommand(Java3dUniverse renderer) { + this.renderer = renderer; + } + + public CommandInterface ciInstance() { + return new GUIWrapperCommand(renderer); + } + + static public String[] supportedCommands() { + return supportedCommands.toArray(new String[supportedCommands.size()]); + } + + public Java3dUniverse getRenderer() { + return renderer; + } + + public void setRenderer(Java3dUniverse renderer) { + this.renderer = renderer; + } + + public Object ciExecuteCommand(Object[] args) throws Exception { + if (renderer == null) { + throw new Exception("3d Renderer is not set"); + } + // + MoleculeInterface m = null; + if (args[0] instanceof Variable) { + Object obj = ((Variable) args[0]).getValue(); + if (!(obj instanceof MoleculeInterface)) { + throw new Exception("Execute Show molecule command: variable as the first argument should of type Molecule. Got " + + obj.getClass().getCanonicalName()); + } + m = (MoleculeInterface) obj; + } else if (!(args[0] instanceof MoleculeInterface)) { + throw new Exception("Execute Show molecule command: the first argument should of type Molecule. Got " + + args[0].getClass().getCanonicalName()); + } else { + m = (MoleculeInterface) args[0]; + } + + GlobalSettings.ADD_MOLECULE_MODE mode = GlobalSettings.ADD_MOLECULE_MODE.SET; + + if (args.length > 1 && (!(args[1] instanceof GlobalSettings.ADD_MOLECULE_MODE))) { + throw new Exception("Execute Show molecule command: the first argument should of type " + + GlobalSettings.ADD_MOLECULE_MODE.class.getCanonicalName() + " Got " + + args[1].getClass().getCanonicalName()); + } + + if (args.length > 1) { + mode = (GlobalSettings.ADD_MOLECULE_MODE) args[1]; + } + + renderer.setMolecule(m, mode); + return null; + } + + /** + * Wrapper for GUI related commands. Cuurently available ones are: show Molecule_object - shows molecule in 3r + * renderer (if it's set) + * + * @param tokens - arguments. The first argument is a command name, so it's ignored + * @return parsed and parameters + * @throws Exception + */ + public Object[] ciParseCommand(String[] tokens) throws Exception { + if (!supportedCommands.contains(tokens[0])) { + throw new Exception("No such GUI related command: " + tokens[0]); + } + if (tokens.length < 2) { + throw new Exception("Show molecule command requires at least one argument (molecule object)"); + } + Object[] parsedArgs = new Object[tokens.length > 2 ? 2 : 1]; + parsedArgs[0] = tokens[1]; + + if (tokens.length > 2) { + if (tokens[2].endsWith("a") || tokens[2].equals("append")) { + parsedArgs[1] = GlobalSettings.ADD_MOLECULE_MODE.APPEND; + } else if (tokens[2].endsWith("s") || tokens[2].equals("set")) { + parsedArgs[1] = GlobalSettings.ADD_MOLECULE_MODE.SET; + } else { + throw new Exception("Show molecule command: unknown second argument: " + tokens[2] + + " Expected: a, append or s, set"); + } + } + + return parsedArgs; + } + +} diff --git a/src/main/java/cct/cprocessor/GenericAtom.java b/src/main/java/cct/cprocessor/GenericAtom.java new file mode 100644 index 0000000..2f6daa3 --- /dev/null +++ b/src/main/java/cct/cprocessor/GenericAtom.java @@ -0,0 +1,66 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.cprocessor; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class GenericAtom { + public float x,y,z; + public int element=0; + public int substructure = 0; + public String name=""; + public GenericAtom() { + } + public GenericAtom(float x, float y, float z, int element, String name ) { + this.x = x; + this.y = y; + this.z = z; + this.element = element; + this.name = name; + } +} diff --git a/src/main/java/cct/cprocessor/GenericBond.java b/src/main/java/cct/cprocessor/GenericBond.java new file mode 100644 index 0000000..ff8c3da --- /dev/null +++ b/src/main/java/cct/cprocessor/GenericBond.java @@ -0,0 +1,58 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.cprocessor; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class GenericBond { + public int i, j; + public GenericBond(int a1, int a2) { + i = a1; + j = a2; + } +} diff --git a/src/main/java/cct/cprocessor/GeometryCommand.java b/src/main/java/cct/cprocessor/GeometryCommand.java new file mode 100644 index 0000000..fadbc9b --- /dev/null +++ b/src/main/java/cct/cprocessor/GeometryCommand.java @@ -0,0 +1,93 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.cprocessor; + +import static cct.cprocessor.MoleculeCommand.supportedCommands; +import cct.vecmath.Point3f; +import java.util.HashSet; +import java.util.Set; + +/** + * + * @author vvv900 + */ +public class GeometryCommand implements CommandInterface { + + public static final String DISTANCE_COMMAND = "distance"; + public static final String ANGLE_COMMAND = "angle"; + public static final String DIHEDRAL_COMMAND = "dihedral"; + private static Set supportedCommands = new HashSet(); + + static { + supportedCommands.add(DISTANCE_COMMAND); + supportedCommands.add(ANGLE_COMMAND); + supportedCommands.add(DIHEDRAL_COMMAND); + } + + public CommandInterface ciInstance() { + return new GeometryCommand(); + } + + public Object ciExecuteCommand(Object[] args) throws Exception { + if (args[0].equals(DISTANCE_COMMAND)) { + Point3f p1 = getPoint3f(args[1]); + Point3f p2 = getPoint3f(args[2]); + return Point3f.distance(p1, p2); + } else if (args[0].equals(ANGLE_COMMAND)) { + Point3f p1 = getPoint3f(args[1]); + Point3f p2 = getPoint3f(args[2]); + Point3f p3 = getPoint3f(args[3]); + return Point3f.RADIANS_TO_DEGREES * Point3f.angleBetween(p1, p2, p3); + } else if (args[0].equals(DIHEDRAL_COMMAND)) { + Point3f p1 = getPoint3f(args[1]); + Point3f p2 = getPoint3f(args[2]); + Point3f p3 = getPoint3f(args[3]); + Point3f p4 = getPoint3f(args[4]); + return Point3f.RADIANS_TO_DEGREES * Point3f.dihedralAngle(p1, p2, p3, p4); + } + return null; + } + + public Object[] ciParseCommand(String[] tokens) throws Exception { + if (!supportedCommands.contains(tokens[1])) { + throw new Exception(this.getClass().getCanonicalName() + ": Unknown command: " + tokens[1]); + } + // --- + + if (tokens[1].equals(DISTANCE_COMMAND)) { // Geometry distance Point3f_object Point3f_object + if (tokens.length != 4) { + throw new Exception(this.getClass().getCanonicalName() + ": " + DISTANCE_COMMAND + " command requires three arguments"); + } + return new Object[]{tokens[1], tokens[2], tokens[3]}; + // ----- + } else if (tokens[1].equals(ANGLE_COMMAND)) { // Geometry angle Point3f_object Point3f_object Point3f_object + if (tokens.length != 5) { + throw new Exception(this.getClass().getCanonicalName() + ": " + ANGLE_COMMAND + " command requires three arguments"); + } + return new Object[]{tokens[1], tokens[2], tokens[3], tokens[4]}; + } // ---- + else if (tokens[1].equals(DIHEDRAL_COMMAND)) { // Geometry angle Point3f_object Point3f_object Point3f_object Point3f_object + if (tokens.length != 6) { + throw new Exception(this.getClass().getCanonicalName() + ": " + DIHEDRAL_COMMAND + " command requires three arguments"); + } + return new Object[]{tokens[1], tokens[2], tokens[3], tokens[4], tokens[5]}; + } + throw new Exception(this.getClass().getCanonicalName() + ": was unable to parse a command"); + } + + public Point3f getPoint3f(Object obj) throws Exception { + if (!(obj instanceof Variable)) { + throw new Exception(this.getClass().getCanonicalName() + ": expected a variable, got " + + obj.getClass().getCanonicalName()); + } + Variable var = (Variable) obj; + if (var.getValue() instanceof Point3f) { + return (Point3f) var.getValue(); + } + throw new Exception(this.getClass().getCanonicalName() + ": expected a variable of type Point3f, got " + + var.getValue().getClass().getCanonicalName()); + } +} diff --git a/src/main/java/cct/cprocessor/InbuiltCommandInterface.java b/src/main/java/cct/cprocessor/InbuiltCommandInterface.java new file mode 100644 index 0000000..2377886 --- /dev/null +++ b/src/main/java/cct/cprocessor/InbuiltCommandInterface.java @@ -0,0 +1,20 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.cprocessor; + +import java.util.List; +import java.util.Map; + +/** + * + * @author vvv900 + */ +public interface InbuiltCommandInterface extends CommandInterface { + + int getNewCommandCounter(); + + void setCommandProcessor(CommandProcessor commandProcessor); +} diff --git a/src/main/java/cct/cprocessor/ListCommand.java b/src/main/java/cct/cprocessor/ListCommand.java new file mode 100644 index 0000000..ae793c6 --- /dev/null +++ b/src/main/java/cct/cprocessor/ListCommand.java @@ -0,0 +1,116 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.cprocessor; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; + +/** + * + * @author vvv900 + */ +public class ListCommand extends ArrayList implements CommandInterface { + + static public final String ADD_COMMAND = "add"; + static public final String GET_COMMAND = "get"; + static public final String SIZE_COMMAND = "size"; + static public final String TOARRAY_COMMAND = "toArray"; + static private Set listCommands = new HashSet(); + + static { + listCommands.add(ADD_COMMAND); + listCommands.add(GET_COMMAND); + listCommands.add(SIZE_COMMAND); + listCommands.add(TOARRAY_COMMAND); + } + + public CommandInterface ciInstance() { + return new ListCommand(); + } + + public Object ciExecuteCommand(Object[] args) throws Exception { + if (args[0].equals(ADD_COMMAND)) { // add item + Object obj = args[1]; + if (obj instanceof Variable) { + obj = ((Variable) args[1]).getValue(); + } + add(obj); + return obj; + } else if (args[0].equals(GET_COMMAND)) { // get item_number + Object obj = args[1]; + if (CommandProcessor.isIntegerNumber(obj)) { + int n = CommandProcessor.getIntValue(obj); + return get(n); + } + if (obj instanceof Variable) { + obj = ((Variable) args[1]).getValue(); + if (CommandProcessor.isIntegerNumber(obj)) { + int n = CommandProcessor.getIntValue(obj); + return get(n); + } + } + throw new Exception(this.getClass().getCanonicalName() + ": executing " + ADD_COMMAND + + ": expected integer argument. Got " + obj.getClass().getCanonicalName()); + } else if (args[0].equals(TOARRAY_COMMAND)) { // toArray + if (size() == 0) { + System.out.println(this.getClass().getCanonicalName() + ": " + TOARRAY_COMMAND + ": size of array = 0"); + return null; + + } + Object item = get(0); + if (item instanceof Double || item instanceof Float || CommandProcessor.isIntegerNumber(item)) { + double[] d = new double[size()]; + for (int i = 0; i < size(); i++) { + d[i] = ((Number) get(i)).doubleValue(); + } + return d; + } else { + return this.toArray(); + } + } + return null; + } + + /** + * Parses command parameters. + * + * @param tokens - arguments. The first argument is a command name, so it's ignored + * @return parsed and parameters + * @throws Exception + */ + public Object[] ciParseCommand(String[] tokens) throws Exception { + if (tokens == null || tokens.length <= 1) { + return null; // Initialization + } + // --- + if (!listCommands.contains(tokens[1])) { + throw new Exception(this.getClass().getCanonicalName() + ": Uknown command: " + tokens[1]); + } + if (tokens[1].equals(ADD_COMMAND)) { // add item + if (tokens.length != 3) { + throw new Exception(this.getClass().getCanonicalName() + ": " + ADD_COMMAND + " command requires one argument"); + } + return new Object[]{ADD_COMMAND, tokens[2]}; + } else if (tokens[1].equals(GET_COMMAND)) { // get item_number + if (tokens.length != 3) { + throw new Exception(this.getClass().getCanonicalName() + ": " + GET_COMMAND + " command requires one argument"); + } + if (CommandProcessor.isIntegerNumber(tokens[2])) { + return new Object[]{GET_COMMAND, Integer.parseInt(tokens[2])}; + } else { + return new Object[]{GET_COMMAND, tokens[2]}; + } + } else if (tokens[1].equals(TOARRAY_COMMAND)) { // toArray + if (tokens.length != 2) { + throw new Exception(this.getClass().getCanonicalName() + ": " + TOARRAY_COMMAND + + " command does not require argument(s)"); + } + return new Object[]{TOARRAY_COMMAND}; + } + return null; + } +} diff --git a/src/main/java/cct/cprocessor/MacroProcessor.java b/src/main/java/cct/cprocessor/MacroProcessor.java new file mode 100644 index 0000000..a15eb9a --- /dev/null +++ b/src/main/java/cct/cprocessor/MacroProcessor.java @@ -0,0 +1,112 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.cprocessor; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class MacroProcessor + implements MacroProcessorInterface { + MolProcessorInterface MPI = null; + CommandProcessorDeprecated commandProcessor; + + Map macroNames = new HashMap(); + List Macros = new ArrayList(); + String currentMacroName = null; + List currentMacroBlock = null; + + public MacroProcessor(MolProcessorInterface mpi) { + MPI = mpi; + commandProcessor = new CommandProcessorDeprecated(MPI); + } + + public static void main(String[] args) { + //UndoProcessor undoprocessor = new UndoProcessor(); + } + + @Override + public void addAtom(Object atom) { + Object[] commLine = { + Commands.ADD, AddCommandObjects.ATOM, atom}; + currentMacroBlock.add(commLine); + } + + @Override + public void addBond(Object atom_1, Object atom_2) { + Object[] args = { + atom_1, atom_2}; + Object[] commLine = { + Commands.ADD, AddCommandObjects.BOND, args}; + currentMacroBlock.add(commLine); + } + + @Override + public void recordMacro(String macroName) { + // --- close previous macro first... + + if (currentMacroName != null) { + stopRecordMacro(); + } + + currentMacroName = macroName; + currentMacroBlock = new ArrayList(); + } + + @Override + public void stopRecordMacro() { + + Macros.add(0, currentMacroBlock); + macroNames.put(currentMacroName, currentMacroBlock); + currentMacroName = null; + + } +} diff --git a/src/main/java/cct/cprocessor/MacroProcessorInterface.java b/src/main/java/cct/cprocessor/MacroProcessorInterface.java new file mode 100644 index 0000000..2075865 --- /dev/null +++ b/src/main/java/cct/cprocessor/MacroProcessorInterface.java @@ -0,0 +1,59 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.cprocessor; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface MacroProcessorInterface { + + void addAtom(Object atom); + void addBond(Object atom_1, Object atom_2); + + void recordMacro(String macroName); + void stopRecordMacro(); +} diff --git a/src/main/java/cct/cprocessor/MathExpressionOperator.java b/src/main/java/cct/cprocessor/MathExpressionOperator.java new file mode 100644 index 0000000..5276d88 --- /dev/null +++ b/src/main/java/cct/cprocessor/MathExpressionOperator.java @@ -0,0 +1,48 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.cprocessor; + +/** + * + * @author vvv900 + */ +public class MathExpressionOperator implements InbuiltCommandInterface { + + private CommandProcessor commandProcessor; + + public MathExpressionOperator() { + } + + public MathExpressionOperator(CommandProcessor commandProcessor) { + this.commandProcessor = commandProcessor; + } + + public CommandInterface ciInstance() { + return new MathExpressionOperator(commandProcessor); + } + + /** + * + * @param args - A singe argument - string with expression + * @return - double value (result of evaluation of expression) + * @throws Exception + */ + public Object ciExecuteCommand(Object[] args) throws Exception { + return commandProcessor.evaluateMathExpression(args[0].toString()); + } + + public Object[] ciParseCommand(String[] tokens) throws Exception { + return null; + } + + public int getNewCommandCounter() { + return -1; + } + + public void setCommandProcessor(CommandProcessor commandProcessor) { + this.commandProcessor = commandProcessor; + } +} diff --git a/src/main/java/cct/cprocessor/MolProcessorInterface.java b/src/main/java/cct/cprocessor/MolProcessorInterface.java new file mode 100644 index 0000000..1bc64b5 --- /dev/null +++ b/src/main/java/cct/cprocessor/MolProcessorInterface.java @@ -0,0 +1,58 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.cprocessor; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface MolProcessorInterface { + void addAtom(Object atom) throws Exception; + void addBond(Object bond) throws Exception; + void eraseAtoms(Object atoms) throws Exception; + void centerMolecule(Object center) throws Exception; + void setRenderingStyle(Object style) throws Exception; +} diff --git a/src/main/java/cct/cprocessor/MoleculeCommand.java b/src/main/java/cct/cprocessor/MoleculeCommand.java new file mode 100644 index 0000000..c05e426 --- /dev/null +++ b/src/main/java/cct/cprocessor/MoleculeCommand.java @@ -0,0 +1,165 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.cprocessor; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.Molecule; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +/** + * + * @author vvv900 + */ +public class MoleculeCommand extends Molecule implements CommandInterface { + + public static final Set supportedCommands = new HashSet(); + boolean debug = false; + + static { + supportedCommands.add("setXYZ"); + supportedCommands.add("centroid"); + supportedCommands.add("getAtom"); + } + + public CommandInterface ciInstance() { + return new MoleculeCommand(); + } + + public Object ciExecuteCommand(Object[] args) throws Exception { + if (args == null || args.length == 0) { + return this; // Returning coomand as object + } + // --- Execute "set" command + if (args[0].equals("setXYZ")) { + MoleculeInterface mol = this.getMolecule(args[1]); + float[][] coords = null; + + // --- + if (args[2] instanceof float[][]) { + coords = (float[][]) args[2]; + } else if (args[2] instanceof Variable) { + Object obj = ((Variable) args[2]).getValue(); + if (!(obj instanceof float[][])) { + throw new Exception(this.getClass().getCanonicalName() + + ": Wrong argument variable type for setXYZ command. Should be float[][], got" + + obj.getClass().getCanonicalName()); + } + coords = (float[][]) obj; + } else { + throw new Exception(this.getClass().getCanonicalName() + + ": Wrong argument type for setXYZ command. Should be float[][], got" + args[2].getClass().getCanonicalName()); + } + if (debug) { + System.out.println(this.getClass().getSimpleName() + ": Extracted Coordinates from parameters:"); + } + for (int i = 0; i < mol.getNumberOfAtoms(); i++) { + AtomInterface atom = mol.getAtomInterface(i); + atom.setXYZ(coords[i][0], coords[i][1], coords[i][2]); + if (debug) { + System.out.printf("%5d %8.2f %8.2f %8.2f\n", i + 1, coords[i][0], coords[i][1], coords[i][2]); + } + //System.out.printf("%5d %8.2f %8.2f %8.2f\n",i+1,atom.getX(),atom.getY(),atom.getZ()); + } + }// --- + // --- Centroid command + else if (args[0].equals("centroid")) { + MoleculeInterface mol = this.getMolecule(args[1]); + if (args.length == 2) { + return Molecule.getCentroid(mol); + } + Set list = Molecule.getAtomListUsingAtomMaskSelection(mol, args[2].toString()); + System.out.println("List: " + args[2].toString() + " Size: " + list.size()); + return Molecule.getCentroid(list); + }// --- + // --- getAtom command + else if (args[0].equals("getAtom")) { + MoleculeInterface mol = this.getMolecule(args[1]); + int n = this.getIntValue(args[2]); + return mol.getAtomInterface(n - 1); + } + + return null; + } + + public Object[] ciParseCommand(String[] tokens) throws Exception { + if (tokens == null || tokens.length <= 1) { + return null; // Initialization + } + if (!supportedCommands.contains(tokens[1])) { + throw new Exception(this.getClass().getCanonicalName() + ": Unknown command: " + tokens[1]); + } + // --- + if (tokens[1].equals("setXYZ")) { // Molecule setXYZ Molecule_object float[][]_object + if (tokens.length < 4) { + throw new Exception(this.getClass().getCanonicalName() + ": setXYZ command requires three arguments"); + } else if (tokens.length > 4) { + throw new Exception(this.getClass().getCanonicalName() + ": setXYZ command requires three arguments"); + } + return new Object[]{tokens[1], tokens[2], tokens[3]}; + } // --- + // --- Centroid command + else if (tokens[1].equals("centroid")) { // Molecule centroid Molecule_object [atom(s) list] + if (tokens.length < 3) { + throw new Exception(this.getClass().getCanonicalName() + ": centroid command requires at least one argument"); + } + if (tokens.length == 3) { + return new Object[]{tokens[1], tokens[2]}; + } + String line = ""; + for (int i = 3; i < tokens.length; i++) { + line += tokens[i] + " "; + } + return new Object[]{tokens[1], tokens[2], line}; + }// --- + // --- getAtom command + else if (tokens[1].equals("getAtom")) { // Molecule getAtom Molecule_object Number_value] + if (tokens.length != 4) { + throw new Exception(this.getClass().getCanonicalName() + ": getAtom command requires two arguments"); + } + + Integer atomNumber; + try { + atomNumber = Integer.parseInt(tokens[3]); + return new Object[]{tokens[1], tokens[2], atomNumber}; + } catch (Exception ex) { + // Do nothing. Probably is's a variable + } + return new Object[]{tokens[1], tokens[2], tokens[3]}; + } + + return null; + } + + public MoleculeInterface getMolecule(Object obj) throws Exception { + if (obj instanceof MoleculeInterface) { + return (MoleculeInterface) obj; + } else if (obj instanceof Variable) { + Object value = ((Variable) obj).getValue(); + if (!(value instanceof MoleculeInterface)) { + throw new Exception(this.getClass().getCanonicalName() + + ": Wrong argument variable type. Should be Molecule, got" + + value.getClass().getCanonicalName()); + } + return (MoleculeInterface) value; + } else { + throw new Exception(this.getClass().getCanonicalName() + + ": Wrong argument type. Should be Molecule, got" + obj.getClass().getCanonicalName()); + } + } + + public int getIntValue(Object obj) throws Exception { + if (obj instanceof Variable) { + return ((Variable) obj).getIntValue(); + } + if (obj instanceof Number) { + return ((Number) obj).intValue(); + } + throw new Exception(this.getClass().getCanonicalName() + " argument " + obj.toString() + " cannot be converted into integer value"); + } +} diff --git a/src/main/java/cct/cprocessor/PrintCommand.java b/src/main/java/cct/cprocessor/PrintCommand.java new file mode 100644 index 0000000..69c963a --- /dev/null +++ b/src/main/java/cct/cprocessor/PrintCommand.java @@ -0,0 +1,222 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.cprocessor; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileReader; +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * + * @author vvv900 + */ +public class PrintCommand implements InbuiltCommandInterface { + + private BufferedWriter bufferedWriter; + private String fileName; + + private CommandProcessor commandProcessor; + + public PrintCommand() { + + } + + public PrintCommand(CommandProcessor commandProcessor) { + this.commandProcessor = commandProcessor; + } + + public int getNewCommandCounter() { + return -1; + } + + public CommandInterface ciInstance() { + return new PrintCommand(commandProcessor); + } + + public Object ciExecuteCommand(Object[] args) throws Exception { + if (args == null || args.length == 0) { + return null; + } + + if (args[0].toString().equals("setLog")) { + try { + BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); + setBufferedWriter(out); + return null; + } catch (Exception ex) { + throw new Exception(this.getClass().getCanonicalName() + ": CreateLog: cannot create file " + + fileName + " for writing: " + ex.getLocalizedMessage()); + } + } else if (args[0].toString().equals("close")) { + bufferedWriter.close(); + return null; + } + + if (bufferedWriter != null) { + for (Object obj : args) { + if (obj instanceof Variable) { + Variable var = (Variable) obj; + if (var.getValue() == null) { + bufferedWriter.write(var.getValue() + " "); + } else { + bufferedWriter.write(var.getValue().toString() + " "); + } + } else { + bufferedWriter.write(obj.toString()); + } + } + bufferedWriter.newLine(); + return null; + } + + for (Object obj : args) { + if (obj instanceof Variable) { + Variable var = (Variable) obj; + if (var.getValue() == null) { + System.out.print(var.getValue() + " "); + } else { + if (var.getValue().getClass().isArray()) { + printArray(var.getValue()); + System.out.print(var.getValue().toString() + " "); + } else { + System.out.print(var.getValue().toString() + " "); + } + } + } else { + System.out.print(obj.toString()); + } + } + System.out.println(); + return null; + } + + public Object[] ciParseCommand(String[] tokens) throws Exception { + if (tokens == null || tokens.length <= 1) { + return null; + } + + if (tokens[0].equals("CreateLog")) { + if (tokens.length != 1) { + throw new Exception(this.getClass().getCanonicalName() + ": CreateLog requires no argument(s)"); + } + return new Object[]{new PrintCommand(this.commandProcessor)}; + // ---- + } else if (tokens[1].equals("setLog")) { + try { + setFileName(tokens[2]); + return new Object[]{"setLog", tokens[2]}; + } catch (Exception ex) { + throw new Exception(this.getClass().getCanonicalName() + ": CreateLog: cannot create file " + + tokens[1] + " for writing: " + ex.getLocalizedMessage()); + } + } else if (tokens[1].equals("close")) { + return new Object[]{"close"}; + } + + StringBuilder sb = new StringBuilder(); + boolean buildingStr = false; + List list = new ArrayList(); + boolean oneTime = true; + for (String token : tokens) { + if (oneTime) { + oneTime = false; + continue; + } + if (commandProcessor.isHasVariable(token)) { + if (buildingStr) { + list.add(sb.toString()); + buildingStr = false; + list.add(commandProcessor.getVariable(token)); + } else { + list.add(commandProcessor.getVariable(token)); + } + } else { + if (buildingStr) { + sb.append(token + " "); + } else { + if (sb.length() < 1) { + sb.delete(0, sb.length()); + } + buildingStr = true; + sb.append(token + " "); + } + } + } + if (buildingStr) { + list.add(sb.toString()); + } + return list.toArray(); + } + + public void setCommandProcessor(CommandProcessor commandProcessor) { + this.commandProcessor = commandProcessor; + } + + public static void printArray(Object inputArray) { + if (inputArray instanceof float[][]) { + printArray((float[][]) inputArray); + } else if (inputArray instanceof float[]) { + printArray((float[]) inputArray); + } else if (inputArray instanceof Object[]) { + printArray((Object[]) inputArray); + } else if (inputArray instanceof Object[][]) { + if (inputArray != null) { + System.out.printf("%s ", inputArray.toString()); + return; + } + } + System.out.printf("%s ", inputArray.toString()); + } + + public static void printArray(E[] inputArray) { + for (E element : inputArray) { + if (element.getClass().isArray()) { + printArray(element); + } else { + System.out.printf("%s ", element); + } + } + System.out.println(); + } + + public static void printArray(float[][] inputArray) { + for (int i = 0; i < inputArray.length; i++) { + System.out.printf("%5d: ", i); + for (int j = 0; j < inputArray[i].length; j++) { + System.out.printf("%10.4f ", inputArray[i][j]); + } + System.out.print("\n"); + } + } + + public static void printArray(float[] inputArray) { + for (int i = 0; i < inputArray.length; i++) { + System.out.printf("%5d: %10.4f ", i, inputArray[i]); + System.out.print("\n"); + } + } + + public BufferedWriter getBufferedWriter() { + return bufferedWriter; + } + + public void setBufferedWriter(BufferedWriter bufferedWriter) { + this.bufferedWriter = bufferedWriter; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + +} diff --git a/src/main/java/cct/cprocessor/RenderCommandObject.java b/src/main/java/cct/cprocessor/RenderCommandObject.java new file mode 100644 index 0000000..b6c457c --- /dev/null +++ b/src/main/java/cct/cprocessor/RenderCommandObject.java @@ -0,0 +1,57 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.cprocessor; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public enum RenderCommandObject { + WIREFRAME, STICKS, BALLS, SPACEFILL; + + RenderCommandObject() { + } +} diff --git a/src/main/java/cct/cprocessor/ScriptProcessor.java b/src/main/java/cct/cprocessor/ScriptProcessor.java new file mode 100644 index 0000000..5b49994 --- /dev/null +++ b/src/main/java/cct/cprocessor/ScriptProcessor.java @@ -0,0 +1,81 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.cprocessor; + +import cct.math.expparser.ExpressionParser; +import cct.tools.Utils; +import java.util.Properties; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + * @author vvv900 + */ +public class ScriptProcessor extends ExpressionParser { + + public static final String ScriptProcessorFunsProps_Key = "scriptProcessorFunctionsProps"; + private String ScriptProcessorFunctions_PROPERTY_FILE; + + public static final String ScriptProcessorClassesProps_Key = "scriptProcessorClassesProps"; + private String ScriptProcessorClasses_PROPERTY_FILE; + + private String ScriptProcessor_PROPERTY_FILE = ScriptProcessor.class.getCanonicalName(); + private Properties classProperties, functionProperties, typesProperties; + + static final Logger logger = Logger.getLogger(ScriptProcessor.class.getCanonicalName()); + + public ScriptProcessor() throws Exception { + super(); + ScriptProcessor_PROPERTY_FILE = ScriptProcessor_PROPERTY_FILE.replaceAll("[.]", "/") + ".properties"; + try { + classProperties = Utils.getProperties(ScriptProcessor_PROPERTY_FILE); + } catch (Exception ex) { + Logger.getLogger(ScriptProcessor.class.getName()).log(Level.WARNING, null, ex); + } + if (classProperties != null) { + ScriptProcessorFunctions_PROPERTY_FILE = classProperties.getProperty(ScriptProcessorFunsProps_Key); + ScriptProcessorClasses_PROPERTY_FILE = classProperties.getProperty(ScriptProcessorClassesProps_Key); + } + + // --- + if (ScriptProcessorFunctions_PROPERTY_FILE != null) { + try { + functionProperties = Utils.getProperties(ScriptProcessorFunctions_PROPERTY_FILE); + this.addFunctionDefenitions(functionProperties); + } catch (Exception ex) { + logger.log(Level.SEVERE, null, ex); + throw new Exception("Error while loading function definitions: " + ex.getLocalizedMessage()); + } + } + // --- + if (ScriptProcessorClasses_PROPERTY_FILE != null) { + try { + typesProperties = Utils.getProperties(ScriptProcessorClasses_PROPERTY_FILE); + } catch (Exception ex) { + logger.log(Level.WARNING, ex.getLocalizedMessage()); + } + // --- + try { + this.addClassesDefenitions(typesProperties); + } catch (Exception ex) { + logger.log(Level.SEVERE, null, ex); + throw new Exception("Error while loading classes/data types definitions: " + ex.getLocalizedMessage()); + } + } + + } + + public static void main(String[] args) { + try { + ScriptProcessor sp = new ScriptProcessor(); + } catch (Exception ex) { + Logger.getLogger(ScriptProcessor.class.getName()).log(Level.SEVERE, null, ex); + System.exit(1); + } + System.exit(0); + } +} diff --git a/src/main/java/cct/cprocessor/ScriptProcessor.properties b/src/main/java/cct/cprocessor/ScriptProcessor.properties new file mode 100644 index 0000000..27570b4 --- /dev/null +++ b/src/main/java/cct/cprocessor/ScriptProcessor.properties @@ -0,0 +1,3 @@ +# +scriptProcessorFunctionsProps = cct/cprocessor/ScriptProcessorFunctions.properties +scriptProcessorClassesProps = cct/cprocessor/ScriptProcessorClasses.properties diff --git a/src/main/java/cct/cprocessor/ScriptProcessorFunctions.properties b/src/main/java/cct/cprocessor/ScriptProcessorFunctions.properties new file mode 100644 index 0000000..a9bd7fd --- /dev/null +++ b/src/main/java/cct/cprocessor/ScriptProcessorFunctions.properties @@ -0,0 +1,2 @@ +# + diff --git a/src/main/java/cct/cprocessor/StatisticsCommand.java b/src/main/java/cct/cprocessor/StatisticsCommand.java new file mode 100644 index 0000000..929e004 --- /dev/null +++ b/src/main/java/cct/cprocessor/StatisticsCommand.java @@ -0,0 +1,118 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.cprocessor; + +import static cct.cprocessor.MoleculeCommand.supportedCommands; +import cct.math.Statistics; +import java.util.HashSet; +import java.util.Set; + +/** + * + * @author vvv900 + */ +public class StatisticsCommand implements CommandInterface { + + public static final String LinearCorrelationCoefficientCommand = "linearCorrelationCoefficient"; + public static final Set supportedCommands = new HashSet(); + + static { + supportedCommands.add(LinearCorrelationCoefficientCommand); + } + + public CommandInterface ciInstance() { + return new StatisticsCommand(); + } + + public Object ciExecuteCommand(Object[] args) throws Exception { + if (args == null || args.length == 0) { + return this; // Returning coomand as object + } + // --- + if (args[0].equals(LinearCorrelationCoefficientCommand)) { + Object obj1 = args[1]; + if (obj1 == null) { + throw new Exception(this.getClass().getCanonicalName() + ": Executing " + LinearCorrelationCoefficientCommand + + ": the first argument is null. Expecting data array"); + } + if (obj1 instanceof Variable) { + Variable var = (Variable) obj1; + obj1 = var.getValue(); + if (obj1 == null) { + throw new Exception(this.getClass().getCanonicalName() + ": Executing " + LinearCorrelationCoefficientCommand + + ": a variable " + var.getName() + " as the first argument is null. Expecting data array"); + } + } + + if (!obj1.getClass().isArray()) { + throw new Exception(this.getClass().getCanonicalName() + ": Executing " + LinearCorrelationCoefficientCommand + + ": Expecting data array as athe first arg. Got: " + obj1.getClass().getCanonicalName()); + } + // -- The second argument + Object obj2 = args[2]; + if (obj2 == null) { + throw new Exception(this.getClass().getCanonicalName() + ": Executing " + LinearCorrelationCoefficientCommand + + ": the second argument is null. Expecting data array"); + } + if (obj2 instanceof Variable) { + Variable var = (Variable) obj2; + obj2 = var.getValue(); + if (obj2 == null) { + throw new Exception(this.getClass().getCanonicalName() + ": Executing " + LinearCorrelationCoefficientCommand + + ": a variable " + var.getName() + " as the second argument is null. Expecting data array"); + } + } + + if (!obj2.getClass().isArray()) { + throw new Exception(this.getClass().getCanonicalName() + ": Executing " + LinearCorrelationCoefficientCommand + + ": Expecting data array as athe first arg. Got: " + obj1.getClass().getCanonicalName()); + } + // --- CAlculating a result + + if (obj1 instanceof double[] && obj2 instanceof double[]) { + return Statistics.linearCorrelationCoefficient((double[]) obj1, (double[]) obj2); + } else if (obj1 instanceof float[] && obj1 instanceof float[]) { + return Statistics.linearCorrelationCoefficient((float[]) obj1, (float[]) obj2); + } else if (obj1 instanceof Number[] && obj1 instanceof Number[]) { + return Statistics.linearCorrelationCoefficient((Number[]) obj1, (Number[]) obj2); + } else { + throw new Exception(this.getClass().getCanonicalName() + ": Executing " + LinearCorrelationCoefficientCommand + + ": Expecting double, float or NUmber data arrays. Got: " + + obj1.getClass().getCanonicalName() + " and " + obj2.getClass().getCanonicalName()); + } + } + throw new Exception(this.getClass().getCanonicalName() + " Something is wrong with execution"); + } + + /** + * Parses command parameters. + * + * @param tokens - arguments. The first argument is a command name, so it's ignored + * @return parsed and parameters + * @throws Exception + */ + public Object[] ciParseCommand(String[] tokens) throws Exception { + if (tokens == null || tokens.length <= 1) { + return null; // Initialization + } + if (!supportedCommands.contains(tokens[1])) { + throw new Exception(this.getClass().getCanonicalName() + ": Unknown command: " + tokens[1]); + } + // --- + if (tokens[1].equals(LinearCorrelationCoefficientCommand)) { // Stat linearCorrelationCoefficient vector_1 vector_2 + if (tokens.length < 4) { + throw new Exception(this.getClass().getCanonicalName() + ": " + LinearCorrelationCoefficientCommand + + " command requires two arguments"); + } else if (tokens.length > 4) { + throw new Exception(this.getClass().getCanonicalName() + ": " + LinearCorrelationCoefficientCommand + + " command requires two arguments"); + } + return new Object[]{LinearCorrelationCoefficientCommand, tokens[2], tokens[3]}; + } + return null; + } + +} diff --git a/src/main/java/cct/cprocessor/TrajectoryAnalyzerCommand.java b/src/main/java/cct/cprocessor/TrajectoryAnalyzerCommand.java new file mode 100644 index 0000000..05c7552 --- /dev/null +++ b/src/main/java/cct/cprocessor/TrajectoryAnalyzerCommand.java @@ -0,0 +1,144 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.cprocessor; + +import cct.dynamics.SnapshotSequenceAnalyzer; +import cct.interfaces.MoleculeInterface; +import cct.modelling.StructureManager; +import cct.modelling.TRAJECTORY_FILE_FORMAT; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; + +/** + * + * @author vvv900 + */ +public class TrajectoryAnalyzerCommand extends SnapshotSequenceAnalyzer implements CommandInterface { + + static final Logger logger = Logger.getLogger(TrajectoryAnalyzerCommand.class.getCanonicalName()); + static private Map trajFormats = new HashMap(); + static private Set trajCommands = new HashSet(); + boolean debug = false; + + static { + trajFormats.put("g09", TRAJECTORY_FILE_FORMAT.G03_TRAJECTORY); + // --- + trajCommands.add("set"); + trajCommands.add("load"); + trajCommands.add("getXYZ"); + trajCommands.add("getNumSnaps"); + } + + public TrajectoryAnalyzerCommand() { + super(new StructureManager()); + } + + public CommandInterface ciInstance() { + return new TrajectoryAnalyzerCommand(); + } + + public Object ciExecuteCommand(Object[] args) throws Exception { + if (args == null || args.length == 0) { + return this; // Returning coomand as object + } + // --- Execute "set" command + if (args[0].equals("set")) { + if (args[1] instanceof MoleculeInterface) { + this.setReferenceMolecule((MoleculeInterface) args[1]); + } else if (args[1] instanceof Variable) { + Object obj = ((Variable) args[1]).getValue(); + if (!(obj instanceof MoleculeInterface)) { + throw new Exception(this.getClass().getCanonicalName() + + ": Wrong argument variable type for set command. Should be Molecule, got" + + obj.getClass().getCanonicalName()); + } + this.setReferenceMolecule((MoleculeInterface) obj); + } else { + throw new Exception(this.getClass().getCanonicalName() + + ": Wrong argument type for set command. Should be Molecule, got" + args[1].getClass().getCanonicalName()); + } + } // --- Execute "load" command + else if (args[0].equals("load")) { + this.getStructureManager().parseTrajectoryFile(args[1].toString(), (TRAJECTORY_FILE_FORMAT) args[2]); + } // --- Execute "getXYZ" command + else if (args[0].equals("getXYZ")) { + Integer n = null; + if (args[1] instanceof Variable) { + n = (Integer) ((Variable) args[1]).getValue(); + } else { + n = (Integer) args[1]; + } + float[][] coords = new float[this.getReferenceMolecule().getNumberOfAtoms()][3]; + this.getStructureManager().getStructure(n, coords); + if (debug) { + System.out.println(this.getClass().getSimpleName() + ": Extracted coords from the trajectory"); + for (int i = 0; i < coords.length; i++) { + System.out.printf("%5d %8.2f %8.2f %8.2f\n", i + 1, coords[i][0], coords[i][1], coords[i][2]); + } + } + return coords; + } else if (args[0].equals("getNumSnaps")) { + return getStructureManager().getNumberOfSnapshots(); + } else { + throw new Exception(this.getClass().getCanonicalName() + ": Unknown command to execute: " + args[0].toString()); + } + return null; + } + + public Object[] ciParseCommand(String[] tokens) throws Exception { + if (tokens == null || tokens.length <= 1) { + return null; // Initialization + } + if (!trajCommands.contains(tokens[1])) { + throw new Exception(this.getClass().getCanonicalName() + ": Uknown command: " + tokens[1]); + } + // --- "set" command + if (tokens[1].equals("set")) { // set Molecule_object + if (tokens.length == 1) { + throw new Exception(this.getClass().getCanonicalName() + ": set command requires an argument"); + } else if (tokens.length > 3) { + throw new Exception(this.getClass().getCanonicalName() + ": set command requires only one argument"); + } + return new Object[]{tokens[1], tokens[2]}; + + } // --- Load command: "load tajectory-file format", where format = g09 + else if (tokens[1].equals("load")) { + if (tokens.length < 4) { + throw new Exception(this.getClass().getCanonicalName() + ": Load command requies 2 arguments"); + } + if (!trajFormats.containsKey(tokens[3])) { + throw new Exception(this.getClass().getCanonicalName() + ": Unknown trajectory format: " + tokens[3]); + } + return new Object[]{tokens[1], tokens[2], trajFormats.get(tokens[3])}; + } // --- Load command: "getXYZ number", where number - integer number of strcuture in a list (zero-based) + else if (tokens[1].equals("getXYZ")) { + if (tokens.length < 3) { + throw new Exception(this.getClass().getCanonicalName() + ": getXYZ command requies 1 argument"); + } + Number n; + Integer num; + try { + n = CommandProcessor.getNumber(tokens[2]); + num = n.intValue(); + return new Object[]{tokens[1], num}; + } catch (Exception ex) { + } + return new Object[]{tokens[1], tokens[2]}; // Probably it's variable + } else if (tokens[1].equals("getNumSnaps")) { + if (tokens.length > 2) { + throw new Exception(this.getClass().getCanonicalName() + ": getNumSnaps command requies no argument(s)"); + } + return new Object[]{tokens[1]}; + } else { + throw new Exception(this.getClass().getCanonicalName() + ": Unknown command: " + tokens[1]); + } + //return null; + } + +} diff --git a/src/main/java/cct/cprocessor/Variable.java b/src/main/java/cct/cprocessor/Variable.java new file mode 100644 index 0000000..8841b6a --- /dev/null +++ b/src/main/java/cct/cprocessor/Variable.java @@ -0,0 +1,58 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.cprocessor; + +/** + * + * @author vvv900 + */ +public class Variable { + + private String name; + private Object value; + + public Variable(String name, Object value) { + this.name = name; + this.value = value; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + + public String getName() { + return name; + } + + public int getIntValue() throws Exception { + if (value == null) { + throw new Exception("Variable is not defined"); + } + if (value instanceof Number) { + return ((Number) value).intValue(); + } + if (value instanceof String) { + try { + return Integer.parseInt(value.toString()); + } catch (Exception ex) { + + } + } + throw new Exception("Variable value " + value.toString() + " cannot be converted into integer value"); + } + + public String toString() { + if (getValue() == null) { + return getName() + " = null"; + } else { + return getName() + " = " + getValue().toString(); + } + } +} diff --git a/src/main/java/cct/cprocessor/commands.properties b/src/main/java/cct/cprocessor/commands.properties new file mode 100644 index 0000000..73b54ac --- /dev/null +++ b/src/main/java/cct/cprocessor/commands.properties @@ -0,0 +1,10 @@ +# To change this license header, choose License Headers in Project Properties. +# To change this template file, choose Tools | Templates +# and open the template in the editor. + +loadGJF = cct.gaussian.Gaussian +TrajectoryManager = cct.cprocessor.TrajectoryAnalyzerCommand +Molecule = cct.cprocessor.MoleculeCommand +Geometry = cct.cprocessor.GeometryCommand +Stat = cct.cprocessor.StatisticsCommand +List = cct.cprocessor.ListCommand \ No newline at end of file diff --git a/src/main/java/cct/database/ChemistryDatabaseDialog.java b/src/main/java/cct/database/ChemistryDatabaseDialog.java new file mode 100644 index 0000000..f6836e0 --- /dev/null +++ b/src/main/java/cct/database/ChemistryDatabaseDialog.java @@ -0,0 +1,670 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.database; + +import java.awt.Button; +import java.awt.Dialog; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Logger; + +import cct.awtdialogs.MessageWindow; +import cct.awtdialogs.TextEntryDialog; +import cct.interfaces.MoleculeInterface; +import cct.j3d.Java3dUniverse; +import cct.modelling.Molecule; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class ChemistryDatabaseDialog + extends Dialog implements ActionListener, ItemListener { + java.awt.List Molecules = null, Structures = null; + Java3dUniverse parent; + TextField name, formula, aliases; + SQLChemistryDatabase sql_data; + int SelectedMolecule = 0; + java.util.List allMolecules = null; + java.util.List allStructures = null; + String oldName; + boolean error = false; + + static String moleculeNameKey = "name"; + static String structureMethodKey = "method"; + + // Names for controls + static String controlMolList = "mollist"; + static String controlStrList = "strlist"; + static String controlMolName = "molname"; + static String controlButtonOK = "buttonOK"; + static final Logger logger = Logger.getLogger(ChemistryDatabaseDialog.class.getCanonicalName()); + + public ChemistryDatabaseDialog(Java3dUniverse p, SQLChemistryDatabase database, + String Title, boolean modal) { + super(new Frame(), Title, modal); + parent = p; + sql_data = database; + + GridBagLayout gridbag = new GridBagLayout(); + + setLayout(gridbag); + + // --- + + GridBagConstraints c = new GridBagConstraints(); + c.gridx = 0; + c.gridy = 0; + c.gridwidth = 2; + c.gridheight = 20; + //c.weightx = 1; + //c.weighty = 1; + c.fill = GridBagConstraints.BOTH; + c.insets = new Insets(3, 3, 3, 3); + + Molecules = new java.awt.List(10, false); + + allMolecules = sql_data.getMolecules(); + for (int i = 0; i < allMolecules.size(); i++) { + Map row = (Map) allMolecules.get(i); + Molecules.add(row.get(moleculeNameKey).toString()); + } + SelectedMolecule = 0; + Map row = (Map) allMolecules.get(SelectedMolecule); + String currentMolecule = row.get(moleculeNameKey).toString(); + + Molecules.select(SelectedMolecule); + Molecules.setName(controlMolList); + Molecules.addActionListener(this); + Molecules.addItemListener(this); + + gridbag.setConstraints(Molecules, c); + add(Molecules); + + // --- + + GridBagConstraints structureC = new GridBagConstraints(); + structureC.gridx = 2; + structureC.gridy = 0; + structureC.gridwidth = 1; //end row + structureC.gridheight = 15; + structureC.fill = GridBagConstraints.BOTH; + structureC.insets = new Insets(3, 3, 3, 3); + + allStructures = sql_data.getStructures(); + Structures = new java.awt.List(15, false); + + for (int i = 0; i < allStructures.size(); i++) { + row = (Map) allStructures.get(i); + String name = row.get(moleculeNameKey).toString(); + if (name.compareToIgnoreCase(currentMolecule) == 0) { + Structures.add(row.get(structureMethodKey).toString()); + } + } + Structures.setName(controlStrList); + + Structures.addActionListener(this); + Structures.addItemListener(this); + + gridbag.setConstraints(Structures, structureC); + add(Structures); + + // --- + + GridBagConstraints addMolC = new GridBagConstraints(); + + addMolC.gridwidth = 1; //end row + addMolC.gridheight = 1; //reset to the default + addMolC.gridx = 2; + addMolC.gridy = 15; + addMolC.fill = GridBagConstraints.BOTH; + addMolC.insets = new Insets(3, 3, 3, 3); + + Button addMol = new Button("Add Molecule"); + gridbag.setConstraints(addMol, addMolC); + add(addMol); + addMol.addActionListener(this); + + // --- + + GridBagConstraints delMolC = new GridBagConstraints(); + + delMolC.gridx = 2; + delMolC.gridy = 16; + delMolC.gridwidth = 1; //end row + delMolC.gridheight = 1; //reset to the default + delMolC.fill = GridBagConstraints.BOTH; + + Button delMol = new Button("Delete Molecule"); + gridbag.setConstraints(delMol, delMolC); + add(delMol); + delMol.addActionListener(this); + + // --- + + GridBagConstraints addStrC = new GridBagConstraints(); + + addStrC.gridx = 2; + addStrC.gridy = 17; + addStrC.gridwidth = 1; //end row + addStrC.gridheight = 1; //reset to the default + + Button addStr = new Button("Add Structure"); + gridbag.setConstraints(addStr, addStrC); + add(addStr); + addStr.addActionListener(this); + + // ---- + + GridBagConstraints delStrC = new GridBagConstraints(); + + delStrC.gridx = 2; + delStrC.gridy = 18; + delStrC.gridwidth = GridBagConstraints.REMAINDER; //end row + delStrC.gridheight = 1; //reset to the default + + Button delStr = new Button("Delete Structure"); + gridbag.setConstraints(delStr, delStrC); + add(delStr); + delStr.addActionListener(this); + + // --- + GridBagConstraints loadStrC = new GridBagConstraints(); + + loadStrC.gridx = 2; + loadStrC.gridy = 19; + loadStrC.gridwidth = GridBagConstraints.REMAINDER; //end row + loadStrC.gridheight = 1; //reset to the default + + Button loadStr = new Button("Load Structure"); + gridbag.setConstraints(loadStr, loadStrC); + add(loadStr); + loadStr.addActionListener(this); + + // --- + + GridBagConstraints hideC = new GridBagConstraints(); + + hideC.gridx = 1; + hideC.gridy = 21; + hideC.gridwidth = 1; + hideC.gridheight = 1; + hideC.fill = GridBagConstraints.BOTH; + + Button OK = new Button("Hide"); + OK.addActionListener(this); + gridbag.setConstraints(OK, hideC); + add(OK); + + name = new TextField(20); + + /* + //FlowLayout sizer = new FlowLayout( FlowLayout.CENTER); + GridLayout sizer = new GridLayout(0, 2, 5, 5); + setLayout(sizer); + + Molecules = new java.awt.List(10, false); + + allMolecules = sql_data.getMolecules(); + for (int i = 0; i < allMolecules.size(); i++) { + HashMap row = (HashMap) allMolecules.get(i); + Molecules.add(row.get(moleculeNameKey).toString()); + } + SelectedMolecule = 0; + HashMap row = (HashMap) allMolecules.get(SelectedMolecule); + String currentMolecule = row.get(moleculeNameKey).toString(); + + Molecules.select(SelectedMolecule); + Molecules.setName(controlMolList); + add(Molecules); + + allStructures = sql_data.getStructures(); + Structures = new java.awt.List(10, false); + + for (int i = 0; i < allStructures.size(); i++) { + row = (HashMap) allStructures.get(i); + String name = row.get(moleculeNameKey).toString(); + if (name.compareToIgnoreCase(currentMolecule) == 0) { + Structures.add(row.get(structureMethodKey).toString()); + } + } + Structures.setName(controlStrList); + add(Structures); + + add(new Label("Name: ", Label.LEFT)); + name = new TextField(20); + name.setName(controlMolName); + name.setText(currentMolecule); + oldName = currentMolecule; // remember name + add(name); + name.addActionListener(this); + + add(new Label("Formula: ", Label.LEFT)); + formula = new TextField(20); + + add(new Label("Name Aliases: ", Label.LEFT)); + aliases = new TextField(20); + + Button addMol = new Button("Add Molecule"); + add(addMol); + addMol.addActionListener(this); + + Button delMol = new Button("Delete Molecule"); + add(delMol); + delMol.addActionListener(this); + + + Button addStr = new Button("Add Structure"); + add(addStr); + addStr.addActionListener(this); + + Button delStr = new Button("Delete Structure"); + add(delStr); + delStr.addActionListener(this); + + + Button loadStr = new Button("Load Structure"); + add(loadStr); + loadStr.addActionListener(this); + + + Button OK = new Button("OK"); + add(OK); + */ + + + setSize(300, 450); + + } + + @Override + public void itemStateChanged(ItemEvent ie) { + String controlName = ie.getItemSelectable().toString(); + controlName = controlName.substring(controlName.indexOf('[') + 1); + controlName = controlName.substring(0, controlName.indexOf(',')); + + logger.info("Item: " + ie.getItem()); + logger.info("Item Selectable: " + ie.getItemSelectable()); + logger.info("ControlName: " + controlName); + + if (controlName.equals(controlMolList)) { + SelectedMolecule = Molecules.getSelectedIndex(); + selectMolecule(SelectedMolecule); + } + else if (controlName.equals(controlStrList)) { + + } + } + + /** + * + * @param ae ActionEvent + */ + @Override + public void actionPerformed(ActionEvent ae) { + + String controlName = ae.getSource().toString(); + controlName = controlName.substring(controlName.indexOf('[') + 1); + controlName = controlName.substring(0, controlName.indexOf(',')); + logger.info("controlName: " + controlName); + logger.info("ActionCommand: " + ae.getActionCommand()); + logger.info("paramString: " + ae.paramString()); + logger.info("getSource: " + ae.getSource()); + logger.info("getSource.getClass: " + ae.getSource().getClass()); + logger.info("getSource.hasgCode: " + ae.getSource().hashCode()); + + // --- Molecule name is changed + if (controlName.equals(controlMolName) && + isMoleculeNameUnique(name.getText())) { + // ??? for now... + if (sql_data.changeMoleculeName(oldName, name.getText())) { + Map row = (Map) allMolecules.get(SelectedMolecule); + row.put(moleculeNameKey, name.getText()); + String currentMolecule = row.get(moleculeNameKey).toString(); + Molecules.remove(SelectedMolecule); + Molecules.add(name.getText(), SelectedMolecule); + + for (int i = 0; i < allStructures.size(); i++) { + row = (Map) allStructures.get(i); + row.put(moleculeNameKey, name.getText()); + } + oldName = currentMolecule; + + } + else { + // ERROR + } + } + + // --- New molecule from the list is selected + else if (controlName.equals(controlMolList)) { + SelectedMolecule = Molecules.getSelectedIndex(); + selectMolecule(SelectedMolecule); + } + + else if (ae.getActionCommand().toString().equals("Add Molecule")) { + TextEntryDialog new_name = new TextEntryDialog(new Frame(), + "Enter name for new molecule", true); + new_name.setVisible(true); + if (!new_name.isTextEntered()) { + return; + } + String str = new_name.getValue(); + if (isMoleculeNameUnique(str) && sql_data.addNewMolecule(str)) { + Map row = new HashMap(); + row.put(moleculeNameKey, str); + allMolecules.add(row); + SelectedMolecule = allMolecules.size() - 1; + oldName = str; + + Molecules.add(str); + Molecules.select(SelectedMolecule); + + Structures.removeAll(); + } + else { + MessageWindow er = new MessageWindow("ERROR", + "Molecule name is not unique!", true); + er.setVisible(true); + } + //dispose(); + + // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + // --- Delete Molecule and corresponding structures... + } + else if (ae.getActionCommand().toString().equals("Delete Molecule")) { + SelectedMolecule = Molecules.getSelectedIndex(); + if (Molecules.getSelectedIndex() == -1) { + MessageWindow er = new MessageWindow("ERROR", + "Select Molecule first!", true); + er.setVisible(true); + return; + } + + Map row = (Map) allMolecules.get(SelectedMolecule); + + // --- First, delete all structures of a molecule + for (int i = 0; i < allStructures.size(); i++) { + row = (Map) allStructures.get(i); + String mol_name = (String) row.get(moleculeNameKey); + if (!mol_name.equals(Molecules.getSelectedItem())) { + continue; + } + String method = (String) row.get(structureMethodKey); + if (!sql_data.deleteStructure(Molecules.getSelectedItem(), + method)) { + MessageWindow er = new MessageWindow("ERROR", + "Cannot delete structure " + method + + ", so cannot delete molecule ", true); + er.setVisible(true); + return; + } + } + + for (int i = allStructures.size() - 1; i >= 0; i--) { + row = (Map) allStructures.get(i); + String mol_name = (String) row.get(moleculeNameKey); + if (mol_name.equals(Molecules.getSelectedItem())) { + allStructures.remove(i); + } + } + + // --- Structures deleted, now we can delete molecule + + if (!sql_data.deleteMolecule(Molecules.getSelectedItem())) { + MessageWindow er = new MessageWindow("ERROR", + "Cannot delete Molecule from database!", true); + er.setVisible(true); + return; + } + + allMolecules.remove(SelectedMolecule); + + // --- now we need to select a new molecule from the list + + updateMoleculesList(); + + if (SelectedMolecule >= allMolecules.size()) { + --SelectedMolecule; + } + Structures.removeAll(); + + if (SelectedMolecule < 0) { + return; + } + + Molecules.select(SelectedMolecule); + oldName = Molecules.getSelectedItem(); + + updateStructureList(Molecules.getSelectedItem()); + Structures.select(0); + + // -- Add new structure + } + else if (ae.getActionCommand().toString().equals("Add Structure")) { + TextEntryDialog new_name = new TextEntryDialog(new Frame(), + "Enter method/name for new structure", true); + new_name.setVisible(true); + if (!new_name.isTextEntered()) { + return; + } + String str = new_name.getValue(); + logger.info("New Structure: " + str); + + if (!isStructureNameUnique(str, oldName)) { + MessageWindow er = new MessageWindow("ERROR", + "Structure name is not unique!", true); + er.setVisible(true); + return; + } + + MoleculeInterface mol = parent.getMolecule(); + if (!sql_data.addNewStructure(oldName, str, mol)) { + MessageWindow er = new MessageWindow("ERROR", + "Unable to add new Structure to database!", true); + er.setVisible(true); + return; + } + Map row = new HashMap(); + row.put(moleculeNameKey, Molecules.getSelectedItem()); + row.put(structureMethodKey, str); + allStructures.add(row); + + updateStructureList(Molecules.getSelectedItem()); + Structures.select(Structures.getItemCount() > 0 ? + Structures.getItemCount() - 1 : 0); + + } + else if (ae.getActionCommand().toString().equals("Load Structure")) { + if (Structures.getSelectedIndex() == -1) { + MessageWindow er = new MessageWindow("ERROR", + "Select Structure first!", true); + er.setVisible(true); + return; + } + Molecule mol = + sql_data.loadStructure(Molecules.getSelectedItem(), + Structures.getSelectedItem()); + if (mol.getNumberOfBonds() == 0) { + mol.guessCovalentBonds(); + } + parent.addMolecule(mol); + + // --- Delete Structure + } + else if (ae.getActionCommand().toString().equals("Delete Structure")) { + if (Structures.getSelectedIndex() == -1) { + MessageWindow er = new MessageWindow("ERROR", + "Select Structure first!", true); + er.setVisible(true); + return; + } + + if (!sql_data.deleteStructure(Molecules.getSelectedItem(), + Structures.getSelectedItem())) { + MessageWindow er = new MessageWindow("ERROR", + "Cannot delete structure!", true); + er.setVisible(true); + return; + } + + deleteStructureFromArray(Molecules.getSelectedItem(), + Structures.getSelectedItem()); + updateStructureList(Molecules.getSelectedItem()); + Structures.select(0); + + // --- OK Button + } + else if (ae.getActionCommand().toString().equals("Hide")) { + //dispose(); + setVisible(false); + } + + //logger.info("getClass: " + ae.getClass() ); + //logger.info("getClass.getName: " + ae.getClass().getName() ); + //logger.info("getClass.getSimpleName: " + ae.getClass().getSimpleName() ); + + //dispose(); + } + + /** + * + * @param items List + */ + public void populateItemsList(java.util.List items) { + for (int i = 0; i < items.size(); i++) { + Molecules.add( (String) items.get(i)); + } + if (items.size() > 0) { + Molecules.select(0); + } + } + + /** + * + */ + public boolean isMoleculeNameUnique(String new_name) { + for (int i = 0; i < allMolecules.size(); i++) { + Map row = (Map) allMolecules.get(i); + if (new_name.compareToIgnoreCase(row.get(moleculeNameKey).toString()) == + 0) { + return false; + } + } + return true; + } + + public boolean isStructureNameUnique(String new_name, String mol_name) { + for (int i = 0; i < allStructures.size(); i++) { + Map row = (Map) allStructures.get(i); + if (mol_name.compareToIgnoreCase(row.get(moleculeNameKey).toString()) != + 0) { + continue; + } + if (new_name.compareToIgnoreCase(row.get(structureMethodKey). + toString()) == 0) { + return false; + } + } + return true; + } + + void updateStructureList(String currentMolecule) { + Structures.removeAll(); + for (int i = 0; i < allStructures.size(); i++) { + Map row = (Map) allStructures.get(i); + String name = row.get(moleculeNameKey).toString(); + if (name.compareToIgnoreCase(currentMolecule) == 0) { + Structures.add(row.get(structureMethodKey).toString()); + } + } + } + + void updateMoleculesList() { + Molecules.removeAll(); + for (int i = 0; i < allMolecules.size(); i++) { + Map row = (Map) allMolecules.get(i); + Molecules.add(row.get(moleculeNameKey).toString()); + } + + } + + boolean deleteStructureFromArray(String mol_name, String method) { + for (int i = 0; i < allStructures.size(); i++) { + Map row = (Map) allStructures.get(i); + String name = row.get(moleculeNameKey).toString(); + String meth = row.get(structureMethodKey).toString(); + if (name.equals(mol_name) && meth.equals(method)) { + allStructures.remove(i); + return true; + } + } + return false; // Was unable to delete. Who knows why... :-) + } + + public void selectMolecule(int selected) { + // !!! ERROR CHECK HERE... !!! + + Map row = (Map) allMolecules.get(selected); + String currentMolecule = row.get(moleculeNameKey).toString(); + + name.setText(currentMolecule); + oldName = currentMolecule; // remember name + + updateStructureList(currentMolecule); + } + // --- Subclasses + +} diff --git a/src/main/java/cct/database/ConnectToDatabaseDialog.form b/src/main/java/cct/database/ConnectToDatabaseDialog.form new file mode 100644 index 0000000..82321db --- /dev/null +++ b/src/main/java/cct/database/ConnectToDatabaseDialog.form @@ -0,0 +1,141 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/cct/database/ConnectToDatabaseDialog.java b/src/main/java/cct/database/ConnectToDatabaseDialog.java new file mode 100644 index 0000000..f026547 --- /dev/null +++ b/src/main/java/cct/database/ConnectToDatabaseDialog.java @@ -0,0 +1,274 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.database; + +import cct.GlobalSettings; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.JOptionPane; + +/** + * + * @author vvv900 + */ +public class ConnectToDatabaseDialog extends javax.swing.JDialog { + + private DatabaseManager databaseManager; + private boolean isAdjusting = false; + private boolean dialogCancelled = false; + + /** + * Creates new form ConnectToDatabaseDialog + */ + public ConnectToDatabaseDialog(java.awt.Frame parent, boolean modal) { + super(parent, modal); + initComponents(); + } + + /** + * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The + * content of this method is always regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jPanel1 = new javax.swing.JPanel(); + jLabel1 = new javax.swing.JLabel(); + hostnameTextField = new javax.swing.JTextField(); + jLabel2 = new javax.swing.JLabel(); + usernameTextField = new javax.swing.JTextField(); + jLabel3 = new javax.swing.JLabel(); + passwordField = new javax.swing.JPasswordField(); + jLabel4 = new javax.swing.JLabel(); + databaseTextField = new javax.swing.JTextField(); + jLabel5 = new javax.swing.JLabel(); + portTextField = new javax.swing.JTextField(); + jLabel6 = new javax.swing.JLabel(); + dbInterfaceComboBox = new javax.swing.JComboBox(); + jPanel2 = new javax.swing.JPanel(); + connectDBButton = new javax.swing.JButton(); + cancelButton = new javax.swing.JButton(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + + jPanel1.setLayout(new java.awt.GridLayout(6, 2)); + + jLabel1.setText("Hostname (if any):"); + jPanel1.add(jLabel1); + + hostnameTextField.setText("localhost"); + jPanel1.add(hostnameTextField); + + jLabel2.setText("Username (if any):"); + jPanel1.add(jLabel2); + + usernameTextField.setText("jamberoo"); + jPanel1.add(usernameTextField); + + jLabel3.setText("Password (if any):"); + jPanel1.add(jLabel3); + + passwordField.setText("jPasswordField1"); + jPanel1.add(passwordField); + + jLabel4.setText("Database:"); + jPanel1.add(jLabel4); + + databaseTextField.setText("jamberoo"); + databaseTextField.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + databaseTextFieldActionPerformed(evt); + } + }); + jPanel1.add(databaseTextField); + + jLabel5.setText("Port (if any):"); + jPanel1.add(jLabel5); + + portTextField.setText("3306"); + jPanel1.add(portTextField); + + jLabel6.setText("Database type:"); + jPanel1.add(jLabel6); + + dbInterfaceComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); + dbInterfaceComboBox.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + dbInterfaceComboBoxActionPerformed(evt); + } + }); + jPanel1.add(dbInterfaceComboBox); + + getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); + + connectDBButton.setText("Connect"); + connectDBButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + connectDBButtonActionPerformed(evt); + } + }); + jPanel2.add(connectDBButton); + + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + cancelButtonActionPerformed(evt); + } + }); + jPanel2.add(cancelButton); + + getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH); + + pack(); + }// //GEN-END:initComponents + + public boolean isDialogCancelled() { + return dialogCancelled; + } + + public DatabaseManager getDatabaseManager() { + return databaseManager; + } + + public void setDatabaseManager(DatabaseManager databaseManager) { + this.databaseManager = databaseManager; + Map drivers = this.databaseManager.getDatabaseDrivers(); + isAdjusting = true; + dbInterfaceComboBox.removeAllItems(); + for (String dname : drivers.keySet()) { + dbInterfaceComboBox.addItem(dname); + } + isAdjusting = false; + dbInterfaceComboBox.setSelectedIndex(0); + } + + + private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed + dialogCancelled = true; + this.setVisible(false); + }//GEN-LAST:event_cancelButtonActionPerformed + + private void databaseTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_databaseTextFieldActionPerformed + // TODO add your handling code here: + }//GEN-LAST:event_databaseTextFieldActionPerformed + + private void dbInterfaceComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dbInterfaceComboBoxActionPerformed + if (isAdjusting) { + return; + } + Object obj = dbInterfaceComboBox.getSelectedItem(); + DatabaseDriver driver = databaseManager.getDatabaseDrivers().get(obj); + if (driver == null) { + JOptionPane.showMessageDialog(this, "INTERNAL ERROR: driver == null for " + obj.toString(), + "Error", JOptionPane.ERROR_MESSAGE); + return; + } + hostnameTextField.setEnabled(driver.isUseHostname()); + hostnameTextField.setText(driver.getDefaultHostname()); + // --- + usernameTextField.setEnabled(driver.isUseUsername()); + usernameTextField.setText(driver.getDefaultUsername()); + // --- + passwordField.setEnabled(driver.isUsePassword()); + passwordField.setText(driver.getDefaultPassword()); + // --- + portTextField.setText(String.valueOf(driver.getDefaultPort())); + this.portTextField.setEnabled(driver.isUsePort()); + // --- + this.databaseTextField.setText(driver.getDefaultDatabase()); + }//GEN-LAST:event_dbInterfaceComboBoxActionPerformed + + private void connectDBButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectDBButtonActionPerformed + // --- + Object obj = dbInterfaceComboBox.getSelectedItem(); + if (obj == null) { + JOptionPane.showMessageDialog(this, "ERROR: No DB type was selected", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + String dbType = (String) obj; + DatabaseDriver driver = databaseManager.getDatabaseDrivers().get(dbType); + String host = this.hostnameTextField.getText().trim(); + String database = this.databaseTextField.getText().trim(); + if (database.length() < 1) { + JOptionPane.showMessageDialog(this, "ERROR: No database name selected", "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + String user = this.usernameTextField.getText().trim(); + char[] password = this.passwordField.getPassword(); + int port = 0; + String portStr = portTextField.getText().trim(); + if (portStr.length() > 0) { + try { + port = Integer.parseInt(portStr); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "ERROR: Cannot parse port number " + portStr, "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + } + // --- + String newDBEntry = ""; + try { + newDBEntry = databaseManager.makeAndRegisterConnection(driver, database, host, user, password); + } catch (Exception ex) { + Logger.getLogger(ConnectToDatabaseDialog.class.getName()).log(Level.SEVERE, null, ex); + JOptionPane.showMessageDialog(this, "ERROR: Cannot make connection to database " + database, "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + JOptionPane.showMessageDialog(this, "Connection to " + newDBEntry + " was successfully established", "Success", + JOptionPane.INFORMATION_MESSAGE); + + dialogCancelled = false; + this.setVisible(false); + }//GEN-LAST:event_connectDBButtonActionPerformed + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + ConnectToDatabaseDialog dialog = new ConnectToDatabaseDialog(new javax.swing.JFrame(), true); + dialog.addWindowListener(new java.awt.event.WindowAdapter() { + @Override + public void windowClosing(java.awt.event.WindowEvent e) { + System.exit(0); + } + }); + + DatabaseManager dbm = new DatabaseManager(); + try { + dbm.initiateFromProperties(GlobalSettings.getProperties()); + } catch (Exception ex) { + Logger.getLogger(DatabaseDriver.class.getName()).log(Level.SEVERE, null, ex); + System.exit(1); + } + dialog.setDatabaseManager(dbm); + dialog.setVisible(true); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton cancelButton; + private javax.swing.JButton connectDBButton; + private javax.swing.JTextField databaseTextField; + private javax.swing.JComboBox dbInterfaceComboBox; + private javax.swing.JTextField hostnameTextField; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel3; + private javax.swing.JLabel jLabel4; + private javax.swing.JLabel jLabel5; + private javax.swing.JLabel jLabel6; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + private javax.swing.JPasswordField passwordField; + private javax.swing.JTextField portTextField; + private javax.swing.JTextField usernameTextField; + // End of variables declaration//GEN-END:variables +} diff --git a/src/main/java/cct/database/DatabaseAccess.java b/src/main/java/cct/database/DatabaseAccess.java new file mode 100644 index 0000000..d8cd5b0 --- /dev/null +++ b/src/main/java/cct/database/DatabaseAccess.java @@ -0,0 +1,56 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.database; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public interface DatabaseAccess { + String COLUMN_NAME = "COLUMN_NAME"; + String COLUMN_TYPE = "COLUMN_TYPE"; + String COLUMN_COUNT = "COLUMN_COUNT"; +} diff --git a/src/main/java/cct/database/DatabaseDriver.java b/src/main/java/cct/database/DatabaseDriver.java new file mode 100644 index 0000000..4c2d686 --- /dev/null +++ b/src/main/java/cct/database/DatabaseDriver.java @@ -0,0 +1,295 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.database; + +import cct.interfaces.MoleculeInterface; +import cct.modelling.Molecule; +import java.io.BufferedReader; +import java.io.FileReader; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.JOptionPane; + +/** + * + * @author vvv900 + */ +public class DatabaseDriver { + + private final Logger logger = Logger.getLogger(DatabaseDriver.class.getName()); + private Level infoLevel = Level.INFO; + + private String dbType; + + private String className; + + private Connection connection = null; + // + private boolean usePort = true; + private int defaultPort = 3306; + // + private boolean useUsername = true; + private String defaultUsername = "admin"; + private String defaultDatabase = "database"; + // + private boolean usePassword = true; + private String defaultPassword = ""; + // + private boolean useHostname = true; + private String defaultHostname = "localhost"; + + public void initializeDatabase(String dbEntry, String sqlScript) { + + } + + public String getDefaultDatabase() { + return defaultDatabase; + } + + public void setDefaultDatabase(String defaultDatabase) { + this.defaultDatabase = defaultDatabase; + } + + public boolean isUsePort() { + return usePort; + } + + public void setUsePort(boolean usePort) { + this.usePort = usePort; + } + + public int getDefaultPort() { + return defaultPort; + } + + public void setDefaultPort(int defaultPort) { + this.defaultPort = defaultPort; + } + + public boolean isUseUsername() { + return useUsername; + } + + public void setUseUsername(boolean useUsername) { + this.useUsername = useUsername; + } + + public String getDefaultUsername() { + return defaultUsername; + } + + public void setDefaultUsername(String defaultUsername) { + this.defaultUsername = defaultUsername; + } + + public boolean isUsePassword() { + return usePassword; + } + + public void setUsePassword(boolean usePassword) { + this.usePassword = usePassword; + } + + public String getDefaultPassword() { + return defaultPassword; + } + + public void setDefaultPassword(String defaultPassword) { + this.defaultPassword = defaultPassword; + } + + public boolean isUseHostname() { + return useHostname; + } + + public void setUseHostname(boolean useHostname) { + this.useHostname = useHostname; + } + + public String getDefaultHostname() { + return defaultHostname; + } + + public void setDefaultHostname(String defaultHostname) { + this.defaultHostname = defaultHostname; + } + + public Level getInfoLevel() { + return infoLevel; + } + + public void setInfoLevel(Level infoLevel) { + infoLevel = infoLevel; + } + + public DatabaseDriver(String className) throws Exception { + this.className = className; + Class.forName(className).newInstance(); + } + + public String getDbType() { + return dbType; + } + + public void setDbType(String dbType) { + this.dbType = dbType; + } + + public String getClassName() { + return className; + } + + public Connection getConnection() { + return connection; + } + + public Connection makeConnection(String databaseName) throws Exception { + return makeConnection(databaseName, null, null, null); + } + + + public Connection makeConnection(String databaseName, String hostname, String username, char[] password) throws Exception { + return makeConnection(databaseName, hostname, username, password, null); + } + + public Connection makeConnection(String databaseName, String hostname, String username, char[] password, String params) throws Exception { + //connection = DriverManager.getConnection("jdbc:sqlite:test.db"); + //String hostName = "jdbc:mysql://" + host; // !!! + //Conn = DriverManager.getConnection(hostName, user, pass); + String connStr = "jdbc:" + dbType + ":"; + if (useHostname) { + connStr += "//" + hostname + "/"; + } else { + connStr += ":" + databaseName; + } + if (params != null) { + params = params.trim(); + connStr += "?" + params; + } + // --- + try { + if (params != null) { + params = params.trim(); + } + if (params != null && params.length() > 0) { + connStr += "?" + params; + } + if (useHostname) { + connection = DriverManager.getConnection(connStr, username, String.valueOf(password)); + } else { + connection = DriverManager.getConnection(connStr); + } + } catch (Exception ex) { + throw new Exception("Unable establish connection " + connStr + " : " + ex.getLocalizedMessage()); + } + if (logger.isLoggable(infoLevel)) { + logger.log(infoLevel, "Connection to " + connStr + " was successfully established"); + } + // --- + if (useHostname) { + try { + Statement stmt = connection.createStatement(); + stmt.executeUpdate("use " + databaseName); + } catch (Exception ex) { + throw new Exception("Unable to select database " + databaseName + " on a host " + connStr + " : " + + ex.getLocalizedMessage()); + } + if (logger.isLoggable(infoLevel)) { + logger.log(infoLevel, "Database " + databaseName + " on a host " + connStr + " was successfully selected"); + } + } + + return connection; + } + + public void executeSQLScript(String scriptFile) throws Exception { + + Statement statement = connection.createStatement(); + + BufferedReader in = new BufferedReader(new FileReader(scriptFile)); + String line; + StringBuilder query = new StringBuilder(1024); + while ((line = in.readLine()) != null) { + line = line.trim(); + if (line.startsWith("-- ") || line.startsWith("#")) { + continue; + } + query.append(line + "\n"); + if (line.endsWith(";")) { + try { + statement.execute(query.toString()); + query.delete(0, query.length()); + } catch (Exception ex) { + throw new Exception("Cannot execute query =====\n" + query.toString() + "\n======================\nReason: " + + ex.getMessage()); + } + } + } + + System.out.println("SQL Script " + scriptFile + " is successfuly executed"); + } + + public static void main(String[] args) { + String driverClass = "com.mysql.jdbc.Driver"; + String db = "jamberoo"; + String user = "jamberoo"; + String pass = "jamberoo"; + String host = "localhost"; + DatabaseDriver dd = null; + Connection conn = null; + try { + dd = new DatabaseDriver(driverClass); + dd.setDbType("mysql"); + System.out.println(driverClass + " was successfully loaded..."); + } catch (Exception ex) { + Logger.getLogger(DatabaseDriver.class.getName()).log(Level.SEVERE, null, ex); + System.exit(1); + } + Object[] options = {"Yes", "No"}; + int n = JOptionPane.showOptionDialog(null, "Do you want to use the defaults for DB", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, + null, options, options[0]); + if (n == JOptionPane.YES_OPTION) { + System.out.println("Default DB parameters will be used..."); + + } else { + System.out.println("No was selected"); + } + + try { + conn = dd.makeConnection(db, host, user, pass.toCharArray()); + System.out.println("Connection to db " + db + " on " + host + " as " + user + " was created..."); + } catch (Exception ex) { + Logger.getLogger(DatabaseDriver.class.getName()).log(Level.SEVERE, null, ex); + System.exit(1); + } + + n = JOptionPane.showOptionDialog(null, "Reinitialize DB?", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, + null, options, options[0]); + if (n == JOptionPane.YES_OPTION) { + System.out.println("Reinitializing DB..."); + try { + dd.executeSQLScript("/home/vvv900/SVN/Jamberoo/trunk/current/etc/sql/jamberoo.sql"); + } catch (Exception ex) { + Logger.getLogger(DatabaseDriver.class.getName()).log(Level.SEVERE, null, ex); + System.exit(1); + } + + } + + n = JOptionPane.showOptionDialog(null, "Add Molecule?", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, + null, options, options[0]); + if (n == JOptionPane.NO_OPTION) { + System.exit(0); + } + + System.exit(0); + } +} diff --git a/src/main/java/cct/database/DatabaseManager.java b/src/main/java/cct/database/DatabaseManager.java new file mode 100644 index 0000000..300c0b5 --- /dev/null +++ b/src/main/java/cct/database/DatabaseManager.java @@ -0,0 +1,507 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.database; + +import cct.GlobalSettings; +import cct.awtdialogs.ConnectSQLServer; +import cct.awtdialogs.MessageWindow; +import cct.j3d.Java3dUniverse; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.net.URL; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; + +/** + * + * @author vvv900 + */ +public class DatabaseManager implements ActionListener { + + static String JDBC_KEY = "jdbc"; + static String DRIVER_KEY = "driver"; + static String HOST_KEY = "default_host"; + static String USE_HOST_KEY = "use_host"; + static String PORT_KEY = "default_port"; + static String USE_PORT_KEY = "use_port"; + static String USER_KEY = "default_user"; + static String USE_USER_KEY = "use_user"; + static String PASSWORD_KEY = "default_password"; + static String USE_PASSWORD_KEY = "use_password"; + static String DATABASE_KEY = "default_database"; + static String JDBC_DRIVERS_KEY = JDBC_KEY + ".drivers"; + static String DATABASE_CREATE_SCRIPT_KEY = "database.create.script"; + + // --- + private static final Logger logger = Logger.getLogger(DatabaseManager.class.getName()); + private static Level infoLevel = Level.INFO; + + static protected Map databaseEntries = new HashMap(); + static protected Map databaseDrivers = new HashMap(); + + // ------------------- + static protected ConnectSQLServer sqlServerDialog = null; + protected SQLDatabaseAccess databaseAccess = null; + + public new_SQLChemistryDatabase new_sqlChemistryDatabase = null; + public new_ChemistryDatabaseDialog new_chemistryDatabase = null; + + public SQLChemistryDatabase sqlChemistryDatabase = null; + public ChemistryDatabaseDialog chemistryDatabase = null; + + protected Java3dUniverse target = null; + + protected boolean connectedToDB = false; + private String databaseCreateScript; + private URL databaseCreateScriptURL; + + static protected JMenuItem jMenuDBLogin = null; + static protected JMenuItem jMenuDBLogout = null; + static protected JButton jDBLogin = new JButton(); + + //static private DatabaseManager dummy = new DatabaseManager(); + public DatabaseManager() { + if (jMenuDBLogin == null) { + jMenuDBLogin = new JMenuItem("Login"); + jMenuDBLogin.setToolTipText("Login Database"); + jMenuDBLogin.addActionListener(this); + } + // --- + if (jMenuDBLogout == null) { + jMenuDBLogout = new JMenuItem("Logout"); + jMenuDBLogout.setEnabled(false); + jMenuDBLogout.addActionListener(this); + } + + if (jDBLogin == null) { + jDBLogin = new JButton(); + //jDBLogin.setIcon(dbImage); + jDBLogin.setToolTipText("Login/Logout Database"); + jDBLogin.addActionListener(this); + } + + if (logger.isLoggable(infoLevel)) { + logger.log(infoLevel, "Available Drivers"); + for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements();) { + logger.log(infoLevel, e.nextElement().toString()); + } + } + } + + public void resetDBEntry(String dbEntry) throws Exception { + DabaseEntry entry = databaseEntries.get(dbEntry); + if (entry == null) { + throw new Exception("No such database entry: " + dbEntry); + } + if (this.databaseCreateScript == null) { + throw new Exception("Database creation script is not defined"); + } + if (databaseCreateScriptURL == null) { + throw new Exception("No valid URL to the Database creation script"); + } + String path = this.databaseCreateScriptURL.getPath(); + SQLTools.executeSQLScript(path, entry.getConnection(), entry.getDatabaseDriver().getDbType()); + } + + public String[] getDBEntriesAsArray() { + Object[] obj = databaseEntries.keySet().toArray(); + String[] entries = new String[obj.length]; + for (int i = 0; i < obj.length; i++) { + entries[i] = obj[i].toString(); + } + return entries; + } + + public String[] getDBEntriesAsSortedArray() { + String[] entries = getDBEntriesAsArray(); + Arrays.sort(entries); + return entries; + } + + public String makeAndRegisterConnection(DatabaseDriver dbDriver, String databaseName, String hostname, + String username, char[] password) throws Exception { + Connection conn = dbDriver.makeConnection(databaseName, hostname, username, password); + DabaseEntry dabaseEntry = new DabaseEntry(dbDriver, databaseName, hostname, username, password); + databaseEntries.put(dabaseEntry.getDbEntryName(), dabaseEntry); + return dabaseEntry.getDbEntryName(); + } + + public Connection getConnection(String connectionName) { + return databaseEntries.get(connectionName).getConnection(); + } + + public Map getDatabaseDrivers() { + return databaseDrivers; + } + + public DatabaseDriver getDatabaseDriver(String driverName) { + return databaseDrivers.get(driverName); + } + + public void setDatabaseDrivers(Map databaseDrivers) { + DatabaseManager.databaseDrivers = databaseDrivers; + } + + public void initiateFromProperties(Properties properties) throws Exception { + String driversSt = properties.getProperty(JDBC_DRIVERS_KEY); + if (driversSt == null) { + throw new Exception("No jdbc driver(s) information in properties file"); + } + String[] drivers = driversSt.trim().split("\\s+"); + + Set drs = new HashSet(); + for (String i : drivers) { + drs.add(i); + } + + if (logger.isLoggable(infoLevel)) { + logger.log(infoLevel, "Number of DB driver(s) in properties: " + drivers.length + " Unique drivers: " + drs.size()); + } + + for (String i : drivers) { + String key = JDBC_KEY + "." + i + "." + DRIVER_KEY; + String className = properties.getProperty(key); + if (className == null) { + logger.severe("No key " + key + " in properties"); + continue; + } + // --- + try { + DatabaseDriver driver = loadDriver(className); + if (logger.isLoggable(infoLevel)) { + logger.log(infoLevel, "Driver class " + className + " was successfully loaded"); + } + driver.setDbType(i); + // --- + key = JDBC_KEY + "." + i + "." + HOST_KEY; + className = properties.getProperty(key, ""); + driver.setDefaultHostname(className); + // --- + key = JDBC_KEY + "." + i + "." + USE_HOST_KEY; + className = properties.getProperty(key, "true"); + try { + boolean bool = Boolean.parseBoolean(className); + driver.setUseHostname(bool); + } catch (Exception ex) { + + } + // --- + + key = JDBC_KEY + "." + i + "." + PORT_KEY; + className = properties.getProperty(key, "3306"); + try { + int port = Integer.parseInt(className); + driver.setDefaultPort(port); + } catch (Exception ex) { + + } + // --- + key = JDBC_KEY + "." + i + "." + USE_PORT_KEY; + className = properties.getProperty(key, "true"); + try { + boolean bool = Boolean.parseBoolean(className); + driver.setUsePort(bool); + } catch (Exception ex) { + + } + // --- + key = JDBC_KEY + "." + i + "." + USER_KEY; + className = properties.getProperty(key, ""); + driver.setDefaultUsername(className); + // --- + key = JDBC_KEY + "." + i + "." + USE_USER_KEY; + className = properties.getProperty(key, "true"); + try { + boolean bool = Boolean.parseBoolean(className); + driver.setUseUsername(bool); + } catch (Exception ex) { + + } + // --- + key = JDBC_KEY + "." + i + "." + PASSWORD_KEY; + className = properties.getProperty(key, ""); + driver.setDefaultPassword(className); + // --- + key = JDBC_KEY + "." + i + "." + USE_PASSWORD_KEY; + className = properties.getProperty(key, "true"); + try { + boolean bool = Boolean.parseBoolean(className); + driver.setUsePassword(bool); + } catch (Exception ex) { + + } + // --- + key = JDBC_KEY + "." + i + "." + DATABASE_KEY; + className = properties.getProperty(key, "jamberoo"); + driver.setDefaultDatabase(className); + // --- + databaseDrivers.put(i, driver); + } catch (Exception ex) { + logger.severe("Error loading driver class " + className + " : " + ex.getMessage()); + continue; + } + + databaseCreateScript = properties.getProperty(DATABASE_CREATE_SCRIPT_KEY); + if (this.databaseCreateScript == null) { + if (logger.isLoggable(Level.WARNING)) { + logger.log(Level.WARNING, "Database Creation script is not defined"); + } + } else { + try { + if (databaseCreateScript.matches("\\w+[.]sql")) { + databaseCreateScriptURL = this.getClass().getResource(databaseCreateScript); + } else { + databaseCreateScriptURL = new URL(databaseCreateScript); + } + } catch (Exception ex) { + logger.severe("Unable to open Database Creation script as " + databaseCreateScriptURL.getPath() + " : " + ex.getMessage()); + } + } + + } + + } + + public DatabaseDriver loadDriver(String name) throws Exception { + return new DatabaseDriver(name); + } + + public boolean connectToDatabase() { + + /* + // Invoke a dialog to get hostname, user name, etc... + //ConnectSQLServer server = new ConnectSQLServer(menuFrame, + // So, now we can open only one database during a session + if (sqlServerDialog == null) { + sqlServerDialog = new ConnectSQLServer("Connect to Database Server", true); + if (sqlServerDialog.getDatabase().length() == 0) { + sqlServerDialog.setDatabase("chemistry"); + } + + //server.dispose(); + //menuFrame.sqlServerDialog.setVisible(false); + } + + if (!connectedToDB) { + sqlServerDialog.setVisible(true); + } + + if (!sqlServerDialog.pressedOK()) { + return false; + } + + String host = sqlServerDialog.getHostname(); + String user = sqlServerDialog.getUsername(); + String pass = sqlServerDialog.getPassword(); + String database = sqlServerDialog.getDatabase(); + + // --- Connect to the SQL Server + // --- Load connector and make connection + if (databaseAccess == null) { + databaseAccess = new SQLDatabaseAccess(); + if (databaseAccess.wasError()) { + JOptionPane.showMessageDialog(new JFrame(), + databaseAccess.getErrorMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return false; + + } + } + if (!databaseAccess.isDriverLoaded()) { + return false; + } + if (!databaseAccess.getConnection(host, user, pass)) { + return false; + } + if (!databaseAccess.selectDatabase(database)) { + return false; + } + + connectedToDB = true; + + //SQLChemistryDatabase sql_data = new SQLChemistryDatabase(host, + // --- Testing new database + if (cct.GlobalSettings.isNewDatabase()) { + if (new_sqlChemistryDatabase == null) { + new_sqlChemistryDatabase = new new_SQLChemistryDatabase( + databaseAccess, host, + user, pass, database); + //new_sqlChemistryDatabase.setParentFrame(parentFrame); + } + if (new_sqlChemistryDatabase.isError()) { + logger.info("connectToDatabase: " + new_sqlChemistryDatabase.getErrorMessage()); + MessageWindow er = new MessageWindow("ERROR", + new_sqlChemistryDatabase.getErrorMessage(), true); + er.setVisible(true); + } else { + //ConnectSQLServer sql = new ConnectSQLServer( menuFrame, "Connect to SQL Server", true ); + if (new_chemistryDatabase == null) { + new_chemistryDatabase = new new_ChemistryDatabaseDialog(target, new_sqlChemistryDatabase, + "Chemical Database", false); + } + new_chemistryDatabase.setVisible(true); + + } + + } else { + // --- Old Database Design + if (sqlChemistryDatabase == null) { + sqlChemistryDatabase = new SQLChemistryDatabase( + databaseAccess, host, + user, pass, database); + } + + if (sqlChemistryDatabase.isError()) { + logger.info(": " + + sqlChemistryDatabase.getErrorMessage()); + MessageWindow er = new MessageWindow("ERROR", + sqlChemistryDatabase.getErrorMessage(), true); + er.setVisible(true); + } else { + //ConnectSQLServer sql = new ConnectSQLServer( menuFrame, "Connect to SQL Server", true ); + if (chemistryDatabase == null) { + chemistryDatabase = new ChemistryDatabaseDialog(target, sqlChemistryDatabase, + "Chemical Database", false); + } + chemistryDatabase.setVisible(true); + + } + } + */ + return true; + } + + public Java3dUniverse getTarget() { + return target; + } + + public void setTarget(Java3dUniverse target) { + this.target = target; + } + + public List getMenuItems() { + List items = new ArrayList(); + items.add(jMenuDBLogin); + items.add(jMenuDBLogout); + return items; + } + + public void actionPerformed(ActionEvent actionEvent) { + if (jMenuDBLogin == actionEvent.getSource() || jDBLogin == actionEvent.getSource()) { + + if (connectToDatabase()) { + jMenuDBLogin.setText("Save/Retrieve Data"); + jMenuDBLogin.setToolTipText( + "Save/Retrieve Data to/from Database"); + jMenuDBLogout.setEnabled(true); + } + } else if (jMenuDBLogout == actionEvent.getSource()) { + //java3dUniverse.logoutDatabase(); + jMenuDBLogin.setText("Login Database"); + jMenuDBLogin.setToolTipText("Login Database"); + jMenuDBLogout.setEnabled(false); + } + } + + public static void main(String[] args) { + DatabaseManager dbm = new DatabaseManager(); + try { + dbm.initiateFromProperties(GlobalSettings.getProperties()); + + } catch (Exception ex) { + Logger.getLogger(DatabaseDriver.class.getName()).log(Level.SEVERE, null, ex); + } + System.exit(0); + + } + +} + +class DabaseEntry { + + private DatabaseDriver databaseDriver; + private String databaseName, hostname, username; + private char[] password; + private String dbEntryName = ""; + + // --- + private Connection connection = null; + + public DabaseEntry(DatabaseDriver databaseDriver, String databaseName, String hostname, String username, char[] password) { + this.databaseDriver = databaseDriver; + this.databaseName = databaseName; + this.hostname = hostname; + this.username = username; + this.password = password; + connection = databaseDriver.getConnection(); + dbEntryName = databaseDriver.getDbType() + ":" + databaseName + + ((hostname != null && hostname.length() > 0) ? " on " + hostname : "") + + ((username != null && username.length() > 0) ? " as " + username : ""); + } + + public DatabaseDriver getDatabaseDriver() { + return databaseDriver; + } + + public String getDbEntryName() { + return dbEntryName; + } + + public Connection getConnection() { + //connection.isValid(1); + return connection; + } + +} diff --git a/src/main/java/cct/database/DatabaseManagerDialog.form b/src/main/java/cct/database/DatabaseManagerDialog.form new file mode 100644 index 0000000..9d0f0fc --- /dev/null +++ b/src/main/java/cct/database/DatabaseManagerDialog.form @@ -0,0 +1,114 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/cct/database/DatabaseManagerDialog.java b/src/main/java/cct/database/DatabaseManagerDialog.java new file mode 100644 index 0000000..3e1ee0f --- /dev/null +++ b/src/main/java/cct/database/DatabaseManagerDialog.java @@ -0,0 +1,261 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.database; + +import cct.GlobalSettings; +import java.awt.Frame; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.DefaultListModel; +import javax.swing.JOptionPane; + +/** + * + * @author vvv900 + */ +public class DatabaseManagerDialog extends javax.swing.JDialog { + + private Set databases; + private DatabaseManager databaseManager; + + /** + * Creates new form DatabaseManagerDialog + */ + public DatabaseManagerDialog(Frame parent, boolean modal) { + super(parent, modal); + initComponents(); + } + + /** + * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The + * content of this method is always regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jPanel1 = new javax.swing.JPanel(); + jScrollPane1 = new javax.swing.JScrollPane(); + databaseList = new javax.swing.JList(); + jPanel2 = new javax.swing.JPanel(); + addDBButton = new javax.swing.JButton(); + removeSelectedButton = new javax.swing.JButton(); + initButton = new javax.swing.JButton(); + cancelButton = new javax.swing.JButton(); + + setTitle("Databases"); + setAlwaysOnTop(true); + + jPanel1.setLayout(new java.awt.BorderLayout()); + + databaseList.setBorder(javax.swing.BorderFactory.createTitledBorder("Available Databases")); + databaseList.setModel(new javax.swing.AbstractListModel() { + String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; + public int getSize() { return strings.length; } + public Object getElementAt(int i) { return strings[i]; } + }); + jScrollPane1.setViewportView(databaseList); + + jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER); + + getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); + + addDBButton.setText("Add Database"); + addDBButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + addDBButtonActionPerformed(evt); + } + }); + jPanel2.add(addDBButton); + + removeSelectedButton.setText("Remove Selected"); + removeSelectedButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + removeSelectedButtonActionPerformed(evt); + } + }); + jPanel2.add(removeSelectedButton); + + initButton.setText("Initialize/Reset DB"); + initButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + initButtonActionPerformed(evt); + } + }); + jPanel2.add(initButton); + + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + cancelButtonActionPerformed(evt); + } + }); + jPanel2.add(cancelButton); + + getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH); + + pack(); + }// //GEN-END:initComponents + + private Set getDatabases() { + return databases; + } + + private void setDatabases(Set databases) { + this.databases = databases; + DefaultListModel dlm = new DefaultListModel(); + for (String str : databases) { + dlm.addElement(str); + } + databaseList.setModel(dlm); + } + + private void setDatabases(String[] dbEntries) { + databases.clear(); + DefaultListModel dlm = new DefaultListModel(); + for (String str : dbEntries) { + databases.add(str); + dlm.addElement(str); + } + databaseList.setModel(dlm); + } + + public DatabaseManager getDatabaseManager() { + return databaseManager; + } + + public void setDatabaseManager(DatabaseManager databaseManager) { + this.databaseManager = databaseManager; + } + + + private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed + this.setVisible(false); + }//GEN-LAST:event_cancelButtonActionPerformed + + private void removeSelectedButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeSelectedButtonActionPerformed + int[] list = this.databaseList.getSelectedIndices(); // List list = this.databaseList.getSelectedValuesList(); + //int[] list = databaseList.getSelectedIndices();databaseList.getModel(). + if (list == null || list.length < 1) { + JOptionPane.showMessageDialog(this, "Nothing to delete", "Nothing to delete", JOptionPane.WARNING_MESSAGE); + return; + } + DefaultListModel dlm = (DefaultListModel) databaseList.getModel(); + for (int i : list) { + dlm.removeElementAt(i); + } + validate(); + }//GEN-LAST:event_removeSelectedButtonActionPerformed + + private void addDBButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addDBButtonActionPerformed + ConnectToDatabaseDialog connectToDatabaseDialog = new ConnectToDatabaseDialog(new Frame(), true); + connectToDatabaseDialog.setLocationRelativeTo(this); + connectToDatabaseDialog.setDatabaseManager(databaseManager); + connectToDatabaseDialog.validate(); + connectToDatabaseDialog.setAlwaysOnTop(true); + connectToDatabaseDialog.setVisible(true); + + if (connectToDatabaseDialog.isDialogCancelled()) { + return; + } + // --- + connectToDatabaseDialog.dispose(); + this.setDatabases(databaseManager.getDBEntriesAsSortedArray()); + + }//GEN-LAST:event_addDBButtonActionPerformed + + private void initButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_initButtonActionPerformed + //List list = this.databaseList.getSelectedValuesList(); + int[] list = this.databaseList.getSelectedIndices(); + //int[] list = databaseList.getSelectedIndices();databaseList.getModel(). + if (list == null || list.length < 1) { + JOptionPane.showMessageDialog(this, "Select database first", "Select database first", JOptionPane.WARNING_MESSAGE); + return; + } + for (int i : list) { + try { + databaseManager.resetDBEntry(databaseList.getModel().getElementAt(i).toString()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error reseting/creating database: " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + } + JOptionPane.showMessageDialog(this, "Initialization/reset of database(s) was successful", "Success", + JOptionPane.INFORMATION_MESSAGE); + }//GEN-LAST:event_initButtonActionPerformed + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + /* Set the Nimbus look and feel */ + // + /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. + * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html + */ + try { + for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + javax.swing.UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (ClassNotFoundException ex) { + Logger.getLogger(DatabaseManagerDialog.class.getName()).log(Level.SEVERE, null, ex); + } catch (InstantiationException ex) { + Logger.getLogger(DatabaseManagerDialog.class.getName()).log(Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + Logger.getLogger(DatabaseManagerDialog.class.getName()).log(Level.SEVERE, null, ex); + } catch (javax.swing.UnsupportedLookAndFeelException ex) { + Logger.getLogger(DatabaseManagerDialog.class.getName()).log(Level.SEVERE, null, ex); + } + // + + /* Create and display the dialog */ + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + + DatabaseManagerDialog dialog = new DatabaseManagerDialog(new javax.swing.JFrame(), true); + dialog.addWindowListener(new java.awt.event.WindowAdapter() { + @Override + public void windowClosing(java.awt.event.WindowEvent e) { + System.exit(0); + } + }); + Set db = new HashSet(); + //db.add("mysql:localhost:chemistry"); + //db.add("sqlite:chemistry.db"); + dialog.setDatabases(db); + + DatabaseManager dbm = new DatabaseManager(); + try { + dbm.initiateFromProperties(GlobalSettings.getProperties()); + + } catch (Exception ex) { + Logger.getLogger(DatabaseDriver.class.getName()).log(Level.SEVERE, null, ex); + } + + dialog.setDatabaseManager(dbm); + dialog.setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton addDBButton; + private javax.swing.JButton cancelButton; + private javax.swing.JList databaseList; + private javax.swing.JButton initButton; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JButton removeSelectedButton; + // End of variables declaration//GEN-END:variables +} diff --git a/src/main/java/cct/database/SQLChemistryDatabase.java b/src/main/java/cct/database/SQLChemistryDatabase.java new file mode 100644 index 0000000..4dc5072 --- /dev/null +++ b/src/main/java/cct/database/SQLChemistryDatabase.java @@ -0,0 +1,252 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.database; + +import java.io.InputStream; +import java.io.OutputStream; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; +import java.util.logging.Logger; + +import cct.interfaces.MoleculeInterface; +import cct.modelling.Molecule; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class SQLChemistryDatabase { + SQLDatabaseAccess database = null; + boolean wasError = true; + String errorMessage = "No error(s) yet"; + List moleculeTableInfo = null; + List moleculeTable = null; + List structureTableInfo = null; + List structureTable = null; + + static String MoleculeTable = "molecule"; + static String StructureTable = "structure"; + + static String moleculeNameKey = "name"; + static String structureIdKey = "str_id"; + static String methodNameKey = "method"; + static String structureKey = "structure"; + static final Logger logger = Logger.getLogger(SQLChemistryDatabase.class.getCanonicalName()); + + public SQLChemistryDatabase(SQLDatabaseAccess db, String host, String user, String pass, String datab) { + wasError = true; + database = db; + if (!database.isDriverLoaded()) { + return; + } + if (!database.getConnection(host, user, pass)) { + return; + } + if (!database.selectDatabase(datab)) { + return; + } + wasError = false; + } + + public String getErrorMessage() { + return database.getErrorMessage(); + } + + public List getMolecules() { + if (database == null) { + return null; + } + Connection conn = database.getConnection(); + if (conn == null) { + return null; + } + + Statement stmt = null; + ResultSet rs = null; + ResultSetMetaData rsmd; + String str; + + // --- Get info about table + moleculeTableInfo = database.getTableMetaData(MoleculeTable); + + moleculeTable = database.getColumnsFromTable(MoleculeTable, "*"); + + return moleculeTable; + } + + /** + * + * @return ArrayList + */ + public List getStructures() { + if (database == null) { + return null; + } + if (database.getConnection() == null) { + return null; + } + + // --- Get info about table + structureTableInfo = database.getTableMetaData(StructureTable); + + structureTable = database.getColumnsFromTable(StructureTable, "*"); + + return structureTable; + } + + public boolean changeMoleculeName(String oldName, String newName) { + if (!database.updateItem(StructureTable, moleculeNameKey, oldName, newName)) { + return false; + } + return database.updateItem(MoleculeTable, moleculeNameKey, oldName, newName); + } + + public boolean addNewMolecule(String name) { + return database.addStringItem(MoleculeTable, moleculeNameKey, name); + } + + public boolean addNewStructure(String name, String method, MoleculeInterface mol) { + // --- First add new row to "structure" table + // --- insert into structure (name, method) values('Acetone',�STO-3G�); + if (!database.addManyStringItems(StructureTable, + structureIdKey + "," + moleculeNameKey + "," + methodNameKey, + name + "_" + method + "," + name + "," + method)) { + return false; + } + // --- get OuputStream to write structure + //Blob structure = database.getBlob(StructureTable, structureKey, + // structureIdKey, + // name + "_" + method ); + Clob structure = database.getClob(StructureTable, structureKey, + structureIdKey, + name + "_" + method); + + try { + //OutputStream out = structure.setBinaryStream(1); + OutputStream out = structure.setAsciiStream(1); + Molecule.toArchiveFormat(mol, out); + } + catch (SQLException ex) { + logger.info("addNewStructure: SQLException: " + ex.getMessage()); + return false; + } + + //boolean result = database.setBlob( StructureTable, structureKey, + // structureIdKey, + // name + "_" + method, structure ); + boolean result = database.setClob(StructureTable, structureKey, + structureIdKey, + name + "_" + method, structure); + + if (!result) { + database.deleteRows(StructureTable, structureIdKey, name + "_" + method); + } + return result; + } + + public Molecule loadStructure(String name, String method) { + + // --- get InputStream to write structure + //Blob structure = database.getBlob(StructureTable, structureKey, + // structureIdKey, + // name + "_" + method ); + Clob structure = database.getClob(StructureTable, structureKey, + structureIdKey, + name + "_" + method); + + //byte arch[] = database.getBytes( StructureTable, structureKey, + // structureIdKey, + // name + "_" + method ); + + try { + String str = structure.getSubString(1L, structure.length() > 255 ? 255 : (int) structure.length()); + logger.info("loadStructure: substring: " + str); + + //InputStream in = structure.getBinaryStream( ); + InputStream in = structure.getAsciiStream(); + Molecule mol = new Molecule(); + mol.fromArchiveFormat(in); + return mol; + } + catch (SQLException ex) { + logger.info("addNewStructure: SQLException: " + ex.getMessage()); + return null; + } + + /* + try { + //char arch[] = structure.getSubString(1L, (int)structure.length()).toCharArray(); + byte arch[] = structure.getSubString(1L, (int)structure.length()).getBytes(); + logger.info( "addNewStructure: s " + structure.getSubString(1L, (int)structure.length()) ); + logger.info( "addNewStructure: b " + arch[0] + arch[1] + arch[2] ); + Molecule mol = new Molecule(); + mol.fromArchiveFormat( arch ); + return mol; + } catch (SQLException ex) { + logger.info( "addNewStructure: SQLException: " + ex.getMessage() ); + return null; + } + */ + + } + + public boolean deleteStructure(String name, String method) { + return database.deleteRows( StructureTable, structureIdKey, name + "_" + method ) != 0; + } + + public boolean deleteMolecule(String name) { + return database.deleteRows( MoleculeTable, moleculeNameKey, name ) != 0; + } + + public boolean isError() { + return wasError; + } +} diff --git a/src/main/java/cct/database/SQLDatabaseAccess.java b/src/main/java/cct/database/SQLDatabaseAccess.java new file mode 100644 index 0000000..4f8c421 --- /dev/null +++ b/src/main/java/cct/database/SQLDatabaseAccess.java @@ -0,0 +1,1409 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.database; + +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.Driver; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class SQLDatabaseAccess + implements DatabaseAccess { + static boolean SuccessLoadDriver = false; + Connection Conn = null; + Statement stmt = null; + PreparedStatement pstmt = null; + ResultSet rs = null; + boolean errorHappened = false; + String errorMessage = "No error messages yet"; + static final Logger logger = Logger.getLogger(SQLDatabaseAccess.class.getCanonicalName()); + + public SQLDatabaseAccess() { + try { + // The newInstance() call is a work around for some + // broken Java implementations + Class.forName("com.mysql.jdbc.Driver").newInstance(); + SuccessLoadDriver = true; + } + catch (Exception ex) { + errorHappened = true; + errorMessage = "Cannot load driver: " + ex.getMessage(); + logger.info(errorMessage); + // handle the error + SuccessLoadDriver = false; + } + + } + + public boolean isDriverLoaded() { + return SuccessLoadDriver; + } + + public boolean wasError() { + return errorHappened; + } + + public boolean getConnection(String host, String user, String pass) { + + if (!SuccessLoadDriver) { + return false; + } + + try { + logger.info("Available Drivers"); + for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements(); ) { + logger.info(e.nextElement().toString()); + } + + //conn = DriverManager.getConnection( + // "jdbc:mysql://localhost/test?user=vlad&password=victor"); + String hostName = "jdbc:mysql://" + host; // !!! + if (!hostName.endsWith("/")) { + hostName = hostName + "/"; + } + + logger.info("Connecting to " + hostName + " as " + user); + Conn = DriverManager.getConnection(hostName, user, pass); + //"jdbc:mysql://localhost/test?user=vlad&password=victor"); + // Do something with the Connection + + } + catch (SQLException ex) { + // handle any errors + errorMessage = "Cannot connect to database: SQLException: " + + ex.getMessage(); + logger.info(errorMessage); + //logger.info("SQLException: " + ex.getMessage()); + logger.info("SQLState: " + ex.getSQLState()); + logger.info("VendorError: " + ex.getErrorCode()); + + try { + Driver dr = DriverManager.getDriver(host); + DriverManager.registerDriver(dr); + Conn = DriverManager.getConnection(host, user, pass); + } + catch (SQLException exep) { + logger.info( + "Cannot locate a driver that understands the given URL" + + " " + host); + } + return false; + } + return true; + } + + /** + * + * @return Connection + */ + public Connection getConnection() { + return Conn; + } + + public boolean closeConnection() { + if (!SuccessLoadDriver || Conn == null) { + return true; // Connection is already closed + } + + try { + Conn.close(); + } + catch (SQLException er) { + + } + return true; + } + + /** + * + * @return String + */ + public String getErrorMessage() { + return errorMessage; + } + + /** + * + * @param database String + * @return boolean + */ + public boolean selectDatabase(String database) { + if (Conn == null) { + return false; + } + + // assume conn is an already created JDBC connection + stmt = null; + rs = null; + String str; + try { + str = "use " + database; + logger.info("SQL Query: " + str); + stmt = Conn.createStatement(); + stmt.executeUpdate(str); + } + catch (SQLException ex) { + // handle any errors + errorMessage = "SQLException: " + ex.getMessage(); + logger.info(errorMessage); + logger.info("SQLState: " + ex.getSQLState()); + logger.info("VendorError: " + ex.getErrorCode()); + return false; + } + finally { + // it is a good idea to release + // resources in a finally{} block + // in reverse-order of their creation + // if they are no-longer needed + if (rs != null) { + try { + rs.close(); + } + catch (SQLException sqlEx) { // ignore } + rs = null; + } + if (stmt != null) { + try { + stmt.close(); + } + catch (SQLException sqlEx) { // ignore } + stmt = null; + } + } + } + } + return true; + } + + /** + * + * @param tableName String + * @return ArrayList + */ + public List getTableMetaData(String tableName) { + if (Conn == null) { + return null; + } + + // assume conn is an already created JDBC connection + stmt = null; + rs = null; + ResultSetMetaData rsmd; + String str = null; + + List tableMD = null; + + try { + stmt = Conn.createStatement(); + str = "select * from " + tableName; + logger.info("SQL Query: " + str); + if (!stmt.execute(str)) { + return null; + } + rs = stmt.getResultSet(); + rsmd = rs.getMetaData(); + + if (rsmd.getColumnCount() > 0) { + tableMD = new ArrayList(); + } + else { + return null; + } + + for (int i = 1; i <= rsmd.getColumnCount(); i++) { + Map info = new HashMap(); + info.put(COLUMN_NAME, rsmd.getColumnName(i)); + logger.info("Column name: " + rsmd.getColumnName(i)); + info.put(COLUMN_TYPE, rsmd.getColumnTypeName(i)); + logger.info("Column SQL Type: " + + rsmd.getColumnTypeName(i)); + tableMD.add(info); + } + } + catch (SQLException ex) { + // handle any errors + errorMessage = "SQLException: " + ex.getMessage(); + logger.info(errorMessage); + logger.info("SQLState: " + ex.getSQLState()); + logger.info("VendorError: " + ex.getErrorCode()); + return null; + } + finally { + // it is a good idea to release + // resources in a finally{} block + // in reverse-order of their creation + // if they are no-longer needed + if (rs != null) { + try { + rs.close(); + } + catch (SQLException sqlEx) { // ignore } + rs = null; + } + if (stmt != null) { + try { + stmt.close(); + } + catch (SQLException sqlEx) { // ignore } + stmt = null; + } + } + } + } + return tableMD; + } + + /** + * + * @param tableName String + * @return ArrayList + */ + public List getColumnsFromTable(String tableName, String Columns) { + if (Conn == null) { + return null; + } + + // assume conn is an already created JDBC connection + stmt = null; + rs = null; + ResultSetMetaData rsmd; + String str = null; + + List columns = null; + + try { + stmt = Conn.createStatement(); + str = "select " + Columns + " from " + tableName; + logger.info("SQL Query: " + str); + if (!stmt.execute(str)) { + return null; + } + rs = stmt.getResultSet(); + rsmd = rs.getMetaData(); + if (rsmd.getColumnCount() < 1) { + return null; + } + + columns = new ArrayList(); + + while (rs.next()) { + Map info = new HashMap(); + for (int i = 1; i <= rsmd.getColumnCount(); i++) { + if (rsmd.getColumnTypeName(i).compareToIgnoreCase("CHAR") == + 0 || + rsmd.getColumnTypeName(i).compareToIgnoreCase("VARCHAR") == + 0 || + rsmd.getColumnTypeName(i).compareToIgnoreCase("TEXT") == + 0) { + info.put(rsmd.getColumnName(i), rs.getString(i)); + } + else + if (rsmd.getColumnTypeName(i).compareToIgnoreCase("FLOAT") == + 0) { + info.put(rsmd.getColumnName(i), new Float(rs.getFloat(i))); + } + else if (rsmd.getColumnTypeName(i).compareToIgnoreCase("INTEGER") == + 0) { + info.put(rsmd.getColumnName(i), new Integer(rs.getInt(i))); + } + else if (rsmd.getColumnTypeName(i).compareToIgnoreCase( + "INTEGER UNSIGNED") == 0) { + info.put(rsmd.getColumnName(i), new Integer(rs.getInt(i))); + } + + // --- General case + else { + info.put(rsmd.getColumnName(i), rs.getString(i)); + } + + } + columns.add(info); + //logger.info(rs.getString(1)); + } + + } + catch (SQLException ex) { + // handle any errors + errorMessage = "SQLException: " + ex.getMessage(); + logger.info(errorMessage); + logger.info("SQLState: " + ex.getSQLState()); + logger.info("VendorError: " + ex.getErrorCode()); + return null; + } + finally { + // it is a good idea to release + // resources in a finally{} block + // in reverse-order of their creation + // if they are no-longer needed + if (rs != null) { + try { + rs.close(); + } + catch (SQLException sqlEx) { // ignore } + rs = null; + } + if (stmt != null) { + try { + stmt.close(); + } + catch (SQLException sqlEx) { // ignore } + stmt = null; + } + } + } + } + return columns; + } + + /** + * + * @param tableName String + * @param Columns String + * @param condition String - Should be prepared by user + * @return ArrayList + */ + public List getSelectedColumnsFromTable(String tableName, + String Columns, + String condition) { + if (Conn == null) { + return null; + } + + // assume conn is an already created JDBC connection + stmt = null; + rs = null; + ResultSetMetaData rsmd; + String str = null; + + List columns = null; + + try { + stmt = Conn.createStatement(); + str = "select " + Columns + " from " + tableName + " where " + + condition; + logger.info("getSelectedColumnsFromTable: SQL Query: " + str); + if (!stmt.execute(str)) { + return null; + } + rs = stmt.getResultSet(); + rsmd = rs.getMetaData(); + if (rsmd.getColumnCount() < 1) { + return null; + } + + columns = new ArrayList(); + + while (rs.next()) { + Map info = new HashMap(); + for (int i = 1; i <= rsmd.getColumnCount(); i++) { + if (rsmd.getColumnTypeName(i).compareToIgnoreCase("CHAR") == + 0 || + rsmd.getColumnTypeName(i).compareToIgnoreCase("VARCHAR") == + 0 || + rsmd.getColumnTypeName(i).compareToIgnoreCase("TEXT") == + 0) { + info.put(rsmd.getColumnName(i), rs.getString(i)); + logger.info(rsmd.getColumnName(i) + " " + + rs.getString(i)); + } + else + if (rsmd.getColumnTypeName(i).compareToIgnoreCase("FLOAT") == + 0) { + info.put(rsmd.getColumnName(i), new Float(rs.getFloat(i))); + logger.info(rsmd.getColumnName(i) + " " + + rs.getFloat(i)); + } + else if (rsmd.getColumnTypeName(i).compareToIgnoreCase("INTEGER") == + 0) { + info.put(rsmd.getColumnName(i), new Integer(rs.getInt(i))); + } + else if (rsmd.getColumnTypeName(i).compareToIgnoreCase( + "INTEGER UNSIGNED") == 0) { + info.put(rsmd.getColumnName(i), new Integer(rs.getInt(i))); + } + else if (rsmd.getColumnTypeName(i).compareToIgnoreCase("INT") == + 0) { + info.put(rsmd.getColumnName(i), new Integer(rs.getInt(i))); + logger.info(rsmd.getColumnName(i) + " " + + rs.getString(i)); + } + + // --- General case + else { + info.put(rsmd.getColumnName(i), rs.getString(i)); + logger.info(rsmd.getColumnName(i) + " " + + rs.getString(i)); + } + + } + columns.add(info); + //logger.info(rs.getString(1)); + } + errorHappened = false; + } + catch (SQLException ex) { + // handle any errors + errorHappened = true; + errorMessage = "getSelectedColumnsFromTable: SQLException: " + + ex.getMessage(); + logger.info(errorMessage); + logger.info("SQLState: " + ex.getSQLState()); + logger.info("VendorError: " + ex.getErrorCode()); + return null; + } + finally { + // it is a good idea to release + // resources in a finally{} block + // in reverse-order of their creation + // if they are no-longer needed + if (rs != null) { + try { + rs.close(); + } + catch (SQLException sqlEx) { // ignore } + rs = null; + } + if (stmt != null) { + try { + stmt.close(); + } + catch (SQLException sqlEx) { // ignore } + stmt = null; + } + } + } + } + return columns; + } + + public boolean updateItem(String Table, String columnName, String oldValue, + String newValue) { + if (Conn == null) { + return false; + } + + // assume conn is an already created JDBC connection + stmt = null; + rs = null; + String str = null; + try { + stmt = Conn.createStatement(); + str = "UPDATE " + Table + " SET " + columnName + + " = '" + + newValue + "' WHERE " + columnName + " LIKE '" + + oldValue + "'"; + + logger.info("SQLState: " + str); + stmt.executeUpdate(str); + } + catch (SQLException ex) { + // handle any errors + errorMessage = "SQLException: " + ex.getMessage(); + logger.info(errorMessage); + logger.info("SQLState: " + ex.getSQLState()); + logger.info("VendorError: " + ex.getErrorCode()); + return false; + } + finally { + // it is a good idea to release + // resources in a finally{} block + // in reverse-order of their creation + // if they are no-longer needed + if (rs != null) { + try { + rs.close(); + } + catch (SQLException sqlEx) { // ignore } + rs = null; + } + if (stmt != null) { + try { + stmt.close(); + } + catch (SQLException sqlEx) { // ignore } + stmt = null; + } + } + } + } + return true; + } + + public boolean updateItemsUsingCondition(String Table, String Values, + String condition) { + if (Conn == null) { + return false; + } + + // assume conn is an already created JDBC connection + stmt = null; + rs = null; + String str = null; + try { + stmt = Conn.createStatement(); + str = "UPDATE " + Table + " SET " + Values + " WHERE " + condition; + + logger.info("SQLState: " + str); + stmt.executeUpdate(str); + errorHappened = false; + } + catch (SQLException ex) { + // handle any errors + errorHappened = true; + errorMessage = "SQLException: " + ex.getMessage(); + logger.info(errorMessage); + logger.info("SQLState: " + ex.getSQLState()); + logger.info("VendorError: " + ex.getErrorCode()); + return false; + } + finally { + // it is a good idea to release + // resources in a finally{} block + // in reverse-order of their creation + // if they are no-longer needed + if (rs != null) { + try { + rs.close(); + } + catch (SQLException sqlEx) { // ignore } + rs = null; + } + if (stmt != null) { + try { + stmt.close(); + } + catch (SQLException sqlEx) { // ignore } + stmt = null; + } + } + } + } + return true; + } + + public boolean addStringItem(String Table, String columnName, + String newValue) { + if (Conn == null) { + return false; + } + + // assume conn is an already created JDBC connection + stmt = null; + rs = null; + String str; + try { + stmt = Conn.createStatement(); + str = "INSERT INTO " + Table + " (" + columnName + + ") " + + " VALUES ('" + newValue + "')"; + logger.info("SQL Query: " + str); + stmt.executeUpdate(str); + } + catch (SQLException ex) { + // handle any errors + errorMessage = "SQLException: " + ex.getMessage(); + logger.info(errorMessage); + logger.info("SQLState: " + ex.getSQLState()); + logger.info("VendorError: " + ex.getErrorCode()); + return false; + } + finally { + // it is a good idea to release + // resources in a finally{} block + // in reverse-order of their creation + // if they are no-longer needed + if (rs != null) { + try { + rs.close(); + } + catch (SQLException sqlEx) { // ignore } + rs = null; + } + if (stmt != null) { + try { + stmt.close(); + } + catch (SQLException sqlEx) { // ignore } + stmt = null; + } + } + } + } + return true; + } + + /** + * + * @param Table String + * @param columnNames String + * @param newValues String + * @return boolean + */ + public boolean addManyStringItems(String Table, String columnNames, + String newValues) { + if (Conn == null) { + return false; + } + + String columns[] = columnNames.split(","); + String values[] = newValues.split(","); + return addManyStringItems(Table, columns, values); + + } + + /** + * + * @param Table String + * @param columnNames String[] + * @param newValues String[] + * @return boolean + */ + public boolean addManyStringItems(String Table, String columnNames[], + String newValues[]) { + if (Conn == null) { + return false; + } + + // Error check + + if ( (columnNames.length != newValues.length) || columnNames.length == 0) { + errorHappened = true; + errorMessage = + "addManyStringItems: Input parameters Error: (columnNames.length != newValues.length ) || columnNames.length == 0"; + return false; + } + // assume conn is an already created JDBC connection + stmt = null; + rs = null; + String str = "INSERT INTO " + Table + " ("; + + // Form columns names + str += columnNames[0]; + for (int i = 1; i < columnNames.length; i++) { + str += "," + columnNames[i]; + } + + str += ") VALUES ("; + + // Form values + + str += "'" + newValues[0] + "'"; + for (int i = 1; i < columnNames.length; i++) { + str += ",'" + newValues[i] + "'"; + } + + str += ")"; + + try { + stmt = Conn.createStatement(); + + logger.info("addManyStringItems: SQL Query: " + str); + stmt.executeUpdate(str); + errorHappened = false; + } + catch (SQLException ex) { + // handle any errors + errorHappened = true; + errorMessage = "addManyStringItems: SQLException: " + ex.getMessage(); + logger.info(errorMessage); + logger.info("SQLState: " + ex.getSQLState()); + logger.info("VendorError: " + ex.getErrorCode()); + return false; + } + finally { + // it is a good idea to release + // resources in a finally{} block + // in reverse-order of their creation + // if they are no-longer needed + if (rs != null) { + try { + rs.close(); + } + catch (SQLException sqlEx) { // ignore } + rs = null; + } + if (stmt != null) { + try { + stmt.close(); + } + catch (SQLException sqlEx) { // ignore } + stmt = null; + } + } + } + } + return true; + } + + public int deleteRows(String Table, String columnNames, String newValues) { + if (Conn == null) { + return 0; + } + + // assume conn is an already created JDBC connection + stmt = null; + rs = null; + String str = "DELETE FROM " + Table + " WHERE "; + try { + stmt = Conn.createStatement(); + String temp[] = newValues.split(","); + String temp2[] = columnNames.split(","); + if ( (temp.length != temp2.length) || temp.length < 1) { + return 0; + } + str += temp2[0] + "='" + temp[0] + "'"; + for (int i = 1; i < temp.length; i++) { + str += " && " + temp2[i] + "='" + temp[i] + "'"; + } + logger.info("deleteRows: SQL Query: " + str); + return stmt.executeUpdate(str); + //rs = stmt.getResultSet(); + //rs.next(); + //return 0; + } + catch (SQLException ex) { + // handle any errors + errorHappened = true; + errorMessage = "deleteRows: SQLException: " + ex.getMessage(); + logger.info(errorMessage); + logger.info("SQLState: " + ex.getSQLState()); + logger.info("VendorError: " + ex.getErrorCode()); + return 0; + } + finally { + // it is a good idea to release + // resources in a finally{} block + // in reverse-order of their creation + // if they are no-longer needed + if (rs != null) { + try { + rs.close(); + } + catch (SQLException sqlEx) { // ignore } + rs = null; + } + if (stmt != null) { + try { + stmt.close(); + } + catch (SQLException sqlEx) { // ignore } + stmt = null; + } + } + } + } + //return null; + } + + public Blob getBlob(String Table, String blobColumnNname, + String columnNames, String newValues) { + if (Conn == null) { + return null; + } + + // assume conn is an already created JDBC connection + stmt = null; + rs = null; + String str = "SELECT " + blobColumnNname + " FROM " + Table + " WHERE "; + try { + stmt = Conn.createStatement(); + String temp[] = newValues.split(" "); + String temp2[] = columnNames.split(" "); + if ( (temp.length != temp2.length) || temp.length < 1) { + return null; + } + str += temp2[0] + "='" + temp[0] + "'"; + for (int i = 1; i < temp.length; i++) { + str += " && " + temp2[i] + "='" + temp[i] + "'"; + } + logger.info("getBlob: SQL Query: " + str); + stmt.executeQuery(str); + rs = stmt.getResultSet(); + rs.next(); + return rs.getBlob(blobColumnNname); + } + catch (SQLException ex) { + // handle any errors + errorMessage = "getBlob: SQLException: " + ex.getMessage(); + logger.info(errorMessage); + logger.info("SQLState: " + ex.getSQLState()); + logger.info("VendorError: " + ex.getErrorCode()); + return null; + } + /*finally { + // it is a good idea to release + // resources in a finally{} block + // in reverse-order of their creation + // if they are no-longer needed + if (rs != null) { + try { + rs.close(); + } catch (SQLException sqlEx) { // ignore } + rs = null; + } + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException sqlEx) { // ignore } + stmt = null; + } + } + } + } + */ + //return null; + } + + public byte[] getBytes(String Table, String blobColumnNname, + String columnNames, String newValues) { + if (Conn == null) { + return null; + } + + // assume conn is an already created JDBC connection + stmt = null; + rs = null; + String str = "SELECT " + blobColumnNname + " FROM " + Table + " WHERE "; + try { + stmt = Conn.createStatement(); + String temp[] = newValues.split(" "); + String temp2[] = columnNames.split(" "); + if ( (temp.length != temp2.length) || temp.length < 1) { + return null; + } + str += temp2[0] + "='" + temp[0] + "'"; + for (int i = 1; i < temp.length; i++) { + str += " && " + temp2[i] + "='" + temp[i] + "'"; + } + logger.info("getBytes: SQL Query: " + str); + stmt.executeQuery(str); + rs = stmt.getResultSet(); + rs.next(); + Blob blob = rs.getBlob(blobColumnNname); + return blob.getBytes(1L, (int) blob.length()); + } + catch (SQLException ex) { + // handle any errors + errorMessage = "getBytes: SQLException: " + ex.getMessage(); + logger.info(errorMessage); + logger.info("SQLState: " + ex.getSQLState()); + logger.info("VendorError: " + ex.getErrorCode()); + return null; + } + } + + /* + public boolean setBlob(String Table, String blobColumnNname, String columnNames, String newValues, Blob myBlob ) { + if (Conn == null) { + return false; + } + + // assume conn is an already created JDBC connection + stmt = null; + rs = null; + String str = "UPDATE " + Table + " SET " + blobColumnNname + " = ? WHERE "; + try { + stmt = Conn.createStatement(); + String temp[] = newValues.split(" "); + String temp2[] = columnNames.split(" "); + if ( (temp.length != temp2.length) || temp.length < 1 ) return false; + str += temp2[0] + "='" + temp[0] + "'"; + for (int i=1; i 255 ? 255 : (int) cl.length()); + logger.info("getClob: substring: " + str); + errorHappened = false; + return rs.getClob(clobColumnNname); + } + catch (SQLException ex) { + // handle any errors + errorHappened = true; + errorMessage = "getClob: SQLException: " + ex.getMessage(); + logger.info(errorMessage); + logger.info("SQLState: " + ex.getSQLState()); + logger.info("VendorError: " + ex.getErrorCode()); + return null; + } + /*finally { + // it is a good idea to release + // resources in a finally{} block + // in reverse-order of their creation + // if they are no-longer needed + if (rs != null) { + try { + rs.close(); + } catch (SQLException sqlEx) { // ignore } + rs = null; + } + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException sqlEx) { // ignore } + stmt = null; + } + } + } + } + */ + //return null; + } + + public boolean setClob(String Table, String clobColumnNname, + String columnNames, String newValues, Clob myClob) { + if (Conn == null) { + return false; + } + + // assume conn is an already created JDBC connection + stmt = null; + rs = null; + //String str = "SELECT " + blobColumnNname + " FROM " + Table + " WHERE "; + String str = "UPDATE " + Table + " SET " + clobColumnNname + + " = ? WHERE "; + try { + String temp[] = newValues.split(","); + String temp2[] = columnNames.split(","); + if ( (temp.length != temp2.length) || temp.length < 1) { + return false; + } + str += temp2[0] + "='" + temp[0] + "'"; + for (int i = 1; i < temp.length; i++) { + str += " && " + temp2[i] + "='" + temp[i] + "'"; + } + /* + stmt = Conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, + ResultSet.CONCUR_UPDATABLE ); + logger.info("setBlob: Query: " + str); + rs = stmt.executeQuery( str ); + if ( rs.getConcurrency() != ResultSet.CONCUR_UPDATABLE ) { + logger.info("setBlob: ResultSet is not updatable..."); + return false; + } + //rs = stmt.getResultSet(); + rs.next(); + Blob xxx = rs.getBlob(blobColumnNname); + byte bytes[] = ";wlehfkwjefbk;wjef".getBytes(); + xxx.setBytes(1,bytes); + logger.info("setBlob: xxx Blob length: " + xxx.length() ); + + rs.updateBlob(blobColumnNname, xxx); + rs.updateRow(); + //rs.updateBlob( blobColumnNname, myBlob); + //return rs.getBlob( blobColumnNname ); + */ + logger.info("setClob: myClob Clob length: " + myClob.length()); + logger.info("setBlob: SQL Query: " + str); + pstmt = Conn.prepareStatement(str); + pstmt.setClob(1, myClob); + pstmt.executeUpdate(); + errorHappened = false; + return true; + } + catch (SQLException ex) { + // handle any errors + errorHappened = true; + errorMessage = "setBlob: SQLException: " + ex.getMessage(); + logger.info(errorMessage); + logger.info("SQLState: " + ex.getSQLState()); + logger.info("VendorError: " + ex.getErrorCode()); + return false; + } + finally { + // it is a good idea to release + // resources in a finally{} block + // in reverse-order of their creation + // if they are no-longer needed + if (rs != null) { + try { + rs.close(); + } + catch (SQLException sqlEx) { // ignore } + rs = null; + } + if (stmt != null) { + try { + stmt.close(); + } + catch (SQLException sqlEx) { // ignore } + stmt = null; + } + } + } + } + //return null; + //return false; + } + + public String getUser() { + if (Conn == null) { + return null; + } + + // assume conn is an already created JDBC connection + stmt = null; + rs = null; + String str = "SELECT CURRENT_USER"; + try { + stmt = Conn.createStatement(); + logger.info("getUser: SQL Query: " + str); + stmt.executeQuery(str); + rs = stmt.getResultSet(); + rs.next(); + String user = rs.getString(1); + logger.info("getUser: User: " + user); + errorHappened = false; + return user; + } + catch (SQLException ex) { + // handle any errors + errorHappened = true; + errorMessage = "getUser: SQLException: " + ex.getMessage(); + logger.info(errorMessage); + logger.info("SQLState: " + ex.getSQLState()); + logger.info("VendorError: " + ex.getErrorCode()); + return null; + } + /*finally { + // it is a good idea to release + // resources in a finally{} block + // in reverse-order of their creation + // if they are no-longer needed + if (rs != null) { + try { + rs.close(); + } catch (SQLException sqlEx) { // ignore } + rs = null; + } + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException sqlEx) { // ignore } + stmt = null; + } + } + } + } + */ + //return null; + + } + + public int getLastInsertId(String tableName) { + if (Conn == null) { + errorHappened = true; + errorMessage = "getLastInsertId: No connection to database"; + return -1; + } + + // assume conn is an already created JDBC connection + int insertedId = -1; + stmt = null; + rs = null; + ResultSetMetaData rsmd; + String str = null; + + // ArrayList columns = null; + + try { + stmt = Conn.createStatement(); + str = "SELECT LAST_INSERT_ID() FROM " + tableName + " LIMIT 1"; + logger.info("SQL Query: " + str); + if (!stmt.execute(str)) { + errorHappened = true; + errorMessage = "getLastInsertId: cannot execute statement"; + return -1; + } + rs = stmt.getResultSet(); + rsmd = rs.getMetaData(); + if (rsmd.getColumnCount() < 1) { + return -1; + } + + rs.next(); + + insertedId = rs.getInt(1); + errorHappened = false; + /* + columns = new ArrayList(); + + while (rs.next()) { + HashMap info = new HashMap(); + for (int i = 1; i <= rsmd.getColumnCount(); i++) { + if (rsmd.getColumnTypeName(i).compareToIgnoreCase("CHAR") == + 0 || + rsmd.getColumnTypeName(i).compareToIgnoreCase("VARCHAR") == + 0 || + rsmd.getColumnTypeName(i).compareToIgnoreCase("TEXT") == + 0) { + info.put(rsmd.getColumnName(i), rs.getString(i)); + } + else + if (rsmd.getColumnTypeName(i).compareToIgnoreCase("FLOAT") == + 0) { + info.put(rsmd.getColumnName(i), new Float(rs.getFloat(i))); + } + else if (rsmd.getColumnTypeName(i).compareToIgnoreCase("INTEGER") == + 0) { + info.put(rsmd.getColumnName(i), new Integer(rs.getInt(i))); + } + else if (rsmd.getColumnTypeName(i).compareToIgnoreCase( + "INTEGER UNSIGNED") == 0) { + info.put(rsmd.getColumnName(i), new Integer(rs.getInt(i))); + } + + // --- General case + else { + info.put(rsmd.getColumnName(i), rs.getString(i)); + } + + } + columns.add(info); + //logger.info(rs.getString(1)); + } + */ + + } + catch (SQLException ex) { + // handle any errors + errorHappened = true; + errorMessage = "SQLException: " + ex.getMessage(); + logger.info(errorMessage); + logger.info("SQLState: " + ex.getSQLState()); + logger.info("VendorError: " + ex.getErrorCode()); + return -1; + } + finally { + // it is a good idea to release + // resources in a finally{} block + // in reverse-order of their creation + // if they are no-longer needed + if (rs != null) { + try { + rs.close(); + } + catch (SQLException sqlEx) { // ignore } + rs = null; + } + if (stmt != null) { + try { + stmt.close(); + } + catch (SQLException sqlEx) { // ignore } + stmt = null; + } + } + } + } + return insertedId; + } + +} diff --git a/src/main/java/cct/database/SQLTools.java b/src/main/java/cct/database/SQLTools.java new file mode 100644 index 0000000..99e4ab9 --- /dev/null +++ b/src/main/java/cct/database/SQLTools.java @@ -0,0 +1,166 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.database; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.logging.Logger; + +/** + * + * @author vvv900 + */ +public class SQLTools { + + public enum SQL_ENGINE { + + MySQL, PostgresSQL, GenericSQL, OracleSQL, SQLite + } + + private static Logger logger = Logger.getLogger(SQLTools.class.getCanonicalName()); + + /** + * Executes arbitrary SQL script + * + * @param script - collection of SQL commands + * @param connection - Connection + * @throws Exception + */ + public static void executeSQLScript(String script, Connection connection) throws Exception { + executeSQLScript(script, connection, SQL_ENGINE.GenericSQL); + } + + public static void executeSQLScript(String script, Connection connection, String sqlEngine) throws Exception { + SQL_ENGINE engine = SQL_ENGINE.GenericSQL; + SQL_ENGINE[] values = SQL_ENGINE.values(); + for (SQL_ENGINE iter : values) { + if (iter.toString().equalsIgnoreCase(sqlEngine)) { + engine = iter; + break; + } + } + executeSQLScript(script, connection, engine); + } + + public static void executeSQLScript(String script, Connection connection, SQL_ENGINE sqlEngine) throws Exception { + + Statement statement = connection.createStatement(); + + BufferedReader in = new BufferedReader(new FileReader(script)); + String line; + StringBuilder query = new StringBuilder(1024); + while ((line = in.readLine()) != null) { + line = line.trim(); + if (line.startsWith("-- ") || line.startsWith("#")) { + continue; + } else if (line.length() < 1) { + continue; + } + query.append(line + "\n"); + if (line.endsWith(";")) { + try { + String sqlQuery = query.toString().trim(); + if (sqlEngine == SQL_ENGINE.SQLite) { + // -- drop these lines + if (sqlQuery.matches("(?s)(DROP|drop)\\s+(DATABASE|database).*") + || sqlQuery.matches("(?s)(CREATE|create)\\s+(DATABASE|database).*") + || sqlQuery.matches("(?s)(USE|use)\\s+.*") + || sqlQuery.matches("(?s)(SET|set)\\s+(FOREIGN_KEY_CHECKS|foreign_key_checks).*")) { + System.out.println("Skiping command for " + SQL_ENGINE.SQLite.toString() + ": " + sqlQuery); + query.delete(0, query.length()); + continue; + } + + // --- Modify string for SQLite + sqlQuery = modifySQLStringForSQLite(sqlQuery); + } + statement.executeUpdate(sqlQuery); + query.delete(0, query.length()); + } catch (Exception ex) { + logger.severe("Cannot execute query =====\n" + query.toString() + "\n======================\nReason: " + + ex.getMessage()); + throw new Exception("Cannot execute query =====\n" + query.toString() + "\n======================\nReason: " + + ex.getMessage()); + } + } + } + + System.out.println("SQL Script " + script + " was successfuly executed"); + } + + static public String modifySQLStringForSQLite(String sql) { + sql = sql.replaceAll("(?s)(CHARACTER|character)", ""); + sql = sql.replaceAll("(?s)(AUTO_INCREMENT|auto_increment)", ""); + sql = sql.replaceAll("(?s)(SET|set)\\s+\\w+", ""); + sql = sql.replaceAll("(?s)(COLLATE|collate)\\s+utf8\\w+", "collate NOCASE"); + sql = sql.replaceAll("(?s)(INT|int)[(]\\d+[)]", "INTEGER"); + sql = sql.replaceAll("(?s)(DOUBLE|double)([(]\\d+[)]|[(]\\d+[,]\\d+[)])", "REAL"); + sql = sql.replaceAll("(?s)(FLOAT|float)([(]\\d+[)]|[(]\\d+[,]\\d+[)])", "REAL"); + sql = sql.replaceAll("(?s)(ENGINE|engine)\\s*=\\s*\\w+", ""); + return sql; + } + + /** + * Checks a table named for existence + * + * @param con - Connection + * @param tableName - table name + * @return - true if table exists, false otherwise + * @throws Exception + */ + public static boolean isTableExists(Connection con, String tableName) throws Exception { + DatabaseMetaData dbm = con.getMetaData(); + ResultSet tables = dbm.getTables(null, null, tableName, null); + if (tables.next()) { + // Table exists + logger.info("Table " + tableName + " exists"); + return true; + } else { + // Table does not exist + logger.info("Table " + tableName + " does not exist"); + return false; + } + } + + /** + * Tries to delete table in DB + * + * @param con - Connection + * @param tableName - table name + * @return either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements + * that return nothing + * @throws Exception + */ + public static int deleteTable(Connection con, String tableName) throws Exception { + + Statement st = con.createStatement(); + int res = st.executeUpdate("DROP TABLE IF EXISTS `" + tableName + "`"); + logger.info("Deleting Table: " + res); + return res; + } + + /** + * Execute update query + * + * @param con - Connection + * @param updateQuery - SQL update query + * @return either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements + * that return nothing + * @throws Exception + */ + public static int executeUpdate(Connection con, String updateQuery) throws Exception { + + Statement st = con.createStatement(); + logger.info("Executing update: " + updateQuery); + int res = st.executeUpdate(updateQuery); + logger.info("Executed update: " + res); + return res; + } +} diff --git a/src/main/java/cct/database/TablesDescription.java b/src/main/java/cct/database/TablesDescription.java new file mode 100644 index 0000000..b602619 --- /dev/null +++ b/src/main/java/cct/database/TablesDescription.java @@ -0,0 +1,99 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.database; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public interface TablesDescription { + String MoleculeTable = "Molecules"; + String StructureTable = "Structures"; + String MethodsTable = "Methods"; + String BasisSetsTable = "BasisSets"; + String PropertiesTypeTable = "Prop_types"; + String PropertiesTable = "Properties"; + + String moleculeIdKey = "Molec_Id"; + String moleculeNameKey = "MolName"; + String moleculeAliasesKey = "Aliases"; + String moleculeIsModelKey = "IsModel"; + String moleculeChargeKey = "Charge"; + String moleculeMultiplicityKey = "Multiplicity"; + String moleculeNotesKey = "Notes"; + String moleculeUserKey = "User"; + String moleculeFormulaKey = "Formula"; + String moleculeWeightKey = "Weight"; + + String structureIdKey = "Struct_Id"; + String structureNameKey = "StrName"; + String structureNotesKey = "Notes"; + String structureUserKey = "User"; + String structureKey = "Structure3d"; + + String methodNameKey = "MethodName"; + String methodExpKey = "IsExperiment"; + String methodFixedBasisKey = "IsFixedBasis"; + String methodEffectiveCorePKey = "IsEffectiveCoreP"; + String methodDFTPKey = "IsDFT"; + String methodNotesKey = "Notes"; + + String basisSetsNameKey = "BSName"; + + String PropertyTypeNameKey = "PropName"; + String PropertyTypeIsTextKey = "IsText"; + String PropertyTypeIsVectorKey = "IsVector"; + String PropertyTypeIsFloatKey = "IsFloat"; + String PropertyTypeNotesKey = "Notes"; + + String propertiesNameKey = PropertyTypeNameKey; + String propertiesMethodKey = methodNameKey; + String propertiesValueKey = "Value"; + String propertiesVectorKey = "ManyValues"; + String propertiesNotesKey = "Notes"; + String propertiesStructId = structureIdKey; + +} diff --git a/src/main/java/cct/database/jamberoo.sql b/src/main/java/cct/database/jamberoo.sql new file mode 100644 index 0000000..c53cb09 --- /dev/null +++ b/src/main/java/cct/database/jamberoo.sql @@ -0,0 +1,328 @@ +-- ============================================================================= +-- Diagram Name: jamberoo +-- Created on: 25/11/2014 4:47:00 PM +-- Diagram Version: 1.0 +-- ============================================================================= +DROP DATABASE IF EXISTS `jamberoo`; + +-- ------------------------------------------------------------ +-- Description: +-- Chemistry structural database +-- Version 1.0 +-- ------------------------------------------------------------ + +-- ------------------------------------------------------------ +-- Annotation: +-- Version 1.0 +-- ------------------------------------------------------------ + +CREATE DATABASE IF NOT EXISTS `jamberoo` +CHARACTER SET utf8 +COLLATE utf8_general_ci; + +USE `jamberoo`; + +SET FOREIGN_KEY_CHECKS=0; + +-- Drop table StructureTypes +DROP TABLE IF EXISTS `StructureTypes`; + +CREATE TABLE `StructureTypes` ( + `type` char(25) NOT NULL DEFAULT 'Unknown', + PRIMARY KEY(`type`) +) +ENGINE=INNODB; + +insert into `StructureTypes` (`type`) values +('Minimum'), +('Local minimum'), +('Global minimum'), +('Transition state'); + +-- Drop table GeneralPropertiesTypes +DROP TABLE IF EXISTS `GeneralPropertiesTypes`; + +CREATE TABLE `GeneralPropertiesTypes` ( + `propertyName` char(50) NOT NULL, + `description` varchar(255), + PRIMARY KEY(`propertyName`) +) +ENGINE=INNODB; + +-- Drop table PropertyTypes +DROP TABLE IF EXISTS `PropertyTypes`; + +CREATE TABLE `PropertyTypes` ( + `propertyName` char(50) NOT NULL, + `description` varchar(255), + PRIMARY KEY(`propertyName`) +) +ENGINE=INNODB; + +-- Drop table Elements +DROP TABLE IF EXISTS `Elements`; + +CREATE TABLE `Elements` ( + `name` char(50) NOT NULL, + `symbol` char(10) NOT NULL, + `atomicNumber` int(11) UNSIGNED NOT NULL, + `standardAtomicWeight` double(15,3) UNSIGNED NOT NULL, + PRIMARY KEY(`name`) +) +ENGINE=INNODB; + +insert into `Elements` (`name`, `symbol`,`atomicNumber`,`standardAtomicWeight`) values +('Hydrogen','H',1,1.008), +('Helium','He',2,4.002602), +('Lithium','Li',3,6.94), +('Beryllium','Be',4,9.0121831), +('Boron','B',5,10.81), +('Carbon','C',6,12.011), +('Nitrogen','N',7,14.007), +('Oxygen','O',8,15.999), +('Fluorine','F',9,18.998403163), +('Neon','Ne',10,20.1797), +('Sodium','Na',11,22.98976928), +('Magnesium','Mg',12,24.305), +('Aluminium','Al',13,26.9815385), +('Silicon','Si',14,28.085), +('Phosphorus','P',15,30.973761998), +('Sulfur','S',16,32.06), +('Chlorine','Cl',17,35.45), +('Argon','Ar',18,39.948), +('Potassium','K',19,39.0983), +('Calcium','Ca',20,40.08), +('Scandium','Sc',21,44.9559), +('Titanium','Ti',22,47.9), +('Vanadium','V',23,50.9415), +('Chromium','Cr',24,51.996), +('Manganese','Mn',25,54.938), +('Iron','Fe',26,55.847), +('Cobalt','Co',27,58.9332), +('Nickel','Ni',28,58.71), +('Copper','Cu',29,63.546), +('Zinc','Zn',30,65.38), +('Gallium','Ga',31,65.735), +('Germanium','Ge',32,72.59), +('Arsenic','As',33,74.9216), +('Selenium','Se',34,78.96), +('Bromine','Br',35,79.904), +('Krypton','Kr',36,83.8), +('Rubidium','Rb',37,85.467), +('Strontium','Sr',38,87.62), +('Yttrium','Y',39,88.9059), +('Zirconium','Zr',40,91.22), +('Niobium','Nb',41,92.9064), +('Molybdenum','Mo',42,95.94), +('Technetium','Tc',43,98.9062), +('Ruthenium','Ru',44,101.07), +('Rhodium','Rh',45,102.9055), +('Palladium','Pd',46,106.4), +('Silver','Ag',47,107.868), +('Cadmium','Cd',48,112.41), +('Indium','In',49,114.82), +('Tin','Sn',50,118.69), +('Antimony','Sb',51,121.75), +('Tellurium','Te',52,127.6), +('Iodine','I',53,126.9045), +('Xenon','Xe',54,131.3), +('Cesium','Cs',55,132.9054), +('Barium','Ba',56,137.33), +('Lanthanum','La',57,138.9055), +('Cerium','Ce',58,140.12), +('Praseodymium','Pr',59,140.9077), +('Neodymium','Nd',60,144.24), +('Promethium','Pm',61,145.0), +('Samarium','Sm',62,150.4), +('Europium','Eu',63,151.96), +('Gadolinium','Gd',64,157.25), +('Terbium','Tb',65,158.9254), +('Dysprosium','Dy',66,162.5), +('Holmium','Ho',67,164.9304), +('Erbium','Er',68,167.26), +('Thulium','Tm',69,168.9342), +('Ytterbium','Yb',70,173.04), +('Lutetium','Lu',71,174.967), +('Hafnium','Hf',72,178.49), +('Tantalum','Ta',73,180.9479), +('Tungsten','W',74,183.85), +('Rhenium','Re',75,186.207), +('Osmium','Os',76,190.2), +('Iridium','Ir',77,192.22), +('Platinum','Pt',78,195.09), +('Gold','Au',79,196.9665), +('Mercury','Hg',80,200.59), +('Thallium','Tl',81,204.37), +('Lead','Pb',82,207.2), +('Bismuth','Bi',83,208.9804), +('Polonium','Po',84,209.0), +('Astatine','At',85,210.0), +('Radon','Rn',86,222.0), +('Francium','Fr',87,223.0), +('Radium','Ra',88,226.0254), +('Actinium','Ac',89,227.0), +('Thorium','Th',90,232.0381), +('Protactinium','Pa',91,231.0359), +('Uranium','U',92,238.029), +('Neptunium','Np',93,237.0482), +('Plutonium','Pu',94,244.0), +('Americium','Am',95,243.0), +('Curium','Cm',96,247.0), +('Berkelium','Bk',97,247.0), +('Californium','Cf',98,251.0), +('Einsteinium','Es',99,254.0), +('Fermium','Fm',100,257.0), +('Mendelevium','Md',101,258.0), +('Nobelium','No',102,259.0), +('Lawrencium','Lr',103,260.0), +('Rutherfordium','Rf',104,260.0), +('Dubnium','Db',105,260.0), +('Seaborgium','Sg',106,266.0), +('Bohrium','Bh',107,261.0), +('Hahnium','Hn',108,264.0), +('Meitnerium','Mt',109,266.0); + +-- Drop table Compounds +DROP TABLE IF EXISTS `Compounds`; + +CREATE TABLE `Compounds` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `name` char(255) NOT NULL, + `description` varchar(1024) DEFAULT ' ', + `genericWeight` float(9,3) UNSIGNED DEFAULT '0.0', + `genericFormula` char(50) NOT NULL, + `generic3dStructure` longtext, + `numberAtoms` int(11) UNSIGNED NOT NULL, + PRIMARY KEY(`id`) +) +ENGINE=INNODB; + +-- Drop table Methods +DROP TABLE IF EXISTS `Methods`; + +CREATE TABLE `Methods` ( + `methodName` varchar(100) NOT NULL, + `description` varchar(512) DEFAULT ' ', + PRIMARY KEY(`methodName`) +) +ENGINE=INNODB; + +insert into `Methods` (`methodName`, `description`) values +('HF/3-21G','Hartree-Fock method using 3-21G basis set'), +('HF/3-21G//IEFPCM=WATER','Hartree-Fock method using 3-21G basis set + default Gaussian PCM method (scrf=(solvent=water)) with water as a solvent'), +('HF/6-31G','Hartree-Fock method using 6-31G basis set'), +('HF/6-31G//IEFPCM=WATER','Hartree-Fock method using 6-31G basis set + default Gaussian PCM method (scrf=(solvent=water)) with water as a solvent'), +('B3LYP/6-31G(d,p)','DFT B3LYP method using 6-31G(d,p) basis set'), +('B3LYP/6-31G(d,p)//IEFPCM=WATER','DFT B3LYP method using 6-31G(d,p) basis set + default Gaussian PCM method (scrf=(solvent=water)) with water as a solvent'), +('B3LYP/aug-cc-pVDZ','DFT B3LYP method using aug-cc-pVDZ basis set'), +('B3LYP/aug-cc-pVDZ//IEFPCM=WATER','DFT B3LYP method using aug-cc-pVDZ basis set + default Gaussian PCM method (scrf=(solvent=water)) with water as a solvent'), +('B3LYP/aug-cc-pVTZ','DFT B3LYP method using aug-cc-pVTZ basis set'), +('B3LYP/aug-cc-pVTZ//IEFPCM=WATER','DFT B3LYP method using aug-cc-pVTZ basis set + default Gaussian PCM method (scrf=(solvent=water)) with water as a solvent'), +('B3LYP/aug-cc-pVQZ','DFT B3LYP method using aug-cc-pVQZ basis set'), +('B3LYP/aug-cc-pVQZ//IEFPCM=WATER','DFT B3LYP method using aug-cc-pVQZ basis set + default Gaussian PCM method (scrf=(solvent=water)) with water as a solvent'), +('CAM-B3LYP/aug-cc-pVTZ/Def2TZV','DFT CAM-B3LYP method using aug-cc-pVTZ basis set and Def2TZV as a fitting b.s.'), +('CAM-B3LYP/aug-cc-pVTZ/Def2TZV//IEFPCM=WATER','DFT CAM-B3LYP method using aug-cc-pVTZ basis set and Def2TZV as a fitting b.s. + default Gaussian PCM method (scrf=(solvent=water)) with water as a solvent'), +('MP2/aug-cc-pVDZ','MP2 method using aug-cc-pVDZ basis set'), +('MP2/aug-cc-pVDZ//IEFPCM=WATER','MP2 method using aug-cc-pVDZ basis set + default Gaussian PCM method (scrf=(solvent=water)) with water as a solvent'), +('MP2/aug-cc-pVTZ','MP2 method using aug-cc-pVTZ basis set'), +('MP2/aug-cc-pVTZ//IEFPCM=WATER','MP2 method using aug-cc-pVTZ basis set + default Gaussian PCM method (scrf=(solvent=water)) with water as a solvent'), +('Unknown','Unknown method'); + +-- Drop table Aliases +DROP TABLE IF EXISTS `Aliases`; + +CREATE TABLE `Aliases` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `aliasName` varchar(50) NOT NULL, + `description` varchar(255), + `idCompound` int(11) UNSIGNED NOT NULL DEFAULT '0', + PRIMARY KEY(`id`), + CONSTRAINT `alias2compound` FOREIGN KEY (`idCompound`) + REFERENCES `Compounds`(`id`) + ON DELETE CASCADE + ON UPDATE CASCADE +) +ENGINE=INNODB; + +-- Drop table ElementContents +DROP TABLE IF EXISTS `ElementContents`; + +CREATE TABLE `ElementContents` ( + `int` int(11) UNSIGNED NOT NULL, + `idCompound` int(11) UNSIGNED NOT NULL DEFAULT '0', + `element` char(50) NOT NULL, + CONSTRAINT `elementContent2compounds` FOREIGN KEY (`idCompound`) + REFERENCES `Compounds`(`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `elementContent2element` FOREIGN KEY (`element`) + REFERENCES `Elements`(`name`) + ON DELETE NO ACTION + ON UPDATE NO ACTION +) +ENGINE=INNODB; + +-- Drop table Conformers +DROP TABLE IF EXISTS `Conformers`; + +CREATE TABLE `Conformers` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `name` char(50) NOT NULL, + `description` varchar(255), + `idCompoundFK` int(11) UNSIGNED NOT NULL DEFAULT '0', + `typeFK` char(25) NOT NULL, + PRIMARY KEY(`id`), + CONSTRAINT `conformer2compound` FOREIGN KEY (`idCompoundFK`) + REFERENCES `Compounds`(`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `conformer2structureType` FOREIGN KEY (`typeFK`) + REFERENCES `StructureTypes`(`type`) + ON DELETE CASCADE + ON UPDATE CASCADE +) +ENGINE=INNODB; + +-- Drop table GeneralProperties +DROP TABLE IF EXISTS `GeneralProperties`; + +CREATE TABLE `GeneralProperties` ( + `propertyNameFK` char(50) NOT NULL, + `idCompound` int(11) UNSIGNED NOT NULL DEFAULT '0', + CONSTRAINT `property2type` FOREIGN KEY (`propertyNameFK`) + REFERENCES `GeneralPropertiesTypes`(`propertyName`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `generalProperty2compound` FOREIGN KEY (`idCompound`) + REFERENCES `Compounds`(`id`) + ON DELETE CASCADE + ON UPDATE CASCADE +) +ENGINE=INNODB; + +-- Drop table Properties +DROP TABLE IF EXISTS `Properties`; + +CREATE TABLE `Properties` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `property` longtext NOT NULL, + `propertyNameFK` char(50) NOT NULL, + `methodNameFK` varchar(100) NOT NULL, + `idMethodFK` int(11) UNSIGNED NOT NULL DEFAULT '0', + PRIMARY KEY(`id`), + CONSTRAINT `property2propertyType` FOREIGN KEY (`propertyNameFK`) + REFERENCES `PropertyTypes`(`propertyName`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `property2method` FOREIGN KEY (`methodNameFK`) + REFERENCES `Methods`(`methodName`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `property2conformer` FOREIGN KEY (`idMethodFK`) + REFERENCES `Conformers`(`id`) + ON DELETE CASCADE + ON UPDATE CASCADE +) +ENGINE=INNODB; + +SET FOREIGN_KEY_CHECKS=1; diff --git a/src/main/java/cct/database/new_ChemistryDatabaseDialog.java b/src/main/java/cct/database/new_ChemistryDatabaseDialog.java new file mode 100644 index 0000000..6eac200 --- /dev/null +++ b/src/main/java/cct/database/new_ChemistryDatabaseDialog.java @@ -0,0 +1,758 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.database; + +import java.awt.Button; +import java.awt.Dialog; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Logger; + +import cct.awtdialogs.AddNewMoleculeDialog; +import cct.awtdialogs.AddNewStructureDialog; +import cct.awtdialogs.MessageWindow; +import cct.awtdialogs.TextEntryDialog; +import cct.interfaces.MoleculeInterface; +import cct.j3d.Java3dUniverse; +import cct.modelling.Molecule; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class new_ChemistryDatabaseDialog + extends Dialog implements ActionListener, ItemListener, TablesDescription { + + java.awt.List Molecules = null, Structures = null; + java.awt.List Methods = null, BasisSets = null; + Java3dUniverse target; + TextField name, formula, aliases; + new_SQLChemistryDatabase sql_data; + int SelectedMolecule = 0; + java.util.List allMolecules = null; + java.util.List allStructures = null; + java.util.List structuresIndex = null; + java.util.List allMethods = null; + java.util.List allBasisSets = null; + String oldName; + boolean error = false; + // Names for controls + static String controlMolList = "mollist"; + static String controlStrList = "strlist"; + static String controlMolName = "molname"; + static String controlButtonOK = "buttonOK"; + static final Logger logger = Logger.getLogger(new_ChemistryDatabaseDialog.class.getCanonicalName()); + + public new_ChemistryDatabaseDialog(Java3dUniverse target, new_SQLChemistryDatabase database, + String Title, boolean modal) { + super(new Frame(), Title, modal); + this.target = target; + sql_data = database; + + java.util.List items = sql_data.getMolecules(); + + GridBagLayout gridbag = new GridBagLayout(); + + setLayout(gridbag); + + // --- + + GridBagConstraints c = new GridBagConstraints(); + c.gridx = 0; + c.gridy = 0; + c.gridwidth = 2; + c.gridheight = 20; + //c.weightx = 1; + //c.weighty = 1; + c.fill = GridBagConstraints.BOTH; + c.insets = new Insets(3, 3, 3, 3); + + Molecules = new java.awt.List(10, false); + Molecules.setName(controlMolList); + + Molecules.addActionListener(this); + Molecules.addItemListener(this); + + gridbag.setConstraints(Molecules, c); + add(Molecules); + + // --- + + GridBagConstraints structureC = new GridBagConstraints(); + structureC.gridx = 2; + structureC.gridy = 0; + structureC.gridwidth = 1; //end row + structureC.gridheight = 15; + structureC.fill = GridBagConstraints.BOTH; + structureC.insets = new Insets(3, 3, 3, 3); + + Structures = new java.awt.List(15, false); + Structures.setName(controlStrList); + + Structures.addActionListener(this); + Structures.addItemListener(this); + + gridbag.setConstraints(Structures, structureC); + add(Structures); + + updateData(); + + // --- + + GridBagConstraints addMolC = new GridBagConstraints(); + + addMolC.gridwidth = 1; //end row + addMolC.gridheight = 1; //reset to the default + addMolC.gridx = 2; + addMolC.gridy = 15; + addMolC.fill = GridBagConstraints.BOTH; + addMolC.insets = new Insets(3, 3, 3, 3); + + Button addMol = new Button("Add Molecule"); + gridbag.setConstraints(addMol, addMolC); + add(addMol); + addMol.addActionListener(this); + + // --- + + GridBagConstraints delMolC = new GridBagConstraints(); + + delMolC.gridx = 2; + delMolC.gridy = 16; + delMolC.gridwidth = 1; //end row + delMolC.gridheight = 1; //reset to the default + delMolC.fill = GridBagConstraints.BOTH; + + Button delMol = new Button("Delete Molecule"); + gridbag.setConstraints(delMol, delMolC); + add(delMol); + delMol.addActionListener(this); + + // --- + + GridBagConstraints addStrC = new GridBagConstraints(); + + addStrC.gridx = 2; + addStrC.gridy = 17; + addStrC.gridwidth = 1; //end row + addStrC.gridheight = 1; //reset to the default + + Button addStr = new Button("Add Structure"); + gridbag.setConstraints(addStr, addStrC); + add(addStr); + addStr.addActionListener(this); + + // ---- + + GridBagConstraints delStrC = new GridBagConstraints(); + + delStrC.gridx = 2; + delStrC.gridy = 18; + delStrC.gridwidth = GridBagConstraints.REMAINDER; //end row + delStrC.gridheight = 1; //reset to the default + + Button delStr = new Button("Delete Structure"); + gridbag.setConstraints(delStr, delStrC); + add(delStr); + delStr.addActionListener(this); + + // --- + GridBagConstraints loadStrC = new GridBagConstraints(); + + loadStrC.gridx = 2; + loadStrC.gridy = 19; + loadStrC.gridwidth = GridBagConstraints.REMAINDER; //end row + loadStrC.gridheight = 1; //reset to the default + + Button loadStr = new Button("Retrieve Structure"); + gridbag.setConstraints(loadStr, loadStrC); + add(loadStr); + loadStr.addActionListener(this); + + // --- + + GridBagConstraints hideC = new GridBagConstraints(); + + hideC.gridx = 1; + hideC.gridy = 21; + hideC.gridwidth = 1; + hideC.gridheight = 1; + hideC.fill = GridBagConstraints.BOTH; + + Button OK = new Button("Hide"); + OK.addActionListener(this); + gridbag.setConstraints(OK, hideC); + add(OK); + + name = new TextField(20); + + /* + //FlowLayout sizer = new FlowLayout( FlowLayout.CENTER); + GridLayout sizer = new GridLayout(0, 2, 5, 5); + setLayout(sizer); + + Molecules = new java.awt.List(10, false); + + allMolecules = sql_data.getMolecules(); + for (int i = 0; i < allMolecules.size(); i++) { + HashMap row = (HashMap) allMolecules.get(i); + Molecules.add(row.get(moleculeNameKey).toString()); + } + SelectedMolecule = 0; + HashMap row = (HashMap) allMolecules.get(SelectedMolecule); + String currentMolecule = row.get(moleculeNameKey).toString(); + + Molecules.select(SelectedMolecule); + Molecules.setName(controlMolList); + add(Molecules); + + allStructures = sql_data.getStructures(); + Structures = new java.awt.List(10, false); + + for (int i = 0; i < allStructures.size(); i++) { + row = (HashMap) allStructures.get(i); + String name = row.get(moleculeNameKey).toString(); + if (name.compareToIgnoreCase(currentMolecule) == 0) { + Structures.add(row.get(structureMethodKey).toString()); + } + } + Structures.setName(controlStrList); + add(Structures); + + add(new Label("Name: ", Label.LEFT)); + name = new TextField(20); + name.setName(controlMolName); + name.setText(currentMolecule); + oldName = currentMolecule; // remember name + add(name); + name.addActionListener(this); + + add(new Label("Formula: ", Label.LEFT)); + formula = new TextField(20); + + add(new Label("Name Aliases: ", Label.LEFT)); + aliases = new TextField(20); + + Button addMol = new Button("Add Molecule"); + add(addMol); + addMol.addActionListener(this); + + Button delMol = new Button("Delete Molecule"); + add(delMol); + delMol.addActionListener(this); + + + Button addStr = new Button("Add Structure"); + add(addStr); + addStr.addActionListener(this); + + Button delStr = new Button("Delete Structure"); + add(delStr); + delStr.addActionListener(this); + + + Button loadStr = new Button("Retrieve Structure"); + add(loadStr); + loadStr.addActionListener(this); + + + Button OK = new Button("OK"); + add(OK); + */ + + + setSize(300, 450); + + } + + @Override + public void itemStateChanged(ItemEvent ie) { + String controlName = ie.getItemSelectable().toString(); + controlName = controlName.substring(controlName.indexOf('[') + 1); + controlName = controlName.substring(0, controlName.indexOf(',')); + + logger.info("Item: " + ie.getItem()); + logger.info("Item Selectable: " + ie.getItemSelectable()); + logger.info("ControlName: " + controlName); + + if (controlName.equals(controlMolList)) { + SelectedMolecule = Molecules.getSelectedIndex(); + selectMolecule(SelectedMolecule); + } else if (controlName.equals(controlStrList)) { + } + } + + /** + * + * @param ae ActionEvent + */ + @Override + public void actionPerformed(ActionEvent ae) { + + String controlName = ae.getSource().toString(); + controlName = controlName.substring(controlName.indexOf('[') + 1); + controlName = controlName.substring(0, controlName.indexOf(',')); + logger.info("controlName: " + controlName); + logger.info("ActionCommand: " + ae.getActionCommand()); + logger.info("paramString: " + ae.paramString()); + logger.info("getSource: " + ae.getSource()); + logger.info("getSource.getClass: " + ae.getSource().getClass()); + logger.info("getSource.hasgCode: " + ae.getSource().hashCode()); + + // --- Molecule name is changed + if (controlName.equals(controlMolName) + && isMoleculeNameUnique(name.getText())) { + // ??? for now... + if (sql_data.changeMoleculeName(oldName, name.getText())) { + Map row = (Map) allMolecules.get(SelectedMolecule); + row.put(moleculeNameKey, name.getText()); + String currentMolecule = row.get(moleculeNameKey).toString(); + Molecules.remove(SelectedMolecule); + Molecules.add(name.getText(), SelectedMolecule); + + for (int i = 0; i < allStructures.size(); i++) { + row = (Map) allStructures.get(i); + row.put(moleculeNameKey, name.getText()); + } + oldName = currentMolecule; + + } else { + // ERROR + } + } // --- New molecule from the list is selected + else if (controlName.equals(controlMolList)) { + SelectedMolecule = Molecules.getSelectedIndex(); + selectMolecule(SelectedMolecule); + } else if (ae.getActionCommand().toString().equals("Add Molecule")) { + TextEntryDialog new_name = new TextEntryDialog("Enter name for new molecule (unique)", true); + new_name.setVisible(true); + if (!new_name.isTextEntered()) { + return; + } + String str = new_name.getValue(); + + if (isMoleculeNameUnique(str)) { + AddNewMoleculeDialog new_mol = new AddNewMoleculeDialog("Adding New Molecule", true, str); + new_mol.setVisible(true); + if (!new_mol.isOKPressed()) { + return; + } + String aliases = new_mol.getAliases(); + String notes = new_mol.getNotes(); + boolean is_model = new_mol.isModel(); + int charge = new_mol.getCharge(); + int mult = new_mol.getMultiplicity(); + + if (sql_data.addNewMolecule(str, aliases, notes, is_model, charge, mult)) { + Map row = new HashMap(); + row.put(moleculeNameKey, str); + allMolecules.add(row); + SelectedMolecule = allMolecules.size() - 1; + oldName = str; + + Molecules.add(str); + Molecules.select(SelectedMolecule); + + Structures.removeAll(); + structuresIndex.clear(); + } + + } else { + MessageWindow er = new MessageWindow("ERROR", + "Molecule name is not unique!", true); + er.setVisible(true); + } + //dispose(); + + // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + // --- Delete Molecule and corresponding structures... + } else if (ae.getActionCommand().toString().equals("Delete Molecule")) { + SelectedMolecule = Molecules.getSelectedIndex(); + if (Molecules.getSelectedIndex() == -1) { + MessageWindow er = new MessageWindow("ERROR", + "Select Molecule first!", true); + er.setVisible(true); + return; + } + + Map row = (Map) allMolecules.get(SelectedMolecule); + String currentMolecule = row.get(moleculeNameKey).toString(); + + // --- First, delete all structures of a molecule + boolean err = false; + for (int i = 0; i < allStructures.size(); i++) { + row = (Map) allStructures.get(i); + String mol_name = (String) row.get(moleculeNameKey); + if (!mol_name.equals(Molecules.getSelectedItem())) { + continue; + } + + // Now it's SQL server busness to delete structures... + /* + String method = (String) row.get(structureMethodKey); + if (!sql_data.deleteStructure(Molecules.getSelectedItem(), + method)) { + MessageWindow er = new MessageWindow(parent, "ERROR", + "Cannot delete structure " + method + + ", so cannot delete molecule ", true); + er.setVisible(true); + return; + } + */ + } + + for (int i = allStructures.size() - 1; i >= 0; i--) { + row = (Map) allStructures.get(i); + String mol_name = (String) row.get(moleculeNameKey); + if (mol_name.equals(Molecules.getSelectedItem())) { + allStructures.remove(i); + } + } + + // --- Structures deleted, now we can delete molecule + + if (!sql_data.deleteMolecule(Molecules.getSelectedItem())) { + MessageWindow er = new MessageWindow("ERROR", + sql_data.getErrorMessage(), true); + er.setVisible(true); + return; + } + + allMolecules.remove(SelectedMolecule); + + // --- now we need to select a new molecule from the list + + updateMoleculesList(); + + if (SelectedMolecule >= allMolecules.size()) { + --SelectedMolecule; + } + Structures.removeAll(); + structuresIndex.clear(); + + if (SelectedMolecule < 0) { + return; + } + + Molecules.select(SelectedMolecule); + oldName = Molecules.getSelectedItem(); + + updateStructureList(Molecules.getSelectedItem()); + Structures.select(0); + + // -- Add new structure + } else if (ae.getActionCommand().toString().equals("Add Structure")) { + AddNewStructureDialog new_str = new AddNewStructureDialog("New Structure", + true, Molecules.getSelectedItem(), sql_data); + new_str.setVisible(true); + if (!new_str.isOKPressed()) { + return; + } + + String str_name = new_str.getName(); + String notes = new_str.getNotes(); + new_str.dispose(); // Don't need it any more + + logger.info("New Structure: " + str_name); + + /* + SelectMethodDialog md = new SelectMethodDialog(parent,"Select Method",true,allMethods,allBasisSets); + md.setVisible(true); + if (!md.isOKPressed()) { + return; + } + String method = md.getSelectedMethod(); + md.dispose(); + */ + String method = new_str.getMethod(); + + MoleculeInterface mol = target.getMolecule(); + Map row = sql_data.addNewStructure(Molecules.getSelectedItem(), str_name, notes, + method, mol); + if (row == null) { + MessageWindow er = new MessageWindow("ERROR", + sql_data.getErrorMessage(), true); + er.setVisible(true); + return; + } + allStructures.add(row); + + updateStructureList(Molecules.getSelectedItem()); + Structures.select(Structures.getItemCount() > 0 + ? Structures.getItemCount() - 1 : 0); + + } else if (ae.getActionCommand().toString().equals("Retrieve Structure")) { + if (Structures.getSelectedIndex() == -1) { + MessageWindow er = new MessageWindow("ERROR", + "Select Structure first!", true); + er.setVisible(true); + return; + } + Integer index = (Integer) structuresIndex.get(Structures.getSelectedIndex()); + int sel_str = index.intValue(); + Map row = (Map) allStructures.get(sel_str); + //Integer strid = (Integer)row.get(structureIdKey); + //String struct_id = strid.toString(); + String struct_name = row.get(structureNameKey).toString(); + //logger.info("Struct_Id: "+ struct_id+" strid="+strid); + MoleculeInterface mol = + sql_data.loadStructure(Molecules.getSelectedItem(), + struct_name); + //struct_id); + if (mol.getNumberOfBonds() == 0) { + Molecule.guessCovalentBonds(mol); + } + target.addMolecule(mol); + + // --- Delete Structure + } else if (ae.getActionCommand().toString().equals("Delete Structure")) { + if (Structures.getSelectedIndex() == -1) { + MessageWindow er = new MessageWindow("ERROR", + "Select Structure first!", true); + er.setVisible(true); + return; + } + + Integer index = (Integer) structuresIndex.get(Structures.getSelectedIndex()); + int sel_str = index.intValue(); + Map row = (Map) allStructures.get(sel_str); + Integer strid = (Integer) row.get(structureIdKey); + String struct_id = strid.toString(); + logger.info("Struct_Id: " + struct_id + " strid=" + strid); + + if (!sql_data.deleteStructure(Molecules.getSelectedItem(), + struct_id)) { + MessageWindow er = new MessageWindow("ERROR", + "Cannot delete structure!", true); + er.setVisible(true); + return; + } + + deleteStructureFromArray(Molecules.getSelectedItem(), + Structures.getSelectedItem()); + updateStructureList(Molecules.getSelectedItem()); + Structures.select(0); + + // --- OK Button + } else if (ae.getActionCommand().toString().equals("Hide")) { + //dispose(); + setVisible(false); + } + + //logger.info("getClass: " + ae.getClass() ); + //logger.info("getClass.getName: " + ae.getClass().getName() ); + //logger.info("getClass.getSimpleName: " + ae.getClass().getSimpleName() ); + + //dispose(); + } + + /** + * + * @param items ArrayList + */ + public void populateItemsList(java.util.List items) { + for (int i = 0; i < items.size(); i++) { + Molecules.add((String) items.get(i)); + } + if (items.size() > 0) { + Molecules.select(0); + } + } + + /** + * + */ + public boolean isMoleculeNameUnique(String new_name) { + for (int i = 0; i < allMolecules.size(); i++) { + Map row = (Map) allMolecules.get(i); + if (new_name.compareToIgnoreCase(row.get(moleculeNameKey).toString()) + == 0) { + return false; + } + } + return true; + } + + public boolean isStructureNameUnique(String new_name, String mol_name) { + for (int i = 0; i < allStructures.size(); i++) { + Map row = (Map) allStructures.get(i); + if (mol_name.compareToIgnoreCase(row.get(moleculeNameKey).toString()) + != 0) { + continue; + } + if (new_name.compareToIgnoreCase(row.get(structureNameKey). + toString()) == 0) { + return false; + } + } + return true; + } + + void updateStructureList(String currentMolecule) { + Structures.removeAll(); + structuresIndex.clear(); + for (int i = 0; i < allStructures.size(); i++) { + Map row = (Map) allStructures.get(i); + String name = row.get(moleculeNameKey).toString(); + if (name.compareToIgnoreCase(currentMolecule) == 0) { + String strip_name = row.get(structureNameKey).toString(); + int end_name = strip_name.indexOf("@"); + Structures.add(strip_name.substring(0, end_name)); + structuresIndex.add(new Integer(i)); + } + } + if (Structures.getItemCount() > 0) { + Structures.select(0); + } + } + + void updateMoleculesList() { + Molecules.removeAll(); + for (int i = 0; i < allMolecules.size(); i++) { + Map row = (Map) allMolecules.get(i); + Molecules.add(row.get(moleculeNameKey).toString()); + } + + } + + boolean deleteStructureFromArray(String mol_name, String method) { + int i = Structures.getSelectedIndex(); + Integer I = (Integer) structuresIndex.get(i); + int n = I.intValue(); + allStructures.remove(n); + return true; + /* + for (int i = 0; i < allStructures.size(); i++) { + HashMap row = (HashMap) allStructures.get(i); + String name = row.get(moleculeNameKey).toString(); + String meth = row.get(structureNameKey).toString(); + if (name.equals(mol_name) && meth.equals(method)) { + allStructures.remove(i); + return true; + } + } + */ + //return false; // Was unable to delete. Who knows why... :-) + } + + public void selectMolecule(int selected) { + // !!! ERROR CHECK HERE... !!! + + Map row = (Map) allMolecules.get(selected); + String currentMolecule = row.get(moleculeNameKey).toString(); + + name.setText(currentMolecule); + oldName = currentMolecule; // remember name + + updateStructureList(currentMolecule); + } + + // --- Subclasses + public void updateData() { + + // --- Update molecules list + + allMethods = sql_data.getMethods(); + allBasisSets = sql_data.getBasisSets(); + + allMolecules = sql_data.getMolecules(); + + if (Molecules.getItemCount() > 0) { + Molecules.removeAll(); + } + + for (int i = 0; i < allMolecules.size(); i++) { + Map row = (Map) allMolecules.get(i); + Molecules.add(row.get(moleculeNameKey).toString()); + } + SelectedMolecule = 0; + + Map row = null; + String currentMolecule = " "; + if (allMolecules.size() > 0) { + row = (Map) allMolecules.get(SelectedMolecule); + currentMolecule = row.get(moleculeNameKey).toString(); + + Molecules.select(SelectedMolecule); + } + + // --- Update structures + + allStructures = sql_data.getStructures(); + if (structuresIndex == null) { + structuresIndex = new ArrayList(); + } else { + structuresIndex.clear(); + } + + if (Structures.getItemCount() > 0) { + Structures.removeAll(); + } + + if (allStructures != null) { + for (int i = 0; i < allStructures.size(); i++) { + row = (Map) allStructures.get(i); + String name = row.get(moleculeNameKey).toString(); + if (name.compareToIgnoreCase(currentMolecule) == 0) { + String strip_name = row.get(structureNameKey).toString(); + int end_name = strip_name.indexOf("@"); + Structures.add(strip_name.substring(0, end_name)); + structuresIndex.add(new Integer(i)); // Keep track of real indexes + } + } + } + + } +} diff --git a/src/main/java/cct/database/new_SQLChemistryDatabase.java b/src/main/java/cct/database/new_SQLChemistryDatabase.java new file mode 100644 index 0000000..14eafb6 --- /dev/null +++ b/src/main/java/cct/database/new_SQLChemistryDatabase.java @@ -0,0 +1,897 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.database; + +import java.io.InputStream; +import java.io.OutputStream; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.Set; +import java.util.logging.Logger; + +import cct.awtdialogs.MessageWindow; +import cct.interfaces.MoleculeInterface; +import cct.modelling.MolecularProperties; +import cct.modelling.Molecule; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class new_SQLChemistryDatabase + implements TablesDescription, MolecularProperties { + SQLDatabaseAccess database = null; + + boolean wasError = true; + String errorMessage = "No error(s) yet"; + List moleculeTableInfo = null; + List moleculeTable = null; + List structureTableInfo = null; + List structureTable = null; + List methodsTableInfo = null; + List methodsTable = null; + List basisSetsTableInfo = null; + List basisSetsTable = null; + List propertiesTableInfo = null; + List propertiesTable = null; + static final Logger logger = Logger.getLogger(new_SQLChemistryDatabase.class.getCanonicalName()); + + public new_SQLChemistryDatabase(SQLDatabaseAccess db, String host, + String user, String pass, String datab) { + wasError = true; + database = db; + if (!database.isDriverLoaded()) { + return; + } + if (!database.getConnection(host, user, pass)) { + return; + } + if (!database.selectDatabase(datab)) { + return; + } + wasError = false; + } + + public String getErrorMessage() { + return database.getErrorMessage(); + } + + public List getMolecules() { + return getTable(MoleculeTable, moleculeTableInfo); + } + + public List getTable(String tableName, List metadataTable) { + if (database == null) { + return null; + } + Connection conn = database.getConnection(); + if (conn == null) { + return null; + } + + // --- Get info about table + + metadataTable = database.getTableMetaData(tableName); + + List table = database.getColumnsFromTable(tableName, "*"); + + return table; + } + + /** + * + * @return ArrayList + */ + public List getStructures() { + return getTable(StructureTable, structureTableInfo); + } + + public List getStructuresForMolecule(String mol_name) { + if (database == null) { + return null; + } + if (database.getConnection() == null) { + return null; + } + + // --- Get info about table + if (structureTableInfo == null) { + structureTableInfo = database.getTableMetaData(StructureTable); + } + + String condition = moleculeNameKey + "='" + mol_name + "'"; + + List given_str = database.getSelectedColumnsFromTable( + StructureTable, "*", condition); + + if (given_str == null && database.wasError()) { + MessageWindow mess = new MessageWindow("SQL Error Message", + getErrorMessage(), true); + mess.setVisible(true); + } + + return given_str; + } + + public List getMethods() { + return getTable(MethodsTable, methodsTableInfo); + } + + /** + * + * @return String[] + */ + public String[] getAvailableMethods() { + List methods = getTable(MethodsTable, methodsTableInfo); + if (methods == null || methods.size() < 1) { + return null; + } + String allMethods[] = new String[methods.size()]; + for (int i = 0; i < methods.size(); i++) { + Map row = (Map) methods.get(i); + allMethods[i] = row.get(methodNameKey).toString(); + } + + return allMethods; + } + + /** + * + * @return String[] + */ + public String[] getAvailableBasisSets() { + List methods = getTable(BasisSetsTable, basisSetsTableInfo); + if (methods == null || methods.size() < 1) { + return null; + } + String allMethods[] = new String[methods.size()]; + for (int i = 0; i < methods.size(); i++) { + Map row = (Map) methods.get(i); + allMethods[i] = row.get(basisSetsNameKey).toString(); + } + + return allMethods; + } + + public List getBasisSets() { + return getTable(BasisSetsTable, basisSetsTableInfo); + } + + public boolean changeMoleculeName(String oldName, String newName) { + if (!database.updateItem(StructureTable, moleculeNameKey, oldName, + newName)) { + return false; + } + return database.updateItem(MoleculeTable, moleculeNameKey, oldName, + newName); + } + + // Depreciated!!! + public boolean addNewMolecule(String name) { + return database.addStringItem(MoleculeTable, moleculeNameKey, name); + } + + public boolean addNewMolecule(String name, String aliases, String notes, + boolean model, int charge, int mult) { + String user = database.getUser(); + if (database.wasError()) { + MessageWindow mess = new MessageWindow("SQL Error Message", + getErrorMessage(), true); + mess.setVisible(true); + // For a moment we ignore the error + } + + String columns = moleculeNameKey; + String values = name; + + if (aliases != null && aliases.length() > 0) { + columns += "," + moleculeAliasesKey; + values += "," + aliases; + } + if (notes != null && notes.length() > 0) { + columns += "," + moleculeNotesKey; + values += "," + notes; + } + if (user != null && user.length() > 0) { + columns += "," + moleculeUserKey; + values += "," + user; + } + if (model) { + columns += "," + moleculeIsModelKey; + values += ",1"; + } + else { + columns += "," + moleculeIsModelKey; + values += ",0"; + columns += "," + moleculeChargeKey; + values += "," + String.valueOf(charge); + columns += "," + moleculeMultiplicityKey; + values += "," + String.valueOf(mult); + } + + if (!database.addManyStringItems(MoleculeTable, columns, values)) { + if (database.wasError()) { + MessageWindow mess = new MessageWindow("SQL Error Message", + getErrorMessage(), true); + mess.setVisible(true); + } + return false; + } + + return true; // OK + } + + // Old subroutine + /* + public boolean addNewStructure(String name, String method, Molecule mol) { + // --- First add new row to "structure" table + // --- insert into structure (name, method) values('Acetone',�STO-3G�); + if (!database.addManyStringItems(StructureTable, + structureIdKey + "," + moleculeNameKey + + "," + methodNameKey, + name + "_" + method + " " + name + " " + + method)) { + return false; + } + // --- get OuputStream to write structure + //Blob structure = database.getBlob(StructureTable, structureKey, + // structureIdKey, + // name + "_" + method ); + Clob structure = database.getClob(StructureTable, structureKey, + structureIdKey, + name + "_" + method); + + try { + //OutputStream out = structure.setBinaryStream(1); + OutputStream out = structure.setAsciiStream(1); + mol.toArchiveFormat(out); + } catch (SQLException ex) { + logger.info("addNewStructure: SQLException: " + + ex.getMessage()); + return false; + } + + //boolean result = database.setBlob( StructureTable, structureKey, + // structureIdKey, + // name + "_" + method, structure ); + boolean result = database.setClob(StructureTable, structureKey, + structureIdKey, + name + "_" + method, structure); + + if (!result) { + database.deleteRows(StructureTable, structureIdKey, + name + "_" + method); + } + return result; + } + */ + // New subroutine + public Map addNewStructure(String mol_name, String str_name, + String notes, String method, MoleculeInterface mol) { + + // First, query whether it is the first structure to be added or not + + List existedStr = getStructuresForMolecule(mol_name); + if (database.wasError()) { + return null; + } + + // Get current user info + String user = database.getUser(); + if (database.wasError()) { + MessageWindow mess = new MessageWindow("SQL Error Message", + getErrorMessage(), true); + mess.setVisible(true); + // For a moment we ignore the error + } + + // Get Molecule Id + + List mol_id = database.getSelectedColumnsFromTable(MoleculeTable, + moleculeIdKey + ", " + + moleculeIsModelKey + ", " + + moleculeChargeKey + ", " + + moleculeMultiplicityKey, + moleculeNameKey + "='" + mol_name + "'"); + if (database.wasError()) { + MessageWindow mess = new MessageWindow("SQL Error Message", + getErrorMessage(), true); + mess.setVisible(true); + return null; + } + else if (mol_id == null) { + MessageWindow mess = new MessageWindow("SQL Error Message", + "SQL Query returned nothing. Look at debug output", true); + mess.setVisible(true); + return null; + } + + // Assuming we have only one row (as it should be!) + Map row = (Map) mol_id.get(0); + logger.info("Molec_Id: " + row.get(moleculeIdKey).toString()); + // --- Get Molecular ID + int molec_id = Integer.parseInt(row.get(moleculeIdKey).toString()); + int charge = Integer.parseInt(row.get(moleculeChargeKey).toString()); + int multiplicity = Integer.parseInt(row.get(moleculeMultiplicityKey). + toString()); + // --- Whether it's a model or regular molecule + boolean not_a_model = + Integer.parseInt(row.get(moleculeIsModelKey).toString()) == 0; + // --- Check charge and multiplicity + if (not_a_model) { + Map prop = mol.getProperties(); + // --- Check total charge + if (prop.containsKey(MoleculeInterface.ChargeProperty)) { + Integer ch = (Integer) prop.get(MoleculeInterface.ChargeProperty); + if (charge != ch.intValue()) { + MessageWindow mess = new MessageWindow("Error Message", + "Molecule charge " + charge + " and structure's charge " + + ch.intValue() + " are different", true); + mess.setVisible(true); + logger.info("Molecule charge " + charge + + " and structure's charge " + ch.intValue() + + " are different"); + return null; + } + } + // --- Check multiplicity + if (prop.containsKey(MoleculeInterface.MultiplicityProperty)) { + Integer mult = (Integer) prop.get(MoleculeInterface.MultiplicityProperty); + if (multiplicity != mult.intValue()) { + MessageWindow mess = new MessageWindow("Error Message", + "Molecule multiplicity " + multiplicity + + " and structure's one " + + mult.intValue() + " are different", true); + mess.setVisible(true); + logger.info("Molecule multiplicity " + charge + + " and structure's one " + mult.intValue() + + " are different"); + return null; + } + } + // --- try to guess from molecule + + if (!Molecule.isMatchChargeAndMultiplicity(mol, charge, multiplicity)) { + MessageWindow mess = new MessageWindow("Error Message", + "Charge and multiplicity (" + + charge + " and " + + multiplicity + + ") do not match current structure", true); + mess.setVisible(true); + logger.info("Charge and multiplicity (" + charge + + " and " + + multiplicity + + ") do not match current structure"); + return null; + } + } + + float weight = Molecule.getMolecularWeight(mol); + String formula = Molecule.getChemicalFormula(mol); + int count[] = Molecule.getElementCount(mol); + + // Special case for the first added structure. Fill in some fields in + // Molecules table for a given molecule + + if (existedStr == null || existedStr.size() == 0) { // The first structure + String values = moleculeFormulaKey + "='" + formula + "'"; + String condition = moleculeNameKey + "='" + mol_name + "'"; + + values += "," + moleculeWeightKey + "='" + String.valueOf(weight) + + "'"; + + if (count[1] > 0) { + values += ",H_atoms='" + String.valueOf(count[1]) + "'"; + } + if (count[6] > 0) { + values += ",C_atoms='" + String.valueOf(count[6]) + "'"; + } + if (count[7] > 0) { + values += ",N_atoms='" + String.valueOf(count[7]) + "'"; + } + if (count[8] > 0) { + values += ",O_atoms='" + String.valueOf(count[8]) + "'"; + } + if (count[9] > 0) { + values += ",F_atoms='" + String.valueOf(count[9]) + "'"; + } + if (count[15] > 0) { + values += ",P_atoms='" + String.valueOf(count[15]) + "'"; + } + if (count[16] > 0) { + values += ",S_atoms='" + String.valueOf(count[16]) + "'"; + } + if (count[17] > 0) { + values += ",Cl_atoms='" + String.valueOf(count[17]) + "'"; + } + + if (!database.updateItemsUsingCondition(MoleculeTable, values, + condition)) { + if (database.wasError()) { + MessageWindow mess = new MessageWindow("SQL Error Message", + getErrorMessage(), true); + mess.setVisible(true); + } + return null; + } + } + // --- For the next added structures make a check + else { + List to_formula = database.getSelectedColumnsFromTable( + MoleculeTable, + moleculeFormulaKey, moleculeNameKey + "='" + mol_name + "'"); + if (database.wasError()) { + return null; + } + row = (Map) to_formula.get(0); + String original_formula = row.get(moleculeFormulaKey).toString(); + if (!original_formula.contentEquals(formula)) { + MessageWindow mess = new MessageWindow("Error Message", + "Molecule formula (" + original_formula + + ") is different from structure's one " + + formula, true); + mess.setVisible(true); + logger.info("Molecule formula (" + original_formula + + ") is different from structure's one " + + formula + ); + return null; + } + } + + // --- Form internal representation of structure name + + Random rand = new Random(); + int random_number = rand.nextInt(); + String Structure_name = str_name + "@" + mol_name + "_" + method + "_" + + String.valueOf(random_number); + + // --- First add new row to "structure" table + // --- insert into Structure (StrName,Notes,User,MolName) values(...�); + + String str_col[] = { + structureNameKey, + structureNotesKey, + structureUserKey, + moleculeNameKey, + moleculeIdKey + }; + String str_val[] = { + Structure_name, + notes, + user, + mol_name, + String.valueOf(molec_id) + }; + + if (!database.addManyStringItems(StructureTable, str_col, str_val)) { + if (database.wasError()) { + MessageWindow mess = new MessageWindow("SQL Error Message", + getErrorMessage(), true); + mess.setVisible(true); + } + return null; + } + + // now we need to know Struct_Id + + int lastStrId = database.getLastInsertId(StructureTable); + logger.info("Last inserted Struct_Id: " + lastStrId); + + if (lastStrId == -1) { + logger.info(getErrorMessage()); + } + + // Get Structure Id + + List str_id = database.getSelectedColumnsFromTable(StructureTable, + structureIdKey, structureNameKey + "='" + Structure_name + "'"); + if (database.wasError()) { + MessageWindow mess = new MessageWindow("SQL Error Message", + getErrorMessage(), true); + mess.setVisible(true); + return null; + } + else if (str_id == null) { + MessageWindow mess = new MessageWindow("SQL Error Message", + "SQL Query returned nothing. Look at debug output", true); + mess.setVisible(true); + return null; + } + + // Assuming we have only one row (as it should be!) + Map str_row = (Map) str_id.get(0); + + logger.info("Struct_Id: " + str_row.get(structureIdKey).toString()); + + int Struct_Id = Integer.parseInt(str_row.get(structureIdKey).toString()); + + // --- get OuputStream to write structure + //Blob structure = database.getBlob(StructureTable, structureKey, + // structureNameKey, + // name + "_" + method ); + Clob structure = database.getClob(StructureTable, structureKey, + structureNameKey, + Structure_name); + if (structure == null) { + logger.info("Add Structure: structure == null"); + if (database.wasError()) { + MessageWindow mess = new MessageWindow("SQL Error Message", + getErrorMessage(), true); + mess.setVisible(true); + } + + return null; + } + + try { + //OutputStream out = structure.setBinaryStream(1); + OutputStream out = structure.setAsciiStream(1); + Molecule.toArchiveFormat(mol, out); + } + catch (SQLException ex) { + logger.info("addNewStructure: SQLException: " + + ex.getMessage()); + return null; + } + + //boolean result = database.setBlob( StructureTable, structureKey, + // structureIdKey, + // name + "_" + method, structure ); + boolean result = database.setClob(StructureTable, structureKey, + structureNameKey, + Structure_name, structure); + + if (!result) { + database.deleteRows(StructureTable, structureNameKey, + Structure_name); + } + + // --- Now we need to save molecular properties + + // --- First, get property types + + List prop_types = database.getColumnsFromTable(PropertiesTypeTable, + PropertyTypeNameKey + "," + + PropertyTypeIsTextKey + "," + + PropertyTypeIsVectorKey + "," + + PropertyTypeIsFloatKey); + + if (database.wasError()) { + return null; + } + + String columns[] = { + propertiesNameKey, + propertiesMethodKey, + propertiesValueKey, + propertiesVectorKey, + propertiesNotesKey, + propertiesStructId + }; + String values[] = new String[6]; + + String Value = new String(), Values = new String(), Notes = new String(); + Map prop = mol.getProperties(); + Set set = prop.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + List data; + Map.Entry me = (Map.Entry) iter.next(); + String name = me.getKey().toString(); + Object something = me.getValue(); + String class_type = something.getClass().getSimpleName(); + + // --- Method exists??? --- Assume that exists + + // --- Property type exists??? + + boolean isText = true; + boolean isFloat = false; + boolean isVector = false; + + row = getSelectedRowFromQuery(prop_types, PropertyTypeNameKey, name); + + if (row != null) { + isText = Integer.parseInt( row.get( PropertyTypeIsTextKey ).toString() ) == + 1; + isFloat = Integer.parseInt( row.get( PropertyTypeIsFloatKey ).toString() ) == + 1; + isVector = Integer.parseInt( row.get( PropertyTypeIsVectorKey ). + toString() ) == 1; + } + else { + MessageWindow mess = new MessageWindow("ERROR", + "No such property - " + name + " - in database", true); + mess.setVisible(true); + continue; + } + /* + data = database.getSelectedColumnsFromTable(PropertiesTypeTable, + PropertyTypeNameKey, + PropertyTypeNameKey + "='" + + name + "'"); + if (database.wasError()) { + if (menuFrame != null) { + MessageWindow mess = new MessageWindow(menuFrame, + "SQL Error Message", + "Checking PropertyType: " + + getErrorMessage(), true); + mess.setVisible(true); + } + return null; + } + if (data == null) { // Property Type is not in database yet + // Add property type with some "generic" parameters + if (!database.addManyStringItems(PropertiesTypeTable, + + PropertyTypeNameKey + "," + + PropertyTypeIsTextKey + "," + + PropertyTypeIsVectorKey + "," + + PropertyTypeIsFloatKey + "," + + PropertyTypeNotesKey, + + name + "," + "1,0" + "," + + "0" + "," + + "Automatically added - edit manually")) { + if (database.wasError() && menuFrame != null) { + MessageWindow mess = new MessageWindow(menuFrame, + "SQL Error Message", + "Adding new property type: " + + getErrorMessage(), true); + mess.setVisible(true); + } + return null; + } + } + */ + + // --- Now, add property + /* + if (class_type.equals("Float")) { + Value = something.toString(); + Values = ""; + } + else if (class_type.equals("Integer")) { + Value = something.toString(); + Values = ""; + } + else if (class_type.equals("String")) { // Vector values or Text + Values = something.toString(); + if (Values.indexOf(' ') != -1) { + Value = Values.substring(0, Values.indexOf(' ')); + try { + float temp = Float.parseFloat(Value); + } + catch (NumberFormatException e) { + Value = ""; + } + } + else { + Value = ""; + } + } + */ + + if (isText) { + Value = ""; + Values = something.toString(); + } + else if (isFloat) { + Value = something.toString(); + Values = Value; + } + else if (isVector) { // Vector values or Text + Values = something.toString().trim(); + String temp[] = Values.split(" "); // Number of element in vector + Value = String.valueOf(temp.length); + } + + values[0] = name; + values[1] = method; + values[2] = Value; + values[3] = Values; + values[4] = Notes; + values[5] = String.valueOf(Struct_Id); + + if (!database.addManyStringItems(PropertiesTable, columns, values)) { + + if (database.wasError()) { + MessageWindow mess = new MessageWindow("SQL Error Message", + "Adding new property type: " + + getErrorMessage(), true); + mess.setVisible(true); + } + return null; + } + + } + + // --- Fimanally get info about new added structure + + mol_id = database.getSelectedColumnsFromTable(StructureTable, + "*", + structureNameKey + "='" + + Structure_name + + "' AND " + + moleculeNameKey + "='" + + mol_name + "'"); + row = (Map) mol_id.get(0); // !!! ERROR CHECK !!! + + return row; + } + + /** + * + * @param molecule_name String + * @param struct_name String + * @return MoleculeInterface + */ + //public Molecule loadStructure(String molecule_name, String struct_id) { + public MoleculeInterface loadStructure(String molecule_name, String struct_name) { + // --- get InputStream to write structure + //Blob structure = database.getBlob(StructureTable, structureKey, + // structureIdKey, + // name + "_" + method ); + //Clob structure = database.getClob(StructureTable, structureKey, + // structureIdKey, + // struct_id); + Clob structure = database.getClob(StructureTable, structureKey, + structureNameKey, + struct_name); + + //byte arch[] = database.getBytes( StructureTable, structureKey, + // structureIdKey, + // name + "_" + method ); + + try { + String str = structure.getSubString(1L, + structure.length() > 255 ? 255 : + (int) structure.length()); + logger.info("loadStructure: substring: " + str); + + //InputStream in = structure.getBinaryStream( ); + InputStream in = structure.getAsciiStream(); + Molecule mol = new Molecule(); + mol.fromArchiveFormat(in); + return mol; + } + catch (SQLException ex) { + logger.info("addNewStructure: SQLException: " + + ex.getMessage()); + return null; + } + + /* + try { + //char arch[] = structure.getSubString(1L, (int)structure.length()).toCharArray(); + byte arch[] = structure.getSubString(1L, (int)structure.length()).getBytes(); + logger.info( "addNewStructure: s " + structure.getSubString(1L, (int)structure.length()) ); + logger.info( "addNewStructure: b " + arch[0] + arch[1] + arch[2] ); + Molecule mol = new Molecule(); + mol.fromArchiveFormat( arch ); + return mol; + } catch (SQLException ex) { + logger.info( "addNewStructure: SQLException: " + ex.getMessage() ); + return null; + } + */ + + } + + public boolean deleteStructure(String mol_name, String struct_id) { + return database.deleteRows( StructureTable, structureIdKey, + struct_id ) != 0; + } + + public boolean deleteMolecule(String name) { + return database.deleteRows( MoleculeTable, moleculeNameKey, name ) != 0; + } + + public boolean isError() { + return wasError; + } + + public boolean addNewMethod(String Name, String notes, boolean exp, + boolean fixedb, boolean dft, boolean effcore) { + int i_exp = exp ? 1 : 0; + int i_fixedb = fixedb ? 1 : 0; + int i_dft = dft ? 1 : 0; + int i_effcore = effcore ? 1 : 0; + String columns = methodNameKey + "," + + methodExpKey + "," + + methodFixedBasisKey + "," + + methodEffectiveCorePKey + "," + + methodDFTPKey; + String values = Name + "," + i_exp + "," + + i_fixedb + "," + i_effcore + "," + + i_dft; + + if (notes != null && notes.trim().length() > 0) { + columns += "," + methodNotesKey; + values += "," + notes; + } + + if (!database.addManyStringItems(MethodsTable, columns, values)) { + if (database.wasError()) { + MessageWindow mess = new MessageWindow("SQL Error Message", + "Adding new property type: " + + getErrorMessage(), true); + mess.setVisible(true); + } + return false; + } + return true; + } + + /** + * + * @param query ArrayList + * @param key String + * @param value String + * @return Map + */ + Map getSelectedRowFromQuery(List query, String key, String value) { + if (query == null || query.size() < 1) { + return null; + } + for (int i = 0; i < query.size(); i++) { + Map row = (Map) query.get(i); + if (row.containsKey(key)) { + String val = row.get(key).toString(); + if (value.equals(val)) { + return row; + } + } + } + return null; + } +} diff --git a/src/main/java/cct/dialogs/AddMoleculeDialog.java b/src/main/java/cct/dialogs/AddMoleculeDialog.java new file mode 100644 index 0000000..24d20d8 --- /dev/null +++ b/src/main/java/cct/dialogs/AddMoleculeDialog.java @@ -0,0 +1,180 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.Dialog; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JPanel; +import javax.swing.JRadioButton; + +import cct.interfaces.MoleculeRendererInterface; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class AddMoleculeDialog + extends JDialog { + + private JPanel panel1 = new JPanel(); + private BorderLayout borderLayout1 = new BorderLayout(); + private JPanel jPanel1 = new JPanel(); + private JPanel jPanel2 = new JPanel(); + private JButton cancelButton = new JButton(); + private JButton jButton2 = new JButton(); + private JRadioButton overwriteRadioButton = new JRadioButton(); + private BorderLayout borderLayout2 = new BorderLayout(); + private JRadioButton newWinRadioButton = new JRadioButton(); + private JRadioButton mergeRadioButton = new JRadioButton(); + private ButtonGroup buttonGroup1 = new ButtonGroup(); + + private int cond = 1; + + public AddMoleculeDialog(Frame owner, String title) { + super(owner, title, true); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public AddMoleculeDialog(Dialog owner, String title) { + super(owner, title, true); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public int getLoadMode() { + if (overwriteRadioButton.isSelected()) { + return MoleculeRendererInterface.OVERWRITE_MOLECULE; + } + else if (newWinRadioButton.isSelected()) { + return MoleculeRendererInterface.NEW_MOLECULE; + } + + return MoleculeRendererInterface.MERGE_MOLECULE; + } + + public void EnableNewWindowButton(boolean enable) { + newWinRadioButton.setVisible(enable); + this.validateTree(); + } + + public AddMoleculeDialog() { + this(new Frame(), "AddMoleculeDialog"); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + cancelButton.setToolTipText(""); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + cancelButton_actionPerformed(e); + } + }); + jButton2.setToolTipText(""); + jButton2.setText(" Open "); + jButton2.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + jButton2_actionPerformed(e); + } + }); + overwriteRadioButton.setToolTipText("Erase Molecule in Active Window and Load a New One"); + overwriteRadioButton.setSelected(true); + overwriteRadioButton.setText("Overwrite Molecule in Active Window"); + jPanel1.setLayout(borderLayout2); + newWinRadioButton.setToolTipText("Load Molecule into New Window"); + newWinRadioButton.setText("Open in New Window"); + mergeRadioButton.setToolTipText("Append New Molecule to a Molecule in Active Window"); + mergeRadioButton.setText("Merge with Molecule in Active Window"); + getContentPane().add(panel1); + panel1.add(jPanel1, BorderLayout.CENTER); + panel1.add(jPanel2, BorderLayout.SOUTH); + jPanel2.add(jButton2); + jPanel2.add(cancelButton); + jPanel1.add(newWinRadioButton, BorderLayout.SOUTH); + buttonGroup1.add(overwriteRadioButton); + jPanel1.add(mergeRadioButton, BorderLayout.CENTER); + jPanel1.add(overwriteRadioButton, BorderLayout.NORTH); + buttonGroup1.add(newWinRadioButton); + buttonGroup1.add(mergeRadioButton); + } + + public int showDialog() { + setVisible(true); + return cond; + } + + public void jButton2_actionPerformed(ActionEvent e) { + cond = getLoadMode(); + setVisible(false); + } + + public void cancelButton_actionPerformed(ActionEvent e) { + cond = MoleculeRendererInterface.LOAD_CANCELED; + setVisible(false); + } +} diff --git a/src/main/java/cct/dialogs/AddNewFragmentDialog.java b/src/main/java/cct/dialogs/AddNewFragmentDialog.java new file mode 100644 index 0000000..bd56897 --- /dev/null +++ b/src/main/java/cct/dialogs/AddNewFragmentDialog.java @@ -0,0 +1,257 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; + +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JTextField; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class AddNewFragmentDialog + extends JDialog { + public static final int CANCELED = 0; + public static final int APPROVED = 1; + + private int outcome = APPROVED; + + private JPanel panel1 = new JPanel(); + private BorderLayout borderLayout1 = new BorderLayout(); + private JPanel jPanel1 = new JPanel(); + private JPanel jPanel2 = new JPanel(); + private JButton cancelButton = new JButton(); + private JButton okButton = new JButton(); + private JLabel jLabel1 = new JLabel(); + private JTextField nameTextField = new JTextField(); + private JLabel jLabel2 = new JLabel(); + private JTextField pathTextField = new JTextField(); + private JComboBox pathComboBox = new JComboBox(); + private ButtonGroup buttonGroup1 = new ButtonGroup(); + private JRadioButton customRadioButton = new JRadioButton(); + private JRadioButton existingRadioButton = new JRadioButton(); + private JLabel jLabel3 = new JLabel(); + private GridBagLayout gridBagLayout1 = new GridBagLayout(); + + public AddNewFragmentDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public AddNewFragmentDialog() { + this(new Frame(), "AddNewFragmentDialog", false); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + cancelButton.setSelectedIcon(null); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + cancelButton_actionPerformed(e); + } + }); + okButton.setToolTipText(""); + okButton.setText(" OK "); + okButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + okButton_actionPerformed(e); + } + }); + jLabel1.setToolTipText(""); + jLabel1.setText("Fragment Name: "); + nameTextField.setToolTipText(""); + nameTextField.setText("Magic"); + nameTextField.setColumns(40); + jLabel2.setToolTipText(""); + jLabel2.setText("Custom Path: "); + pathTextField.setToolTipText(""); + pathTextField.setText("Toxic Residues"); + pathTextField.setColumns(40); + jPanel1.setLayout(gridBagLayout1); + customRadioButton.setToolTipText(""); + customRadioButton.setText("Custom Path"); + customRadioButton.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + customRadioButton_itemStateChanged(e); + } + }); + existingRadioButton.setToolTipText(""); + existingRadioButton.setText("Existing Path"); + existingRadioButton.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + existingRadioButton_itemStateChanged(e); + } + }); + jLabel3.setToolTipText(""); + jLabel3.setText("Existing Path(s): "); + pathComboBox.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + pathComboBox_itemStateChanged(e); + } + }); + + existingRadioButton.setSelected(true); + customRadioButton.setSelected(false); + + getContentPane().add(panel1); + panel1.add(jPanel1, BorderLayout.CENTER); + jPanel2.add(okButton); + jPanel2.add(cancelButton); + panel1.add(jPanel2, BorderLayout.SOUTH); + buttonGroup1.add(customRadioButton); + buttonGroup1.add(existingRadioButton); + jPanel1.add(jLabel1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 0, 0), 0, 0)); + jPanel1.add(jLabel2, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(pathTextField, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(customRadioButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(existingRadioButton, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(pathComboBox, new GridBagConstraints(1, 3, 1, 1, 1.0, 1.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(jLabel3, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, + 0)); + jPanel1.add(nameTextField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); + } + + public void setFragmentName(String name) { + nameTextField.setText(name); + } + + public String getFragmentName() { + return nameTextField.getText().trim(); + } + + public void setPath(String path) { + pathTextField.setText(path); + pathComboBox.setSelectedItem(path); + } + + public String getPath() { + return pathTextField.getText().trim(); + } + + public int showDialog() { + this.setModal(true); + setVisible(true); + return outcome; + } + + public void cancelButton_actionPerformed(ActionEvent e) { + outcome = AddNewFragmentDialog.CANCELED; + setVisible(false); + } + + public void okButton_actionPerformed(ActionEvent e) { + outcome = AddNewFragmentDialog.APPROVED; + setVisible(false); + } + + public void setExistingPaths(String[] paths) { + pathComboBox.removeAllItems(); + for (String item : paths) { + pathComboBox.addItem(item); + } + pathComboBox.setSelectedIndex(0); + } + + public void customRadioButton_itemStateChanged(ItemEvent e) { + if (e.getStateChange() == ItemEvent.DESELECTED) { + return; + } + pathTextField.setEnabled(true); + } + + public void pathComboBox_itemStateChanged(ItemEvent e) { + if (e.getStateChange() == ItemEvent.DESELECTED) { + pathTextField.setText(""); + return; + } + pathTextField.setText(pathComboBox.getSelectedItem().toString()); + } + + public void existingRadioButton_itemStateChanged(ItemEvent e) { + if (e.getStateChange() == ItemEvent.DESELECTED) { + return; + } + pathTextField.setEnabled(false); + } + +} diff --git a/src/main/java/cct/dialogs/AnimationPanel.java b/src/main/java/cct/dialogs/AnimationPanel.java new file mode 100644 index 0000000..a33e81d --- /dev/null +++ b/src/main/java/cct/dialogs/AnimationPanel.java @@ -0,0 +1,701 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.dialogs; + +import cct.modelling.StructureManagerInterface; +import cct.modelling.TrajectoryClientInterface; +import cct.resources.images.ImageResources; + +import javax.swing.*; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.HashSet; +import java.util.Set; +import java.util.logging.Logger; + +/** + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class AnimationPanel + extends JPanel implements TrajectoryClientInterface, ActionListener { + + public static final int ANIMATION_STARTED = 1; + public static final int ANIMATION_FINISHED = ANIMATION_STARTED + 1; + + private static final String[] MOVIE_MODES = { + "Once", "Loop", "Rock"}; + + private int minStep = 1, maxStep = 100, stepStep = 1; + private int Step = 1; + private int animDirection = 1; + private int framesPerSeconds = 25; + private int delay; + private int animationMode; + private Timer timer; + private boolean animationInProgress = false; + + private StructureManagerInterface structureManagerInterface = null; + private Set actionListeners = new HashSet(); + + protected SpinnerModel stepModel = new SpinnerNumberModel(Step, minStep, maxStep, stepStep); + protected SpinnerModel fpsModel = new SpinnerNumberModel(framesPerSeconds, 1, 200, 1); + + protected BorderLayout borderLayout1 = new BorderLayout(); + protected JPanel jPanel1 = new JPanel(); + protected JButton startMediaButton = new JButton(); + + protected JSpinner stepSpinner = new JSpinner(stepModel); + protected JPanel sliderPanel = new JPanel(); + protected JLabel maxLabel = new JLabel(); + protected JTextField currentFrameTextField = new JTextField(); + + private ImageIcon mediaBeginningImage = new ImageIcon(ImageResources.class.getResource( + "icons16x16/media_beginning.png")); + private ImageIcon mediaEndImage = new ImageIcon(ImageResources.class.getResource("icons16x16/media_end.png")); + private ImageIcon mediaPauseImage = new ImageIcon(ImageResources.class.getResource( + "icons16x16/media_pause.png")); + private ImageIcon mediaPlayImage = new ImageIcon(ImageResources.class.getResource( + "icons16x16/media_play.png")); + private ImageIcon mediaPlayBackImage = new ImageIcon(ImageResources.class.getResource( + "icons16x16/media_play_back.png")); + private ImageIcon mediaStepBackImage = new ImageIcon(ImageResources.class.getResource( + "icons16x16/media_step_back.png")); + private ImageIcon mediaStepForwardImage = new ImageIcon(ImageResources.class.getResource( + "icons16x16/media_step_forward.png")); + + protected JButton mediaEndButton = new JButton(); + protected JSlider trajSlider = new JSlider(); + protected JButton pauseButton = new JButton(); + protected JButton playBackButton = new JButton(); + protected JButton playButton = new JButton(); + protected JLabel minLabel = new JLabel(); + protected JLabel jLabel3 = new JLabel(); + protected JButton stepBackButton = new JButton(); + protected JButton stepForwardButton = new JButton(); + protected GridBagLayout gridBagLayout1 = new GridBagLayout(); + protected JPanel jPanel2 = new JPanel(); + protected GridBagLayout gridBagLayout2 = new GridBagLayout(); + protected JLabel jLabel4 = new JLabel(); + protected JSpinner fpsSpinner = new JSpinner(fpsModel); + protected JPanel jPanel3 = new JPanel(); + protected JPanel jPanel4 = new JPanel(); + protected BorderLayout borderLayout2 = new BorderLayout(); + protected JComboBox animationComboBox = new JComboBox(); + static final Logger logger = Logger.getLogger(AnimationPanel.class.getCanonicalName()); + + public AnimationPanel() { + try { + jbInit(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public AnimationPanel(StructureManagerInterface smi) { + structureManagerInterface = smi; + try { + jbInit(); + } catch (Exception exception) { + exception.printStackTrace(); + } + + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + startMediaButton.setMaximumSize(new Dimension(24, 24)); + startMediaButton.setMinimumSize(new Dimension(24, 24)); + startMediaButton.setPreferredSize(new Dimension(24, 24)); + startMediaButton.setToolTipText("Beginning of Trajectory"); + startMediaButton.setIcon(mediaBeginningImage); + startMediaButton.setMargin(new Insets(0, 0, 0, 0)); + startMediaButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + startMediaButton_actionPerformed(e); + } + }); + maxLabel.setToolTipText(""); + maxLabel.setText(" 0"); + currentFrameTextField.setToolTipText("Enter New Value and Press Enter"); + currentFrameTextField.setText("0"); + currentFrameTextField.setColumns(7); + currentFrameTextField.setHorizontalAlignment(SwingConstants.CENTER); + currentFrameTextField.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + currentFrameTextField_actionPerformed(e); + } + }); + mediaEndButton.setMaximumSize(new Dimension(24, 24)); + mediaEndButton.setMinimumSize(new Dimension(24, 24)); + mediaEndButton.setPreferredSize(new Dimension(24, 24)); + mediaEndButton.setToolTipText("End of Trajectory"); + mediaEndButton.setIcon(mediaEndImage); + mediaEndButton.setMargin(new Insets(0, 0, 0, 0)); + mediaEndButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + mediaEndButton_actionPerformed(e); + } + }); + pauseButton.setMaximumSize(new Dimension(24, 24)); + pauseButton.setMinimumSize(new Dimension(24, 24)); + pauseButton.setPreferredSize(new Dimension(24, 24)); + pauseButton.setToolTipText("Stop/Pause Animation"); + pauseButton.setIcon(mediaPauseImage); + pauseButton.setMargin(new Insets(0, 0, 0, 0)); + pauseButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + pauseButton_actionPerformed(e); + } + }); + playBackButton.setMaximumSize(new Dimension(24, 24)); + playBackButton.setMinimumSize(new Dimension(24, 24)); + playBackButton.setPreferredSize(new Dimension(24, 24)); + playBackButton.setToolTipText("Play Back"); + playBackButton.setIcon(mediaPlayBackImage); + playBackButton.setMargin(new Insets(0, 0, 0, 0)); + playBackButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + playBackButton_actionPerformed(e); + } + }); + playButton.setMaximumSize(new Dimension(24, 24)); + playButton.setMinimumSize(new Dimension(24, 24)); + playButton.setPreferredSize(new Dimension(24, 24)); + playButton.setToolTipText("Play Forward"); + playButton.setIcon(mediaPlayImage); + playButton.setMargin(new Insets(0, 0, 0, 0)); + playButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + playButton_actionPerformed(e); + } + }); + minLabel.setToolTipText(""); + minLabel.setText("0 "); + jLabel3.setText("Step: "); + stepBackButton.setMaximumSize(new Dimension(24, 24)); + stepBackButton.setMinimumSize(new Dimension(24, 24)); + stepBackButton.setPreferredSize(new Dimension(24, 24)); + stepBackButton.setToolTipText("Step Back"); + stepBackButton.setIcon(mediaStepBackImage); + stepBackButton.setMargin(new Insets(0, 0, 0, 0)); + stepBackButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + stepBackButton_actionPerformed(e); + } + }); + stepForwardButton.setMaximumSize(new Dimension(24, 24)); + stepForwardButton.setMinimumSize(new Dimension(24, 24)); + stepForwardButton.setPreferredSize(new Dimension(24, 24)); + stepForwardButton.setToolTipText("Step Forward"); + stepForwardButton.setIcon(mediaStepForwardImage); + stepForwardButton.setMargin(new Insets(0, 0, 0, 0)); + stepForwardButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + stepForwardButton_actionPerformed(e); + } + }); + sliderPanel.setLayout(gridBagLayout1); + jPanel2.setLayout(gridBagLayout2); + jLabel4.setToolTipText(""); + jLabel4.setText("Frames per second: "); + jPanel1.setLayout(borderLayout2); + trajSlider.setMinimum(1); + stepSpinner.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + stepSpinner_stateChanged(e); + } + }); + fpsSpinner.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + fpsSpinner_stateChanged(e); + } + }); + animationComboBox.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + animationComboBox_itemStateChanged(e); + } + }); + jPanel4.add(jLabel3); + jPanel4.add(stepSpinner); + jPanel4.add(jLabel4); + jPanel4.add(fpsSpinner); + jPanel4.add(animationComboBox); + jPanel3.add(stepBackButton); + jPanel3.add(playBackButton); + jPanel3.add(pauseButton); + jPanel3.add(playButton); + jPanel3.add(stepForwardButton); + this.add(jPanel1, BorderLayout.SOUTH); + sliderPanel.add(startMediaButton, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + sliderPanel.add(mediaEndButton, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + jPanel2.add(minLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 0), 0, 0)); + jPanel2.add(maxLabel, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 0, 5, 5), 0, 0)); + sliderPanel.add(jPanel2, new GridBagConstraints(0, 0, 3, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); + jPanel2.add(currentFrameTextField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 0), 0, 0)); + sliderPanel.add(trajSlider, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 0), 1, 0)); + jPanel1.add(jPanel4, BorderLayout.SOUTH); + jPanel1.add(jPanel3, BorderLayout.NORTH); + this.add(sliderPanel, BorderLayout.NORTH); + + trajSlider.setValue(Step); + + //Set up a timer that calls this object's action handler. + delay = 1000 / framesPerSeconds; + //timer.setDelay(delay); + //timer.setInitialDelay(delay * 10); + + timer = new Timer(delay, this); + //timer.setInitialDelay(delay * 7); //We pause animation twice per cycle by restarting the timer + timer.setCoalesce(true); + + for (int i = 0; i < MOVIE_MODES.length; i++) { + animationComboBox.addItem(MOVIE_MODES[i]); + } + animationComboBox.setSelectedIndex(0); + animationMode = animationComboBox.getSelectedIndex(); + + trajSlider.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + trajSlider_stateChanged(e); + } + }); + + } + + public void setStructureManagerInterface(StructureManagerInterface smi) { + structureManagerInterface = smi; + } + + public void setMaxSnapshotCount(int new_max) { + trajSlider.setEnabled(false); + currentFrameTextField.setEnabled(false); + + //int value = trajSlider.getValue(); + trajSlider.setMaximum(new_max); + boolean update = false; + if (Step <= new_max) { + trajSlider.setValue(Step); + } else { + update = true; + Step = new_max; + } + + currentFrameTextField.setText(String.valueOf(Step)); + + maxLabel.setText(String.format("%-7s", new_max)); + if (new_max > 0) { + minLabel.setText(String.format("%7s", 1)); + } else { + minLabel.setText(String.format("%7s", 0)); + } + trajSlider.setEnabled(true); + currentFrameTextField.setEnabled(true); + + if (update) { + trajSlider.setValue(Step); + } + //else { + // trajSlider.setValue(Step); + //} + } + + public void setSnapshotValue(int new_value) { + /* + try { + (new_value); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Cannot select structure # " + new_value + " : " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + */ + + trajSlider.setEnabled(false); + currentFrameTextField.setEnabled(false); + + Step = new_value; + trajSlider.setValue(Step); + currentFrameTextField.setText(String.valueOf(Step)); + + trajSlider.setEnabled(true); + currentFrameTextField.setEnabled(true); + } + + public void trajSlider_stateChanged(ChangeEvent e) { + if (!trajSlider.isEnabled()) { + return; + } + + int value = trajSlider.getValue(); + if (trajSlider.getValueIsAdjusting()) { + currentFrameTextField.setEnabled(false); + currentFrameTextField.setText(String.valueOf(value)); + currentFrameTextField.setEnabled(true); + return; + } + + trajSlider.setEnabled(false); + + Step = value; + currentFrameTextField.setEnabled(false); + currentFrameTextField.setText(String.valueOf(value)); + currentFrameTextField.setEnabled(true); + + try { + selectStructure(Step); + setSnapshotValue(Step); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error during animation: " + ex.getMessage() + "\nAnimation stopped", "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + trajSlider.setEnabled(true); + } + + void selectStructure(int n) throws Exception { + + if (trajSlider.getMaximum() < 1) { + return; + } + + if (structureManagerInterface == null) { + JOptionPane.showMessageDialog(this, "Structure Manager Interface is not set", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + try { + structureManagerInterface.selectStructure(n - 1); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Cannot select structure # " + n + " : " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + } + + @Override + public void setSnapshotsCount(int new_max) { + setMaxSnapshotCount(new_max); + } + + public void startMediaButton_actionPerformed(ActionEvent e) { + try { + selectStructure(1); + setSnapshotValue(1); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error during animation: " + ex.getMessage() + "\nAnimation stopped", "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + } + + public void mediaEndButton_actionPerformed(ActionEvent e) { + try { + selectStructure(trajSlider.getMaximum()); + setSnapshotValue(trajSlider.getMaximum()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error during animation: " + ex.getMessage() + "\nAnimation stopped", "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + } + + /** + * Called when the Timer fires. + * + * @param e ActionEvent + */ + @Override + public void actionPerformed(ActionEvent e) { + + if (animationInProgress) { + logger.info("Lost frame..."); + return; + } + animationInProgress = true; + + int value = Step + stepStep * animDirection; + if (value < 1) { + value = 1; + } else if (value > trajSlider.getMaximum()) { + value = trajSlider.getMaximum(); + } + + Step = value; + + try { + long start = System.currentTimeMillis(); + selectStructure(Step); + //structureManagerInterface.selectStructure(Step - 1); + float secs = (System.currentTimeMillis() - start) / 1000.0f; + logger.info("Elapsed time: " + secs); + setSnapshotValue(Step); + } catch (Exception ex) { + animationInProgress = false; + timer.stop(); + JOptionPane.showMessageDialog(this, "Error during animation: " + ex.getMessage() + "\nAnimation stopped", "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + if (animationMode == 0) { // Animate once + if (Step == 1 && animDirection == -1) { + stopAnimation(); + } else if (Step == trajSlider.getMaximum() && animDirection == 1) { + stopAnimation(); + } + } else if (animationMode == 1) { // Animate in loop + if (Step == 1 && animDirection == -1) { + Step = trajSlider.getMaximum(); + } else if (Step == trajSlider.getMaximum() && animDirection == 1) { + Step = 1; + } + } else if (animationMode == 2) { // Animate back & forth + if (Step == 1 && animDirection == -1) { + if (trajSlider.getMaximum() > 1) { + Step = 1; + animDirection = 1; + } + } else if (Step == trajSlider.getMaximum() && animDirection == 1) { + if (trajSlider.getMaximum() > 1) { + Step = trajSlider.getMaximum() - 1; + animDirection = -1; + } + } + } + + animationInProgress = false; + + } + + public void playButton_actionPerformed(ActionEvent e) { + if (animationInProgress && animDirection == 1) { + return; + } + + animDirection = 1; + + startAnimation(); + } + + public void startAnimation() { + //Start (or restart) animating! + this.sendActionEvent(ANIMATION_STARTED); + timer.start(); + } + + public void stopAnimation() { + //Stop animation + timer.stop(); + animationInProgress = false; + this.sendActionEvent(ANIMATION_FINISHED); + } + + public void pauseButton_actionPerformed(ActionEvent e) { + stopAnimation(); + } + + public void playBackButton_actionPerformed(ActionEvent e) { + if (animationInProgress && animDirection == -1) { + return; + } + + animDirection = -1; + + startAnimation(); + + } + + public void stepSpinner_stateChanged(ChangeEvent e) { + Integer value = (Integer) stepSpinner.getValue(); + stepStep = value; + } + + public void fpsSpinner_stateChanged(ChangeEvent e) { + Integer value = (Integer) fpsSpinner.getValue(); + framesPerSeconds = value; + delay = 1000 / framesPerSeconds; + timer.setDelay(delay); + } + + public void stepForwardButton_actionPerformed(ActionEvent e) { + if (animationInProgress) { + timer.stop(); + animationInProgress = false; + } + + animDirection = 1; + int value = Step + stepStep * animDirection; + if (value > trajSlider.getMaximum()) { + value = trajSlider.getMaximum(); + } + + Step = value; + + try { + selectStructure(Step); + setSnapshotValue(Step); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error during animation: " + ex.getMessage() + "\nAnimation stopped", "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + } + + public void stepBackButton_actionPerformed(ActionEvent e) { + if (animationInProgress) { + timer.stop(); + animationInProgress = false; + } + + animDirection = -1; + int value = Step + stepStep * animDirection; + if (value < 1) { + value = 1; + } + + Step = value; + + try { + selectStructure(Step); + setSnapshotValue(Step); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error during animation: " + ex.getMessage() + "\nAnimation stopped", "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + } + + public void animationComboBox_itemStateChanged(ItemEvent e) { + if (!animationComboBox.isEnabled()) { + return; + } + if (e.getStateChange() == ItemEvent.DESELECTED) { + return; + } else if (e.getStateChange() == ItemEvent.SELECTED) { + animationMode = animationComboBox.getSelectedIndex(); + } + } + + public void currentFrameTextField_actionPerformed(ActionEvent e) { + if (animationInProgress) { + timer.stop(); + animationInProgress = false; + } + + try { + int n = Integer.parseInt(currentFrameTextField.getText().trim()); + if (n < 1 || n > trajSlider.getMaximum()) { + JOptionPane.showMessageDialog(this, + "MD Snapshot should be within range " + trajSlider.getMinimum() + " to " + + trajSlider.getMaximum() + " Got: " + n, "Error", JOptionPane.ERROR_MESSAGE); + currentFrameTextField.setText(String.valueOf(Step)); + return; + } + + Step = n; + try { + selectStructure(Step); + setSnapshotValue(Step); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Cannot select snapshot # " + Step + " : " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Wrong value for MD Snapshot: " + currentFrameTextField.getText().trim() + " : " + + ex.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE); + currentFrameTextField.setText(String.valueOf(Step)); + } + } + + public void addActionListener(ActionListener a) { + actionListeners.add(a); + } + + public void removeActionListener(ActionListener a) { + actionListeners.remove(a); + } + + public void removeActionListeners() { + actionListeners.clear(); + } + + public void sendActionEvent(int eventId) { + if (actionListeners == null || actionListeners.size() < 1) { + return; + } + ActionEvent event = new ActionEvent(this, eventId, ""); + for (ActionListener a : actionListeners) { + a.actionPerformed(event); + } + } +} diff --git a/src/main/java/cct/dialogs/AtomSelectionDialog.java b/src/main/java/cct/dialogs/AtomSelectionDialog.java new file mode 100644 index 0000000..20c3da2 --- /dev/null +++ b/src/main/java/cct/dialogs/AtomSelectionDialog.java @@ -0,0 +1,1010 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.dialogs; + +import cct.interfaces.AtomInterface; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.GridLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.Arrays; + +import javax.swing.BorderFactory; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JTextField; +import javax.swing.SwingConstants; +import javax.swing.border.TitledBorder; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +import cct.interfaces.MoleculeInterface; +import cct.j3d.Java3dUniverse; +import cct.modelling.*; +import cct.tools.ui.TaskProgessDialog; +import java.awt.*; +import javax.swing.*; + +/** + *

+ * Title: Molecular Structure Viewer/Editor

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class AtomSelectionDialog + extends JDialog implements OperationsOnAtoms, ActionListener { + + enum SELECTION_TYPE { + + SELECT_ALL_ATOMS, PROCESS_SELECTED_ATOMS, CLEAR_SELECTION, INVERT_SELECTION, SELECT_ATOM_TYPES, SELECT_MONOMER_TYPES, + SELECT_SUBSTRUCTURE, SELECT_SETS, SELECT_WITHIN_SPHERE, CANCEL_DIALOG + } + JButton Invert = new JButton(); + JButton Clear = new JButton(); + JButton All = new JButton(); + JButton Undo = new JButton(); + JPanel quickSelPanel = new JPanel(); + JButton atomTypes = new JButton(); + JButton monomer = new JButton(); + JButton Sphere = new JButton(); + JButton Substructure = new JButton(); + JButton Sets = new JButton(); + JPanel specialPanel = new JPanel(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + JRadioButton typeMonomer = new JRadioButton(); + JRadioButton typeMolecule = new JRadioButton(); + JRadioButton typeAtom = new JRadioButton(); + JPanel selTypePanel = new JPanel(); + ButtonGroup buttonGroup1 = new ButtonGroup(); + GridLayout gridLayout1 = new GridLayout(); + JRadioButton Union = new JRadioButton(); + JRadioButton Difference = new JRadioButton(); + JRadioButton Intersection = new JRadioButton(); + JPanel selRulePanel = new JPanel(); + GridLayout gridLayout2 = new GridLayout(); + ButtonGroup buttonGroup2 = new ButtonGroup(); + JPanel P1 = new JPanel(); + GridLayout gridLayout3 = new GridLayout(); + JPanel P2 = new JPanel(); + BorderLayout borderLayout2 = new BorderLayout(); + JPanel P3 = new JPanel(); + BorderLayout borderLayout3 = new BorderLayout(); + JCheckBox highlightCheckBox = new JCheckBox(); + private JLabel jLabel1 = new JLabel(); + private JTextField numSelectedAtomsTextField = new JTextField(); + private JPanel infoPanel = new JPanel(); + private JPanel buttonPanel = new JPanel(); + private JButton Cancel = new JButton(); + private JButton OK = new JButton(); + private JButton Help = new JButton(); + private Java3dUniverse daddy = null; + private Frame parentFrame = null; + private JSelectAtomTypesDialog jSelectAtomTypesDialog = null; + private JSelectMonomersDialog jSelectMonomersDialog = null; + private JSelectSubstructureDialog jSelectSubstructureDialog = null; + private JDialog nextDialog = null; + private JPanel jPanel2 = new JPanel(); + private BorderLayout borderLayout1 = new BorderLayout(); + private FlowLayout flowLayout1 = new FlowLayout(); + private JComponent userComponent = null; + private TaskProgessDialog taskProgessDialog = null; + + public AtomSelectionDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + parentFrame = owner; + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public AtomSelectionDialog() { + this(new Frame(), "Atom Selection", false); + } + + public JButton getHelpButton() { + return Help; + } + + public void setNextDialog(JDialog next) { + nextDialog = next; + } + + public void addUserComponent(JComponent uC) { + if (userComponent != null) { + infoPanel.remove(userComponent); + } + userComponent = uC; + infoPanel.add(userComponent, BorderLayout.SOUTH); + this.validate(); + this.pack(); + } + + private void jbInit() throws Exception { + Invert.setToolTipText("Invert Selection"); + Invert.setText("Invert"); + //Invert.addActionListener(new JAtomSelectionDialog_Invert_actionAdapter(this)); + Invert.addActionListener(this); + Clear.setToolTipText("Clear Selection"); + Clear.setText("Clear"); + Clear.addActionListener(new JAtomSelectionDialog_Clear_actionAdapter(this)); + All.setToolTipText("Select all atoms"); + All.setText("All"); + All.addActionListener(new JAtomSelectionDialog_All_actionAdapter(this)); + Undo.setEnabled(false); + Undo.setToolTipText("Undo last Selection"); + Undo.setText("Undo"); + atomTypes.setToolTipText("Select Atoms of particular Type"); + atomTypes.setText("Atom Types"); + atomTypes.addActionListener(new JAtomSelectionDialog_atomTypes_actionAdapter(this)); + monomer.setToolTipText("Select all Atoms of particular Monomers"); + monomer.setVerifyInputWhenFocusTarget(false); + monomer.setText("Monomer Types"); + monomer.addActionListener(new JAtomSelectionDialog_monomer_actionAdapter(this)); + Sphere.setEnabled(true); + Sphere.setToolTipText("Select all Atoms within specified radius"); + Sphere.setText("Sphere"); + Sphere.addActionListener(this); + Substructure.setToolTipText("Select Atoms in Substructure"); + Substructure.setText("Substructure"); + Substructure.addActionListener(new JAtomSelectionDialog_Substructure_actionAdapter(this)); + Sets.setToolTipText("Select Atoms in Set(s)"); + Sets.setText("Sets"); + Sets.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + Sets_actionPerformed(e); + } + }); + specialPanel.setLayout(gridBagLayout1); + typeMonomer.setToolTipText("Select all atoms in monomer"); + typeMonomer.setText("Monomer"); + typeMonomer.addChangeListener(new JAtomSelectionDialog_typeMonomer_changeAdapter(this)); + typeMolecule.setToolTipText("Select all atoms in Molecule"); + typeMolecule.setText("Molecule"); + typeMolecule.addChangeListener(new JAtomSelectionDialog_typeMolecule_changeAdapter(this)); + typeAtom.setToolTipText("Select Atom"); + typeAtom.setSelected(true); + typeAtom.setText("Atom"); + typeAtom.addChangeListener(new JAtomSelectionDialog_typeAtom_changeAdapter(this)); + selTypePanel.setLayout(gridLayout1); + gridLayout1.setColumns(-1); + gridLayout1.setRows(3); + Union.setToolTipText("Add to Selection"); + Union.setSelected(true); + Union.setText("Union"); + Union.addChangeListener(new JAtomSelectionDialog_Union_changeAdapter(this)); + Difference.setToolTipText("Subtract from Selection"); + Difference.setText("Difference"); + Difference.addChangeListener(new JAtomSelectionDialog_Difference_changeAdapter(this)); + Intersection.setToolTipText("Intersect with Selection"); + Intersection.setText("Intersection"); + Intersection.addChangeListener(new JAtomSelectionDialog_Intersection_changeAdapter(this)); + selRulePanel.setLayout(gridLayout2); + gridLayout2.setColumns(1); + gridLayout2.setRows(3); + selRulePanel.setBorder(new TitledBorder(BorderFactory.createLineBorder( + Color.lightGray, 1), "Selection Rule")); + selTypePanel.setBorder(new TitledBorder(BorderFactory.createLineBorder( + Color.lightGray, 1), "Selection Type")); + P1.setLayout(gridLayout3); + quickSelPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder( + Color.lightGray, 1), "Quick Selection")); + P2.setLayout(borderLayout2); + P3.setLayout(borderLayout3); + highlightCheckBox.setEnabled(true); + highlightCheckBox.setAlignmentX((float) 1.0); + highlightCheckBox.setHorizontalAlignment(SwingConstants.RIGHT); + highlightCheckBox.setHorizontalTextPosition(SwingConstants.RIGHT); + highlightCheckBox.setMargin(new Insets(2, 15, 2, 2)); + highlightCheckBox.setSelected(true); + highlightCheckBox.setText("Highlight selected atoms"); + highlightCheckBox.addItemListener(new ItemListener() { + + @Override + public void itemStateChanged(ItemEvent e) { + highlightCheckBox_itemStateChanged(e); + } + }); + jLabel1.setHorizontalAlignment(SwingConstants.LEFT); + jLabel1.setHorizontalTextPosition(SwingConstants.LEFT); + jLabel1.setText("Selected Atoms:"); + numSelectedAtomsTextField.setMaximumSize(new Dimension(60, 100)); + numSelectedAtomsTextField.setToolTipText("Shows number of selected atoms"); + numSelectedAtomsTextField.setEditable(false); + numSelectedAtomsTextField.setColumns(5); + Cancel.setToolTipText("Cancel Selection"); + Cancel.setText("Cancel"); + //Cancel.addActionListener(new JAtomSelectionDialog_Cancel_actionAdapter(this)); + Cancel.addActionListener(this); + OK.setToolTipText("Confirm Selection"); + OK.setText("OK"); + OK.addActionListener(new JAtomSelectionDialog_OK_actionAdapter(this)); + Help.setEnabled(false); + Help.setText("Help"); + this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); + addWindowListener(new WindowAdapter() { + + @Override + public void windowClosing(WindowEvent we) { + //setLabel("Thwarted user attempt to close window."); + finishDialog(); + } + }); + infoPanel.setLayout(borderLayout1); + jPanel2.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + quickSelPanel.add(All); + quickSelPanel.add(Clear); + quickSelPanel.add(Invert); + quickSelPanel.add(Undo); + P2.add(P1, BorderLayout.NORTH); + + selTypePanel.add(typeAtom); + selTypePanel.add(typeMonomer); + selTypePanel.add(typeMolecule); + + P1.add(selTypePanel); + P1.add(selRulePanel); + selRulePanel.add(Union); + selRulePanel.add(Difference); + selRulePanel.add(Intersection); + buttonGroup1.add(typeAtom); + buttonGroup1.add(typeMolecule); + buttonGroup1.add(typeMonomer); + buttonGroup2.add(Union); + buttonGroup2.add(Difference); + buttonGroup2.add(Intersection); + P2.add(quickSelPanel, BorderLayout.SOUTH); + P3.add(P2, BorderLayout.CENTER); + P3.add(specialPanel, BorderLayout.EAST); + specialPanel.add(atomTypes, + new GridBagConstraints(0, 0, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 0, 5), 0, 0)); + specialPanel.add(monomer, + new GridBagConstraints(0, 1, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(0, 5, 0, 5), 0, 0)); + specialPanel.add(Substructure, + new GridBagConstraints(0, 2, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(0, 5, 0, 5), 0, 0)); + specialPanel.add(Sets, + new GridBagConstraints(0, 3, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(0, 5, 0, 5), 0, 0)); + specialPanel.add(Sphere, + new GridBagConstraints(0, 4, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(0, 5, 0, 5), 0, 0)); + jPanel2.add(jLabel1); + jPanel2.add(numSelectedAtomsTextField); + jPanel2.add(highlightCheckBox); + this.getContentPane().add(buttonPanel, BorderLayout.SOUTH); + buttonPanel.add(OK); + buttonPanel.add(Cancel); + buttonPanel.add(Help); + + this.getContentPane().add(infoPanel, BorderLayout.CENTER); + + this.getContentPane().add(P3, BorderLayout.NORTH); + infoPanel.add(jPanel2, BorderLayout.NORTH); + } + + public void setTargetClass(Java3dUniverse parent) { + daddy = parent; + } + + public void initTaskProgressDialog() { + if (taskProgessDialog == null) { + Frame parentFrame = null; + Object parentObj = null; + while ((parentObj = this.getParent()) != null) { + if (parentObj instanceof Frame) { + parentFrame = (Frame) parentObj; + break; + } + } + taskProgessDialog = new TaskProgessDialog(parentFrame, false); + taskProgessDialog.setLocationRelativeTo(this); + taskProgessDialog.showHelpButton(false); + taskProgessDialog.setAlwaysOnTop(true); + } else { + taskProgessDialog.setProgress(0); // Reset progress bar + } + } + + private void perfomTask(Java3dUniverse daddy, SELECTION_TYPE job) { + perfomTask(daddy, job, null, null); + } + + private void perfomTask(Java3dUniverse daddy, SELECTION_TYPE job, int[] intArray) { + perfomTask(daddy, job, null, null, intArray, null); + } + + private void perfomTask(Java3dUniverse daddy, SELECTION_TYPE job, boolean[] booleanArray) { + perfomTask(daddy, job, null, null, null, booleanArray); + } + + private void perfomTask(Java3dUniverse daddy, SELECTION_TYPE job, Object[] array_1, Object[] array_2) { + perfomTask(daddy, job, array_1, array_2, null, null); + } + + private void perfomTask(Java3dUniverse daddy, SELECTION_TYPE job, Object[] array_1, Object[] array_2, int[] intArray, + boolean[] booleanArray) { + initTaskProgressDialog(); + SelectAtomsTask task = new SelectAtomsTask(this, daddy, taskProgessDialog, job, array_1, array_2, intArray, booleanArray); + + task.execute(); + } + + public void enableControls(boolean enable) { + Invert.setEnabled(enable); + Clear.setEnabled(enable); + All.setEnabled(enable); + //Undo.setEnabled(enable); + atomTypes.setEnabled(enable); + monomer.setEnabled(enable); + Sphere.setEnabled(enable); + Substructure.setEnabled(enable); + Sets.setEnabled(enable); + typeMonomer.setEnabled(enable); + typeMolecule.setEnabled(enable); + typeAtom.setEnabled(enable); + + Union.setEnabled(enable); + Difference.setEnabled(enable); + Intersection.setEnabled(enable); + + highlightCheckBox.setEnabled(enable); + + Cancel.setEnabled(enable); + OK.setEnabled(enable); + } + + public void OK_actionPerformed(ActionEvent e) { + setVisible(false); + if (nextDialog != null) { + daddy.enableMousePicking(false); + nextDialog.setVisible(true); + } else { + perfomTask(daddy, SELECTION_TYPE.PROCESS_SELECTED_ATOMS); + + //taskProgessDialog.showTaskProgress(true); + //showProgress.start(); + //daddy.processSelectedAtoms(showProgress); + //taskProgessDialog.showTaskProgress(false); + //showProgress.interrupt(); + } + + removeUserComponent(); + } + + public void removeUserComponent() { + if (userComponent != null) { + infoPanel.remove(userComponent); + } + validate(); + pack(); + } + + private void finishDialog() { + finishDialog(taskProgessDialog); + } + + private void finishDialog(TaskProgessDialog progress) { + daddy.cancelSelection(progress); + setVisible(false); + } + + //public void Cancel_actionPerformed(ActionEvent e) { + // finishDialog(); + // removeUserComponent(); + //} + public void Clear_actionPerformed(ActionEvent e) { + perfomTask(daddy, SELECTION_TYPE.CLEAR_SELECTION); + //daddy.clearSelection(); + } + + public void All_actionPerformed(ActionEvent e) { + + perfomTask(daddy, SELECTION_TYPE.SELECT_ALL_ATOMS); + + //taskProgessDialog.showTaskProgress(true); + //showProgress.start(); + //daddy.selectAll(showProgress); + //taskProgessDialog.showTaskProgress(false); + //showProgress.interrupt(); + } + + //public void Invert_actionPerformed(ActionEvent e) { + // perfomTask(daddy, SELECTION_TYPE.INVERT_SELECTION); + //} + public void Union_stateChanged(ChangeEvent e) { + if (Union.isSelected()) { + daddy.setSelectionRule(SELECTION_RULE.UNION); + //Union.setSelected(true); + } + validate(); + } + + public void Difference_stateChanged(ChangeEvent e) { + if (Difference.isSelected()) { + daddy.setSelectionRule(SELECTION_RULE.DIFFERENCE); + //Difference.setSelected(true); + } + + validate(); + } + + public void Intersection_stateChanged(ChangeEvent e) { + if (Intersection.isSelected()) { + daddy.setSelectionRule(SELECTION_RULE.INTERSECTION); + //Intersection.setSelected(true); + } + + validate(); + } + + public void typeAtom_stateChanged(ChangeEvent e) { + if (typeAtom.isSelected()) { + daddy.setSelectionType(cct.modelling.SELECTION_TYPE.ATOMS); + } + validate(); + } + + public void typeMolecule_stateChanged(ChangeEvent e) { + if (typeMolecule.isSelected()) { + daddy.setSelectionType(cct.modelling.SELECTION_TYPE.MOLECULES); + } + validate(); + } + + public void typeMonomer_stateChanged(ChangeEvent e) { + if (typeMonomer.isSelected()) { + daddy.setSelectionType(cct.modelling.SELECTION_TYPE.MONOMERS); + } + validate(); + } + + public void atomTypes_actionPerformed(ActionEvent e) { + if (jSelectAtomTypesDialog == null) { + jSelectAtomTypesDialog = new JSelectAtomTypesDialog(parentFrame != null ? parentFrame : new Frame(), "Select Atom Types", true); + jSelectAtomTypesDialog.setLocationRelativeTo(this); + } + + jSelectAtomTypesDialog.setupElements(daddy.getElementsInMolecule()); + jSelectAtomTypesDialog.setupAtomNames(daddy.getAtomNamesInMolecule()); + jSelectAtomTypesDialog.setVisible(true); + + if (jSelectAtomTypesDialog.isOK()) { + Object elements[] = jSelectAtomTypesDialog.getSelectedElements(); + Object atom_names[] = jSelectAtomTypesDialog.getSelectedAtomNames(); + perfomTask(daddy, SELECTION_TYPE.SELECT_ATOM_TYPES, elements, atom_names); + //daddy.makeSelection(elements, atom_names); + } + } + + public void monomer_actionPerformed(ActionEvent e) { + if (jSelectMonomersDialog == null) { + String title = "Select Monomers"; + jSelectMonomersDialog = new JSelectMonomersDialog(parentFrame != null ? parentFrame : new Frame(), title, true); + jSelectMonomersDialog.setLocationRelativeTo(this); + } + + jSelectMonomersDialog.setupMonomers(daddy.getUniqueMonomersInMolecule()); + jSelectMonomersDialog.setVisible(true); + + if (jSelectMonomersDialog.isOK()) { + Object monomers[] = jSelectMonomersDialog.getSelectedMonomers(); + perfomTask(daddy, SELECTION_TYPE.SELECT_MONOMER_TYPES, monomers, null); + //daddy.makeMonomersSelection(monomers); + } + + } + + public void Substructure_actionPerformed(ActionEvent e) { + if (jSelectSubstructureDialog == null) { + String title = "Select Monomers"; + jSelectSubstructureDialog = new JSelectSubstructureDialog(parentFrame != null ? parentFrame : new Frame(), title, true); + jSelectSubstructureDialog.setLocationRelativeTo(this); + } + + jSelectSubstructureDialog.setupSubstructure(daddy.getMolecularSubstructure()); + jSelectSubstructureDialog.setVisible(true); + + if (jSelectSubstructureDialog.isOK()) { + int monomers[] = jSelectSubstructureDialog.getSelectedMonomers(); + perfomTask(daddy, SELECTION_TYPE.SELECT_SUBSTRUCTURE, monomers); + //daddy.makeMonomersSelection(monomers); + } + } + + public void highlightCheckBox_itemStateChanged(ItemEvent e) { + daddy.highlighSelectedAtoms(highlightCheckBox.isSelected()); + } + + private class JAtomSelectionDialog_Substructure_actionAdapter + implements ActionListener { + + private AtomSelectionDialog adaptee; + + JAtomSelectionDialog_Substructure_actionAdapter(AtomSelectionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Substructure_actionPerformed(e); + } + } + + private class JAtomSelectionDialog_atomTypes_actionAdapter + implements ActionListener { + + private AtomSelectionDialog adaptee; + + JAtomSelectionDialog_atomTypes_actionAdapter(AtomSelectionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.atomTypes_actionPerformed(e); + } + } + + private class JAtomSelectionDialog_monomer_actionAdapter + implements ActionListener { + + private AtomSelectionDialog adaptee; + + JAtomSelectionDialog_monomer_actionAdapter(AtomSelectionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.monomer_actionPerformed(e); + } + } + + public void Sets_actionPerformed(ActionEvent e) { + if (daddy == null) { + return; + } + Sets.setEnabled(false); + Object obj = daddy.getMoleculeInterface().getProperty(MoleculeInterface.AtomicSets); + if (obj == null) { + JOptionPane.showMessageDialog(this, "No atomic set(s) in molecule", "No sets", JOptionPane.WARNING_MESSAGE); + Sets.setEnabled(true); + return; + } else if (!(obj instanceof AtomicSets)) { + System.err.println(this.getClass().getCanonicalName() + ": Sets_actionPerformed: expected AtomicSets, got " + + obj.getClass().getCanonicalName() + " Ignored..."); + Sets.setEnabled(true); + return; + } + AtomicSets sets = (AtomicSets) obj; + if (sets.size() < 1) { + JOptionPane.showMessageDialog(this, "No atomic set(s) in molecule", "No sets", JOptionPane.WARNING_MESSAGE); + Sets.setEnabled(true); + return; + } + + String[] names = new String[sets.size()]; + sets.keySet().toArray(names); + Arrays.sort(names); + + SelectListDialog selectListDialog = new SelectListDialog(new Frame(), "Select available set(s)"); + selectListDialog.setList(names); + selectListDialog.setLocationRelativeTo(this); + if (!selectListDialog.showDialog()) { + Sets.setEnabled(true); + return; + } + + Object[] selSets = selectListDialog.getSelectedValues(); + if (selSets == null || selSets.length < 1) { + Sets.setEnabled(true); + return; + } + + boolean selectedAtoms[] = new boolean[daddy.getMoleculeInterface().getNumberOfAtoms()]; + for (int i = 0; i < selectedAtoms.length; i++) { + selectedAtoms[i] = false; + } + + for (int i = 0; i < selSets.length; i++) { + AtomicSet aset = sets.get(selSets[i]); + for (int j = 0; j < aset.size(); j++) { + int n = daddy.getMoleculeInterface().getAtomIndex(aset.get(j)); + if (n == -1) { + continue; + } + selectedAtoms[n] = true; + } + } + + perfomTask(daddy, SELECTION_TYPE.SELECT_SETS, selectedAtoms); + //daddy.makeSelection(selectedAtoms); + + Sets.setEnabled(true); + + } + + class JAtomSelectionDialog_typeMonomer_changeAdapter + implements ChangeListener { + + private AtomSelectionDialog adaptee; + + JAtomSelectionDialog_typeMonomer_changeAdapter(AtomSelectionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.typeMonomer_stateChanged(e); + } + } + + class JAtomSelectionDialog_typeMolecule_changeAdapter + implements ChangeListener { + + private AtomSelectionDialog adaptee; + + JAtomSelectionDialog_typeMolecule_changeAdapter(AtomSelectionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.typeMolecule_stateChanged(e); + } + } + + class JAtomSelectionDialog_typeAtom_changeAdapter + implements ChangeListener { + + private AtomSelectionDialog adaptee; + + JAtomSelectionDialog_typeAtom_changeAdapter(AtomSelectionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.typeAtom_stateChanged(e); + } + } + + class JAtomSelectionDialog_Union_changeAdapter + implements ChangeListener { + + private AtomSelectionDialog adaptee; + + JAtomSelectionDialog_Union_changeAdapter(AtomSelectionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.Union_stateChanged(e); + } + } + + class JAtomSelectionDialog_Difference_changeAdapter + implements ChangeListener { + + private AtomSelectionDialog adaptee; + + JAtomSelectionDialog_Difference_changeAdapter(AtomSelectionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.Difference_stateChanged(e); + } + } + + class JAtomSelectionDialog_Intersection_changeAdapter + implements ChangeListener { + + private AtomSelectionDialog adaptee; + + JAtomSelectionDialog_Intersection_changeAdapter(AtomSelectionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.Intersection_stateChanged(e); + } + } + + class JAtomSelectionDialog_All_actionAdapter + implements ActionListener { + + private AtomSelectionDialog adaptee; + + JAtomSelectionDialog_All_actionAdapter(AtomSelectionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.All_actionPerformed(e); + } + } + + class JAtomSelectionDialog_OK_actionAdapter + implements ActionListener { + + private AtomSelectionDialog adaptee; + + JAtomSelectionDialog_OK_actionAdapter(AtomSelectionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.OK_actionPerformed(e); + } + } + + //class JAtomSelectionDialog_Cancel_actionAdapter + // implements ActionListener { + // private AtomSelectionDialog adaptee; + // JAtomSelectionDialog_Cancel_actionAdapter(AtomSelectionDialog adaptee) { + // this.adaptee = adaptee; + // } + // @Override + // public void actionPerformed(ActionEvent e) { + // adaptee.Cancel_actionPerformed(e); + // } + //} + class JAtomSelectionDialog_Clear_actionAdapter + implements ActionListener { + + private AtomSelectionDialog adaptee; + + JAtomSelectionDialog_Clear_actionAdapter(AtomSelectionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Clear_actionPerformed(e); + } + } + + public void actionPerformed(ActionEvent e) { + if (e.getSource() == Invert) { + perfomTask(daddy, SELECTION_TYPE.INVERT_SELECTION); + //************************************************************************ + + } else if (e.getSource() == Cancel) { + //finishDialog(); + //removeUserComponent(); + this.perfomTask(daddy, SELECTION_TYPE.CLEAR_SELECTION); + //***** Sphere Selection + } else if (e.getSource() == Sphere) { + if (daddy == null) { + JOptionPane.showMessageDialog(this, "daddy == null", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + String str = JOptionPane.showInputDialog(this, "Input Shere radius: ", "Input Shere radius", JOptionPane.QUESTION_MESSAGE); + if (str == null || str.trim().length() < 1) { + return; + } + + double rad = 0; + try { + rad = Double.parseDouble(str.trim()); + if (rad <= 0) { + JOptionPane.showMessageDialog(this, "Radius should be positive value, got " + rad, "Error", JOptionPane.ERROR_MESSAGE); + return; + } + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Wrong number " + str.trim() + " : " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + MoleculeInterface mol = daddy.getMoleculeInterface(); + //boolean selectedAtoms[] = new boolean[mol.getNumberOfAtoms()]; + int nsel = 0; + boolean noSelectedAtoms = true; + for (int i = 0; i < mol.getNumberOfAtoms(); i++) { + if (mol.getAtomInterface(i).isSelected()) { + noSelectedAtoms = false; + break; + } + } + + if (noSelectedAtoms) { + JOptionPane.showMessageDialog(this, "Select some atom(s) first!", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + boolean selectedAtoms[] = null; + try { + selectedAtoms = AtomSelection.selectAtomsWithinSphere(mol, rad, daddy.getSelectionType(), null); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error while selected atoms withon a sphere: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + //for (int i = 0; i < mol.getNumberOfAtoms(); i++) { + // AtomInterface at = mol.getAtomInterface(i); + // if (!at.isSelected()) { + // continue; + // } + // for (int j = 0; j < mol.getNumberOfAtoms(); j++) { + // AtomInterface atom = mol.getAtomInterface(j); + // if (atom.isSelected()) { + // continue; + // } + // if (atom.distanceTo(at) <= rad) { + // selectedAtoms[j] = true; + // } + // } + //} + this.perfomTask(daddy, SELECTION_TYPE.SELECT_WITHIN_SPHERE, selectedAtoms); + //daddy.makeSelection(selectedAtoms); + } + } + + class SelectAtomsTask extends SwingWorker { + + AtomSelectionDialog parentDialog; + TaskProgessDialog progress; + Java3dUniverse daddy; + SELECTION_TYPE job; + Object[] array_1, array_2; + int[] intArray; + boolean[] booleanArray; + boolean done = false; + + SelectAtomsTask(AtomSelectionDialog parentDialog, Java3dUniverse daddy, TaskProgessDialog progress, SELECTION_TYPE job) { + this(parentDialog, daddy, progress, job, null, null, null, null); + } + + SelectAtomsTask(AtomSelectionDialog parentDialog, Java3dUniverse daddy, TaskProgessDialog progress, SELECTION_TYPE job, + boolean[] booleanArray) { + this(parentDialog, daddy, progress, job, null, null, null, booleanArray); + } + + SelectAtomsTask(AtomSelectionDialog parentDialog, Java3dUniverse daddy, TaskProgessDialog progress, SELECTION_TYPE job, + Object[] array_1, Object[] array_2, int[] intArray, boolean[] booleanArray) { + //initialize + this.parentDialog = parentDialog; + this.daddy = daddy; + this.progress = progress; + this.job = job; + this.array_1 = array_1; + this.array_2 = array_2; + this.intArray = intArray; + this.booleanArray = booleanArray; + } + + @Override + public Void doInBackground() { + parentDialog.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + parentDialog.enableControls(false); + progress.setCanceled(false); + progress.setVisible(true); + try { + switch (job) { + case PROCESS_SELECTED_ATOMS: + daddy.processSelectedAtoms(progress); + return null; + case CANCEL_DIALOG: + finishDialog(); + removeUserComponent(); + break; + case SELECT_ALL_ATOMS: + daddy.selectAll(progress); + break; + case CLEAR_SELECTION: + daddy.clearSelection(progress); + break; + case INVERT_SELECTION: + daddy.invertSelection(progress); + break; + case SELECT_ATOM_TYPES: + daddy.makeSelection(array_1, array_2, progress); + break; + case SELECT_MONOMER_TYPES: + daddy.makeMonomersSelection(array_1, progress); + break; + case SELECT_SUBSTRUCTURE: + daddy.makeMonomersSelection(intArray, progress); + break; + case SELECT_SETS: + daddy.makeSelection(booleanArray, progress); + break; + case SELECT_WITHIN_SPHERE: + daddy.makeSelection(booleanArray, progress); + break; + } + } catch (Exception ex) { + ex.printStackTrace(); + } + numSelectedAtomsTextField.setText(String.valueOf(daddy.getNumberSelectedAtoms())); + return null; + } + + @Override + public void done() { + //parentDialog.setEnabled(true); + parentDialog.enableControls(true); + parentDialog.setCursor(null); + progress.setVisible(false); + progress.setCanceled(false); + done = true; + } + } +} diff --git a/src/main/java/cct/dialogs/CalculateMenu.java b/src/main/java/cct/dialogs/CalculateMenu.java new file mode 100644 index 0000000..0957e39 --- /dev/null +++ b/src/main/java/cct/dialogs/CalculateMenu.java @@ -0,0 +1,259 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.dialogs; + +import cct.GlobalSettings; +import cct.dynamics.Dynamics; +import cct.interfaces.ForceFieldInterface; +import cct.interfaces.JamberooCoreInterface; +import cct.interfaces.MoleculeInterface; +import cct.interfaces.ParentInterface; +import cct.j3d.Java3dUniverse; +import cct.math.MinimizerInterface; +import cct.modelling.BackgroundMinimizer; +import cct.modelling.FFMolecule; +import cct.modelling.MinimizeStructure; +import cct.modelling.MolecularEnergy; +import cct.modelling.ui.JSetupEnergyDialog; +import cct.sff.SimpleForceField; +import cct.tools.ui.JShowText; +import java.awt.Component; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.logging.Logger; +import javax.swing.JDialog; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; + +/** + * + * @author Sap + */ +public class CalculateMenu extends JMenu implements ActionListener, ParentInterface { + + static final Logger logger = Logger.getLogger(CalculateMenu.class.getCanonicalName()); + private JamberooCoreInterface jamberooCore; + private Java3dUniverse java3dUniverse; + private JMenuItem jMenuCalcEnergy = new JMenuItem("Energy"); + private JMenuItem jMenuMinEnergy2 = new JMenuItem("Minimize Energy"); + private JMenuItem jMenuMinEnergy = new JMenuItem("Minimize Energy Simplex"); + private JMenuItem jMenuMD = new JMenuItem("Molecular Dynamics"); + private JSetupEnergyDialog jSetupEnergyDialog = null; + private Component parentComponent = null; + private MinimizeStructure mimimizeStructure = null; + private BackgroundMinimizer backgroundMinimizer = null; + private static String LABEL_ENERGY_SETUP_DIALOG = CalculateMenu.class.getCanonicalName() + "/EnergySetupDialog"; + + public Component getParentComponent() { + return parentComponent; + } + + public void setParentComponent(Component parentComponent) { + this.parentComponent = parentComponent; + } + + public CalculateMenu(JamberooCoreInterface core) { + super(); + jamberooCore = core; + java3dUniverse = jamberooCore.getJamberooRenderer(); + + } + + public void createMenu() { + + jMenuCalcEnergy.addActionListener(this); + add(jMenuCalcEnergy); + + jMenuMinEnergy2.addActionListener(this); + add(jMenuMinEnergy2); + + jMenuMinEnergy.addActionListener(this); + jMenuMinEnergy.setEnabled(false); + add(jMenuMinEnergy); + } + + public void actionPerformed(ActionEvent actionEvent) { + // --- Calculating Energy + + + if (actionEvent.getSource() == this.jMenuCalcEnergy && java3dUniverse.getMolecule() != null) { + + //if (jSetupEnergyDialog == null) { + if (GlobalSettings.getRegisterDialog(LABEL_ENERGY_SETUP_DIALOG) == null) { + jSetupEnergyDialog = new JSetupEnergyDialog(getParentFrame(), "Energy Setup", true); + GlobalSettings.registerDialog(LABEL_ENERGY_SETUP_DIALOG, jSetupEnergyDialog); + ForceFieldInterface ff[] = new ForceFieldInterface[1]; + ff[0] = new SimpleForceField(); + jSetupEnergyDialog.setForceFields(ff); + jSetupEnergyDialog.setLocationRelativeTo(this); + } else { + JDialog dial = (JDialog) GlobalSettings.getRegisterDialog(LABEL_ENERGY_SETUP_DIALOG); + jSetupEnergyDialog = (JSetupEnergyDialog) dial; + } + + jSetupEnergyDialog.setTitle("Energy Setup"); + + jSetupEnergyDialog.energySetupMode(); + jSetupEnergyDialog.setVisible(true); + if (!jSetupEnergyDialog.isOkPressed()) { + return; + } + + ForceFieldInterface selectedFF = jSetupEnergyDialog.getSelectedFF(); + + FFMolecule ffMol = new FFMolecule(java3dUniverse.getMolecule()); + ffMol.applyForceField(selectedFF); + + try { + ffMol.formFFParameters(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), "Error calculating Energy", JOptionPane.ERROR_MESSAGE); + return; + } + + MolecularEnergy en = new MolecularEnergy(ffMol); + try { + double energy = en.calculateEnergy(false); + logger.info("Total Energy: " + energy); + en.printEnergyDecomposition(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), + "Error calculating Energy", JOptionPane.ERROR_MESSAGE); + return; + } + JShowText show = new JShowText("Energy Decomposition"); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + PrintStream store = System.out; + System.setOut(new PrintStream(out)); + en.printEnergyDecomposition(); + show.setText(out); + show.setSize(500, 300); + show.setLocationRelativeTo(this); + show.setVisible(true); + System.setOut(store); + } // --- Minimizing Energy + else if (actionEvent.getSource() == this.jMenuMinEnergy && java3dUniverse.getMolecule() != null) { + + MinimizeStructure ms = new MinimizeStructure(java3dUniverse.getMolecule()); + ms.setForceField(jSetupEnergyDialog.getSelectedFF()); + try { + ms.minimize(0); + java3dUniverse.addMolecule(ms.getMolecule()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), + "Error minimizing Energy", JOptionPane.ERROR_MESSAGE); + return; + } + + } else if (actionEvent.getSource() == this.jMenuMinEnergy2 && java3dUniverse.getMolecule() != null) { + if (GlobalSettings.getRegisterDialog(LABEL_ENERGY_SETUP_DIALOG) == null) { + jSetupEnergyDialog = new JSetupEnergyDialog(getParentFrame(), "Minimization Setup", true); + GlobalSettings.registerDialog(LABEL_ENERGY_SETUP_DIALOG, jSetupEnergyDialog); + ForceFieldInterface ff[] = new ForceFieldInterface[1]; + ff[0] = new SimpleForceField(); + jSetupEnergyDialog.setForceFields(ff); + jSetupEnergyDialog.setLocationRelativeTo(this); + } else { + JDialog dial = (JDialog) GlobalSettings.getRegisterDialog(LABEL_ENERGY_SETUP_DIALOG); + jSetupEnergyDialog = (JSetupEnergyDialog) dial; + } + + if (!jSetupEnergyDialog.areMinimizersSet()) { + MinimizerInterface mins[] = new MinimizerInterface[1]; + mins[0] = new cct.math.DFPMin(); + jSetupEnergyDialog.setMinimizers(mins); + } + jSetupEnergyDialog.minimizationSetupMode(); + jSetupEnergyDialog.setTitle("Minimization Setup"); + jSetupEnergyDialog.setVisible(true); + if (!jSetupEnergyDialog.isOkPressed()) { + return; + } + + MinimizerInterface min = jSetupEnergyDialog.getSelectedMinimizer(); + + mimimizeStructure = new MinimizeStructure(java3dUniverse.getMolecule()); + mimimizeStructure.setForceField(jSetupEnergyDialog.getSelectedFF()); + mimimizeStructure.setMinimizer(min); + + backgroundMinimizer = new BackgroundMinimizer(jMenuMinEnergy2, this, mimimizeStructure); + backgroundMinimizer.setVariablesFrequencyUpdate(jSetupEnergyDialog.getScreenRefreshRate()); + backgroundMinimizer.setVisualizer(java3dUniverse); + + mimimizeStructure.setMinimizeProgressInterface(backgroundMinimizer); + jMenuMinEnergy2.setEnabled(false); + backgroundMinimizer.start(); + + } // Molecular Dynamics + else if (actionEvent.getSource() == this.jMenuMD && java3dUniverse.getMolecule() != null) { + /* + if (GlobalSettings.getRegisterDialog(LABEL_ENERGY_SETUP_DIALOG) == null) { + jSetupEnergyDialog = new JSetupEnergyDialog(getParentFrame(), "Minimization Setup", true); + GlobalSettings.registerDialog(LABEL_ENERGY_SETUP_DIALOG, jSetupEnergyDialog); + ForceFieldInterface ff[] = new ForceFieldInterface[1]; + ff[0] = new SimpleForceField(); + jSetupEnergyDialog.setForceFields(ff); + jSetupEnergyDialog.setLocationRelativeTo(this); + } else { + JDialog dial = (JDialog) GlobalSettings.getRegisterDialog(LABEL_ENERGY_SETUP_DIALOG); + jSetupEnergyDialog = (JSetupEnergyDialog) dial; + } + */ + + /* + if (!jSetupEnergyDialog.areMinimizersSet()) { + MinimizerInterface mins[] = new MinimizerInterface[1]; + mins[0] = new cct.math.DFPMin(); + jSetupEnergyDialog.setMinimizers(mins); + } + jSetupEnergyDialog.minimizationSetupMode(); + jSetupEnergyDialog.setTitle("Minimization Setup"); + jSetupEnergyDialog.setVisible(true); + if (!jSetupEnergyDialog.isOkPressed()) { + return; + } + */ + + + Dynamics dynamics = new Dynamics(java3dUniverse.getMolecule()); + + MinimizerInterface min = jSetupEnergyDialog.getSelectedMinimizer(); + + mimimizeStructure = new MinimizeStructure(java3dUniverse.getMolecule()); + mimimizeStructure.setForceField(jSetupEnergyDialog.getSelectedFF()); + mimimizeStructure.setMinimizer(min); + + backgroundMinimizer = new BackgroundMinimizer(jMenuMinEnergy2, this, mimimizeStructure); + backgroundMinimizer.setVariablesFrequencyUpdate(jSetupEnergyDialog.getScreenRefreshRate()); + backgroundMinimizer.setVisualizer(java3dUniverse); + + mimimizeStructure.setMinimizeProgressInterface(backgroundMinimizer); + jMenuMinEnergy2.setEnabled(false); + backgroundMinimizer.start(); + + } + } + + public void childFinished(Object child) { + if (child instanceof JMenuItem && child == jMenuMinEnergy2) { + jMenuMinEnergy2.setEnabled(true); + final MoleculeInterface mol = backgroundMinimizer.getMolecule(); + if (mol != null) { + java3dUniverse.updateMolecularGeometry(); + } + } + } + + public Frame getParentFrame() { + if (parentComponent != null && parentComponent instanceof Frame) { + return (Frame) parentComponent; + } + return new Frame(); + } +} diff --git a/src/main/java/cct/dialogs/EditMenu.java b/src/main/java/cct/dialogs/EditMenu.java new file mode 100644 index 0000000..41f5ec8 --- /dev/null +++ b/src/main/java/cct/dialogs/EditMenu.java @@ -0,0 +1,890 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.dialogs; + +import java.awt.Component; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.io.File; +import java.io.InputStream; +import java.net.URL; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; + +import javax.swing.JButton; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.KeyStroke; +import javax.swing.SwingUtilities; + +import cct.GlobalSettings; +import cct.gaussian.ui.ManageCubesFrame; +import cct.interfaces.AtomInterface; +import cct.interfaces.HelperInterface; +import cct.interfaces.JamberooCoreInterface; +import cct.interfaces.MoleculeChangeListener; +import cct.interfaces.MoleculeEventObject; +import cct.interfaces.MoleculeEventObject.MOLECULE_EVENT; +import cct.interfaces.MoleculeInterface; +import cct.j3d.Java3dUniverse; +import cct.modelling.AtomicSets; +import cct.modelling.CCTAtomTypes; +import cct.modelling.ChemicalElements; +import cct.modelling.FormatManager; +import cct.modelling.MolecularDataWizard; +import cct.modelling.MolecularFileFormats; +import cct.modelling.Molecule; +import cct.modelling.OperationsOnAtoms; +import cct.modelling.ui.EditAndPasteCoordFrame; +import cct.modelling.ui.EditAndSaveCoordDialog; +import cct.modelling.ui.SetNamePanel; +import cct.tools.FileFilterImpl; +import cct.tools.FragmentDictionaryParser; +import cct.tools.TextClipboard; +import java.util.LinkedHashSet; +import java.util.Set; + +/** + * + * @author vvv900 + */ +public class EditMenu extends JMenu implements ActionListener { + + private static final String ERROR_MESSAGE = "Error"; + public static final String ADD_ATOMS_MESSAGE = "Add Atoms"; + public static final String ADD_MOLECULE_MESSAGE = "Add Molecule"; + public static final String MODIFY_ATOMS_MESSAGE = "Modify Atoms"; + public static final String DELETE_ATOMS_MESSAGE = "Delete Atoms"; + + public enum EDIT_MENU_ACTIONS { + + UNKNOWN_EDIT_ACTION, SET_MOLECULE_NAME, ADD_ATOMS, ADD_MOLECULE, ADD_FRAGMENT, ADD_HYDROGENS, MODIFY_ATOMS, MODIFY_BONDS, + MODIFY_ANGLES, MODIFY_TORSIONS, GUESS_ATOM_TYPES, RECALC_CONNECTIVITY, DELETE_ATOMS, ERASE_MOLECULE, CREATE_CENTROID, + SOLVATE_CAP, SOLVATE_SHELL, CREATE_ATOM_SET, EDIT_ATOM_SET + } + private JMenuItem jMenuSetMolName = new JMenuItem(); + private Java3dUniverse java3dUniverse; + private Java3dUniverse secondJ3D = null, thirdJ3D = null; + private EditAndSaveCoordDialog editAndSaveCoordDialog = null; + private Component parentComponent = null; + private EditAndPasteCoordFrame editAndPasteCoordFrame = null; + private JMenu jSubmenuAdd = new JMenu("Add"); + private JMenuItem jAddMolecule = new JMenuItem(); + static final Logger logger = Logger.getLogger(EditMenu.class.getCanonicalName()); + private HelperInterface helper = null; + private JAddMoleculeDialog jAddMoleculeDialog = null; + private JAddFragmentDialog jAddFragmentDialog = null; + private URL fragDic = null; + private List volumeDataList = null; + private ManageCubesFrame manageCubesDialog = null; + private JamberooCoreInterface jamberooCore; + private Set moleculeChangeListeners = new LinkedHashSet(); + + public EditMenu(JamberooCoreInterface core) { + super(); + jamberooCore = core; + java3dUniverse = jamberooCore.getJamberooRenderer(); + helper = jamberooCore.getHelper(); + } + + public void addMoleculeChangeListener(MoleculeChangeListener listener) { + moleculeChangeListeners.add(listener); + } + + public void removeMoleculeChangeListener(MoleculeChangeListener listener) { + moleculeChangeListeners.remove(listener); + } + + public void removeAllMoleculeChangeListeners() { + moleculeChangeListeners.removeAll(moleculeChangeListeners); + } + + public void createMenu() { + + jMenuSetMolName.setText("Set Molecule Name"); + jMenuSetMolName.setActionCommand(EDIT_MENU_ACTIONS.SET_MOLECULE_NAME.name()); + jMenuSetMolName.addActionListener(this); + jMenuSetMolName.setIcon(GlobalSettings.ICON_16x16_DOCUMENT_EDIT); + add(jMenuSetMolName); + // --- Clipboard stuff + + addSeparator(); + + if (parentComponent == null) { + parentComponent = this; + } + + JMenuItem jMenuItem = new JMenuItem("Copy to Clipboard"); + jMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK)); + jMenuItem.setIcon(GlobalSettings.ICON_16x16_DOCUMENT_INTO); + jMenuItem.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + try { + if (editAndSaveCoordDialog == null) { + editAndSaveCoordDialog = new EditAndSaveCoordDialog("Clipboard content"); + editAndSaveCoordDialog.setFormatManager(new FormatManager()); + editAndSaveCoordDialog.setIconImage(GlobalSettings.ICON_16x16_DOCUMENT_INTO.getImage()); + editAndSaveCoordDialog.setDefaultFileName("coordinates.txt"); + editAndSaveCoordDialog.setLocationRelativeTo(parentComponent); + editAndSaveCoordDialog.pack(); + editAndSaveCoordDialog.setSize(320, 480); + } + editAndSaveCoordDialog.setMoleculeInterface(java3dUniverse.getMolecule()); + editAndSaveCoordDialog.setVisible(true); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + } + } + }); + + add(jMenuItem); + + jMenuItem = new JMenuItem("Paste from Clipboard"); + jMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, + ActionEvent.CTRL_MASK)); + jMenuItem.setIcon(GlobalSettings.ICON_16x16_DOCUMENT_OUT); + jMenuItem.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + + if (editAndPasteCoordFrame != null + && editAndPasteCoordFrame.isVisible()) { + return; + } + + TextClipboard textTransfer = new TextClipboard(); + try { + String contents = textTransfer.getClipboardContents(); + if (contents.trim().length() < 1) { + JOptionPane.showMessageDialog(parentComponent, "Clipboad contents is empty", "error", + JOptionPane.ERROR_MESSAGE); + return; + } + + if (editAndPasteCoordFrame == null) { + editAndPasteCoordFrame = new EditAndPasteCoordFrame(); + editAndPasteCoordFrame.setTitle("Clipboard contents"); + editAndPasteCoordFrame.setIconImage(GlobalSettings.ICON_16x16_DOCUMENT_OUT.getImage()); + editAndPasteCoordFrame.setDefaultFileName("coordinates.txt"); + editAndPasteCoordFrame.setLocationRelativeTo(parentComponent); + editAndPasteCoordFrame.pack(); + int width = 320; + if (editAndPasteCoordFrame.getSize().width > 320) { + width = editAndPasteCoordFrame.getSize().width; + } + editAndPasteCoordFrame.setSize(width, 480); + } + editAndPasteCoordFrame.setJava3dUniverse(java3dUniverse); + editAndPasteCoordFrame.setCoordinates(contents); + editAndPasteCoordFrame.setVisible(true); + } catch (Exception ex) { + JOptionPane.showMessageDialog(parentComponent, ex.getMessage(), ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + } + } + }); + + add(jMenuItem); + + addSeparator(); + + // --- "Add Atoms" item + jMenuItem = new JMenuItem(ADD_ATOMS_MESSAGE, GlobalSettings.ICON_16x16_ADD_ATOM); + jMenuItem.setActionCommand(EDIT_MENU_ACTIONS.ADD_ATOMS.name()); + jMenuItem.addActionListener(this); + jSubmenuAdd.add(jMenuItem); + + // --- Add Molecule + jAddMolecule.setText(ADD_MOLECULE_MESSAGE); + jAddMolecule.setIcon(GlobalSettings.ICON_16x16_MOLECULE); + jAddMolecule.setActionCommand(EDIT_MENU_ACTIONS.ADD_MOLECULE.name()); + jAddMolecule.addActionListener(this); + jSubmenuAdd.add(jAddMolecule); + + // --- Add Fragment + jMenuItem = new JMenuItem(); + jMenuItem.setText("Add Fragment"); + jMenuItem.setIcon(GlobalSettings.ICON_16x16_ADD_FRAGMENT); + jMenuItem.setActionCommand(EDIT_MENU_ACTIONS.ADD_FRAGMENT.name()); + jMenuItem.addActionListener(this); + jSubmenuAdd.add(jMenuItem); + + // --- Generate Hydrogens + jMenuItem = new JMenuItem("Add Hydrogens", GlobalSettings.ICON_16x16_ADD_ATOM); + jMenuItem.setActionCommand(EDIT_MENU_ACTIONS.ADD_HYDROGENS.name()); + jMenuItem.addActionListener(this); + jSubmenuAdd.add(jMenuItem); + jSubmenuAdd.setIcon(GlobalSettings.ICON_16x16_ADD_ATOM); + add(jSubmenuAdd); + + // --- Modify submenu + JMenu jSubmenuModify = new JMenu(); + jSubmenuModify.setText("Modify"); + jSubmenuModify.setIcon(GlobalSettings.ICON_16x16_WRENCH); + add(jSubmenuModify); + + // --- "Modify Atoms" item + jMenuItem = new JMenuItem(MODIFY_ATOMS_MESSAGE, GlobalSettings.ICON_16x16_ATOM); + jMenuItem.setActionCommand(EDIT_MENU_ACTIONS.MODIFY_ATOMS.name()); + jMenuItem.addActionListener(this); + jSubmenuModify.add(jMenuItem); + + // --- "Modify Bond" + JMenuItem jMenuModifyBond = new JMenuItem("Modify Bonds"); + jMenuModifyBond.setIcon(GlobalSettings.ICON_16x16_BOND); + jMenuModifyBond.setActionCommand(EDIT_MENU_ACTIONS.MODIFY_BONDS.name()); + jMenuModifyBond.addActionListener(this); + jSubmenuModify.add(jMenuModifyBond); + + // --- "Modify Angle" + JMenuItem jMenuModifyAngle = new JMenuItem("Modify Angles"); + jMenuModifyAngle.setIcon(GlobalSettings.ICON_16x16_ANGLE); + jMenuModifyAngle.setActionCommand(EDIT_MENU_ACTIONS.MODIFY_ANGLES.name()); + jMenuModifyAngle.addActionListener(this); + jSubmenuModify.add(jMenuModifyAngle); + + // --- Modify Dihedral + JMenuItem jMenuModifyTorsion = new JMenuItem("Modify Torsions"); + jMenuModifyTorsion.setIcon(GlobalSettings.ICON_16x16_HUMMER); + jMenuModifyTorsion.setActionCommand(EDIT_MENU_ACTIONS.MODIFY_TORSIONS.name()); + jMenuModifyTorsion.addActionListener(this); + jSubmenuModify.add(jMenuModifyTorsion); + + // --- Guess atom types + JMenuItem jMenuGuessAtomTypes = new JMenuItem("Guess Atom Types"); + jMenuGuessAtomTypes.setIcon(GlobalSettings.ICON_16x16_HUMMER); + jMenuGuessAtomTypes.setActionCommand(EDIT_MENU_ACTIONS.GUESS_ATOM_TYPES.name()); + jMenuGuessAtomTypes.addActionListener(this); + jSubmenuModify.add(jMenuGuessAtomTypes); + + JMenuItem recalculateConnectivity = new JMenuItem("Redo Connectivity"); + recalculateConnectivity.setIcon(GlobalSettings.ICON_16x16_HUMMER); + recalculateConnectivity.setActionCommand(EDIT_MENU_ACTIONS.RECALC_CONNECTIVITY.name()); + recalculateConnectivity.addActionListener(this); + jSubmenuModify.add(recalculateConnectivity); + + // --- "Delete Atoms" item + jMenuItem = new JMenuItem(DELETE_ATOMS_MESSAGE, GlobalSettings.ICON_16x16_CUT); + jMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK)); + jMenuItem.setActionCommand(EDIT_MENU_ACTIONS.DELETE_ATOMS.name()); + jMenuItem.addActionListener(this); + add(jMenuItem); + + // --- Erase Molecule + JMenuItem jMenuEraseMolecule = new JMenuItem("Erase Molecule"); + jMenuEraseMolecule.setIcon(GlobalSettings.ICON_16x16_CUT); + jMenuEraseMolecule.setActionCommand(EDIT_MENU_ACTIONS.ERASE_MOLECULE.name()); + jMenuEraseMolecule.addActionListener(this); + add(jMenuEraseMolecule); + + // --- "Create Centroid" item + jMenuItem = new JMenuItem("Create Centroid", GlobalSettings.ICON_16x16_CENTROID); + jMenuItem.setActionCommand(EDIT_MENU_ACTIONS.CREATE_CENTROID.name()); + jMenuItem.addActionListener(this); + add(jMenuItem); + + // --- Solvate submenu + JMenu jSubmenuSolvate = new JMenu(); + jSubmenuSolvate.setText("Solvate"); + jSubmenuSolvate.setIcon(GlobalSettings.ICON_16x16_WRENCH); + add(jSubmenuSolvate); + + // --- Cap solvate + jMenuItem = new JMenuItem("Cap", GlobalSettings.ICON_16x16_HUMMER); + jMenuItem.addActionListener(this); + jMenuItem.setActionCommand(EDIT_MENU_ACTIONS.SOLVATE_CAP.name()); + jSubmenuSolvate.add(jMenuItem); + + // --- Shell solvate + jMenuItem = new JMenuItem("Shell", GlobalSettings.ICON_16x16_HUMMER); + jMenuItem.setActionCommand(EDIT_MENU_ACTIONS.SOLVATE_SHELL.name()); + jMenuItem.addActionListener(this); + jSubmenuSolvate.add(jMenuItem); + + // --- Handling sets + addSeparator(); + + jMenuItem = new JMenuItem("Create Atomic Set", GlobalSettings.ICON_16x16_ADD_ENTRY); + jMenuItem.setActionCommand(EDIT_MENU_ACTIONS.CREATE_ATOM_SET.name()); + jMenuItem.addActionListener(this); + add(jMenuItem); + + jMenuItem = new JMenuItem("Edit Atomic Set", GlobalSettings.ICON_16x16_REMOVE_ENTRY); + jMenuItem.setActionCommand(EDIT_MENU_ACTIONS.EDIT_ATOM_SET.name()); + jMenuItem.addActionListener(this); + add(jMenuItem); + } + + private boolean isOtherSelectionInProgress() { + if (java3dUniverse.getMousePickingStatus()) { + JOptionPane.showMessageDialog(this.getParentFrame(), + "Another Selection is already in progress!", ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + return true; + } + return false; + } + + @Override + public void actionPerformed(ActionEvent actionEvent) { + String actionCommand = actionEvent.getActionCommand(); + + logger.info("actionEvent.getActionCommand(): " + actionEvent.getActionCommand()); + + // --- Get action command + EDIT_MENU_ACTIONS action = EDIT_MENU_ACTIONS.UNKNOWN_EDIT_ACTION; + try { + action = EDIT_MENU_ACTIONS.valueOf(actionCommand); + } catch (Exception ex) { + logger.warning("Unknown edit menu action: " + actionCommand); + return; + } + + // --- Switch to action... + switch (action) { + + case SET_MOLECULE_NAME: + if (java3dUniverse.getMolecule() != null) { + Object input = JOptionPane.showInputDialog(null, + "Please enter new Molecule name", + "Set Molecule name", + JOptionPane.QUESTION_MESSAGE, null, null, + java3dUniverse.getMolecule().getName()); + if (input == null) { + return; + } + java3dUniverse.getMolecule().setName(input.toString()); + } + break; + + // --- Add atoms + case ADD_ATOMS: + if (isOtherSelectionInProgress()) { + return; + } + + if (java3dUniverse.getMolecule() == null) { + MoleculeInterface molecule = Molecule.getNewInstance(); + java3dUniverse.addMolecule(molecule); + } + java3dUniverse.enableMousePicking(true); // Enable mouse picking + + if (java3dUniverse.chooseAtomType == null) { + JAtomTypeDialog temp = new JAtomTypeDialog(parentComponent instanceof JFrame ? (JFrame) parentComponent : new Frame(), + "Select Atom Type", false); + if (helper != null) { + JButton h = temp.getHelpButton(); + h.setEnabled(true); + helper.setHelpIDString(h, HelperInterface.JMD_ADD_ATOM_ID); + helper.displayHelpFromSourceActionListener(h); + } + + temp.setOKVisible(false); + temp.setCancelVisible(true); + temp.setTargetClass(java3dUniverse); + + temp.validate(); + temp.pack(); + temp.setLocationByPlatform(true); + java3dUniverse.chooseAtomType = temp; + //menuFrame.new_universe.chooseAtomType.addElements(ChemicalElements. + // getAllElements()); + // } + } + JAtomTypeDialog atd = (JAtomTypeDialog) java3dUniverse.chooseAtomType; + SwingUtilities.updateComponentTreeUI(atd); + atd.setVisible(true); + + java3dUniverse.enableMousePicking(true); + java3dUniverse.selectedMode = OperationsOnAtoms.SELECTION_ONE_ATOM_ONLY; + java3dUniverse.setJobType(OperationsOnAtoms.SELECTED_ADD_ATOMS); + java3dUniverse.selectAndProcessDialog = true; + + break; + + // --- Add molecule + case ADD_MOLECULE: + if (isOtherSelectionInProgress()) { + return; + } + + if (!isMoleculeLoaded()) { + return; + } + + if (secondJ3D == null) { + secondJ3D = new Java3dUniverse(); + } else { + secondJ3D.removeMolecule(); + } + + if (jAddMoleculeDialog == null) { + jAddMoleculeDialog = new JAddMoleculeDialog(parentComponent instanceof JFrame ? (JFrame) parentComponent : new Frame(), + ADD_MOLECULE_MESSAGE, false, secondJ3D); + //jAddMoleculeDialog.setRenderer(secondJ3D); + jAddMoleculeDialog.setParent(java3dUniverse); + jAddMoleculeDialog.setSize(400, 400); + jAddMoleculeDialog.setLocationRelativeTo(this.getParentFrame()); + + if (helper != null) { + JButton h = jAddMoleculeDialog.getHelpButton(); + h.setEnabled(true); + helper.setHelpIDString(h, HelperInterface.JMD_ADD_MOLECULE_ID); + helper.displayHelpFromSourceActionListener(h); + } + + } + SwingUtilities.updateComponentTreeUI(jAddMoleculeDialog); + secondJ3D.selectedMode = OperationsOnAtoms.SELECTION_ONE_ATOM_ONLY; + + java3dUniverse.setOtherRenderer(secondJ3D); + java3dUniverse.jAddMoleculeDialog = jAddMoleculeDialog; + + if (!guessAndOpenFile(secondJ3D)) { + return; + } + + secondJ3D.setJobType(OperationsOnAtoms.SELECTED_ADD_MOLECULE); + secondJ3D.enableMousePicking(true); + + java3dUniverse.enableMousePicking(true); + java3dUniverse.selectedMode = OperationsOnAtoms.SELECTION_ONE_ATOM_ONLY; + java3dUniverse.setJobType(OperationsOnAtoms.SELECTED_ADD_MOLECULE); + java3dUniverse.selectAndProcessDialog = true; + + jAddMoleculeDialog.setVisible(true); + break; + + // --- Add molecule + case ADD_FRAGMENT: + if (isOtherSelectionInProgress()) { + return; + } + + if (java3dUniverse.getMolecule() == null) { + MoleculeInterface molecule = Molecule.getNewInstance(); + java3dUniverse.addMolecule(molecule); + } + + if (thirdJ3D == null) { + thirdJ3D = new Java3dUniverse(); + } + + if (jAddFragmentDialog == null) { + + InputStream is = null; + FragmentDictionaryParser fdp = new FragmentDictionaryParser(); + try { + ClassLoader cl = cct.resources.Resources.class.getClassLoader(); + logger.info("Class loader: " + cl.toString()); + fragDic = cl.getResource(cct.GlobalSettings.getDefaultFragmentDictionary()); + + logger.info("File: " + fragDic.getFile() + " path: " + fragDic.getPath() + " " + fragDic.toString()); + logger.info("Protocol: " + fragDic.getProtocol()); + //logger.info("Query: " + fragDic.getQuery()); + + is = cl.getResourceAsStream(cct.GlobalSettings.getDefaultFragmentDictionary()); + + fdp.setFragmentDictionary(fragDic); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this.getParentFrame(), "Error opening default fragment dictionary: " + ex.getMessage(), + ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + + System.err.println(getClass().getCanonicalName() + " : " + ex.getMessage()); + return; + } + + Map fragTree = FragmentDictionaryParser.parseFragmentDictionary(is); + + jAddFragmentDialog = new JAddFragmentDialog("Add Fragment", fragTree, thirdJ3D); + jAddFragmentDialog.setFragmentDictionaryParser(fdp); + jAddFragmentDialog.setParent(java3dUniverse); + jAddFragmentDialog.setSize(350, 500); + jAddFragmentDialog.setLocationRelativeTo(this.getParentFrame()); + jAddFragmentDialog.setAlwaysOnTop(true); + + if (helper != null) { + JButton h = jAddFragmentDialog.getHelpButton(); + h.setEnabled(true); + helper.setHelpIDString(h, HelperInterface.JMD_ADD_FRAGMENT_ID); + helper.displayHelpFromSourceActionListener(h); + } + + //java3dUniverse.jAddMoleculeDialog = jAddMoleculeDialog; + } + SwingUtilities.updateComponentTreeUI(jAddFragmentDialog); + + try { + thirdJ3D.setFragmentDictionary(fragDic); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this.getParentFrame(), "Error setting default fragment dictionary: " + ex.getMessage(), ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + System.err.println(getClass().getCanonicalName() + " : " + ex.getMessage()); + return; + } + + thirdJ3D.selectedMode = OperationsOnAtoms.SELECTION_ONE_ATOM_ONLY; + java3dUniverse.setOtherRenderer(thirdJ3D); + + java3dUniverse.enableMousePicking(true); + java3dUniverse.selectedMode = OperationsOnAtoms.SELECTION_ONE_ATOM_ONLY; + java3dUniverse.setJobType(OperationsOnAtoms.SELECTED_ADD_FRAGMENT); + java3dUniverse.selectAndProcessDialog = true; + + jAddFragmentDialog.setVisible(true); + break; + + // --- Add hydrogens + case ADD_HYDROGENS: + if (isOtherSelectionInProgress()) { + return; + } + + if (!isMoleculeLoaded()) { + return; + } + + MoleculeInterface molec = java3dUniverse.getMolecule(); + if (molec == null || molec.getNumberOfAtoms() < 1) { + JOptionPane.showMessageDialog(this.getParentFrame(), "Load Molecule first!", "Warning", + JOptionPane.WARNING_MESSAGE); + return; + } + jamberooCore.openAtomSelectionDialog(java3dUniverse, + OperationsOnAtoms.SELECTED_FILL_VALENCES_WITH_HYDROGENS, + OperationsOnAtoms.SELECTION_UNLIMITED, false); + break; + + // --- Modify atoms + case MODIFY_ATOMS: + if (isOtherSelectionInProgress()) { + return; + } + + if (java3dUniverse.jModifyAtomDialog == null) { + java3dUniverse.jModifyAtomDialog = new JModifyAtomDialog(parentComponent instanceof JFrame ? (JFrame) parentComponent : new Frame(), + "Select atoms to modify", false); + java3dUniverse.jModifyAtomDialog.setTargetClass(java3dUniverse); + java3dUniverse.jModifyAtomDialog.setGraphicsRenderer( + java3dUniverse); + java3dUniverse.jModifyAtomDialog.setElements(ChemicalElements.getAllElements()); + java3dUniverse.jModifyAtomDialog.setLocationRelativeTo(this.getParentFrame()); + } + SwingUtilities.updateComponentTreeUI(java3dUniverse.jModifyAtomDialog); + java3dUniverse.enableMousePicking(true); + java3dUniverse.selectedMode = OperationsOnAtoms.SELECTION_ONE_ATOM_ONLY; + java3dUniverse.setJobType(OperationsOnAtoms.SELECTED_MODIFY_ATOMS); + java3dUniverse.selectAndProcessDialog = true; + java3dUniverse.jModifyAtomDialog.setVisible(true); + break; + + // --- Modify bonds + case MODIFY_BONDS: + if (isOtherSelectionInProgress()) { + return; + } + + if (java3dUniverse.jModifyBondDialog == null) { + java3dUniverse.jModifyBondDialog = new JModifyBondDialog(parentComponent instanceof JFrame ? (JFrame) parentComponent : new Frame(), + "Modify selected Bond", false); + java3dUniverse.jModifyBondDialog.setLocationRelativeTo(this.getParentFrame()); + java3dUniverse.jModifyBondDialog.setTargetClass(java3dUniverse); + if (helper != null) { + JButton h = java3dUniverse.jModifyBondDialog.Help; + h.setEnabled(true); + helper.setHelpIDString(h, HelperInterface.JMD_MODIFY_BOND_ID); + helper.displayHelpFromSourceActionListener(h); + } + } + java3dUniverse.enableMousePicking(true); + java3dUniverse.selectedMode = OperationsOnAtoms.SELECTION_TWO_ATOMS_ONLY; + java3dUniverse.setJobType(OperationsOnAtoms.SELECTED_MODIFY_BONDS); + java3dUniverse.selectAndProcessDialog = true; + java3dUniverse.jModifyBondDialog.setVisible(true); + SwingUtilities.updateComponentTreeUI(java3dUniverse.jModifyBondDialog); + break; + + // --- Modify Angles + case MODIFY_ANGLES: + if (isOtherSelectionInProgress()) { + return; + } + + if (java3dUniverse.jModifyAngleDialog == null) { + java3dUniverse.jModifyAngleDialog = new JModifyAngleDialog(getParentFrame(), + "Modify selected Angle", false); + java3dUniverse.jModifyAngleDialog.setLocationRelativeTo(getParentFrame()); + java3dUniverse.jModifyAngleDialog.setTargetClass(java3dUniverse); + if (helper != null) { + JButton h = java3dUniverse.jModifyAngleDialog.getHelpButton(); + h.setEnabled(true); + helper.setHelpIDString(h, HelperInterface.JMD_MODIFY_ANGLE_ID); + helper.displayHelpFromSourceActionListener(h); + } + + } + SwingUtilities.updateComponentTreeUI(java3dUniverse.jModifyAngleDialog); + java3dUniverse.enableMousePicking(true); + java3dUniverse.selectedMode = OperationsOnAtoms.SELECTION_THREE_ATOMS_ONLY; + java3dUniverse.setJobType(OperationsOnAtoms.SELECTED_MODIFY_ANGLES); + java3dUniverse.selectAndProcessDialog = true; + java3dUniverse.jModifyAngleDialog.setVisible(true); + break; + + // --- Modify torsions + case MODIFY_TORSIONS: + if (isOtherSelectionInProgress()) { + return; + } + + java3dUniverse.modifyDihedralAngleDialog(this.getParentFrame()); + + if (helper != null) { + JButton h = java3dUniverse.jModifyTorsionDialog.getHelpButton(); + h.setEnabled(true); + helper.setHelpIDString(h, HelperInterface.JMD_MODIFY_TORSION_ID); + helper.displayHelpFromSourceActionListener(h); + } + break; + + // --- Guess atom types + case GUESS_ATOM_TYPES: + if (isOtherSelectionInProgress()) { + return; + } + Molecule.guessAtomTypes(java3dUniverse.getMolecule(), + AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + break; + + // --- Recalculate connectivity + case RECALC_CONNECTIVITY: + if (isOtherSelectionInProgress()) { + return; + } + java3dUniverse.deleteAllBonds(); + Molecule.guessCovalentBonds(java3dUniverse.getMoleculeInterface()); + java3dUniverse.drawBonds(java3dUniverse.getMoleculeInterface()); + break; + + // --- Delete selected atoms + case DELETE_ATOMS: + if (isOtherSelectionInProgress()) { + return; + } + jamberooCore.openAtomSelectionDialog(java3dUniverse, OperationsOnAtoms.SELECTED_DELETE_ATOMS, + OperationsOnAtoms.SELECTION_UNLIMITED, false); + break; + + // --- Erase molecule + case ERASE_MOLECULE: + java3dUniverse.removeMolecule(); + sendMoleculeChangedEvent("", MOLECULE_EVENT.MOLECULE_DELETED); + if (volumeDataList != null) { + volumeDataList.clear(); + } + if (manageCubesDialog != null) { + manageCubesDialog.setVisible(false); + } + jamberooCore.showGraphicsObjectsDialog(false); + //if (gopDialog != null) { + // gopDialog.setVisible(false); + //} + break; + + // --- Create centroid + case CREATE_CENTROID: + if (isOtherSelectionInProgress()) { + return; + } + + jamberooCore.openAtomSelectionDialog(java3dUniverse, OperationsOnAtoms.SELECTED_CREATE_CENTROID, + OperationsOnAtoms.SELECTION_UNLIMITED, false); + break; + + // --- Solvate with a cap + case SOLVATE_CAP: + if (isOtherSelectionInProgress()) { + return; + } + jamberooCore.openAtomSelectionDialog(java3dUniverse, OperationsOnAtoms.SELECTED_SOLVATE_CAP, + OperationsOnAtoms.SELECTION_UNLIMITED, false); + + break; + + // --- Solvate with a shell + case SOLVATE_SHELL: + if (isOtherSelectionInProgress()) { + return; + } + jamberooCore.openAtomSelectionDialog(java3dUniverse, OperationsOnAtoms.SELECTED_SOLVATE_SHELL, + OperationsOnAtoms.SELECTION_UNLIMITED, false); + break; + + // --- Create atom set + case CREATE_ATOM_SET: + if (isOtherSelectionInProgress()) { + return; + } + SetNamePanel setNamePanel = new SetNamePanel(); + setNamePanel.setJava3dUniverse(java3dUniverse); + jamberooCore.openAtomSelectionDialog(java3dUniverse, OperationsOnAtoms.SELECTED_CREATE_ATOMIC_SET, + OperationsOnAtoms.SELECTION_UNLIMITED, false, setNamePanel); + break; + + // --- Edit atom set + case EDIT_ATOM_SET: + if (isOtherSelectionInProgress()) { + return; + } + + if (java3dUniverse.getMoleculeInterface().getNumberOfAtoms() < 1) { + return; + } + + Object obj = java3dUniverse.getMoleculeInterface().getProperty(MoleculeInterface.AtomicSets); + if (obj == null) { + JOptionPane.showMessageDialog(this.getParentFrame(), "Molecule has no atom set(s)", + "Warning", JOptionPane.WARNING_MESSAGE); + return; + } else if (!(obj instanceof AtomicSets)) { + System.err.println(this.getClass().getCanonicalName() + + ": expected AtomicSets, got " + obj.getClass().getCanonicalName() + + " Ignored..."); + return; + } + AtomicSets sets = (AtomicSets) obj; + if (sets.size() < 1) { + JOptionPane.showMessageDialog(this.getParentFrame(), "No atom set(s) in molecule", "No sets", JOptionPane.WARNING_MESSAGE); + return; + } + + String[] names = new String[sets.size()]; + sets.keySet().toArray(names); + Arrays.sort(names); + + SelectListDialog selectListDialog = new SelectListDialog(new Frame(), + "Select available set(s) to delete"); + selectListDialog.setList(names); + selectListDialog.setLocationRelativeTo(this.getParentFrame()); + if (!selectListDialog.showDialog()) { + return; + } + + Object[] selSets = selectListDialog.getSelectedValues(); + if (selSets == null || selSets.length < 1) { + return; + } + + for (int i = 0; i < selSets.length; i++) { + sets.remove(selSets[i]); + } + Map props = java3dUniverse.getMoleculeInterface().getProperties(); + props.put(MoleculeInterface.AtomicSets, sets); + break; + } + + } + + protected void sendMoleculeChangedEvent(String fileName, MoleculeEventObject.MOLECULE_EVENT moleculeEvent) { + MoleculeEventObject event = new MoleculeEventObject(this, moleculeEvent, fileName); + for (MoleculeChangeListener listener : moleculeChangeListeners) { + listener.moleculeChanged(event); + } + } + + private Frame getParentFrame() { + return parentComponent instanceof JFrame ? (JFrame) parentComponent : new Frame(); + } + + public Component getParentComponent() { + return parentComponent; + } + + public void setParentComponent(Component parentComponent) { + this.parentComponent = parentComponent; + } + + boolean guessAndOpenFile(Java3dUniverse j3d) { + + JFileChooser chooser = new JFileChooser(); + FileFilterImpl filter = new FileFilterImpl(); + String extensions = MolecularFileFormats.allMolecularExtensions; + String temp[] = extensions.split(";"); + for (int i = 0; i < temp.length; i++) { + filter.addExtension(temp[i]); + } + filter.setDescription(MolecularFileFormats.allMolecularFormats); + chooser.setFileFilter(filter); + chooser.setDialogType(JFileChooser.OPEN_DIALOG); + chooser.setDialogTitle("Open Molecular Modeling File"); + + File currentWorkingDirectory = GlobalSettings.getCurrentWorkingDirectory(); + + if (currentWorkingDirectory != null) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } + + int returnVal = chooser.showOpenDialog(this.getParentFrame()); + if (returnVal == JFileChooser.APPROVE_OPTION) { + String fileName = chooser.getSelectedFile().getPath(); + currentWorkingDirectory = chooser.getCurrentDirectory(); + GlobalSettings.setCurrentWorkingDirectory(currentWorkingDirectory); + logger.info("You chose to open this file: " + fileName); + String extension = FileFilterImpl.getExtension(fileName); + int fileFormat = MolecularFileFormats.guessMolecularFileFormat( + fileName, extension); + if (fileFormat == MolecularFileFormats.formatUnknown) { + JOptionPane.showMessageDialog(this.getParentFrame(), "Unknown Molecular Modeling File Format", ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + + return false; + } + + j3d.openMolecularModelingFile(fileFormat, fileName); + return true; + } + return false; + } + + /** + * Checks whether molecule loaded or not + * + * @return boolean "true" if loaded and "false" otherwise + */ + public boolean isMoleculeLoaded() { + MoleculeInterface m = java3dUniverse.getMolecule(); + if (m == null) { + JOptionPane.showMessageDialog(this.getParentFrame(), "Load Molecule first!", "Warning", + JOptionPane.WARNING_MESSAGE); + return false; + } + return true; + } + + public List getVolumeDataList() { + return volumeDataList; + } + + public void setVolumeDataList(List volumeDataList) { + this.volumeDataList = volumeDataList; + } + + public ManageCubesFrame getManageCubesDialog() { + return manageCubesDialog; + } + + public void setManageCubesDialog(ManageCubesFrame manageCubesDialog) { + this.manageCubesDialog = manageCubesDialog; + } +} diff --git a/src/main/java/cct/dialogs/FileMenu.java b/src/main/java/cct/dialogs/FileMenu.java new file mode 100644 index 0000000..a68a5ca --- /dev/null +++ b/src/main/java/cct/dialogs/FileMenu.java @@ -0,0 +1,2843 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import bsh.Interpreter; +import cct.GlobalSettings; +import cct.adf.ADFOutput; +import cct.amber.AmberLib; +import cct.amber.AmberPrep; +import cct.amber.ReadPrmtopDialog; +import cct.chart.ChartFrame; +import cct.chart.VibrationSpectrumChart; +import cct.cpmd.CPMD; +import cct.cprocessor.CommandProcessor; +import cct.cprocessor.CommandProcessorDeprecated; +import cct.cprocessor.MolProcessorInterface; +import cct.gaussian.*; +import cct.gaussian.ui.GaussianInputEditorFrame; +import cct.gaussian.ui.SaveG03GJFDialog; +import cct.grid.ScriptSubmitterDialogInterface; +import cct.gromacs.GromacsParserFactory; +import cct.gulp.Gulp; +import cct.interfaces.*; +import cct.j3d.*; +import cct.mdl.MDLMol; +import cct.modelling.*; +import cct.modelling.ui.VibrationsControlFrame; +import cct.mopac.Mopac; +import cct.mopac.MopacOutput; +import cct.oogl.OOGL; +import cct.oogl.java3d.OoglJava3d; +import cct.pdb.PDB; +import cct.pdb.PDBBankFetcherInterface; +import cct.pdb.ui.PDBFormFrame; +import cct.qchem.QChem; +import cct.qchem.QChemOutput; +import cct.siesta.SiestaInput; +import cct.siesta.ui.SaveSiestaInputDialog; +import cct.tools.*; +import cct.tools.filebrowser.SFTPFileChooserDialog; +import cct.tools.filebrowser.ShadowClientInterface; +import cct.tools.ui.*; +import cct.tripos.TriposParser; +import cct.vasp.VasprunXML; +import cct.vasp.ui.ReadPoscarDialog; +import g03input.G03MenuTree; +import g03input.showMolEditor; +import legacy.editor.commons.Settings; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.FileWriter; +import java.io.PrintStream; +import java.net.URL; +import java.util.*; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.prefs.Preferences; + +/** + * + * @author vvv900 + */ +public class FileMenu extends JMenu implements ActionListener, ShadowClientInterface, PDBBankFetcherInterface { + + //private static String lastPWDKey = "lastPWD"; + private static String REDIRECT_STDERR = "redirectStderr"; + private static String ERROR_MESSAGE = "Error"; + private static String OPEN_MOLECULE_FILE = "Open Molecule File"; + private static String OPENAS = "OpenAs"; + private ImageIcon saveFileImage = new ImageIcon(cct.dialogs.JamberooFrame.class.getResource("/cct/images/disk_blue.png")); + private ImageIcon seagridFileImage = new ImageIcon(cct.dialogs.JamberooFrame.class.getResource("/cct/images/seagrid.png")); + private JMenuItem jMenuOpenMolecule = new JMenuItem(); + private JMenuItem jMenuAppendMolecule = new JMenuItem(); + private JMenu jSubmenuFileOpen = new JMenu(); + private JMenu jSubmenuFileSave = new JMenu(); + private JMenu jSubmenuSEAGridExport = new JMenu(); + private JMenuItem jSEAGridGaussian = new JMenuItem(); + private JMenu gaussianMenu = new JMenu("Gaussian"); + private JMenu mopacMenu = new JMenu("Mopac"); + private JMenu submenuLoadRemote = new JMenu(); + private JMenuItem jExecuteScript = new JMenuItem(); + private Java3dUniverse java3dUniverse; + private JFileChooser clobalChooser = null; + private File currentWorkingDirectory = null; + private Preferences prefs = null; + private CommandProcessorDeprecated commandProcessor = null; + private VibrationsControlFrame vcFrame = null; + private ReadPrmtopDialog prmtopDialog = null; + private MoleculeSelectorDialog moleculeSelectorDialog = null; + private ReadPoscarDialog vaspDialog = null; + private JMenuItem fetchStructure = new JMenuItem("Fetch from PDB bank"); + private Map sftpChoosers = new HashMap(); + private SFTPFileChooserDialog sftpChooserDialog = null; + private Map remoteFileFormats = new HashMap(); + private Map ftpChoosers = new HashMap(); + private JMenu loadObjectMenu = new JMenu("Load Graphics Object"); + private SaveG03GJFDialog saveG03GJFDialog = null; + private SaveSiestaInputDialog saveSiestaInputDialog = null; + private SaveXYZDialog saveXYZDialog = null; + private JMenu jSubmenuImageSave = new JMenu(); + private JMenu jSubmenuMoleculeSubmit = new JMenu(); + private JMenu jSubmenuScriptSubmit = new JMenu(); + private GaussianInputEditorFrame gaussianInputEditorFrame = null; + private JMenuItem submitGaussianJob = new JMenuItem(); + private FileChooserDialog gaussianFileChooserDialog = null; + private static String lastSaveGaussianInputDirKey = "LastSaveGaussianInputDir"; + private JMenuItem errLog = new JMenuItem("Errors Log"); + private LogPanel strerrLogPanel = new LogPanel("Errors Log"); + private boolean redirectStderr = false; + static final Logger logger = Logger.getLogger(FileMenu.class.getCanonicalName()); + private PrintStream storeStderr = null; + private PDBFormFrame pdbFormFrame = null; + private saveImageAs_actionAdapter sia; + private JamberooCoreInterface jamberooCore; + private MolecularDataWizard wizard; + private Map sourceRef = new HashMap(); + private Gaussian gaussianData = null; + private Set moleculeChangeListeners = new LinkedHashSet(); + + private static ResourceBundle messages; + + public FileMenu(JamberooCoreInterface jamberooCore) throws Exception { + super(); + this.jamberooCore = jamberooCore; + java3dUniverse = jamberooCore.getJamberooRenderer(); + wizard = new MolecularDataWizard(); + + try { + prefs = Preferences.userNodeForPackage(getClass()); + } catch (Exception ex) { + logger.warning("Cannot get Preferences: " + ex.getMessage()); + } + + try { + messages = GlobalSettings.getResourceBundle(); + } catch (Exception ex) { + logger.warning("Cannot get ResourceBundle: " + ex.getMessage()); + } + + if (messages != null) { + ERROR_MESSAGE = messages.getString("error"); + OPEN_MOLECULE_FILE = messages.getString("open_molecule_file"); + gaussianMenu.setText(messages.getString("gaussian")); + mopacMenu.setText(messages.getString("mopac")); + fetchStructure.setText(messages.getString("fetch_from_pdb")); + loadObjectMenu.setText(messages.getString("load_graphics_object")); + errLog.setText(messages.getString("errors_log")); + strerrLogPanel.setText(messages.getString("errors_log")); + } + + createMenu(); + } + + public void addMoleculeChangeListener(MoleculeChangeListener listener) { + moleculeChangeListeners.add(listener); + } + + public void removeMoleculeChangeListener(MoleculeChangeListener listener) { + moleculeChangeListeners.remove(listener); + } + + public void removeAllMoleculeChangeListeners() { + moleculeChangeListeners.removeAll(moleculeChangeListeners); + } + + private void createMenu() { + + String className = this.getClass().getCanonicalName(); + + try { + //custom = JamberooFrame.class.getClassLoader().getResource(CCT_PROPERTY_FILE); + Properties props = GlobalSettings.getProperties(); + //props.load(custom.openStream()); + + //--- Whether redirect stderr ?... + String customCommand = props.getProperty(className + GlobalSettings.DIVIDER + + REDIRECT_STDERR, String.valueOf(redirectStderr)); + if (customCommand != null) { + try { + redirectStderr = Boolean.parseBoolean(customCommand); + logger.info("Stderr redirection: " + redirectStderr); + } catch (Exception exx) { + logger.warning("Error parsing " + className + GlobalSettings.DIVIDER + REDIRECT_STDERR + " value from " + GlobalSettings.CCT_PROPERTY_FILE + + " file. Set to " + redirectStderr); + } + } + } catch (Exception ex) { + logger.warning("Cannot get " + className + GlobalSettings.DIVIDER + REDIRECT_STDERR + " value from the " + GlobalSettings.CCT_PROPERTY_FILE + + " file. Set to " + redirectStderr); + } + + // --- Setting up errors log panel... + strerrLogPanel.getTextArea().setText(""); + strerrLogPanel.setIconImage(GlobalSettings.ICON_16x16_ERROR.getImage()); + strerrLogPanel.setSize(640, 480); + strerrLogPanel.setLocationRelativeTo(this); + TextToPost poster = new TextToPost(strerrLogPanel, "Post a Problem", false); + JButton button = new JButton("Post Error Message"); + button.addActionListener(poster); + strerrLogPanel.addButton(button); + strerrLogPanel.popupOnUpdate(true); + storeStderr = System.err; // Store stderr... + + // --- Redirect stderr + if (redirectStderr) { + JTextAreaOutputStream stderrSink = new JTextAreaOutputStream(strerrLogPanel.getTextArea()); + System.setErr(new PrintStream(stderrSink)); + } + + jMenuOpenMolecule.setText(OPEN_MOLECULE_FILE); + jMenuOpenMolecule.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK)); + jMenuOpenMolecule.setIcon(GlobalSettings.ICON_16x16_OPEN_FILE); + jMenuOpenMolecule.addActionListener(this); + + jMenuAppendMolecule.setText(messages != null ? messages.getString("append_molecule_file") : "Append Molecule File"); + jMenuAppendMolecule.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK)); + jMenuAppendMolecule.setIcon(GlobalSettings.ICON_16x16_OPEN_FILE); + jMenuAppendMolecule.addActionListener(this); + + jSubmenuFileOpen.setText(messages != null ? messages.getString("open_as") : "Open As"); + jSubmenuFileOpen.setIcon(GlobalSettings.ICON_16x16_OPEN_FILE); + jSubmenuFileSave.setText(messages != null ? messages.getString("save_as") : "Save As"); + jSubmenuFileSave.setIcon(saveFileImage); + + // -- SEAGrid Export + jSubmenuSEAGridExport.setText(messages != null ? messages.getString("seagrid_export") : "SEAGrid Export"); + jSubmenuSEAGridExport.setIcon(seagridFileImage); + String seagridGaussianText = messages != null ? messages.getString("seagrid_gaussian_export") : "Gaussian"; + jSEAGridGaussian.setText(seagridGaussianText); + jSEAGridGaussian.setIcon(new ImageIcon(cct.dialogs.JamberooFrame.class.getResource("/cct/images/gaussian-16x16.png"))); + jSubmenuSEAGridExport.add(jSEAGridGaussian); + jSEAGridGaussian.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent actionEvent) { + String arg = actionEvent.getActionCommand(); + + if (java3dUniverse.getMolecule() == null + || java3dUniverse.getMolecule().getNumberOfAtoms() < 1) { + JOptionPane.showMessageDialog(null, "Load Molecule first!", + ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + return; + } + + if(arg.equals(seagridGaussianText)){ + Gaussian g = new Gaussian(); + try { + String gaussOut = Gaussian.getMoleculeSpecsAsString(java3dUniverse.getMolecule()); + File f = new File(Settings.getApplicationDataDir() + Settings.fileSeparator + + "tmp.txt"); + FileWriter fw = new FileWriter(f, false); + fw.write(gaussOut); + System.err.println("gaussOut = "); + System.err.println(gaussOut); + fw.close(); + + G03MenuTree.showG03MenuTree(); + showMolEditor forString = new showMolEditor(); + forString.tempmol = gaussOut; + + JOptionPane.showMessageDialog(null, "WARNING: Molecule information" + + " has been exported correctly. Make sure\n" + + "to edit other sections of GUI.", + "GridChem: Gaussian GUI", + JOptionPane.WARNING_MESSAGE); + } catch (Exception e) { + e.printStackTrace(); + } + + } + } + }); + + // --- "Open As" Submenu + gaussianMenu.setIcon(GlobalSettings.ICON_16x16_GAUSSIAN); + mopacMenu.setIcon(GlobalSettings.ICON_16x16_MOPAC); + + //JEditorFrame_jMenuFileOpenAs_ActionAdapter processFileMenu = new JEditorFrame_jMenuFileOpenAs_ActionAdapter(this); + Map readF = MolecularFileFormats.getReadCoordFormats(); + Set set = readF.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String formatName = me.getKey().toString(); + JMenuItem jMenuItem; + if (formatName.equals(MolecularFileFormats.gaussian03GJF) + || formatName.equals(MolecularFileFormats.gaussian03Output) + || formatName.equals(MolecularFileFormats.gaussianFragment) + || formatName.equals(MolecularFileFormats.gaussian03Cube) + || formatName.equals(MolecularFileFormats.gaussianTrajectory) + || formatName.equals(MolecularFileFormats.gaussianFormCheckpoint)) { + jMenuItem = new JMenuItem(formatName, GlobalSettings.ICON_16x16_GAUSSIAN); + //sourceRef.put(jMenuItem, CHEMISTRY_FILE_FORMAT.PDB) + + if (!jSubmenuFileOpen.isMenuComponent(gaussianMenu)) { + jSubmenuFileOpen.add(gaussianMenu); + } + gaussianMenu.add(jMenuItem); + } else if (formatName.equals(MolecularFileFormats.gamessInput)) { + jMenuItem = new JMenuItem(formatName, GlobalSettings.ICON_16x16_GAMESS); + jMenuItem.setVisible(true); + jSubmenuFileOpen.add(jMenuItem); + } else if (formatName.equals(MolecularFileFormats.gamessOutput)) { + jMenuItem = new JMenuItem(formatName, GlobalSettings.ICON_16x16_GAMESS); + jSubmenuFileOpen.add(jMenuItem); + } else if (formatName.equals(MolecularFileFormats.mopacInput) + || formatName.equals(MolecularFileFormats.mopacLog) + || formatName.equals(MolecularFileFormats.mopacOutput)) { + jMenuItem = new JMenuItem(formatName, GlobalSettings.ICON_16x16_MOPAC); + if (!jSubmenuFileOpen.isMenuComponent(mopacMenu)) { + jSubmenuFileOpen.add(mopacMenu); + } + mopacMenu.add(jMenuItem); + } else if (formatName.equals(MolecularFileFormats.adfInput)) { + jMenuItem = new JMenuItem(formatName, GlobalSettings.ICON_16x16_ADF); + jMenuItem.setVisible(true); + jSubmenuFileOpen.add(jMenuItem); + } else if (formatName.equals(MolecularFileFormats.adfOutput)) { + jMenuItem = new JMenuItem(formatName, GlobalSettings.ICON_16x16_ADF); + jMenuItem.setVisible(true); + jSubmenuFileOpen.add(jMenuItem); + } else if (formatName.equals(MolecularFileFormats.siestaInputFormat)) { + jMenuItem = new JMenuItem(formatName, GlobalSettings.ICON_16x16_SIESTA); + jMenuItem.setVisible(true); + jSubmenuFileOpen.add(jMenuItem); + } else if (formatName.equals(MolecularFileFormats.triposMol2)) { + jMenuItem = new JMenuItem(formatName, + new ImageIcon(cct.dialogs.JamberooFrame.class.getResource("/cct/images/tripos-transp-16x16.png"))); + jSubmenuFileOpen.add(jMenuItem); + } else if (formatName.equals(MolecularFileFormats.pdbFile)) { + jMenuItem = new JMenuItem(formatName, + new ImageIcon(cct.dialogs.JamberooFrame.class.getResource("/cct/images/pdb-transp-16x16.png"))); + jSubmenuFileOpen.add(jMenuItem); + } else if (formatName.equals(MolecularFileFormats.mdlMolfileFormat)) { + jMenuItem = new JMenuItem(formatName, GlobalSettings.ICON_16x16_MDL); + jSubmenuFileOpen.add(jMenuItem); + } else if (formatName.equals(MolecularFileFormats.gromacsGROFormat)) { + jMenuItem = new JMenuItem(formatName, GlobalSettings.ICON_16x16_GROMACS); + jSubmenuFileOpen.add(jMenuItem); + } else if (formatName.equals(MolecularFileFormats.vaspPoscarFormat)) { + jMenuItem = new JMenuItem(formatName, GlobalSettings.ICON_16x16_VASP); + jSubmenuFileOpen.add(jMenuItem); + } else if (formatName.equals(MolecularFileFormats.vaspVasprunFormat)) { + jMenuItem = new JMenuItem(formatName, GlobalSettings.ICON_16x16_VASP); + jSubmenuFileOpen.add(jMenuItem); + } else if (formatName.equals(MolecularFileFormats.qchemFormat) + || formatName.equals(MolecularFileFormats.qchemOutputFormat)) { + jMenuItem = new JMenuItem(formatName, GlobalSettings.ICON_16x16_QCHEM); + jSubmenuFileOpen.add(jMenuItem); + } else if (formatName.equals(MolecularFileFormats.gulpInputFormat)) { + jMenuItem = new JMenuItem(formatName, GlobalSettings.ICON_16x16_GULP); + jSubmenuFileOpen.add(jMenuItem); + } else { + jMenuItem = new JMenuItem(formatName, GlobalSettings.ICON_16x16_MOLECULE); + jSubmenuFileOpen.add(jMenuItem); + } + //jMenuItem.addActionListener(processFileMenu); + jMenuItem.addActionListener(this); + jMenuItem.setName(OPENAS); + } + + // --- Load from sftp host + jamberooCore.getShadowSFTPManager().addClient(this); + submenuLoadRemote.setText(messages != null ? messages.getString("load_from_sftp") : "Load from sftp server"); + submenuLoadRemote.setIcon(GlobalSettings.ICON_16x16_REMOTE_DOWNLOAD); + submenuLoadRemote.setVisible(true); + + // --- Fetch + fetchStructure.setIcon(GlobalSettings.ICON_16x16_REMOTE_DOWNLOAD); + fetchStructure.addActionListener(this); + + // --- Load Object Submenu + JMenuItem jMenuItem = new JMenuItem("off File"); + jMenuItem.setName(GraphicsFormat.OOGL_OFF_FORMAT.name()); + jMenuItem.addActionListener(this); + loadObjectMenu.add(jMenuItem); + loadObjectMenu.setIcon(GlobalSettings.ICON_16x16_ADD_COMPONENT); + + // --- "Save As" Submenu + JEditorFrame_jMenuFileSaveAs_ActionAdapter processSaveFileMenu = new JEditorFrame_jMenuFileSaveAs_ActionAdapter(this); + set = MolecularFileFormats.getSaveCoordFormats().entrySet(); + iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String formatName = me.getKey().toString(); + if (formatName.equals(MolecularFileFormats.gaussian03GJF)) { + jMenuItem = new JMenuItem(formatName, new ImageIcon(cct.dialogs.JamberooFrame.class.getResource("/cct/images/gaussian-16x16.png"))); + } else if (formatName.equals(MolecularFileFormats.triposMol2)) { + jMenuItem = new JMenuItem(formatName, + new ImageIcon(cct.dialogs.JamberooFrame.class.getResource("/cct/images/tripos-transp-16x16.png"))); + } else if (formatName.equals(MolecularFileFormats.pdbFile)) { + jMenuItem = new JMenuItem(formatName, + new ImageIcon(cct.dialogs.JamberooFrame.class.getResource("/cct/images/pdb-transp-16x16.png"))); + } else if (formatName.equals(MolecularFileFormats.povrayFormat)) { + jMenuItem = new JMenuItem(formatName, GlobalSettings.ICON_16x16_POVRAY); + } else if (formatName.equals(MolecularFileFormats.siestaInputFormat)) { + jMenuItem = new JMenuItem(formatName, GlobalSettings.ICON_16x16_SIESTA); + } else { + jMenuItem = new JMenuItem(formatName, GlobalSettings.ICON_16x16_MOLECULE); + } + + jMenuItem.addActionListener(processSaveFileMenu); + jSubmenuFileSave.add(jMenuItem); + } + + // --- Save Image as submenu + sia = new saveImageAs_actionAdapter(this); + String formats[] = ImageTools.getSaveImageFormatNames(); + for (int i = 0; i < formats.length; i++) { + jMenuItem = new JMenuItem(formats[i].toUpperCase()); + jMenuItem.setIcon(FileUtilities.getIcon16x16("." + formats[i])); + jMenuItem.addActionListener(sia); + jSubmenuImageSave.add(jMenuItem); + } + jSubmenuImageSave.setText(messages != null ? messages.getString("save_image_as") : "Save Image As"); + jSubmenuImageSave.setIcon(GlobalSettings.ICON_16x16_IMAGE_FILE); + + boolean executeScript = true; // !!! Development option + if (executeScript) { + jExecuteScript.setText("Execute Script (in development)"); + jExecuteScript.setIcon(GlobalSettings.ICON_16x16_GEAR); + jExecuteScript.addActionListener(this); + } + + addSeparator(); + + add(jMenuOpenMolecule); + add(jSubmenuFileOpen); + add(jMenuAppendMolecule); + add(submenuLoadRemote); + add(fetchStructure); + add(loadObjectMenu); + addSeparator(); + add(jSubmenuFileSave); + add(jSubmenuImageSave); + addSeparator(); + + add(jSubmenuSEAGridExport); + addSeparator(); + + if (executeScript) { + add(jExecuteScript); + addSeparator(); + } + + List submitters = GridProviders.getAvailableScriptSubmitters(); + if (submitters != null && submitters.size() > 0) { + jSubmenuMoleculeSubmit.setText("Submit Molecule"); + jSubmenuMoleculeSubmit.setIcon(GlobalSettings.ICON_16x16_SERVER_INTO); + submitMolecule_actionAdapter sm = new submitMolecule_actionAdapter(this); + for (int i = 0; i < submitters.size(); i++) { + jMenuItem = new JMenuItem(submitters.get(i)); + jMenuItem.addActionListener(sm); + jSubmenuMoleculeSubmit.add(jMenuItem); + } + add(jSubmenuMoleculeSubmit); + + jSubmenuScriptSubmit.setText("Submit Existing Input File"); + jSubmenuScriptSubmit.setIcon(GlobalSettings.ICON_16x16_SERVER_INTO); + for (int i = 0; i < submitters.size(); i++) { + jMenuItem = new JMenuItem(submitters.get(i)); + GridProviders.addActionListener(jMenuItem, GridProviders.SCRIPT_SUBMITTER_ARG); + jMenuItem.addActionListener(GridProviders.getActionListener()); + jSubmenuScriptSubmit.add(jMenuItem); + } + add(jSubmenuScriptSubmit); + } + + addSeparator(); + + // --- Errors log menuitem + errLog.setIcon(GlobalSettings.ICON_16x16_DOCUMENT_WARNING); + errLog.addActionListener(new ActionListener() { + + public void actionPerformed(ActionEvent e) { + strerrLogPanel.setVisible(true); + } + }); + add(errLog); + + if (redirectStderr) { + errLog.setVisible(true); + } else { + errLog.setVisible(false); + } + } + + public JButton getSnapshotButton() { + JButton snapshotButton = new JButton(); + + snapshotButton.setEnabled(true); + snapshotButton.setToolTipText(messages != null ? messages.getString("save_image") : "Save Image"); + snapshotButton.setActionCommand(null); + snapshotButton.addActionListener(sia); + snapshotButton.setIcon(new ImageIcon(cct.resources.Resources.class.getResource( + "/cct/images/icons16x16/camera.png"))); + return snapshotButton; + } + + public void fetchStructure(String host, String entry_directory, String code) { + + String slash = "/"; + if (entry_directory.endsWith("/")) { + slash = ""; + } + // Now rcsb uses gz instead of Z + String url_address = "ftp://" + host + entry_directory + slash + "pdb/" + + code.substring(1, 3) + "/pdb" + code + ".ent.gz"; + logger.info("Pdb entry: " + url_address); + MoleculeInterface mol = new Molecule(); + try { + URL url = new URL(url_address); + mol = PDB.parsePDBFile(url, mol); + this.java3dUniverse.addMolecule(mol); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + } + } + + public void actionPerformed(ActionEvent actionEvent) { + + Object source = actionEvent.getSource(); + String arg = actionEvent.getActionCommand(); + String eventName = ""; + boolean openAsMenuItem = false; + if (source instanceof JMenuItem) { + JMenuItem jMenuItem = (JMenuItem) source; + eventName = jMenuItem.getName(); + if (eventName != null) { + openAsMenuItem = eventName.equals(OPENAS); + } + } + + // --- Open Molecule Menuitem + if (openAsMenuItem) { + try { + openFile(java3dUniverse, arg); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + } + } else if (actionEvent.getSource() == jMenuOpenMolecule) { + openMoleculeFile(OPEN_MOLECULE_FILE, this.java3dUniverse, GlobalSettings.ADD_MOLECULE_MODE.SET); + } else if (actionEvent.getSource() == jMenuAppendMolecule) { + openMoleculeFile(OPEN_MOLECULE_FILE, this.java3dUniverse, GlobalSettings.ADD_MOLECULE_MODE.APPEND); + } else if (actionEvent.getSource() == fetchStructure) { + if (pdbFormFrame == null) { + pdbFormFrame = new PDBFormFrame(this); + pdbFormFrame.pack(); + pdbFormFrame.setLocationRelativeTo(this); + } + pdbFormFrame.setVisible(true); + } else if (actionEvent.getSource() == jExecuteScript) { + + FileDialog fd = new FileDialog(new Frame(), "Open Script File", FileDialog.LOAD); + fd.setFile("*.txt;*.scr"); + fd.setVisible(true); + if (fd.getFile() == null) { + return; + } + + try { + Interpreter i = new Interpreter(); // Construct an interpreter + i.source(fd.getDirectory() + fd.getFile()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error Executing Script : " + ex.getMessage(), ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + + if (false) { + try { + CommandProcessor cp = new CommandProcessor(); + cp.setRenderer(java3dUniverse); + cp.parseScript(fd.getDirectory() + fd.getFile(), 0); + cp.executeScript(); + } catch (Exception ex) { + Logger.getLogger(FileMenu.class.getName()).log(Level.SEVERE, null, ex); + JOptionPane.showMessageDialog(this, "Error Executing Script : " + ex.getMessage(), ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + return; + } + } + if (false) { + MolProcessorInterface mpi = new ScriptProcessorWrapper(java3dUniverse); + commandProcessor = new CommandProcessorDeprecated(mpi); + try { + commandProcessor.parseScript(fd.getDirectory() + fd.getFile(), 0); + commandProcessor.executeScript(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error Executing Script : " + ex.getMessage(), ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + } + // ---- + } else if (eventName.equals(GraphicsFormat.OOGL_OFF_FORMAT.name())) { + FileDialog fd = new FileDialog(new Frame(), "Open OOGL File", FileDialog.LOAD); + fd.setFile("*.off;*.ogl"); + fd.setVisible(true); + if (fd.getFile() == null) { + return; + } + + OOGL oogl = new OOGL(); + try { + oogl.parseOFF(fd.getDirectory() + fd.getFile()); + java3dUniverse.addGraphics(OoglJava3d.getGraphicsObject(oogl)); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error Opening off file: " + ex.getMessage(), + ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + + } else if (gaussianInputEditorFrame != null && actionEvent.getSource() == gaussianInputEditorFrame.returnBackButton) { + gaussianInputEditorFrame.setVisible(false); + int n = gaussianInputEditorFrame.getSelectedStep(); + MoleculeInterface m = Molecule.getNewInstance(); + m = gaussianData.getMolecule(m, n); + Molecule.guessCovalentBonds(m); + //MoleculeInterface m2 = Molecule.divideIntoMolecules(m); + java3dUniverse.addMolecule(m); + } + + } + + /** + * Enables/disables redirection of stderr. + * + * @param enable boolean - if true, redirects sdterr to the errors log panel and adds "Errors Log" menu item to the + * File menu. if false, remove menu item from the File menu and directs sdterr to the standard stream + */ + public void interceptStderr(final boolean enable) { + if (redirectStderr && enable) { + return; + } else if (!redirectStderr && !enable) { + return; + } else if (enable && !redirectStderr) { + final JTextAreaOutputStream stderrSink = new JTextAreaOutputStream( + strerrLogPanel.getTextArea()); + System.setErr(new PrintStream(stderrSink)); + errLog.setVisible(true); + } else if (!enable && redirectStderr) { + System.setErr(storeStderr); + errLog.setVisible(false); + } + + } + + public void openMoleculeFile(String title, Java3dUniverse j3d, GlobalSettings.ADD_MOLECULE_MODE add_mode) { + + if (clobalChooser == null) { + clobalChooser = new JFileChooser(); + clobalChooser.setAcceptAllFileFilterUsed(false); + clobalChooser.setDialogTitle(title); + clobalChooser.setDialogType(JFileChooser.OPEN_DIALOG); + clobalChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + clobalChooser.setMultiSelectionEnabled(false); + + // --- First, add filter for all molecular formats + Map allFormats = MolecularFileFormats.getReadCoordFormats(); + + FileFilterImpl filter = new FileFilterImpl(); + filter.setDescription("All Molecular Formats"); + + Set set = allFormats.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String description = me.getKey().toString(); + String ext = me.getValue().toString(); + + String temp[] = ext.split(";"); + for (int i = 0; i < temp.length; i++) { + filter.addExtension(temp[i]); + } + } + + clobalChooser.addChoosableFileFilter(filter); + + // --- Add separate filters + javax.swing.filechooser.FileFilter[] filters = FileFilterImpl.getFileFilters(MolecularFileFormats.getReadCoordFormats()); + + for (int i = 0; i < filters.length; i++) { + clobalChooser.addChoosableFileFilter(filters[i]); + logger.info("Adding filter: " + filters[i].getDescription()); + } + + // --- Set default filter + clobalChooser.setFileFilter(filter); + } + + currentWorkingDirectory = GlobalSettings.getCurrentWorkingDirectory(); + if (currentWorkingDirectory != null) { + clobalChooser.setCurrentDirectory(currentWorkingDirectory); + } else if (prefs != null) { + String lastPWD = prefs.get(GlobalSettings.lastPWDKey, ""); + if (lastPWD.length() > 0) { + currentWorkingDirectory = new File(lastPWD); + if (currentWorkingDirectory.isDirectory() + && currentWorkingDirectory.exists()) { + clobalChooser.setCurrentDirectory(currentWorkingDirectory); + } + } + } else { + logger.warning("Cannot get currentWorkingDirectory: prefs == null"); + } + + // --- Show dialog + int returnVal = JFileChooser.CANCEL_OPTION; + + returnVal = clobalChooser.showOpenDialog(this); + + if (returnVal != JFileChooser.APPROVE_OPTION) { + return; + } + + String fileName = null; + + fileName = clobalChooser.getSelectedFile().getPath(); + currentWorkingDirectory = clobalChooser.getCurrentDirectory(); + GlobalSettings.setCurrentWorkingDirectory(currentWorkingDirectory); + try { + prefs.put(GlobalSettings.lastPWDKey, currentWorkingDirectory.getAbsolutePath()); + } catch (Exception ex) { + System.err.println("Cannot save cwd: " + ex.getMessage() + " Ignored..."); + } + logger.info("You chose to open this file: " + fileName); + + // --- Open File + int fileFormat = MolecularFileFormats.formatUnknown; + javax.swing.filechooser.FileFilter selectedFilter = clobalChooser.getFileFilter(); + + javax.swing.filechooser.FileFilter[] allFilters = clobalChooser.getChoosableFileFilters(); + + if (selectedFilter == allFilters[0]) { + String extension = FileFilterImpl.getExtension(fileName); + fileFormat = MolecularFileFormats.guessMolecularFileFormat(fileName, extension); + if (fileFormat == MolecularFileFormats.formatUnknown) { + JOptionPane.showMessageDialog(this, "Unknown Molecular Modeling File Format: " + extension, ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + return; + } + } else if (selectedFilter instanceof FileFilterImpl) { + FileFilterImpl fltr = (FileFilterImpl) selectedFilter; + fileFormat = MolecularFileFormats.getReadFileType(fltr.getDescription()); + if (fileFormat == MolecularFileFormats.formatUnknown) { + JOptionPane.showMessageDialog(this, "Unknown Molecular Modeling File Format: " + fltr.getDescription(), + ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + } else { + String descr = selectedFilter.getDescription(); + JOptionPane.showMessageDialog(this, "Cannot open file of type: " + descr, ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + + //j3d.openMolecularModelingFile(fileFormat, fileName, add_mode); + openMolecularModelingFile(j3d, fileFormat, fileName, add_mode); + } + + protected void sendMoleculeChangedEvent(String fileName, MoleculeEventObject.MOLECULE_EVENT moleculeEvent) { + MoleculeEventObject event = new MoleculeEventObject(this, moleculeEvent, fileName); + for (MoleculeChangeListener listener : moleculeChangeListeners) { + listener.moleculeChanged(event); + } + } + + public boolean openMolecularModelingFile(Java3dUniverse j3d, int fileType, String fileName, + GlobalSettings.ADD_MOLECULE_MODE read_mode) { + if (fileType == MolecularFileFormats.formatG03_GJF) { // G03 Input file + + if (gaussianInputEditorFrame != null && gaussianInputEditorFrame.isVisible()) { + gaussianInputEditorFrame.setVisible(false); + } + + gaussianData = new Gaussian(); + int n = gaussianData.parseGJF(fileName, 0); + logger.info("Number of molecules: " + n); + if (n > 1) { + if (gaussianInputEditorFrame == null) { + gaussianData.setGraphicsRenderer(j3d); + gaussianInputEditorFrame = new GaussianInputEditorFrame(gaussianData); + gaussianInputEditorFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); + try { + gaussianInputEditorFrame.removeMenuItem("File", "Exit"); + } catch (Exception ex) { + } + JMenuItem item = new JMenuItem("Select current step & return back to Editor"); + + item.addActionListener(this); + gaussianInputEditorFrame.addMenuItem("File", item); + gaussianInputEditorFrame.returnBackButton.setVisible(true); + gaussianInputEditorFrame.returnBackButton.addActionListener(this); + } + gaussianInputEditorFrame.setupEditor(gaussianData); + JOptionPane.showMessageDialog(null, "Gaussian Input file has more than 1 step\n" + "Select step in the next dialog", + "Info", JOptionPane.INFORMATION_MESSAGE); + + gaussianInputEditorFrame.setVisible(true); + //logger.info("Loading 1st Molecule..."); + } else { + MoleculeInterface m = Molecule.getNewInstance(); + m = gaussianData.getMolecule(m, 0); + if (m == null || m.getNumberOfAtoms() < 1) { + JOptionPane.showMessageDialog(null, "Didn't find atoms in file", "Warning", JOptionPane.WARNING_MESSAGE); + return false; + } + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + if (GlobalSettings.ADD_MOLECULE_MODE.SET == read_mode) { + sendMoleculeChangedEvent(fileName, MoleculeEventObject.MOLECULE_EVENT.MOLECULE_DELETED); + } + java3dUniverse.setMolecule(m, read_mode); + sendMoleculeChangedEvent(fileName, MoleculeEventObject.MOLECULE_EVENT.MOLECULE_LOADED); + } + //addGaussianData(g); + + } else if (fileType == MolecularFileFormats.formatG03_Output) { // G03 output file + MoleculeInterface m = Molecule.getNewInstance(); + GaussianOutput gaussianOutput = new GaussianOutput(); + GaussianJob results; + try { + results = gaussianOutput.parseFile(m, fileName, false); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, "Cannot open file " + fileName + ": " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return false; + } + m = results.getMolecule(0); + List Geometries = results.getGeometries(0); + if (Geometries == null || Geometries.size() == 0) { + JOptionPane.showMessageDialog(null, "No molecule found in file", "Error", JOptionPane.ERROR_MESSAGE); + return false; + } + + Frame parent = new Frame(); + + JShowText showResume = new JShowText("Gaussian Results"); + showResume.setSize(600, 640); + showResume.setTitle("Gaussian Results: " + fileName); + showResume.setLocationByPlatform(true); + showResume.setText(gaussianOutput.getOutputResume()); + showResume.setVisible(true); + + if (Geometries.size() > 1) { + + JChoiceDialog selectG = new JChoiceDialog(parent, "Select Structure", true); + for (int i = 0; i < Geometries.size(); i++) { + MolecularGeometry gm = Geometries.get(i); + selectG.addItem(gm.getName()); + } + selectG.selectIndex(Geometries.size() - 1); + selectG.pack(); + + selectG.setLocationRelativeTo(parent); + selectG.setVisible(true); + if (selectG.isApproveOption()) { + int n = selectG.getSelectedIndex(); + if (n != -1) { + setupSelectedGeometry(m, Geometries.get(n)); + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + java3dUniverse.setMolecule(m, read_mode); + } + + } + } else if (Geometries.size() == 1) { + setupSelectedGeometry(m, Geometries.get(0)); + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + java3dUniverse.setMolecule(m, read_mode); + } else { + JOptionPane.showMessageDialog(parent, "Didn't find geometries in output file", "Warning", JOptionPane.WARNING_MESSAGE); + } + + } else if (fileType == MolecularFileFormats.formatG03_Fragment) { // Gaussian fragment file + MoleculeInterface m = new Molecule(); + try { + m = GaussianFragment.parseGaussianFragmentFile(m, fileName); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return false; + } + java3dUniverse.setMolecule(m, read_mode); + } else if (fileType == MolecularFileFormats.format_XMol_XYZ) { // XMol XYZ file + MoleculeInterface m = new Molecule(); + try { + XMolXYZ xMolXYZ = new XMolXYZ(); + m = xMolXYZ.parseXMolXYZ(fileName, m); + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return false; + } + java3dUniverse.setMolecule(m, read_mode); + } else if (fileType == MolecularFileFormats.format_MDL_Molfile) { // MDL Molfile file + MoleculeInterface m = new Molecule(); + try { + MDLMol mol = new MDLMol(); + m = mol.parseFile(fileName, m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return false; + } + java3dUniverse.setMolecule(m, read_mode); + } else if (fileType == MolecularFileFormats.format_GRO) { // Gromacs GRO file + MoleculeInterface m = new Molecule(); + try { + m = GromacsParserFactory.parseGromacsCoordFile(fileName, m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return false; + } + java3dUniverse.setMolecule(m, read_mode); + } else if (fileType == MolecularFileFormats.formatPDB) { // PDB file + Molecule m = new Molecule(); + try { + PDB.parsePDBFile(fileName, m); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return false; + } + java3dUniverse.setMolecule(m, read_mode); + } else if (fileType == MolecularFileFormats.formatTripos_Mol2) { // Tripos Mol2 file + Molecule m = new Molecule(); + TriposParser triposParser = new TriposParser(); + try { + triposParser.parseMol2File(fileName, m); + java3dUniverse.setMolecule(m, read_mode); + } catch (Exception ex) { + logger.severe("Error opening " + fileName + " : " + ex.getMessage()); + } + } else if (fileType == MolecularFileFormats.formatCCT) { // CCT file + Molecule m = new Molecule(); + m.setAtomInterface(new Atom()); + m.setBondInterface(new Bond()); + CCTParser cctParser = new CCTParser(m); + List mols = cctParser.parseCCTFile(fileName, m); + m = (Molecule) mols.get(0); + logger.info("Number of atoms: " + m.getNumberOfAtoms()); + java3dUniverse.setMolecule(m, read_mode); + } + + return true; + } + + public int setupSelectedGeometry(MoleculeInterface molec, MolecularGeometry geom) { + + if (geom.size() != molec.getNumberOfAtoms()) { + logger.info("setupSelectedGeometry: geom.size() != getNumberOfAtoms() " + geom.size() + " != " + molec.getNumberOfAtoms()); + return -1; + } + + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + cct.vecmath.Point3f point = geom.getCoordinates(i); + AtomInterface atom = molec.getAtomInterface(i); + atom.setXYZ(point); + } + //selectedGeometry = n; + return 1; + } + + /** + * Opens Molecule File in default mode (erasing old molecule and then adding a new one) + * + * @param title - dialog title + * @param j3d - java3d renderer + */ + public void openMoleculeFile(String title, Java3dUniverse j3d) { + + openMoleculeFile(title, j3d, GlobalSettings.ADD_MOLECULE_MODE.SET); + + } + + //void jMenuFileOpenAs_actionPerformed(ActionEvent actionEvent) { + // String arg = actionEvent.getActionCommand(); + // try { + // openFile(java3dUniverse, arg); + // } catch (Exception ex) { + // JOptionPane.showMessageDialog(null, ex.getMessage(), ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + // } + //} + void openFile(Java3dUniverse j3d, String fileType) throws Exception { + if (fileType.equals(MolecularFileFormats.gaussian03GJF)) { // G03 Input file + openFile(j3d, CHEMISTRY_FILE_FORMAT.G03_GJF, null); + } else if (fileType.equals(MolecularFileFormats.gaussian03Output)) { // G03 output file + openFile(j3d, CHEMISTRY_FILE_FORMAT.G03_OUTPUT, null); + } else if (fileType.equals(MolecularFileFormats.gaussian03Cube)) { // G03 cube file + openFile(j3d, CHEMISTRY_FILE_FORMAT.G03_CUBE, null); + } else if (fileType.equals(MolecularFileFormats.gaussianFragment)) { // Gaussian fragment file + openFile(j3d, CHEMISTRY_FILE_FORMAT.G03_FRAGMENT, null); + } else if (fileType.equals(MolecularFileFormats.gaussianTrajectory)) { + openFile(j3d, CHEMISTRY_FILE_FORMAT.G03_TRAJECTORY, null); + } else if (fileType.equals(MolecularFileFormats.gaussianFormCheckpoint)) { + openFile(j3d, CHEMISTRY_FILE_FORMAT.G03_FORM_CHECKPOINT, null); + } else if (fileType.equals(MolecularFileFormats.CPMDOutputFormat)) { + openFile(j3d, CHEMISTRY_FILE_FORMAT.CPMD_OUTPUT, null); + } else if (fileType.equals(MolecularFileFormats.CPMDTrajectoryFormat)) { + openFile(j3d, CHEMISTRY_FILE_FORMAT.CPMD_TRAJECTORY, null); + } else if (fileType.equals(MolecularFileFormats.gamessInput)) { // GAMESS Input file + openFile(j3d, CHEMISTRY_FILE_FORMAT.GAMESS_INPUT, null); + } else if (fileType.equals(MolecularFileFormats.gamessOutput)) { // GAMESS Output file + openFile(j3d, CHEMISTRY_FILE_FORMAT.GAMESS_OUTPUT, null); + } else if (fileType.equals(MolecularFileFormats.mopacLog)) { // MOPAC Log file + openFile(j3d, CHEMISTRY_FILE_FORMAT.MOPAC2002_LOG, null); + } else if (fileType.equals(MolecularFileFormats.mopacInput)) { // MOPAC Input file + openFile(j3d, CHEMISTRY_FILE_FORMAT.MOPAC_INPUT, null); + } else if (fileType.equals(MolecularFileFormats.mopacOutput)) { // MOPAC Output file + openFile(j3d, CHEMISTRY_FILE_FORMAT.MOPAC_OUTPUT, null); + } else if (fileType.equals(MolecularFileFormats.siestaInputFormat)) { // SIESTA input file + openFile(j3d, CHEMISTRY_FILE_FORMAT.SIESTA_INPUT, null); + } else if (fileType.equals(MolecularFileFormats.adfInput)) { // ADF input file + openFile(j3d, CHEMISTRY_FILE_FORMAT.ADF_INPUT, null); + } else if (fileType.equals(MolecularFileFormats.adfOutput)) { // ADF output file + openFile(j3d, CHEMISTRY_FILE_FORMAT.ADF_OUTPUT, null); + } else if (fileType.equals(MolecularFileFormats.pdbFile)) { // PDB file + openFile(j3d, CHEMISTRY_FILE_FORMAT.PDB, null); + } else if (fileType.equals(MolecularFileFormats.triposMol2)) { // Tripos Mol2 file + openFile(j3d, CHEMISTRY_FILE_FORMAT.MOL2, null); + } else if (fileType.equals(MolecularFileFormats.mdlMolfileFormat)) { // MDL Molfile file + openFile(j3d, CHEMISTRY_FILE_FORMAT.MDL_MOLFILE, null); + } else if (fileType.equals(MolecularFileFormats.gromacsGROFormat)) { // Gromacs GRO file + openFile(j3d, CHEMISTRY_FILE_FORMAT.GROMACS_GRO, null); + } else if (fileType.equals(MolecularFileFormats.amberPrmtopFormat)) { // Amber topology file + openFile(j3d, CHEMISTRY_FILE_FORMAT.AMBER_PRMTOP, null); + } else if (fileType.equals(MolecularFileFormats.amberPrepFormat)) { // Amber PREP file + openFile(j3d, CHEMISTRY_FILE_FORMAT.AMBER_PREP, null); + } else if (fileType.equals(MolecularFileFormats.amberLibFormat)) { // Amber Lib (off) file + openFile(j3d, CHEMISTRY_FILE_FORMAT.AMBER_LIB, null); + } else if (fileType.equals(MolecularFileFormats.cctFileFormat)) { // CCT file + openFile(j3d, CHEMISTRY_FILE_FORMAT.CCT, null); + } else if (fileType.equals(MolecularFileFormats.xmolXYZFileFormat)) { // XMol XYZ file + openFile(j3d, CHEMISTRY_FILE_FORMAT.XMOL_XYZ, null); + } else if (fileType.equals(MolecularFileFormats.vaspPoscarFormat)) { // VASP poscar file + openFile(j3d, CHEMISTRY_FILE_FORMAT.VASP_POSCAR, null); + } else if (fileType.equals(MolecularFileFormats.vaspVasprunFormat)) { // VASP Vasprun file + openFile(j3d, CHEMISTRY_FILE_FORMAT.VASP_VASPRUN, null); + } else if (fileType.equals(MolecularFileFormats.qchemFormat)) { // QChem input file + openFile(j3d, CHEMISTRY_FILE_FORMAT.QCHEM_INPUT, null); + } else if (fileType.equals(MolecularFileFormats.qchemOutputFormat)) { // QChem Output file + openFile(j3d, CHEMISTRY_FILE_FORMAT.QCHEM_OUTPUT, null); + } else if (fileType.equals(MolecularFileFormats.gulpInputFormat)) { // GULP Input file + openFile(j3d, CHEMISTRY_FILE_FORMAT.GULP_INPUT, null); + } + } + + public boolean openMolecularModelingFile(Java3dUniverse j3d, String fileType, String fileName) { + if (fileType == null || fileName == null) { + return false; + } + int formatType = MolecularFileFormats.formatUnknown; + if (fileType.equals(MolecularFileFormats.gaussian03GJF)) { + formatType = MolecularFileFormats.formatG03_GJF; + } else if (fileType.equals(MolecularFileFormats.gaussian03Output)) { + formatType = MolecularFileFormats.formatG03_Output; + } else if (fileType.equals(MolecularFileFormats.gaussianFragment)) { + formatType = MolecularFileFormats.formatG03_Fragment; + } else if (fileType.equals(MolecularFileFormats.pdbFile)) { + formatType = MolecularFileFormats.formatPDB; + } else if (fileType.equals(MolecularFileFormats.triposMol2)) { + formatType = MolecularFileFormats.formatTripos_Mol2; + } else if (fileType.equals(MolecularFileFormats.mdlMolfileFormat)) { + formatType = MolecularFileFormats.format_MDL_Molfile; + } else if (fileType.equals(MolecularFileFormats.gromacsGROFormat)) { + formatType = MolecularFileFormats.format_GRO; + } else if (fileType.equals(MolecularFileFormats.cctFileFormat)) { + formatType = MolecularFileFormats.formatCCT; + } else if (fileType.equals(MolecularFileFormats.xmolXYZFileFormat)) { + formatType = MolecularFileFormats.format_XMol_XYZ; + } + + return openMolecularModelingFile(j3d, formatType, fileName); + } + + public boolean openMolecularModelingFile(Java3dUniverse j3d, int fileType, String fileName) { + return openMolecularModelingFile(j3d, fileType, fileName, GlobalSettings.ADD_MOLECULE_MODE.SET); + } + + void openFile(Java3dUniverse j3d, CHEMISTRY_FILE_FORMAT fileType, String fileName) throws Exception { + + MoleculeInterface m; + SelectPropShowDialog gaussProp = null; + MoleculeInterface mol; + + switch (fileType) { + case ALL_FORMATS: + break; + case G03_GJF: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.gaussian03GJF, "Gaussian G03 Job Files (gjf)", JFileChooser.OPEN_DIALOG); + } + if (fileName != null) { + openMolecularModelingFile(j3d, MolecularFileFormats.gaussian03GJF, fileName); + + } + + break; + + case G03_OUTPUT: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.gaussian03Output, "Gaussian G03 Output Files (*.log;*.out)", + JFileChooser.OPEN_DIALOG); + } + + mol = new Molecule(); + GaussianJob gaussianJob = null; + try { + GaussianOutput gaussianOutput = new GaussianOutput(); + gaussianJob = gaussianOutput.parseFile(mol, fileName, false); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading Gaussian Output file : " + ex.getMessage(), ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + return; + } + + if (gaussianJob.countSteps() < 1) { + JOptionPane.showMessageDialog(this, "Didn't find gaussian steps in output file...", "Warning", JOptionPane.WARNING_MESSAGE); + return; + } + + int index = 0; + + if (gaussianJob.countSteps() > 1) { + JMoleculeSelectorDialog molSelectorDialog = new JMoleculeSelectorDialog(null, "Select Gaussian Step", true); + molSelectorDialog.setSize(320, 240); + molSelectorDialog.setLocationRelativeTo(this); + Java3dUniverse j3dRenderer = new Java3dUniverse(); + molSelectorDialog.set3DRenderer(j3dRenderer); + molSelectorDialog.setMoleculeSelector(gaussianJob); + molSelectorDialog.pack(); + + int cond = molSelectorDialog.showDialog(); + if (cond == JMoleculeSelectorDialog.CANCEL) { + return; + } + index = molSelectorDialog.getSelectedIndex(); + } + + GaussianStep step = gaussianJob.getStep(index); + + step.getMolecule().addProperty(MoleculeInterface.OUTPUT_RESULTS, step); + j3d.setMolecule(step.getMolecule()); + + gaussProp = new SelectPropShowDialog(null, "Select calculated properties to show"); + gaussProp.setLocationRelativeTo(this); + + //gaussProp.setControls(gaussianOutput); + gaussProp.setControls(step); + gaussProp.pack(); + + if (!gaussProp.showDialog()) { + return; + } + + // --- Show summary + if (gaussProp.isShowSummary()) { + JShowText showResume = new JShowText("Gaussian Results"); + showResume.setIconImage(GlobalSettings.ICON_16x16_GAUSSIAN.getImage()); + showResume.setSize(600, 640); + showResume.setTitle("Gaussian Results: " + fileName); + showResume.setLocationRelativeTo(this); + showResume.setText(step.getOutputResume()); + showResume.setVisible(true); + } + + // --- Show interactive chart + if (gaussProp.isShowInteractiveChart()) { + try { + String[] terms = step.getAvailPropToChart(); + if (terms == null || terms.length < 1) { + JOptionPane.showMessageDialog(this, "Didn't find any energy terms in output file...", "Warning", + JOptionPane.WARNING_MESSAGE); + //return; + } else { + SelectFromListDialog list = new SelectFromListDialog(null, "Select Energy Terms to Plot"); + list.setListData(terms); + //list.selectItem(vasprunXML.TOTAL_ENERGY_KEY, true); + list.enableMultipleSelection(true); + list.setLocationRelativeTo(this); + list.setVisible(true); + Object[] objs = list.getSelectedItems(); + if (objs == null || objs.length < 1) { + JOptionPane.showMessageDialog(this, "No Energy terms have been selected...", "Warning", JOptionPane.WARNING_MESSAGE); + //return; + } else { + + double x[] = null; + ChartFrame chart = null; + for (int i = 0; i < objs.length; i++) { + double[] energies = step.getAllTerms(objs[i].toString()); + if (energies == null) { + JOptionPane.showMessageDialog(this, "No Information about energy terms is found in output file...", "Warning", + JOptionPane.WARNING_MESSAGE); + return; + } else if (energies.length < 2) { + JOptionPane.showMessageDialog(this, "File has less than 2 snapshots with energy info. Chart won't be shown", + "Warning", JOptionPane.WARNING_MESSAGE); + } else { + if (i == 0) { + chart = new ChartFrame(); + chart.setIconImage(GlobalSettings.ICON_16x16_GAUSSIAN.getImage()); + chart.setTitle("Gaussian Chart"); + x = new double[energies.length]; + for (int j = 0; j < x.length; j++) { + x[j] = j; + } + chart.setChartTitle("Energy Terms vs Steps"); + chart.setXAxisTitle("Step"); + } + + chart.addDataSeries(x, energies, objs[i].toString()); + } + //chart.setYAxisTitle("Energy"); + } + + if (chart != null) { + chart.setRenderer(j3d); + chart.setStructureManagerInterface(step); + chart.showChart(true); + } + } + } + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Creating chart : " + ex.getMessage(), ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + //return; + } + } + + // --- frequencies + VIBRATIONAL_SPECTRUM[] vibSpectra = gaussProp.spectraToShow(); + if (vibSpectra != null && vibSpectra.length > 0) { + + VibrationsRenderer vRenderer = null; + try { + vRenderer = new VibrationsRenderer(j3d.getMoleculeInterface(), step, j3d); + j3d.getMoleculeInterface().addProperty(MoleculeInterface.VIBRATION_RENDERER, vRenderer); + } catch (Exception ex) { + } + vcFrame = new VibrationsControlFrame(); + vcFrame.setTitle("Vibrations Control"); + vcFrame.setVibrationsRendererProvider(vRenderer); + vcFrame.setSpectraProvider(step); + vcFrame.pack(); + vcFrame.setLocationRelativeTo(this); + vcFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + vcFrame.setVisible(true); + + try { + ChartFrame ref_chart = null; + for (int i = 0; i < vibSpectra.length; i++) { + VibrationSpectrumChart vsChart = new VibrationSpectrumChart(step); + ChartFrame chart = vsChart.createChart(vibSpectra[i]); + + if (ref_chart == null) { + chart.setLocationRelativeTo(this); + } else { + chart.setLocationRelativeTo(ref_chart); + } + ref_chart = chart; + chart.showChart(true); + } + } catch (Exception ex) { + System.err.println("frequencies: " + ex.getMessage()); + } + } + break; + + case G03_FORM_CHECKPOINT: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.gaussianFormCheckpoint, + "Gaussian G03 Formatted Checkpoint Files (*.fchk;*.fch)", + JFileChooser.OPEN_DIALOG); + } + + G03FormCheckpoint g03FormCheckpoint = new G03FormCheckpoint(); + try { + mol = new Molecule(); + g03FormCheckpoint.parseFile(fileName); + g03FormCheckpoint.getMolecule(mol); + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + j3d.setMolecule(mol); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading Gaussian formatted checkpoint file : " + + ex.getMessage(), ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + + break; + + case G03_CUBE: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.gaussian03Cube, + "Extract geometry from Gaussian G03 Cube File (*.cub;*.cube)", + JFileChooser.OPEN_DIALOG); + } + if (fileName == null) { + return; + } + + try { + mol = new Molecule(); + GaussianCube.extractGeometry(fileName, mol); + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + j3d.setMolecule(mol); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading Gaussian Cube file : " + + ex.getMessage(), ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + break; + case G03_FRAGMENT: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.gaussianFragment, + "Gaussian Fragment Files (*.frg)", + JFileChooser.OPEN_DIALOG); + } + if (fileName != null) { + openMolecularModelingFile(j3d, MolecularFileFormats.gaussianFragment, fileName); + } + break; + + case G03_TRAJECTORY: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.gaussianTrajectory, + "Extract geometry from Gaussian G03 Trajectory File (*.trj;*.7;*.log;*.out)", + JFileChooser.OPEN_DIALOG); + } + if (fileName == null) { + return; + } + + try { + int n = JOptionPane.showConfirmDialog(this, "MD trajectory could contain many snapshots.\n" + + "Do you want to load all snapshots? (could take a while) - Press Yes\n" + + "The first snapshot only (fast) - Press No", + "Select one snapshot or a whole trajectory", JOptionPane.YES_NO_OPTION); + mol = new Molecule(); + G03MDTrajectory g03MDTrajectory = new G03MDTrajectory(); + if (n == JOptionPane.NO_OPTION || n == JOptionPane.CLOSED_OPTION) { + g03MDTrajectory.parseMolecularGeometryOnly(mol, fileName); + } else { + //g03MDTrajectory.parseG03Trajectory(fileName, 0); + g03MDTrajectory.parseG03Trajectory(fileName); + g03MDTrajectory.getMolecularInterface(mol); + } + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + //MoleculeInterface m2 = Molecule.divideIntoMolecules(mol); + j3d.setMolecule(mol); + + if (n == JOptionPane.NO_OPTION || n == JOptionPane.CLOSED_OPTION) { + break; + } + + String[] terms = g03MDTrajectory.getAvailPropToChart(); + if (terms == null || terms.length < 2) { + break; + } + + n = JOptionPane.showConfirmDialog(this, "Do you want to plot some properties available in file?", + "Properties for charting are available", JOptionPane.YES_NO_OPTION); + if (n == JOptionPane.NO_OPTION || n == JOptionPane.CLOSED_OPTION) { + break; + } + SelectFromListDialog list = new SelectFromListDialog(null, "Select Energy Terms to Plot"); + list.setListData(terms); + list.selectItem( G03MDTrajectory.TOTAL_ENERGY_KEY, true); + list.enableMultipleSelection(true); + list.setLocationRelativeTo(this); + list.setVisible(true); + Object[] objs = list.getSelectedItems(); + if (objs == null || objs.length < 1) { + JOptionPane.showMessageDialog(this, "No terms have been selected...", "Warning", JOptionPane.WARNING_MESSAGE); + break; + } else { + double x[] = null; + ChartFrame chart = null; + for (int i = 0; i < objs.length; i++) { + double[] energies = g03MDTrajectory.getAllTerms(objs[i].toString()); + if (energies == null) { + JOptionPane.showMessageDialog(this, "No Information about energy terms is found in output file...", + "Warning", JOptionPane.WARNING_MESSAGE); + return; + } else if (energies.length < 2) { + JOptionPane.showMessageDialog(this, "File has less than 2 snapshots with energy info. Chart won't be shown", + "Warning", JOptionPane.WARNING_MESSAGE); + } else { + if (i == 0) { + chart = new ChartFrame(); + x = new double[energies.length]; + for (int j = 0; j < x.length; j++) { + x[j] = j; + } + chart.setChartTitle("Property vs Steps"); + chart.setXAxisTitle("Step"); + } + + chart.addDataSeries(x, energies, objs[i].toString()); + } + //chart.setYAxisTitle("Energy"); + } + + if (chart != null) { + chart.setRenderer(j3d); + chart.setStructureManagerInterface(g03MDTrajectory); + chart.showChart(true); + } + } + + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading Gaussian Trajectory file : " + ex.getMessage(), ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + return; + } + break; + + case CPMD_OUTPUT: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.CPMDOutputFormat, "CPMD Output File (*.out)", JFileChooser.OPEN_DIALOG); + } + if (fileName == null) { + return; + } + + CPMD cpmd_output = new CPMD(); + try { + cpmd_output.parseOutputFile(fileName); + mol = new Molecule(); + cpmd_output.getMolecule(mol); + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + j3d.setMolecule(mol); + + JShowText showResume = new JShowText("CPMD Results"); + showResume.setIconImage(GlobalSettings.ICON_16x16_MOLECULE.getImage()); + showResume.setSize(600, 640); + showResume.setTitle("CPMD Results: " + fileName); + showResume.setLocationRelativeTo(this); + showResume.setText(cpmd_output.getOutputResume()); + showResume.setVisible(true); + + String[] terms = null; + if ((terms = cpmd_output.getAvailPropToChart()) != null && cpmd_output.countSnapshots() > 1) { + + int n = JOptionPane.showConfirmDialog(this, + "CPMD output refer to the MD trajectory with " + cpmd_output.countSnapshots() + + " snapshots.\n" + "Do you want to animate MD trajectory? - Press Yes\n", + "Do you want to animate trajectory", JOptionPane.YES_NO_OPTION); + if (n == JOptionPane.YES_OPTION) { + SelectFromListDialog list = new SelectFromListDialog(null, "Select Properties to Plot"); + list.setListData(terms); + list.enableMultipleSelection(true); + list.setLocationRelativeTo(this); + list.setVisible(true); + Object[] objs = list.getSelectedItems(); + if (objs == null || objs.length < 1) { + JOptionPane.showMessageDialog(this, "No Properties have been selected...", "Warning", JOptionPane.WARNING_MESSAGE); + } else { + + double x[] = null; + ChartFrame chart = null; + for (int i = 0; i < objs.length; i++) { + double[] energies = cpmd_output.getAllTerms(objs[i].toString()); + if (energies == null) { + JOptionPane.showMessageDialog(this, "No Information about energy terms is found in output file...", "Warning", + JOptionPane.WARNING_MESSAGE); + continue; + } else if (energies.length < 2) { + JOptionPane.showMessageDialog(this, + "File has less than 2 snapshots with property " + objs[i].toString() + + ". Chart won't be shown", + "Warning", JOptionPane.WARNING_MESSAGE); + } else { + if (i == 0) { + chart = new ChartFrame(); + chart.setIconImage(GlobalSettings.ICON_16x16_LINE_CHART.getImage()); + chart.setTitle("MD Properties"); + x = new double[energies.length]; + for (int j = 0; j < x.length; j++) { + x[j] = j; + } + chart.setChartTitle("Properties vs Steps"); + chart.setXAxisTitle("Step"); + } + + chart.addDataSeries(x, energies, objs[i].toString()); + } + //chart.setYAxisTitle("Energy"); + } + + if (chart != null) { + chart.setRenderer(j3d); + chart.setStructureManagerInterface(cpmd_output); + chart.showChart(true); + } + } + + } + + } + + if (cpmd_output.hasWarningMessages()) { + JOptionPane.showMessageDialog(this, cpmd_output.getWarnings(), "You have warnings...", JOptionPane.WARNING_MESSAGE); + } + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading CPMD Output file : " + ex.getMessage(), ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + return; + } + + break; + + case CPMD_TRAJECTORY: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.CPMDTrajectoryFormat, "CPMD MD Trajectory File (*.xyz)", + JFileChooser.OPEN_DIALOG); + } + if (fileName == null) { + return; + } + + CPMD cpmd_traj = new CPMD(); + try { + cpmd_traj.parseTrajectoryFile(fileName); + mol = new Molecule(); + cpmd_traj.getMolecule(mol); + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + j3d.setMolecule(mol); + + if (cpmd_traj.hasWarningMessages()) { + JOptionPane.showMessageDialog(this, cpmd_traj.getWarnings(), "You have warnings...", JOptionPane.WARNING_MESSAGE); + } + + if (cpmd_traj.countSnapshots() > 1) { + ChartFrame chart = new ChartFrame(); + chart.setIconImage(GlobalSettings.ICON_16x16_LINE_CHART.getImage()); + chart.setTitle("CPMD MD Control"); + chart.setChartTitle("Energies (no Energy Info)"); + chart.setXAxisTitle("Steps"); + //chart.enableChartPanel(false); + //chart.enableTablePanel(false); + + double x[] = new double[cpmd_traj.countSnapshots()]; + double[] energies = new double[cpmd_traj.countSnapshots()]; + + for (int i = 0; i < cpmd_traj.countSnapshots(); i++) { + x[i] = i; + energies[i] = 0; + } + + chart.addDataSeries(x, energies, "Energies"); + + if (chart != null) { + chart.setRenderer(j3d); + chart.setStructureManagerInterface(cpmd_traj); + chart.pack(); + chart.setLocationRelativeTo(this); + chart.showChart(true); + } + } + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading CPMD Output file : " + ex.getMessage(), ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + return; + } + + break; + + case GAMESS_INPUT: + try { + wizard.parseMolecularData("gamessInput"); + if (wizard.getMolecule() == null) { + return; + } + j3d.setMolecule(wizard.getMolecule()); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading GAMESS Input file : " + ex.getMessage(), ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + return; + } + break; + + case GAMESS_OUTPUT: + + try { + wizard.parseMolecularData("gamessOutput"); + if (wizard.getMolecule() == null) { + return; + } + j3d.setMolecule(wizard.getMolecule()); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading GAMESS Output file : " + ex.getMessage(), ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + break; + + case MOPAC2002_LOG: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.mopacLog, + "MOPAC Log Files (*.log)", JFileChooser.OPEN_DIALOG); + } + if (fileName == null) { + return; + } + + MopacOutput mopac = new MopacOutput(); + try { + mopac.parseMopacLogFile(fileName); + mol = new Molecule(); + mopac.getMolecularInterface(mol); + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + j3d.setMolecule(mol); + + JShowText showMopResume = new JShowText("MOPAC Log File Resume"); + showMopResume.setSize(600, 640); + showMopResume.setTitle("MOPAC Log File Resume: " + fileName); + showMopResume.setLocationRelativeTo(this); + showMopResume.setText(mopac.getOutputResume()); + showMopResume.setVisible(true); + + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading MOPAC Log file : " + + ex.getMessage(), ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + break; + + case MOPAC_INPUT: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.mopacInput, + "MOPAC Input Files (*.dat;*.inp)", JFileChooser.OPEN_DIALOG); + } + if (fileName == null) { + return; + } + + Mopac mopac_in = new Mopac(); + try { + mopac_in.parseMopacInput(fileName, 0); + mol = new Molecule(); + mopac_in.getMolecularInterface(mol); + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + j3d.setMolecule(mol); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading MOPAC Input file : " + + ex.getMessage(), ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + + break; + + case MOPAC_OUTPUT: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.mopacOutput, "MOPAC Output Files (*.out)", + JFileChooser.OPEN_DIALOG); + } + if (fileName == null) { + return; + } + + MopacOutput mopac_out = new MopacOutput(); + try { + mopac_out.parseMopacOutputFile(fileName); + mol = new Molecule(); + mopac_out.getMolecularInterface(mol); + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + j3d.setMolecule(mol); + + JShowText showMopacResume = new JShowText("MOPAC Output File Resume"); + showMopacResume.setSize(600, 640); + showMopacResume.setTitle("MOPAC Output File Resume: " + fileName); + showMopacResume.setLocationRelativeTo(this); + showMopacResume.setText(mopac_out.getOutputResume()); + showMopacResume.setVisible(true); + + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading MOPAC Output file : " + + ex.getMessage(), ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + break; + + case PDB: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.pdbFile, "Brookhaven Protein Bank (PDB) Files", + JFileChooser.OPEN_DIALOG); + } + if (fileName != null) { + openMolecularModelingFile(j3d, MolecularFileFormats.pdbFile, fileName); + } + + break; + + case SIESTA_INPUT: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.siestaInputFormat, "SIESTA Input Files", + JFileChooser.OPEN_DIALOG); + } + if (fileName == null) { + return; + } + SiestaInput siesta_input = new SiestaInput(); + try { + siesta_input.parseFDF(fileName, 0); + mol = new Molecule(); + siesta_input.getMolecularInterface(mol); + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + j3d.setMolecule(mol); + UnitCellGraphics siestaUC = new UnitCellGraphics("Siesta Unit Cell"); + j3d.addGraphics(siestaUC.getCellGraphicsObject(siesta_input.getLatticeVectors())); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading SIESTA input file : " + + ex.getMessage(), ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + + break; + + case ADF_INPUT: + if (fileName == null) { + wizard.parseMolecularData("adfInput"); + if (wizard.getMolecule() == null) { + return; + } + } + try { + j3d.setMolecule(wizard.getMolecule()); + + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading ADF input file : " + ex.getMessage(), ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + + break; + + case ADF_OUTPUT: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.adfOutput, + "Amsterdam Density Functional package (ADF) Files", + JFileChooser.OPEN_DIALOG); + } + if (fileName == null) { + return; + } + ADFOutput adf_output = new ADFOutput(); + try { + adf_output.parseFile(fileName); + if (adf_output.countSectionsWithGeometry() < 1) { + JOptionPane.showMessageDialog(this, "Didn't find geometry in ADF output file", ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + int[] sections = adf_output.getSectionsWithGeometry(); + int nsect; + if (sections.length == 1) { + nsect = sections[0]; + } else { + String[] choices = new String[sections.length]; + for (int i = 0; i < sections.length; i++) { + choices[i] = String.valueOf(sections[i] + 1); + } + String input = (String) JOptionPane.showInputDialog(null, + "ADF Output has several section with geommetry\nSelect a section", + "Select Section", JOptionPane.QUESTION_MESSAGE, null, + choices, choices[choices.length - 1]); + if (input == null) { + return; + } + nsect = Integer.valueOf(input) - 1; + } + adf_output.selectSection(nsect); + mol = new Molecule(); + adf_output.getMolecularInterface(mol, nsect); + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, + CCTAtomTypes.getElementMapping()); + mol.addProperty(MoleculeInterface.OUTPUT_RESULTS, adf_output); + j3d.setMolecule(mol); + + if (adf_output.hasDisplacementVectors()) { + VibrationsRenderer vRenderer = null; + try { + vRenderer = new VibrationsRenderer(j3d.getMoleculeInterface(), adf_output, j3d); + j3d.getMoleculeInterface().addProperty( + MoleculeInterface.VIBRATION_RENDERER, vRenderer); + } catch (Exception ex) { + } + vcFrame = new VibrationsControlFrame(); + vcFrame.setTitle("Vibrations Control"); + vcFrame.setVibrationsRendererProvider(vRenderer); + vcFrame.setSpectraProvider(adf_output); + vcFrame.pack(); + vcFrame.setLocationRelativeTo(this); + vcFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + vcFrame.setVisible(true); + } + + gaussProp = new SelectPropShowDialog(null, "Select calculated properties to show"); + gaussProp.setLocationRelativeTo(this); + gaussProp.setControls(adf_output); + gaussProp.pack(); + + if (!gaussProp.showDialog()) { + return; + } + + // --- Show interactive chart + if (gaussProp.isShowInteractiveChart()) { + try { + String[] terms = adf_output.getAvailPropToChart(); + if (terms == null || terms.length < 1) { + JOptionPane.showMessageDialog(this, "Didn't find any properties to chart in output file...", + "Warning", JOptionPane.WARNING_MESSAGE); + //return; + } else { + SelectFromListDialog list = new SelectFromListDialog(null, "Select Energy Terms to Plot"); + list.setListData(terms); + list.enableMultipleSelection(true); + list.setLocationRelativeTo(this); + list.setVisible(true); + Object[] objs = list.getSelectedItems(); + if (objs == null || objs.length < 1) { + JOptionPane.showMessageDialog(this, "No Energy terms have been selected...", + "Warning", JOptionPane.WARNING_MESSAGE); + } else { + + double x[] = null; + ChartFrame chart = null; + for (int i = 0; i < objs.length; i++) { + double[] energies = adf_output.getAllTerms( + objs[i].toString()); + if (energies == null) { + JOptionPane.showMessageDialog(this, "No Information about energy terms is found in output file...", + "Warning", JOptionPane.WARNING_MESSAGE); + return; + } else if (energies.length < 2) { + JOptionPane.showMessageDialog(this, "File has less than 2 snapshots with energy info. Chart won't be shown", + "Warning", JOptionPane.WARNING_MESSAGE); + } else { + if (i == 0) { + chart = new ChartFrame(); + x = new double[energies.length]; + for (int j = 0; j < x.length; j++) { + x[j] = j; + } + chart.setChartTitle("Properties vs Steps"); + chart.setXAxisTitle("Step"); + } + + chart.addDataSeries(x, energies, + objs[i].toString()); + } + } + + if (chart != null) { + chart.setRenderer(j3d); + chart.setStructureManagerInterface(adf_output); + chart.showChart(true); + } + } + } + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Creating chart : " + ex.getMessage(), + ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + } + } + + } catch (Exception ex) { + //System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading ADF output file : " + ex.getMessage(), + ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + + break; + + case MOL2: + if (fileName == null) { + wizard.parseMolecularData("triposmol2"); + } + if (fileName != null) { + wizard.parseMolecularData("triposmol2", fileName); + } + if (wizard.getNumberMolecules() > 0) { + j3d.addMolecule(wizard.getMolecule()); + } + break; + + case MDL_MOLFILE: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.mdlMolfileFormat, "MDL Molfile Files", JFileChooser.OPEN_DIALOG); + } + if (fileName != null) { + openMolecularModelingFile(j3d, MolecularFileFormats.mdlMolfileFormat, fileName); + } + + break; + + case GROMACS_GRO: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.gromacsGROFormat, "Gromacs Coordinate Files", + JFileChooser.OPEN_DIALOG); + } + if (fileName != null) { + openMolecularModelingFile(j3d, MolecularFileFormats.gromacsGROFormat, fileName); + } + + break; + + case AMBER_PRMTOP: + if (prmtopDialog == null) { + prmtopDialog = new ReadPrmtopDialog(null, "Open Amber Topology File (prmtop)", true, null); + prmtopDialog.setLocationRelativeTo(this); + } + m = new Molecule(); + prmtopDialog.setMolecule(m); + + prmtopDialog.setVisible(true); + + if (prmtopDialog.isOKPressed() && prmtopDialog.getMolecule().getNumberOfAtoms() > 0) { + j3d.addMolecule(prmtopDialog.getMolecule()); + } + + break; + + case AMBER_PREP: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.amberPrepFormat, "Amber PREP Files", JFileChooser.OPEN_DIALOG); + } + if (fileName == null) { + return; + } + AmberPrep amberPrep = new AmberPrep(); + try { + amberPrep.parsePrepFile(fileName, 0); + mol = new Molecule(); + amberPrep.getMolecularInterface(mol); + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + j3d.setMolecule(mol); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading Amber prep file : " + ex.getMessage(), + ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + + break; + + case AMBER_LIB: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.amberLibFormat, "Amber Lib (Off) Files", + JFileChooser.OPEN_DIALOG); + } + if (fileName == null) { + return; + } + MoleculeInterface mol_lib = new Molecule(); + AmberLib amberLib = new AmberLib(mol_lib); + try { + amberLib.parseLibFile(fileName, 0); + logger.info("Number of molecules: " + amberLib.countMolecules()); + if (amberLib.countMolecules() == 1) { + String[] res_name = amberLib.getMoleculeNames(); + mol_lib = amberLib.getMolecule(res_name[0]); + Molecule.guessAtomTypes(mol_lib, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + j3d.addMolecule(mol_lib); + } else { + Map molecules = amberLib.getMolecules(); + if (moleculeSelectorDialog == null) { + moleculeSelectorDialog = new MoleculeSelectorDialog(null, "Select molecule", false); + Java3dUniverse libJ3D = new Java3dUniverse(); + moleculeSelectorDialog.setJ3DParent(j3d); + moleculeSelectorDialog.setJ3DRenderer(libJ3D); + moleculeSelectorDialog.setSize(350, 500); + moleculeSelectorDialog.setLocationRelativeTo(this); + moleculeSelectorDialog.setAlwaysOnTop(true); + } + moleculeSelectorDialog.setMoleculeTree(molecules); + moleculeSelectorDialog.setVisible(true); + } + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading Amber Lib file : " + ex.getMessage(), ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + return; + } + + break; + + case CCT: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.cctFileFormat, "Computational Chemistry Toolkit Format", + JFileChooser.OPEN_DIALOG); + } + if (fileName != null) { + openMolecularModelingFile(j3d, MolecularFileFormats.cctFileFormat, fileName); + } + + break; + + case XMOL_XYZ: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.xmolXYZFileFormat, "XMol XYZ Format", + JFileChooser.OPEN_DIALOG); + } + if (fileName != null) { + openMolecularModelingFile(j3d, MolecularFileFormats.xmolXYZFileFormat, fileName); + } + break; + + case VASP_POSCAR: + if (vaspDialog == null) { + vaspDialog = new ReadPoscarDialog(null, "Open VASP Poscar File (poscar)", true, null); + vaspDialog.setLocationRelativeTo(this); + } + m = new Molecule(); + vaspDialog.setMolecule(m); + + vaspDialog.setVisible(true); + + if (vaspDialog.isOKPressed() && vaspDialog.getMolecule().getNumberOfAtoms() > 0) { + m = vaspDialog.getMolecule(); + Molecule.guessCovalentBonds(m); + j3d.addMolecule(m); + UnitCellGraphics poscarUC = new UnitCellGraphics("VASP Unit Cell"); + j3d.addGraphics(poscarUC.getCellGraphicsObject(vaspDialog.getLatticeVectors())); + } + + break; + + case VASP_VASPRUN: + + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.vaspVasprunFormat, MolecularFileFormats.vaspVasprunFormat, + JFileChooser.OPEN_DIALOG); + } + if (fileName == null) { + return; + } + VasprunXML vasprunXML = null; + try { + vasprunXML = new VasprunXML(); + vasprunXML.parseVasprunXML(fileName); + mol = new Molecule(); + vasprunXML.getMolecularInterface(mol); + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + j3d.addMolecule(mol); + if (vasprunXML.getLatticeVectors() != null) { + UnitCellGraphics vasprunUC = new UnitCellGraphics("VASP Unit Cell"); + j3d.addGraphics(vasprunUC.getCellGraphicsObject(vasprunXML.getLatticeVectors())); + } + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading Vasprun file : " + ex.getMessage(), ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + return; + } + + try { + String[] terms = vasprunXML.getEnergyTerms(); + if (terms == null || terms.length < 1) { + JOptionPane.showMessageDialog(this, "Didn't find any energy terms in Vasprun file...", + "Warning", JOptionPane.WARNING_MESSAGE); + return; + } + SelectFromListDialog list = new SelectFromListDialog(null, "Select Energy Terms to Plot"); + list.setListData(terms); + list.selectItem( VasprunXML.TOTAL_ENERGY_KEY, true); + list.enableMultipleSelection(true); + list.setLocationRelativeTo(this); + list.setVisible(true); + Object[] objs = list.getSelectedItems(); + if (objs == null || objs.length < 1) { + JOptionPane.showMessageDialog(this, "No Energy terms have been selected...", "Warning", + JOptionPane.WARNING_MESSAGE); + return; + } + + List arrays = new ArrayList(objs.length); + double x[] = null; + ChartFrame chart = null; + for (int i = 0; i < objs.length; i++) { + double[] energies = vasprunXML.getAllTerms(objs[i].toString()); + if (energies == null) { + JOptionPane.showMessageDialog(this, "No Information about energy terms is found in Vasprun file...", + "Warning", JOptionPane.WARNING_MESSAGE); + return; + } else if (energies.length < 2) { + JOptionPane.showMessageDialog(this, "File has less than 2 snapshots with energy info. Chart won't be shown", + "Warning", JOptionPane.WARNING_MESSAGE); + return; + } + + if (i == 0) { + chart = new ChartFrame(); + x = new double[energies.length]; + for (int j = 0; j < x.length; j++) { + x[j] = j; + } + chart.setChartTitle("Energy Terms vs Steps"); + chart.setXAxisTitle("Step"); + } + + chart.addDataSeries(x, energies, objs[i].toString()); + } + + chart.setRenderer(j3d); + chart.setStructureManagerInterface(vasprunXML); + chart.showChart(true); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Creating chart : " + + ex.getMessage(), ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + + break; + + case QCHEM_INPUT: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.qchemFormat, MolecularFileFormats.qchemFormat, + JFileChooser.OPEN_DIALOG); + } + if (fileName == null) { + return; + } + + try { + QChem qchem = new QChem(); + qchem.parseQChemInput(fileName, 0); + mol = new Molecule(); + qchem.getMolecularInterface(mol); + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + j3d.addMolecule(mol); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading QChem Input file : " + + ex.getMessage(), ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + + break; + + case QCHEM_OUTPUT: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.qchemOutputFormat, + MolecularFileFormats.qchemOutputFormat, JFileChooser.OPEN_DIALOG); + } + if (fileName == null) { + return; + } + + try { + QChemOutput qchem = new QChemOutput(); + qchem.parseQChemOutputFile(fileName, false); + mol = new Molecule(); + qchem.getMolecularInterface(mol); + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + j3d.addMolecule(mol); + + JShowText showQChemResume = new JShowText("Q-Chem Output File Resume"); + showQChemResume.setSize(600, 640); + showQChemResume.setTitle("Q-Chem Calculation Summary: " + fileName); + showQChemResume.setLocationRelativeTo(this); + showQChemResume.setText(qchem.getOutputResume()); + showQChemResume.setVisible(true); + + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading QChem Output file : " + + ex.getMessage(), ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + + break; + + case GULP_INPUT: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.gulpInputFormat, MolecularFileFormats.gulpInputFormat, + JFileChooser.OPEN_DIALOG); + } + if (fileName == null) { + return; + } + + try { + Gulp gulp = new Gulp(); + gulp.parseInput(fileName, 0); + mol = new Molecule(); + gulp.getMolecularInterface(mol); + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + j3d.addMolecule(mol); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading GULP input file : " + ex.getMessage(), ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + return; + } + + break; + } + } + + String chooseFileDialog(String fileType, String formatDescr, int dialogType) { + JFileChooser chooser = new JFileChooser(); + FileFilterImpl filter = new FileFilterImpl(); + String extensions = MolecularFileFormats.readFormats.get(fileType). + toString(); + String temp[] = extensions.split(";"); + for (int i = 0; i < temp.length; i++) { + filter.addExtension(temp[i]); + } + filter.setDescription(formatDescr); + chooser.setFileFilter(filter); + chooser.setDialogType(dialogType); + if (dialogType == JFileChooser.OPEN_DIALOG) { + chooser.setDialogTitle("Open File"); + chooser.setDialogType(JFileChooser.OPEN_DIALOG); + } else if (dialogType == JFileChooser.SAVE_DIALOG) { + chooser.setDialogTitle("Save File"); + chooser.setDialogType(JFileChooser.SAVE_DIALOG); + } + + currentWorkingDirectory = GlobalSettings.getCurrentWorkingDirectory(); + if (currentWorkingDirectory != null) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } else if (prefs != null) { + String lastPWD = prefs.get(GlobalSettings.lastPWDKey, ""); + if (lastPWD.length() > 0) { + currentWorkingDirectory = new File(lastPWD); + if (currentWorkingDirectory.isDirectory() + && currentWorkingDirectory.exists()) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } + } + } + + int returnVal = JFileChooser.CANCEL_OPTION; + + if (dialogType == JFileChooser.OPEN_DIALOG) { + returnVal = chooser.showOpenDialog(this); + } else if (dialogType == JFileChooser.SAVE_DIALOG) { + returnVal = chooser.showSaveDialog(this); + } + + if (returnVal == JFileChooser.APPROVE_OPTION) { + String fileName = chooser.getSelectedFile().getPath(); + currentWorkingDirectory = chooser.getCurrentDirectory(); + GlobalSettings.setCurrentWorkingDirectory(currentWorkingDirectory); + if (prefs != null) { + try { + prefs.put(GlobalSettings.lastPWDKey, currentWorkingDirectory.getAbsolutePath()); + } catch (Exception ex) { + System.err.println("Cannot save cwd: " + ex.getMessage() + " Ignored..."); + } + } + logger.info("You chose to open this file: " + fileName); + return fileName; + } + return null; + } + + public void setKnownHosts(final String[] hosts) { + + final loadFromSFTP_actionAdapter lfsftp = new loadFromSFTP_actionAdapter(this); + submenuLoadRemote.removeAll(); + for (int i = 0; i < hosts.length; i++) { + final JMenuItem jMenuItem = new JMenuItem(hosts[i]); + jMenuItem.addActionListener(lfsftp); + submenuLoadRemote.add(jMenuItem); + } + + } + + public void setFileBrowser(final String host, final String username, + final FileBrowserInterface file_browser) { + final String key = username + "@" + host; + + if (sftpChoosers.containsKey(key)) { + sftpChooserDialog = sftpChoosers.get(key); + } else if (ftpChoosers.containsKey(file_browser)) { + sftpChooserDialog = ftpChoosers.get(file_browser); + } else { + sftpChooserDialog = new SFTPFileChooserDialog(null, "Select file", true); + + jamberooCore.getShadowSFTPManager().addClient(sftpChooserDialog); + sftpChooserDialog.setLocationRelativeTo(this); + + final Map readFormats = MolecularFileFormats.remoteReadFormats; + final Map readFormatsDescr = MolecularFileFormats.remoteReadFormatDescription; + int count = 0; + final FileFilterImpl[] filter = new FileFilterImpl[readFormats.size()]; + + //filter[count] = new FileFilterImpl(); + //filter[count].setDescription("All files"); + //++count; + remoteFileFormats.clear(); + final Set set = readFormats.entrySet(); + final Iterator iter = set.iterator(); + while (iter.hasNext()) { + final Map.Entry me = (Map.Entry) iter.next(); + final CHEMISTRY_FILE_FORMAT format = (CHEMISTRY_FILE_FORMAT) me.getKey(); + final String extensions = readFormats.get(format); + final String temp[] = extensions.split(";"); + filter[count] = new FileFilterImpl(); + //String descr = readFormatsDescr.get(format); + StringBuilder descr = new StringBuilder(readFormatsDescr.get( + format)); + + for (int i = 0; i < temp.length; i++) { + if (i == 0) { + descr.append(" ("); + } else { + descr.append(";"); + } + filter[count].addExtension(temp[i]); + descr.append("*." + temp[i]); + if (i == temp.length - 1) { + descr.append(")"); + } + } + filter[count].setDescription(descr.toString()); + remoteFileFormats.put(descr.toString(), format); + + ++count; + } + + sftpChooserDialog.setTitle("sftp: " + host + " as " + username); + sftpChooserDialog.setFileBrowser(file_browser); + sftpChooserDialog.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + sftpChooserDialog.setFileFilters(filter); + + ftpChoosers.put(file_browser, sftpChooserDialog); + sftpChoosers.put(key, sftpChooserDialog); + + } + sftpChooserDialog.setVisible(true); + + if (!sftpChooserDialog.isLoadPressed()) { + return; + } + + File local = sftpChooserDialog.getLocalFile(); + if (local == null) { + return; + } + String filter = sftpChooserDialog.getSeletedFilterDescription(); + CHEMISTRY_FILE_FORMAT rFormat = remoteFileFormats.get(filter); + try { + this.openFile(java3dUniverse, rFormat, local.getAbsolutePath()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + } + + public void loadFromSFTP(ActionEvent e) { + String command = e.getActionCommand(); + + if (command.contains(" as ")) { + final String host = command.substring(0, command.indexOf(" ")); + final String username = command.substring(command.lastIndexOf(" ") + 1); + final String hostKey = username + "@" + host; + if (sftpChoosers.containsKey(hostKey)) { + setFileBrowser(host, username, null); + return; + } + } + + if (jamberooCore.getShadowSFTPManager() == null) { + System.err.println("No Shadow Manager is set..."); + return; + } + try { + jamberooCore.getShadowSFTPManager().processConnection(command, this); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + } + } + + void jMenuFileSaveAs_actionPerformed(ActionEvent actionEvent) { + String arg = actionEvent.getActionCommand(); + + if (java3dUniverse.getMolecule() == null + || java3dUniverse.getMolecule().getNumberOfAtoms() < 1) { + JOptionPane.showMessageDialog(this, "Load Molecule first!", + ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + return; + } + + // Gaussian G03 GJF Files + if (arg.equals(MolecularFileFormats.gaussian03GJF)) { // G03 Input file + if (saveG03GJFDialog == null) { + saveG03GJFDialog = new SaveG03GJFDialog(null, "Save Gaussian Input File", false); + //saveG03GJFDialog.setLinkZeroCommands("%nproc=1"); + //saveG03GJFDialog.setRouteSection("# Opt HF/6-31g"); + Gaussian g = new Gaussian(); + g.setGraphicsRenderer(java3dUniverse); + saveG03GJFDialog.setGJFParser(g); + saveG03GJFDialog.setLocationRelativeTo(this); + } + SwingUtilities.updateComponentTreeUI(saveG03GJFDialog); + saveG03GJFDialog.setupMolecule(java3dUniverse.getMolecule()); + saveG03GJFDialog.setVisible(true); + + } else if (arg.equals(MolecularFileFormats.siestaInputFormat)) { // Siesta Input file + if (saveSiestaInputDialog == null) { + saveSiestaInputDialog = new SaveSiestaInputDialog(null, "Save Siesta input file", false); + saveSiestaInputDialog.setJava3dUniverse(java3dUniverse); + saveSiestaInputDialog.setMolecularInterface(java3dUniverse.getMolecule()); + saveSiestaInputDialog.pack(); + saveSiestaInputDialog.setLocationRelativeTo(this); + } else if (!saveSiestaInputDialog.isVisible()) { + saveSiestaInputDialog.setMolecularInterface(java3dUniverse.getMolecule()); + } + + saveSiestaInputDialog.setVisible(true); + } else if (arg.equals(MolecularFileFormats.xmolXYZFileFormat)) { // XMOL XYZ file + + String fileName = chooseFileDialog(MolecularFileFormats.xmolXYZFileFormat, + "XMol XYZ Files (*.xyz)", + JFileChooser.SAVE_DIALOG); + if (fileName != null) { + String name = FileUtilities.getFileName(fileName); + if (name.indexOf(".") == -1) { + fileName += ".xyz"; + } + + if (saveXYZDialog == null) { + saveXYZDialog = new SaveXYZDialog(null, "Select Save Options"); + saveXYZDialog.setLocationRelativeTo(this); + } + saveXYZDialog.setVisible(true); + if (!saveXYZDialog.okPressed) { + return; + } + try { + XMolXYZ xMolXYZ = new XMolXYZ(); + xMolXYZ.saveXMolXYZ(fileName, java3dUniverse.getMolecule(), + saveXYZDialog.isAtomicSymbols(), + saveXYZDialog.isInAngstroms()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), + ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + } + } + } else if (arg.equals(MolecularFileFormats.pdbFile)) { // PDB file + String fileName = chooseFileDialog(MolecularFileFormats.pdbFile, + "Brookhaven Protein Bank (PDB) Files (*.pdb)", + JFileChooser.SAVE_DIALOG); + if (fileName != null) { + String name = FileUtilities.getFileName(fileName); + if (name.indexOf(".") == -1) { + fileName += ".pdb"; + } + + PDB.saveAsPDBFile(java3dUniverse.getMolecule(), + fileName); + } + } else if (arg.equals(MolecularFileFormats.triposMol2)) { // Tripos Mol2 file + String fileName = chooseFileDialog(MolecularFileFormats.triposMol2, + "Tripos Mol2 Files (*.mol2)", + JFileChooser.SAVE_DIALOG); + if (fileName != null) { + String name = FileUtilities.getFileName(fileName); + if (name.indexOf(".") == -1) { + fileName += ".mol2"; + } + + try { + TriposParser.saveTriposMol2File(java3dUniverse.getMolecule(), + fileName); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), + ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + } + } + } else if (arg.equals(MolecularFileFormats.cctFileFormat)) { // CCT file + String fileName = chooseFileDialog(MolecularFileFormats.cctFileFormat, + "Computational Chemistry Toolkit Files (*.cct)", + JFileChooser.SAVE_DIALOG); + if (fileName != null) { + String name = FileUtilities.getFileName(fileName); + if (name.indexOf(".") == -1) { + fileName += ".cct"; + } + try { + CCTParser.saveCCTFile(java3dUniverse.getMolecule(), + fileName); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Error Saving CCT file: " + + ex.getMessage(), + ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + return; + } + } + } else if (arg.equals(MolecularFileFormats.povrayFormat)) { // Povray file + PovrayJava3d povray = new PovrayJava3d(java3dUniverse); + try { + povray.savePovrayFile(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error Saving Pov-Ray file: " + ex.getMessage(), + ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + } else if (arg.equals(MolecularFileFormats.geomFormat)) { // Geom file + GeomFormat geom = new GeomFormat(); + geom.setMolecule(java3dUniverse.getMoleculeInterface()); + try { + geom.saveGeomFormatFile(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Error Saving Geom Format file: " + + ex.getMessage(), + ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + return; + } + } else if (arg.equals(MolecularFileFormats.vrmlFormat)) { // VRML file + //GroupToVRML vrml = new GroupToVRML(java3dUniverse.getMoleculeBranchGroup()); + //GroupToVRML vrml = new GroupToVRML(java3dUniverse.getRootBranchGroup()); + GroupToVRML vrml = new GroupToVRML(java3dUniverse.getLocale()); + vrml.enableColorsPerVertex(false); // Don't write colors per vertex (to be compatible with Acrobat 9,xx) + vrml.setCanvas3D(java3dUniverse.getCanvas3D()); + try { + vrml.saveVRMLFile(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error Saving VRML file: " + ex.getMessage(), + ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + } + } + + public void saveImageAs(ActionEvent e) { + jSubmenuImageSave.setEnabled(false); + + String arg = e.getActionCommand(); + BufferedImage bImage = java3dUniverse.getImageCapture(); + MediaTracker mediaTracker = new MediaTracker(this); + mediaTracker.addImage(bImage, 0); + try { + mediaTracker.waitForID(0); + ImageTools.saveImageAsDialog(bImage, arg, null); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error Saving Image: " + ex.getMessage(), + ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + System.err.println(ex.getMessage()); + } + jSubmenuImageSave.setEnabled(true); + } + + public void submitMolecule(ActionEvent e) { + this.jSubmenuMoleculeSubmit.setEnabled(false); + String arg = e.getActionCommand(); + + if (arg.equalsIgnoreCase("gaussian") || arg.equalsIgnoreCase("g03") || arg.equalsIgnoreCase("g09")) { // Redo this!!! + if (gaussianInputEditorFrame == null) { + Gaussian g = new Gaussian(); + g.setGraphicsRenderer(java3dUniverse); + gaussianInputEditorFrame = new GaussianInputEditorFrame(g); + gaussianInputEditorFrame.setTitle("Edit Options and Submit to Grid"); + gaussianInputEditorFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); + gaussianInputEditorFrame.setLocationRelativeTo(this); + try { + gaussianInputEditorFrame.removeMenuItem("File", "Exit"); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + } + submitGaussianJob.setText("Submit to Grid"); + submitGaussianJob.setActionCommand(arg); + submitGaussian_actionAdapter al = new submitGaussian_actionAdapter(this); + + submitGaussianJob.addActionListener(al); + gaussianInputEditorFrame.addMenuItem("File", submitGaussianJob); + gaussianInputEditorFrame.returnBackButton.setVisible(true); + gaussianInputEditorFrame.returnBackButton.setToolTipText("Submit to Grid"); + gaussianInputEditorFrame.returnBackButton.setIcon(GlobalSettings.ICON_32x32_SERVER_FROM_CLIENT); + gaussianInputEditorFrame.returnBackButton.setActionCommand(arg); + gaussianInputEditorFrame.returnBackButton.addActionListener(al); // ??? + + } + + if (java3dUniverse.getMoleculeInterface() != null + && java3dUniverse.getMoleculeInterface().getNumberOfAtoms() > 0) { + gaussianInputEditorFrame.setupMolecule(java3dUniverse.getMoleculeInterface()); + } + + gaussianInputEditorFrame.setVisible(true); + + } + this.jSubmenuMoleculeSubmit.setEnabled(true); + } + + public void submitGaussianJob(ActionEvent e) { + // --- Save gjf file + String arg = e.getActionCommand(); + + if (gaussianFileChooserDialog == null) { + FileFilterImpl filters[] = new FileFilterImpl[1]; + filters[0] = new FileFilterImpl(); + filters[0].addExtension("gjf"); + filters[0].addExtension("GJF"); + filters[0].addExtension("com"); + filters[0].addExtension("COM"); + filters[0].setDescription( + "Gaussian Input Files (*.gjf;*.com;*.g03)"); + + String pwd = Utils.getPreference(this, lastSaveGaussianInputDirKey); + + gaussianFileChooserDialog = new FileChooserDialog(filters, this, "Select file to save", JFileChooser.SAVE_DIALOG); + gaussianFileChooserDialog.setWorkingDirectory(pwd); + } + + String fileName = gaussianFileChooserDialog.getFile(); + + if (fileName == null || fileName.trim().length() < 1) { + return; + } + + if (fileName.indexOf(".") == -1) { + fileName += ".gjf"; + } + + String pwd = gaussianFileChooserDialog.getCurrentDirectory(). + getAbsolutePath(); + Utils.savePreference(this, lastSaveGaussianInputDirKey, pwd); + + //FileDialog fd = new FileDialog(new Frame(), "Save Gaussian Job File", + // FileDialog.SAVE); + //fd.setFile("*.gjf;*.com"); + //fd.setDirectory(directory); + //fd.setFile(file_name); + //fd.setVisible(true); + //if (fd.getFile() == null) { + // return; + //} + //String newFileName = new String(fd.getFile()); + if (fileName.indexOf(".") == -1) { + fileName += ".gjf"; + } else if (fileName.endsWith(".")) { + fileName += "gjf"; + } + //String newWorkingDirectory = new String(fd.getDirectory()); + + try { + IOUtils.saveStringIntoFile(gaussianInputEditorFrame.toString(), fileName); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + + // --- Open job submit dialog + ScriptSubmitterDialogInterface ssd = GridProviders.getScriptSubmitter( + arg); + JDialog dialog = ssd.getDialog(); + dialog.setModal(true); + if (fileName.contains("/")) { + ssd.setInputFile(fileName.substring(fileName.lastIndexOf("/") + 1)); + } else if (fileName.contains("\\")) { + ssd.setInputFile(fileName.substring(fileName.lastIndexOf("\\") + 1)); + } else { + ssd.setInputFile(fileName); + } + + //ssd.setLocalDirectory(newWorkingDirectory); + ssd.setLocalDirectory(pwd + "/"); + + dialog.setVisible(true); + gaussianInputEditorFrame.setVisible(false); + } + + public File getCurrentWorkingDirectory() { + return currentWorkingDirectory; + } + + public void setCurrentWorkingDirectory(File currentWorkingDirectory) { + this.currentWorkingDirectory = currentWorkingDirectory; + } + + public VibrationsControlFrame getVcFrame() { + return vcFrame; + } + + public void setVcFrame(VibrationsControlFrame vcFrame) { + this.vcFrame = vcFrame; + } + + //class JEditorFrame_jMenuFileOpenAs_ActionAdapter + // implements ActionListener { + // FileMenu adaptee; + // JEditorFrame_jMenuFileOpenAs_ActionAdapter(FileMenu adaptee) { + // this.adaptee = adaptee; + // } + // public void actionPerformed(ActionEvent actionEvent) { + // adaptee.jMenuFileOpenAs_actionPerformed(actionEvent); + // } + //} + private class loadFromSFTP_actionAdapter + implements ActionListener { + + private FileMenu adaptee; + + loadFromSFTP_actionAdapter(FileMenu adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.loadFromSFTP(e); + } + } + + class JEditorFrame_jMenuFileSaveAs_ActionAdapter + implements ActionListener { + + FileMenu adaptee; + + JEditorFrame_jMenuFileSaveAs_ActionAdapter(FileMenu adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent actionEvent) { + adaptee.jMenuFileSaveAs_actionPerformed(actionEvent); + } + } + + private class saveImageAs_actionAdapter + implements ActionListener { + + private FileMenu adaptee; + + saveImageAs_actionAdapter(FileMenu adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.saveImageAs(e); + } + } + + private class submitMolecule_actionAdapter + implements ActionListener { + + private FileMenu adaptee; + + submitMolecule_actionAdapter(FileMenu adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.submitMolecule(e); + } + } + + private class submitGaussian_actionAdapter + implements ActionListener { + + private FileMenu adaptee; + + submitGaussian_actionAdapter(FileMenu adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.submitGaussianJob(e); + } + } +} diff --git a/src/main/java/cct/dialogs/Frame1.java b/src/main/java/cct/dialogs/Frame1.java new file mode 100644 index 0000000..b58651d --- /dev/null +++ b/src/main/java/cct/dialogs/Frame1.java @@ -0,0 +1,372 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Point; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.net.URL; +import java.util.logging.Logger; + +import org.scijava.java3d.Canvas3D; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JToolBar; + +import cct.help.HelpPanel; +import cct.j3d.Java3dUniverse; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Frame1 + extends JFrame { + JPanel contentPane; + BorderLayout borderLayout1 = new BorderLayout(); + JMenuBar jMenuBar1 = new JMenuBar(); + JMenu jMenuFile = new JMenu(); + JMenuItem jMenuFileExit = new JMenuItem(); + JMenu jMenuHelp = new JMenu(); + JMenuItem jMenuHelpAbout = new JMenuItem(); + JToolBar jToolBar = new JToolBar(); + JButton jButton1 = new JButton(); + JButton jButton2 = new JButton(); + JButton helpButton = new JButton(); + //ImageIcon image1 = new ImageIcon(cct.dialogs.Frame1.class.getResource( + // "images/openFile.png")); + ImageIcon image2 = new ImageIcon(Frame1.class.getResource( + "cct/images/closeFile.png")); + ImageIcon image3 = new ImageIcon(Frame1.class.getResource( + "cct/images/help.png")); + ImageIcon addAtomImage = new ImageIcon(Frame1.class.getResource( + "cct/images/add-atom.gif")); + ImageIcon cutImage = new ImageIcon(Frame1.class.getResource( + "cct/images/cut-16x16.gif")); + ImageIcon hummerImage = new ImageIcon(Frame1.class.getResource( + "cct/images/hummer-16x16.gif")); + //ImageIcon openFileImage = new ImageIcon(cct.dialogs.Frame1.class.getResource( + // "images/openFie.png")); + JLabel statusBar = new JLabel(); + JToolBar mainToolBar = new JToolBar(); + JToolBar editToolBar = new JToolBar(); + JButton jButton4 = new JButton(); + JButton jButton5 = new JButton(); + JButton jButton6 = new JButton(); + JMenu openAs = new JMenu(); + + Canvas3D canvas3D; + Java3dUniverse java3dUniverse; + + JMenu editMenu = new JMenu(); + JMenu viewMenu = new JMenu(); + JMenu databaseMenu = new JMenu(); + JMenu saveAsMenu = new JMenu(); + JMenuItem gjfMenuItem = new JMenuItem(); + HelpPanel helpPanel1 = new HelpPanel(); + JMenuItem gaussOutMenuItem = new JMenuItem(); + JMenuItem openPDBMenuItem = new JMenuItem(); + JMenuItem openMol2MenuItem = new JMenuItem(); + JMenuItem saveGJFMenuItem = new JMenuItem(); + JMenuItem savePDBMenuItem = new JMenuItem(); + JMenuItem saveMol2MenuItem = new JMenuItem(); + static final Logger logger = Logger.getLogger(Frame1.class.getCanonicalName()); + + public Frame1() { + try { + setDefaultCloseOperation(EXIT_ON_CLOSE); + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + /** + * Component initialization. + * + * @throws Exception + */ + private void jbInit() throws Exception { + java3dUniverse = new Java3dUniverse(); + //setLayout(new BorderLayout()); + canvas3D = java3dUniverse.getCanvas3D(); + + contentPane = (JPanel) getContentPane(); + contentPane.setLayout(borderLayout1); + setSize(new Dimension(400, 300)); + setTitle("Frame Title"); + statusBar.setText(" "); + jMenuFile.setText("File"); + jMenuFileExit.setText("Exit"); + jMenuFileExit.addActionListener(new Frame1_jMenuFileExit_ActionAdapter(this)); + jMenuHelp.setText("Help"); + jMenuHelpAbout.setText("About"); + jMenuHelpAbout.addActionListener(new Frame1_jMenuHelpAbout_ActionAdapter(this)); + jButton4.setIcon(cutImage); + jButton5.setIcon(addAtomImage); + jButton6.setToolTipText(""); + jButton6.setIcon(hummerImage); + openAs.setText("Open As"); + editMenu.setText("Edit"); + viewMenu.setText("View"); + databaseMenu.setText("Database"); + saveAsMenu.setText("Save As"); + gjfMenuItem.setText("Gaussian G03 GJF"); + helpButton.addActionListener(new Frame1_helpButton_actionAdapter(this)); + gaussOutMenuItem.setToolTipText(""); + gaussOutMenuItem.setActionCommand("Gaussian G03 Output"); + gaussOutMenuItem.setText("Gaussian G03 Output"); + openPDBMenuItem.setToolTipText(""); + openPDBMenuItem.setText("PDB"); + openMol2MenuItem.setToolTipText(""); + openMol2MenuItem.setText("Tripos Mol2"); + saveGJFMenuItem.setText("Gaussian G03 GJF"); + savePDBMenuItem.setToolTipText(""); + savePDBMenuItem.setText("PDB"); + saveMol2MenuItem.setToolTipText(""); + saveMol2MenuItem.setText("Tripos Mol2"); + jMenuBar1.add(jMenuFile); + jMenuBar1.add(editMenu); + jMenuBar1.add(viewMenu); + jMenuBar1.add(databaseMenu); + jMenuFile.add(openAs); + jMenuFile.add(saveAsMenu); + + jMenuFile.addSeparator(); + jMenuFile.add(jMenuFileExit); + jMenuBar1.add(jMenuHelp); + jMenuHelp.add(jMenuHelpAbout); + setJMenuBar(jMenuBar1); + jButton1.setIcon(null); + jButton1.setToolTipText("Open File"); + jButton2.setIcon(image2); + jButton2.setToolTipText("Close File"); + helpButton.setIcon(image3); + helpButton.setToolTipText("Help"); + jToolBar.add(jButton1); + jToolBar.add(jButton2); + jToolBar.add(helpButton); + contentPane.add(statusBar, BorderLayout.SOUTH); + mainToolBar.add(jToolBar); + mainToolBar.add(editToolBar); + editToolBar.add(jButton5); + editToolBar.add(jButton4); + editToolBar.add(jButton6); + openAs.add(gjfMenuItem); + openAs.add(gaussOutMenuItem); + openAs.add(openPDBMenuItem); + openAs.add(openMol2MenuItem); + contentPane.add(helpPanel1, BorderLayout.CENTER); + contentPane.add(mainToolBar, BorderLayout.NORTH); + saveAsMenu.add(saveGJFMenuItem); + saveAsMenu.add(savePDBMenuItem); + saveAsMenu.add(saveMol2MenuItem); + } + + /** + * File | Exit action performed. + * + * @param actionEvent ActionEvent + */ + void jMenuFileExit_actionPerformed(ActionEvent actionEvent) { + System.exit(0); + } + + /** + * Help | About action performed. + * + * @param actionEvent ActionEvent + */ + void jMenuHelpAbout_actionPerformed(ActionEvent actionEvent) { + Frame1_AboutBox dlg = new Frame1_AboutBox(this); + Dimension dlgSize = dlg.getPreferredSize(); + Dimension frmSize = getSize(); + Point loc = getLocation(); + dlg.setLocation( (frmSize.width - dlgSize.width) / 2 + loc.x, + (frmSize.height - dlgSize.height) / 2 + loc.y); + dlg.setModal(true); + dlg.pack(); + dlg.setVisible(true); + } + + /* + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } + catch (Exception exception) { + exception.printStackTrace(); + } + + new testFrame(); + } + }); + } + */ + + public void helpButton_actionPerformed(ActionEvent e) { + String rootDir = getRootDirectory(); + logger.info("Root directory : " + rootDir); + + String protocol = "http://"; //"file:"; + rootDir = "sf.anu.edu.au/~vvv900/cct/appl/jmoleditor/manual/"; + String path = protocol + rootDir + "cct/html/"; + path = protocol + rootDir; + try { + URL helpURL = new URL(path + "index.html"); + helpPanel1.setText(helpURL); + } + catch (java.net.MalformedURLException ex) { + System.err.println(ex.getMessage()); + } + + } + + private String getRootDirectory() { + //cct.BaseClass.getClass().getName() + + String fullName = this.getClass().getName(); + logger.info("full Name : " + fullName); + + //BaseClass bc = new BaseClass(); + //String fullName = bc.getClass().getName(); + + int packageLen = fullName.lastIndexOf('.'); + // get the directory where the contents of this package are stored + + //String packageDir = bc.getClass().getResource(".").getFile(); + String packageDir = this.getClass().getResource(".").getFile(); + logger.info("Package directory : " + packageDir); + String classesDir = packageDir.substring(0, + packageDir.length() - packageLen - + 1); + //int index = classesDir.lastIndexOf('/'); + //String rootDir = classesDir.substring(0, index + 1); + String rootDir = classesDir; + return rootDir; + } + + class testFrame { + public testFrame() { + Frame1 frame = new Frame1(); + + //if (packFrame) { + frame.pack(); + //} + //else { + // frame.validate(); + //} + + // Center the window + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension frameSize = frame.getSize(); + if (frameSize.height > screenSize.height) { + frameSize.height = screenSize.height; + } + if (frameSize.width > screenSize.width) { + frameSize.width = screenSize.width; + } + frame.setLocation( (screenSize.width - frameSize.width) / 2, + (screenSize.height - frameSize.height) / 2); + frame.setVisible(true); + + } + } + +} + +class Frame1_helpButton_actionAdapter + implements ActionListener { + private Frame1 adaptee; + Frame1_helpButton_actionAdapter(Frame1 adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.helpButton_actionPerformed(e); + } +} + +class Frame1_jMenuFileExit_ActionAdapter + implements ActionListener { + Frame1 adaptee; + + Frame1_jMenuFileExit_ActionAdapter(Frame1 adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent actionEvent) { + adaptee.jMenuFileExit_actionPerformed(actionEvent); + } +} + +class Frame1_jMenuHelpAbout_ActionAdapter + implements ActionListener { + Frame1 adaptee; + + Frame1_jMenuHelpAbout_ActionAdapter(Frame1 adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent actionEvent) { + adaptee.jMenuHelpAbout_actionPerformed(actionEvent); + } +} diff --git a/src/main/java/cct/dialogs/Frame1_AboutBox.java b/src/main/java/cct/dialogs/Frame1_AboutBox.java new file mode 100644 index 0000000..5f36c28 --- /dev/null +++ b/src/main/java/cct/dialogs/Frame1_AboutBox.java @@ -0,0 +1,153 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Frame1_AboutBox + extends JDialog implements ActionListener { + JPanel panel1 = new JPanel(); + JPanel panel2 = new JPanel(); + JPanel insetsPanel1 = new JPanel(); + JPanel insetsPanel2 = new JPanel(); + JPanel insetsPanel3 = new JPanel(); + JButton button1 = new JButton(); + JLabel imageLabel = new JLabel(); + JLabel label1 = new JLabel(); + JLabel label2 = new JLabel(); + JLabel label3 = new JLabel(); + JLabel label4 = new JLabel(); + ImageIcon image1 = new ImageIcon(); + BorderLayout borderLayout1 = new BorderLayout(); + BorderLayout borderLayout2 = new BorderLayout(); + FlowLayout flowLayout1 = new FlowLayout(); + GridLayout gridLayout1 = new GridLayout(); + String product = "Molecular Structure Viewer/Editor"; + String version = "1.0"; + String copyright = "Copyright (c) 2005-2013"; + String comments = "Computational Chemistry Toolkit"; + + public Frame1_AboutBox(Frame parent) { + super(parent); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public Frame1_AboutBox() { + this(null); + } + + /** + * Component initialization. + * + * @throws Exception + */ + private void jbInit() throws Exception { + image1 = new ImageIcon(Frame1.class.getResource("about.png")); + imageLabel.setIcon(image1); + setTitle("About"); + panel1.setLayout(borderLayout1); + panel2.setLayout(borderLayout2); + insetsPanel1.setLayout(flowLayout1); + insetsPanel2.setLayout(flowLayout1); + insetsPanel2.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + gridLayout1.setRows(4); + gridLayout1.setColumns(1); + label1.setText(product); + label2.setText(version); + label3.setText(copyright); + label4.setText(comments); + insetsPanel3.setLayout(gridLayout1); + insetsPanel3.setBorder(BorderFactory.createEmptyBorder(10, 60, 10, 10)); + button1.setText("OK"); + button1.addActionListener(this); + insetsPanel2.add(imageLabel, null); + panel2.add(insetsPanel2, BorderLayout.WEST); + getContentPane().add(panel1, null); + insetsPanel3.add(label1, null); + insetsPanel3.add(label2, null); + insetsPanel3.add(label3, null); + insetsPanel3.add(label4, null); + panel2.add(insetsPanel3, BorderLayout.CENTER); + insetsPanel1.add(button1, null); + panel1.add(insetsPanel1, BorderLayout.SOUTH); + panel1.add(panel2, BorderLayout.NORTH); + setResizable(true); + } + + /** + * Close the dialog on a button event. + * + * @param actionEvent ActionEvent + */ + @Override + public void actionPerformed(ActionEvent actionEvent) { + if (actionEvent.getSource() == button1) { + dispose(); + } + } +} diff --git a/src/main/java/cct/dialogs/GraphicsObjectPropertiesFrame.jbx b/src/main/java/cct/dialogs/GraphicsObjectPropertiesFrame.jbx new file mode 100644 index 0000000..da7bd72 --- /dev/null +++ b/src/main/java/cct/dialogs/GraphicsObjectPropertiesFrame.jbx @@ -0,0 +1,10 @@ +[PropertyInfo] +borderLayout1,java.awt.BorderLayout,false,false, , ,false, +JScrollPane1,javax.swing.JScrollPane,false,false, , ,false, +JScrollPane2,javax.swing.JScrollPane,false,false, , ,false, +JSplitPane1,javax.swing.JSplitPane,false,false, , ,false, +[IconNames] + + + + diff --git a/src/main/java/cct/dialogs/ImageSequencePanel.form b/src/main/java/cct/dialogs/ImageSequencePanel.form new file mode 100644 index 0000000..a9330cd --- /dev/null +++ b/src/main/java/cct/dialogs/ImageSequencePanel.form @@ -0,0 +1,70 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/src/main/java/cct/dialogs/ImageSequencePanel.java b/src/main/java/cct/dialogs/ImageSequencePanel.java new file mode 100644 index 0000000..486039c --- /dev/null +++ b/src/main/java/cct/dialogs/ImageSequencePanel.java @@ -0,0 +1,93 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.dialogs; + +import javax.swing.JCheckBox; +import javax.swing.JComboBox; + +/** + * + * @author vvv900 + */ +public class ImageSequencePanel extends javax.swing.JPanel { + + /** + * Creates new form ImageSequencePanel + */ + public ImageSequencePanel() { + initComponents(); + } + + /** + * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The + * content of this method is always regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + generateImageSeqCheckBox = new JCheckBox(); + jLabel1 = new javax.swing.JLabel(); + imageSeqFormatComboBox = new JComboBox(); + + generateImageSeqCheckBox.setText("Generate Image Sequence"); + + jLabel1.setText("Format:"); + + imageSeqFormatComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(generateImageSeqCheckBox) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jLabel1) + .addGap(18, 18, 18) + .addComponent(imageSeqFormatComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(24, Short.MAX_VALUE)) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(20, 20, 20) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel1) + .addComponent(imageSeqFormatComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addComponent(generateImageSeqCheckBox)) + .addContainerGap(256, Short.MAX_VALUE)) + ); + }// //GEN-END:initComponents + + + // Variables declaration - do not modify//GEN-BEGIN:variables + private JCheckBox generateImageSeqCheckBox; + private JComboBox imageSeqFormatComboBox; + private javax.swing.JLabel jLabel1; + // End of variables declaration//GEN-END:variables + + public void setImageSeqFormatComboBox(Object[] formats) { + if (formats == null) { + System.err.println(this.getClass().getCanonicalName() + " : setImageSeqFormatComboBox : formats == null"); + return; + } + imageSeqFormatComboBox.removeAllItems(); + for (Object obj : formats) { + imageSeqFormatComboBox.addItem(obj); + } + } + + public JCheckBox getGenerateImageSeqCheckBox() { + return generateImageSeqCheckBox; + } + + public JComboBox getImageSeqFormatComboBox() { + return imageSeqFormatComboBox; + } +} diff --git a/src/main/java/cct/dialogs/J3DTabbedWorld.java b/src/main/java/cct/dialogs/J3DTabbedWorld.java new file mode 100644 index 0000000..3e549a0 --- /dev/null +++ b/src/main/java/cct/dialogs/J3DTabbedWorld.java @@ -0,0 +1,196 @@ +package cct.dialogs; + +import java.awt.Component; +import java.awt.Container; +import java.awt.Dialog; +import java.awt.Frame; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Logger; + +import org.scijava.java3d.Canvas3D; +import javax.swing.ImageIcon; +import javax.swing.JTabbedPane; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +import cct.interfaces.MoleculeInterface; +import cct.interfaces.MoleculeRendererInterface; +import cct.j3d.Java3dUniverse; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class J3DTabbedWorld + extends JTabbedPane implements MoleculeRendererInterface { + public J3DTabbedWorld() { + try { + jbInit(); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static final int SINGLE_MOLECULE = 0, MULTIPLE_MOLECULES = 1; + private static final ImageIcon moleculeImage = new ImageIcon(cct.resources.Resources.class.getResource( + "cct/images/icons16x16/mol-3.png")); + + private int mode = SINGLE_MOLECULE; + private Map windows = new HashMap (); + private AddMoleculeDialog addMoleculeDialog = null; + private Java3dUniverse java3dUniverse = null; + static final Logger logger = Logger.getLogger(J3DTabbedWorld.class.getCanonicalName()); + + public J3DTabbedWorld(int mode) { + super(); + + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + + if (mode != SINGLE_MOLECULE && mode != MULTIPLE_MOLECULES) { + System.err.println(this.getClass().getCanonicalName() + ": Unknown mode. Set to SINGLE MOLECULE mode"); + this.mode = SINGLE_MOLECULE; + } + else { + this.mode = mode; + } + + java3dUniverse = new Java3dUniverse(); + + if (mode == MULTIPLE_MOLECULES) { + addTab("No Name", moleculeImage, java3dUniverse.getCanvas3D(), "No Name"); + validate(); + windows.put(java3dUniverse.getCanvas3D(), java3dUniverse); + } + } + + @Override + public void addMolecule(MoleculeInterface molecule) { + if (addMoleculeDialog == null) { + Container parent = getParentContainer(this); + if (parent instanceof Frame) { + addMoleculeDialog = new AddMoleculeDialog( (Frame) parent, "Select How to Load a New Molecule"); + } + else if (parent instanceof Dialog) { + addMoleculeDialog = new AddMoleculeDialog( (Dialog) parent, "Select How to Load a New Molecule"); + } + + addMoleculeDialog.setLocationRelativeTo(parent); + addMoleculeDialog.EnableNewWindowButton( (mode == MULTIPLE_MOLECULES)); + } + + int cond = MoleculeRendererInterface.LOAD_CANCELED; + if (hasMolecule()) { + cond = addMoleculeDialog.showDialog(); + } + else { + cond = MoleculeRendererInterface.OVERWRITE_MOLECULE; + } + + addMolecule(molecule, cond); + } + + public Component getComponent() { + if (mode == MULTIPLE_MOLECULES) { + return this; + } + return java3dUniverse.getCanvas3D(); + } + + private Container getParentContainer(Container child) { + Container parent = null; + while ( (parent = child.getParent()) != null) { + if (parent instanceof Frame || parent instanceof Dialog) { + return parent; + } + child = parent; + } + return parent; + } + + @Override + public void addMolecule(MoleculeInterface molecule, int how_to_add) { + + // --- Multiple molecules + if (mode == MULTIPLE_MOLECULES) { + if (how_to_add == OVERWRITE_MOLECULE) { + Canvas3D canvas3d = (Canvas3D)this.getSelectedComponent(); + Java3dUniverse j3d = windows.get(canvas3d); + j3d.addMolecule(molecule); + this.setTitleAt(this.getSelectedIndex(), molecule.getName()); + } + else if (how_to_add == MERGE_MOLECULE) { + Canvas3D canvas3d = (Canvas3D)this.getSelectedComponent(); + Java3dUniverse j3d = windows.get(canvas3d); + j3d.appendMolecule(molecule, true); + this.setTitleAt(this.getSelectedIndex(), molecule.getName()); + } + else if (how_to_add == NEW_MOLECULE) { + Java3dUniverse j3d = new Java3dUniverse(); + this.addTab(molecule.getName(), moleculeImage, j3d.getCanvas3D(), molecule.getName()); + this.validate(); + j3d.addMolecule(molecule); + windows.put(j3d.getCanvas3D(), j3d); + this.setSelectedComponent(j3d.getCanvas3D()); + } + } + // --- Single molecule in the window + else { + if (how_to_add == OVERWRITE_MOLECULE) { + this.java3dUniverse.addMolecule(molecule); + } + else if (how_to_add == MERGE_MOLECULE) { + java3dUniverse.appendMolecule(molecule, true); + } + } + } + + public boolean hasMolecule() { + + if (mode == SINGLE_MOLECULE) { + return !(java3dUniverse.getMoleculeInterface() == null || java3dUniverse.getMoleculeInterface().getNumberOfAtoms() < 1); + } + + // --- Multiple molecules + + if (windows.size() > 1) { + return true; + } + else if (windows.size() == 0) { + return false; + } + Java3dUniverse j3d = windows.get( windows.keySet().iterator().next()); + return j3d.getMoleculeInterface() != null && j3d.getMoleculeInterface().getNumberOfAtoms() > 0; + } + + public static void main(String[] args) { + //J3DTabbedWorld j3dtabbedworld = new J3DTabbedWorld(); + } + + public void this_stateChanged(ChangeEvent e) { + logger.info("this_stateChanged"); + } + + private void jbInit() throws Exception { + this.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + this_stateChanged(e); + } + }); + } +} diff --git a/src/main/java/cct/dialogs/JAddFragmentDialog.java b/src/main/java/cct/dialogs/JAddFragmentDialog.java new file mode 100644 index 0000000..d26e748 --- /dev/null +++ b/src/main/java/cct/dialogs/JAddFragmentDialog.java @@ -0,0 +1,457 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import cct.interfaces.MoleculeInterface; +import cct.j3d.Java3dUniverse; +import cct.tools.FragmentDictionaryParser; + +import javax.swing.*; +import javax.swing.event.TreeSelectionEvent; +import javax.swing.event.TreeSelectionListener; +import javax.swing.tree.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.io.File; +import java.util.*; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class JAddFragmentDialog + extends JFrame { + + private static ImageIcon saveFile = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/saveFile.png")); + private static ImageIcon addNewFragment = new ImageIcon(cct.resources.Resources.class.getResource( + "/cct/images/icons16x16/add-fragment.png")); + public static final String CUSTOM_DICTIONARY_NAME = "Custom"; + + Java3dUniverse java3d = null; + Java3dUniverse parent = null; + JScrollPane jScrollPane1 = new JScrollPane(); + JPanel jPanel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JButton finishButton = new JButton(); + JButton addFragButton = new JButton(); + JButton helpButton = new JButton(); + JTree fragmentsTree = null; + Map referenceTable = new HashMap(); + Map nameReferenceTable = new HashMap(); + JPanel jPanel2 = new JPanel(); + JPanel jPanel3 = new JPanel(); + BorderLayout borderLayout2 = new BorderLayout(); + private JButton saveDicButton = new JButton(); + private FragmentDictionaryParser fdp = null; + private Map fragmentTree; + private JButton newFragButton = new JButton(); + private FlowLayout flowLayout1 = new FlowLayout(); + private AddNewFragmentDialog addNewFragmentDialog; + private DefaultMutableTreeNode rootNode; + private DefaultTreeModel treeModel; + private boolean inDevelopment = true; + + public JAddFragmentDialog(String title, Map fragTree, Java3dUniverse j3d) { + super(title); + java3d = j3d; + fragmentTree = fragTree; + + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(fragmentTree); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public void setFragmentDictionaryParser(FragmentDictionaryParser parser) { + fdp = parser; + } + + private void jbInit(Map fragTree) throws Exception { + + rootNode = new DefaultMutableTreeNode("Fragments"); + treeModel = new DefaultTreeModel(rootNode); + + createNodes(rootNode, fragTree); + JTree jTree1 = new JTree(treeModel); + jTree1.setEditable(true); + jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); + jTree1.setShowsRootHandles(true); + fragmentsTree = jTree1; + + jScrollPane1.setMinimumSize(new Dimension(300, 150)); + saveDicButton.setMaximumSize(new Dimension(24, 24)); + saveDicButton.setMinimumSize(new Dimension(24, 24)); + saveDicButton.setPreferredSize(new Dimension(24, 24)); + saveDicButton.setToolTipText("Save Dictionary"); + + saveDicButton.setIcon(saveFile); + JScrollPane jScrollPane2 = new JScrollPane(); + jScrollPane2.setMinimumSize(new Dimension(300, 200)); + jPanel1.setLayout(borderLayout2); + //saveDicButton.setText("Save Dictionary"); + saveDicButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + saveDicButton_actionPerformed(e); + } + }); + newFragButton.setMaximumSize(new Dimension(24, 24)); + newFragButton.setMinimumSize(new Dimension(24, 24)); + newFragButton.setPreferredSize(new Dimension(24, 24)); + newFragButton.setToolTipText("Add new Fragment"); + newFragButton.setIcon(addNewFragment); + newFragButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + newFragButton_actionPerformed(e); + } + }); + jPanel3.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + jScrollPane2.getViewport().add(java3d.getCanvas3D()); + + JSplitPane jSplitPane1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, //jScrollPane1, java3d.getCanvas3D()); + jScrollPane1, jScrollPane2); + + //jScrollPane1. + this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent we) { + //setLabel("Thwarted user attempt to close window."); + finishDialog(); + } + }); + + this.getContentPane().setLayout(borderLayout1); + finishButton.setText("Finish"); + finishButton.addActionListener(new JAddFragmentDialog_jButton1_actionAdapter(this)); + addFragButton.setText("Add Fragment"); + addFragButton.addActionListener(new JAddFragmentDialog_addFragButton_actionAdapter(this)); + helpButton.setEnabled(false); + helpButton.setToolTipText(""); + helpButton.setText("Help"); + jTree1.addTreeSelectionListener(new + JAddFragmentDialog_jTree1_treeSelectionAdapter(this)); + this.getContentPane().add(jSplitPane1, BorderLayout.CENTER); + this.getContentPane().add(jPanel1, BorderLayout.SOUTH); + jPanel3.add(saveDicButton); + jPanel3.add(newFragButton); + jPanel2.add(addFragButton); + jPanel2.add(finishButton); + jPanel2.add(helpButton); + jScrollPane1.getViewport().add(jTree1); + jPanel1.add(jPanel3, BorderLayout.NORTH); + jPanel1.add(jPanel2, BorderLayout.SOUTH); + addFragButton.setVisible(false); + + if (inDevelopment) { + saveDicButton.setVisible(false); + newFragButton.setVisible(false); + } + } + + public JButton getHelpButton() { + return this.helpButton; + } + + private void createNodes(DefaultMutableTreeNode top, Map fragTree) { + + DefaultMutableTreeNode lastDic = top; + + Set set = fragTree.entrySet(); + Iterator iter = set.iterator(); + + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String dicName = me.getKey().toString(); + Object obj = me.getValue(); + + if (obj instanceof Map) { + DefaultMutableTreeNode dictionary = new DefaultMutableTreeNode(dicName); + top.add(dictionary); + nameReferenceTable.put(dicName, dictionary); + //LinkedHashMap dic = (LinkedHashMap)obj; + createNodes(dictionary, (Map) obj); + lastDic = dictionary; + } + else if (obj instanceof String) { + DefaultMutableTreeNode fragment = new DefaultMutableTreeNode(dicName); + lastDic.add(fragment); + String spec = (String) obj; + referenceTable.put(fragment, spec); + } + } + } + + public static void main(String[] args) { + //JAddFragmentDialog jaddfragmentdialog = new JAddFragmentDialog(); + } + + public void setParent(Java3dUniverse j3d) { + parent = j3d; + } + + public void jButton1_actionPerformed(ActionEvent e) { + finishDialog(); + } + + private void finishDialog() { + parent.endProcessingSelectedAtoms(); + setVisible(false); + } + + public void jTree1_valueChanged(TreeSelectionEvent e) { + if (!fragmentsTree.isEnabled()) { + return; + } + fragmentsTree.setEnabled(false); + + DefaultMutableTreeNode node = (DefaultMutableTreeNode) fragmentsTree.getLastSelectedPathComponent(); + if (node == null) { + fragmentsTree.setEnabled(true); + return; + } + + Object nodeInfo = node.getUserObject(); + + if (node.isLeaf()) { + String spec = (String) referenceTable.get(node); + //java3d.loadFragment((String)nodeInfo ); + try { + MoleculeInterface m = fdp.loadFragment(spec); + java3d.loadFragment(m); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error adding a fragment: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + } + + fragmentsTree.setEnabled(true); + } + + public void addFragButton_actionPerformed(ActionEvent e) { + try { + parent.addFragment(java3d); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error adding a fragment: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + + System.err.println(getClass().getCanonicalName() + " : " + ex.getMessage()); + //ex.printStackTrace(); + return; + } + } + + public void saveDicButton_actionPerformed(ActionEvent e) { + final JFileChooser fc = new JFileChooser(); + String curDir = System.getProperty("user.dir"); + File cwd = new File(curDir); + if (cwd.isDirectory()) { + try { + fc.setCurrentDirectory(cwd); + } + catch (Exception ex) { + System.err.println("Problem listing cwd: " + cwd + " : " + ex.getMessage()); + } + } + int returnVal = fc.showSaveDialog(this); + if (returnVal != JFileChooser.APPROVE_OPTION) { + return; + } + File file = fc.getSelectedFile(); + try { + fdp.saveFragmentDictionary(fragmentTree, file.getAbsolutePath()); + } + catch (Exception ex) { + System.err.println("Problem saving dictionary: " + file.getAbsoluteFile() + " : " + ex.getMessage()); + } + + } + + public void newFragButton_actionPerformed(ActionEvent e) { + if (parent == null) { + JOptionPane.showMessageDialog(this, "Parent is not set", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + MoleculeInterface molecule = parent.getMoleculeInterface(); + if (molecule == null || molecule.getNumberOfAtoms() < 1) { + JOptionPane.showMessageDialog(this, "No molecule in main window", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + TreePath treePath = fragmentsTree.getSelectionPath(); + + String dicPath = ""; + String fragName = "Magic Frag"; + if (treePath != null && treePath.getPathCount() > 1) { + Object[] path = treePath.getPath(); + + for (int i = 1; i < treePath.getPathCount(); i++) { + DefaultMutableTreeNode node = (DefaultMutableTreeNode) path[i]; + if (!node.isLeaf()) { + dicPath += node.getUserObject().toString() + "/"; + } + else { + fragName = node.getUserObject().toString(); + } + } + } + else { + + } + + if (addNewFragmentDialog == null) { + addNewFragmentDialog = new AddNewFragmentDialog(null, "Fragment Name", true); + addNewFragmentDialog.setLocationRelativeTo(this); + addNewFragmentDialog.setAlwaysOnTop(true); + } + + addNewFragmentDialog.setFragmentName(fragName); + String[] paths = getOrderedPaths(fragmentsTree); + addNewFragmentDialog.setExistingPaths(paths); + addNewFragmentDialog.setPath(dicPath); + + int cond = addNewFragmentDialog.showDialog(); + if (cond == AddNewFragmentDialog.CANCELED) { + return; + } + + dicPath = addNewFragmentDialog.getFragmentName(); + if (dicPath == null || dicPath.length() < 1) { + dicPath = CUSTOM_DICTIONARY_NAME; + } + fragName = addNewFragmentDialog.getPath(); + + DefaultMutableTreeNode dictionary = null; + if (nameReferenceTable.containsKey(dicPath)) { + dictionary = (DefaultMutableTreeNode) nameReferenceTable.get(dicPath); + } + else { + dictionary = new DefaultMutableTreeNode(dicPath); + rootNode.add(dictionary); + } + + DefaultMutableTreeNode fragment = new DefaultMutableTreeNode(fragName); + treeModel.insertNodeInto(fragment, dictionary, dictionary.getChildCount()); + //dictionary.add(fragment); + referenceTable.put(fragment, molecule); + fragmentsTree.scrollPathToVisible(new TreePath(fragment.getPath())); + } + + class JAddFragmentDialog_jTree1_treeSelectionAdapter + implements TreeSelectionListener { + private JAddFragmentDialog adaptee; + JAddFragmentDialog_jTree1_treeSelectionAdapter(JAddFragmentDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void valueChanged(TreeSelectionEvent e) { + adaptee.jTree1_valueChanged(e); + } + } + + class JAddFragmentDialog_addFragButton_actionAdapter + implements ActionListener { + private JAddFragmentDialog adaptee; + JAddFragmentDialog_addFragButton_actionAdapter(JAddFragmentDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.addFragButton_actionPerformed(e); + } + } + + class JAddFragmentDialog_jButton1_actionAdapter + implements ActionListener { + private JAddFragmentDialog adaptee; + JAddFragmentDialog_jButton1_actionAdapter(JAddFragmentDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.jButton1_actionPerformed(e); + } + } + + private String[] getOrderedPaths(JTree jtree) { + Set upaths = getAllPaths(jtree); + if (upaths.size() < 1) { + return null; + } + String[] paths = new String[upaths.size()]; + upaths.toArray(paths); + Arrays.sort(paths); + return paths; + } + + private Set getAllPaths(JTree jtree) { + Set paths = new HashSet (); + TreeNode treeNode = (TreeNode) jtree.getModel().getRoot(); + for (Enumeration e = treeNode.children(); e.hasMoreElements(); ) { + TreeNode n = (TreeNode) e.nextElement(); + if (n.isLeaf()) { + continue; + } + DefaultMutableTreeNode node = (DefaultMutableTreeNode) n; + paths.add(node.getUserObject().toString()); + } + return paths; + } + +} diff --git a/src/main/java/cct/dialogs/JAddMoleculeDialog.java b/src/main/java/cct/dialogs/JAddMoleculeDialog.java new file mode 100644 index 0000000..d7f78c2 --- /dev/null +++ b/src/main/java/cct/dialogs/JAddMoleculeDialog.java @@ -0,0 +1,366 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.SwingConstants; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +import cct.j3d.Java3dUniverse; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class JAddMoleculeDialog + extends JFrame { + JPanel controlsPanel = new JPanel(); + JButton helpButton = new JButton(); + JButton cancelButton = new JButton(); + JButton okButton = new JButton(); + + Java3dUniverse java3d = null; + Java3dUniverse parent = null; + BorderLayout borderLayout1 = new BorderLayout(); + JPanel jPanel1 = new JPanel(); + JPanel jPanel2 = new JPanel(); + JPanel jPanel3 = new JPanel(); + JLabel jLabel1 = new JLabel(); + JCheckBox jCheckBox1 = new JCheckBox(); + JTextField jTextField1 = new JTextField(); + JComboBox jComboBox1 = new JComboBox(); + FlowLayout flowLayout1 = new FlowLayout(); + FlowLayout flowLayout2 = new FlowLayout(); + JLabel jLabel2 = new JLabel(); + + private JAddMoleculeDialog(Frame owner, String title, boolean modal) { + //super(owner, title, modal) + super(title); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JAddMoleculeDialog(Frame owner, String title, boolean modal, + Java3dUniverse j3d) { + + //super(owner, title, modal); + java3d = j3d; + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + + } + + private JAddMoleculeDialog() { + this(new Frame(), "JAddMoleculeDialog", false); + } + + public boolean isPredefinedDistance() { + return jCheckBox1.isSelected(); + } + + public float getPredefinedDistance() { + float d = -1.0f; + try { + d = Float.parseFloat(jTextField1.getText()); + } + catch (Exception e) { + JOptionPane.showMessageDialog(this, + "Distance " + jTextField1.getText() + + " is not a valid positive value", + "Error", + JOptionPane.ERROR_MESSAGE); + } + return d; + } + + public void setRenderer(Java3dUniverse j3d) { + java3d = j3d; + pack(); + validate(); + } + + public void setParent(Java3dUniverse j3d) { + parent = j3d; + } + + public JButton getHelpButton() { + return helpButton; + } + + private void jbInit() throws Exception { + this.setDefaultCloseOperation(javax.swing.WindowConstants. + DO_NOTHING_ON_CLOSE); + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent we) { + //setLabel("Thwarted user attempt to close window."); + finishDialog(); + } + }); + + helpButton.setEnabled(false); + helpButton.setText("Help"); + cancelButton.setToolTipText("Cancel adding"); + cancelButton.setText("Finish"); + cancelButton.addActionListener(new + JAddMoleculeDialog_cancelButton_actionAdapter(this)); + okButton.setToolTipText("Confirm adding molecule"); + okButton.setText("OK"); + okButton.addActionListener(new JAddMoleculeDialog_okButton_actionAdapter(this)); + controlsPanel.setLayout(borderLayout1); + jLabel1.setToolTipText(""); + jLabel1.setHorizontalAlignment(SwingConstants.LEFT); + jLabel1.setText( + "Press Shift-Left-Click on the spot to add a Molecule"); + jCheckBox1.setToolTipText(""); + jCheckBox1.setHorizontalAlignment(SwingConstants.LEFT); + jCheckBox1.setText("Predefined Distance Between Atoms"); + jCheckBox1.addChangeListener(new + JAddMoleculeDialog_jCheckBox1_changeAdapter(this)); + jPanel2.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + jPanel3.setLayout(flowLayout2); + flowLayout2.setAlignment(FlowLayout.LEFT); + jTextField1.setToolTipText("Enter New Positive Value & Press Enter"); + jTextField1.setColumns(6); + jTextField1.addActionListener(new + JAddMoleculeDialog_jTextField1_actionAdapter(this)); + jComboBox1.addItemListener(new JAddMoleculeDialog_jComboBox1_itemAdapter(this)); + jLabel2.setToolTipText(""); + jLabel2.setHorizontalAlignment(SwingConstants.LEFT); + jLabel2.setText( + "Select Atom in the Main Window and"); + getContentPane().add(controlsPanel, BorderLayout.SOUTH); + getContentPane().add(java3d.getCanvas3D(), BorderLayout.CENTER); + jPanel1.add(okButton); + jPanel1.add(cancelButton); + jPanel1.add(helpButton); + controlsPanel.add(jPanel3, BorderLayout.NORTH); + jPanel3.add(jLabel2); + jPanel3.add(jLabel1, FlowLayout.LEFT); + controlsPanel.add(jPanel1, BorderLayout.SOUTH); + controlsPanel.add(jPanel2, BorderLayout.CENTER); + jPanel2.add(jCheckBox1, FlowLayout.LEFT); + jPanel2.add(jTextField1); + jPanel2.add(jComboBox1); + okButton.setVisible(false); + + jComboBox1.addItem("0.9"); + jComboBox1.addItem("1.0"); + jComboBox1.addItem("1.1"); + jComboBox1.addItem("1.2"); + jComboBox1.addItem("1.3"); + jComboBox1.addItem("1.4"); + jComboBox1.addItem("1.5"); + jComboBox1.addItem("1.6"); + jComboBox1.addItem("1.7"); + jComboBox1.addItem("1.8"); + jComboBox1.addItem("1.9"); + jComboBox1.addItem("2.0"); + jComboBox1.addItem("2.2"); + jComboBox1.addItem("2.5"); + jComboBox1.addItem("3.0"); + jComboBox1.addItem("4.0"); + + jTextField1.setText(jComboBox1.getItemAt(0).toString()); + + if (jCheckBox1.isSelected()) { + jTextField1.setEnabled(true); + jComboBox1.setEnabled(true); + } + else { + jTextField1.setEnabled(false); + jComboBox1.setEnabled(false); + } + } + + public void setGraphics(Java3dUniverse j3d) { + validate(); + } + + public void okButton_actionPerformed(ActionEvent e) { + parent.appendMolecule(java3d); + } + + private void finishDialog() { + setVisible(false); + parent.endProcessingSelectedAtoms(); + } + + public void cancelButton_actionPerformed(ActionEvent e) { + finishDialog(); + } + + public void jCheckBox1_stateChanged(ChangeEvent e) { + if (jCheckBox1.isSelected()) { + jTextField1.setEnabled(true); + jComboBox1.setEnabled(true); + } + else { + jTextField1.setEnabled(false); + jComboBox1.setEnabled(false); + } + } + + public void jComboBox1_itemStateChanged(ItemEvent e) { + jTextField1.setEnabled(false); + jTextField1.setText(jComboBox1.getSelectedItem().toString()); + jTextField1.setEnabled(true); + } + + public void jTextField1_actionPerformed(ActionEvent e) { + if (!jTextField1.isEnabled()) { + return; + } + jTextField1.setEnabled(false); + float d = -1.0f; + try { + d = Float.parseFloat(jTextField1.getText()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Distance " + jTextField1.getText() + " is not a valid positive value", "Error", + JOptionPane.ERROR_MESSAGE); + jTextField1.setText(jComboBox1.getItemAt(0).toString()); + } + jTextField1.setEnabled(true); + } + +} + +class JAddMoleculeDialog_jTextField1_actionAdapter + implements ActionListener { + private JAddMoleculeDialog adaptee; + JAddMoleculeDialog_jTextField1_actionAdapter(JAddMoleculeDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.jTextField1_actionPerformed(e); + } +} + +class JAddMoleculeDialog_jComboBox1_itemAdapter + implements ItemListener { + private JAddMoleculeDialog adaptee; + JAddMoleculeDialog_jComboBox1_itemAdapter(JAddMoleculeDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void itemStateChanged(ItemEvent e) { + adaptee.jComboBox1_itemStateChanged(e); + } +} + +class JAddMoleculeDialog_jCheckBox1_changeAdapter + implements ChangeListener { + private JAddMoleculeDialog adaptee; + JAddMoleculeDialog_jCheckBox1_changeAdapter(JAddMoleculeDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.jCheckBox1_stateChanged(e); + } +} + +class JAddMoleculeDialog_okButton_actionAdapter + implements ActionListener { + private JAddMoleculeDialog adaptee; + JAddMoleculeDialog_okButton_actionAdapter(JAddMoleculeDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.okButton_actionPerformed(e); + } +} + +class JAddMoleculeDialog_cancelButton_actionAdapter + implements ActionListener { + private JAddMoleculeDialog adaptee; + JAddMoleculeDialog_cancelButton_actionAdapter(JAddMoleculeDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.cancelButton_actionPerformed(e); + } +} diff --git a/src/main/java/cct/dialogs/JAtomSelectionPanel.java b/src/main/java/cct/dialogs/JAtomSelectionPanel.java new file mode 100644 index 0000000..5f9e07b --- /dev/null +++ b/src/main/java/cct/dialogs/JAtomSelectionPanel.java @@ -0,0 +1,122 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.Color; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.util.HashMap; +import java.util.Map; + +import javax.swing.BorderFactory; +import javax.swing.JPanel; +import javax.swing.border.TitledBorder; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class JAtomSelectionPanel + extends JPanel { + JSelectionRulePanel jSelectionRulePanel1 = new JSelectionRulePanel(); + JQuickSelectionPanel jQuickSelectionPanel1 = new JQuickSelectionPanel(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + JSpecialSelectionPanel jSpecialSelectionPanel1 = new JSpecialSelectionPanel(); + JSelectionTypePanel jSelectionTypePanel1 = new JSelectionTypePanel(); + + Map Controls = new HashMap(); + + public JAtomSelectionPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(gridBagLayout1); + jSelectionTypePanel1.setBorder(new TitledBorder(BorderFactory. + createLineBorder(Color.lightGray, 1), "Selection")); + jSpecialSelectionPanel1.setBorder(BorderFactory.createEmptyBorder()); + jQuickSelectionPanel1.setBorder(new TitledBorder(BorderFactory. + createLineBorder(Color.lightGray, 1), "Quick Selection")); + jSelectionRulePanel1.setBorder(new TitledBorder(BorderFactory. + createLineBorder(Color.lightGray, 1), "Selection Rule")); + this.add(jSelectionRulePanel1, + new GridBagConstraints(1, 0, 1, 3, 0.5, 0.5 + , GridBagConstraints.CENTER, + GridBagConstraints.BOTH, + new Insets(0, 0, 0, 0), 0, 0)); + this.add(jSelectionTypePanel1, + new GridBagConstraints(0, 0, 1, 3, 0.5, 0.5 + , GridBagConstraints.NORTHWEST, + GridBagConstraints.BOTH, + new Insets(0, 0, 0, 0), 0, 0)); + this.add(jSpecialSelectionPanel1, + new GridBagConstraints(2, 0, 1, 5, 1.0, 1.0 + , GridBagConstraints.NORTHEAST, + GridBagConstraints.BOTH, + new Insets(0, 0, 0, 0), 0, 0)); + this.add(jQuickSelectionPanel1, + new GridBagConstraints(0, 3, 2, 1, 1.0, 1.0 + , GridBagConstraints.WEST, + GridBagConstraints.BOTH, + new Insets(0, 0, 0, 0), 0, 0)); + + Controls.putAll(jSelectionRulePanel1.getControls()); + Controls.putAll(jQuickSelectionPanel1.getControls()); + Controls.putAll(jSpecialSelectionPanel1.getControls()); + Controls.putAll(jSelectionTypePanel1.getControls()); + + } + + public Map getControls() { + return Controls; + } +} diff --git a/src/main/java/cct/dialogs/JAtomSelectionPanel.jbx b/src/main/java/cct/dialogs/JAtomSelectionPanel.jbx new file mode 100644 index 0000000..c81aa24 --- /dev/null +++ b/src/main/java/cct/dialogs/JAtomSelectionPanel.jbx @@ -0,0 +1,11 @@ +[PropertyInfo] +gridBagLayout1,java.awt.GridBagLayout,false,false, , ,false, +JQuickSelectionPanel1,SwingDialogs.JQuickSelectionPanel,false,false, , ,false, +JSelectionRulePanel1,SwingDialogs.JSelectionRulePanel,false,false, , ,false, +JSelectionTypePanel1,SwingDialogs.JSelectionTypePanel,false,false, , ,false, +JSpecialSelectionPanel1,SwingDialogs.JSpecialSelectionPanel,false,false, , ,false, +[IconNames] + + + + diff --git a/src/main/java/cct/dialogs/JAtomTypeDialog.java b/src/main/java/cct/dialogs/JAtomTypeDialog.java new file mode 100644 index 0000000..6ce9558 --- /dev/null +++ b/src/main/java/cct/dialogs/JAtomTypeDialog.java @@ -0,0 +1,637 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; + +import javax.swing.BorderFactory; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.SwingConstants; + +import cct.j3d.Java3dUniverse; +import cct.modelling.AtomGeometry; +import cct.modelling.CCTAtomTypes; +import cct.modelling.ChemicalElements; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class JAtomTypeDialog + extends JFrame implements ActionListener, ItemListener { + JPanel panel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + private int lastSelected[] = null; + Map elementMapping = null; + Map elementButtons = null; + Java3dUniverse daddy = null; + static final Logger logger = Logger.getLogger(JAtomTypeDialog.class.getCanonicalName()); + + boolean OKpressed = false; + static Object Lengths[] = { + "0.9", "1.0", "1.1", "1.2", "1.3", "1.4", "1.5", "1.6", "1.7", "2.0", + "2.5", "3.0", "3.5"}; + JButton OK = new JButton("Ok"); + JButton Cancel = new JButton("Cancel"); + JButton Help = new JButton("Help"); + int selectedElement = 1; + String currentElement = "H"; + JLabel selectedElem = new JLabel(); + JTextField atomName = new JTextField(6); + JCheckBox drawBond = new JCheckBox("Draw Bond", true); + JCheckBox userDefBondLength = new JCheckBox("User defined", true); + JCheckBox covalentBondLength = new JCheckBox("Covalent Bond Length", false); + JCheckBox predefBondLength = new JCheckBox("Predefined Bond Length", false); + JComboBox bondLength = new JComboBox(Lengths); + + java.util.List elButt = null; + Color oldColor = null; + Color pressedColor = new Color(1.0f, 0.0f, 0.0f); + JButton Previous = null; + JPanel atomTypesPanel = new JPanel(); + JButton type_1_Button = new JButton(); + JButton type_2_Button = new JButton(); + JButton type_3_Button = new JButton(); + JButton type_4_Button = new JButton(); + JButton type_5_Button = new JButton(); + JButton type_6_Button = new JButton(); + JButton type_7_Button = new JButton(); + FlowLayout flowLayout1 = new FlowLayout(); + JMenuBar jMenuBar1 = new JMenuBar(); + JMenu fontMenu = new JMenu("Font"); + JMenuItem increaseFont = new JMenuItem("Increase Font"); + JMenuItem decreaseFont = new JMenuItem("Decrease Font"); + JMenu presentationMenu = new JMenu("Show Elements"); + JMenuItem asTable = new JMenuItem("As Periodic Table"); + JMenuItem asCombobox = new JMenuItem("As Combobox (takes less space)"); + + JElementsPanel ePanel = new JElementsPanel(); + java.util.List atomTypesButtons = new ArrayList (7); + Color defaultAtomTypeColor = null; + Color selectedAtomTypeColor = new Color(255, 0, 0); + ButtonGroup buttonGroup1 = new ButtonGroup(); + public JAtomTypeDialog(Frame owner, String title, boolean modal) { + super(title); + //super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JAtomTypeDialog() { + this(new Frame(), "JAtomTypeDialog", false); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + + elButt = ePanel.getButtons(); + elementButtons = new LinkedHashMap (elButt.size()); + JButton elButton = null; + for (int i = 0; i < elButt.size(); i++) { + elButton = elButt.get(i); + elementButtons.put(elButton.getActionCommand(), elButton); + elButton.addActionListener(this); + } + oldColor = elButton.getForeground(); + oldColor = new Color(oldColor.getRGB()); + this.setDefaultCloseOperation(javax.swing.WindowConstants. + DO_NOTHING_ON_CLOSE); + + JPanel secondP = buildSecondPanel(); + type_1_Button.setPreferredSize(new Dimension(50, 50)); + type_1_Button.setToolTipText(""); + type_1_Button.setHorizontalTextPosition(SwingConstants.CENTER); + type_1_Button.setMargin(new Insets(0, 0, 0, 0)); + type_1_Button.setText("Atom"); + type_2_Button.setPreferredSize(new Dimension(50, 50)); + type_2_Button.setToolTipText(""); + type_2_Button.setHorizontalTextPosition(SwingConstants.CENTER); + type_2_Button.setMargin(new Insets(0, 0, 0, 0)); + type_2_Button.setText("Atom"); + type_3_Button.setPreferredSize(new Dimension(50, 50)); + type_3_Button.setToolTipText(""); + type_3_Button.setHorizontalTextPosition(SwingConstants.CENTER); + type_3_Button.setMargin(new Insets(0, 0, 0, 0)); + type_3_Button.setText("Atom"); + type_4_Button.setPreferredSize(new Dimension(50, 50)); + type_4_Button.setToolTipText(""); + type_4_Button.setHorizontalTextPosition(SwingConstants.CENTER); + type_4_Button.setMargin(new Insets(0, 0, 0, 0)); + type_4_Button.setText("Atom"); + type_5_Button.setPreferredSize(new Dimension(50, 50)); + type_5_Button.setToolTipText(""); + type_5_Button.setHorizontalTextPosition(SwingConstants.CENTER); + type_5_Button.setMargin(new Insets(0, 0, 0, 0)); + type_5_Button.setText("Atom"); + type_6_Button.setPreferredSize(new Dimension(50, 50)); + type_6_Button.setToolTipText(""); + type_6_Button.setHorizontalTextPosition(SwingConstants.CENTER); + type_6_Button.setMargin(new Insets(0, 0, 0, 0)); + type_6_Button.setText("Atom"); + type_7_Button.setPreferredSize(new Dimension(50, 50)); + type_7_Button.setToolTipText(""); + type_7_Button.setHorizontalTextPosition(SwingConstants.CENTER); + type_7_Button.setMargin(new Insets(0, 0, 0, 0)); + type_7_Button.setText("Atom"); + atomTypesPanel.setBorder(BorderFactory.createLineBorder(Color. + DARK_GRAY, + 1)); + atomTypesPanel.setLayout(flowLayout1); + + ePanel.setBorder(BorderFactory.createLineBorder(Color.darkGray, 1)); + flowLayout1.setAlignment(FlowLayout.LEFT); + atomTypesPanel.add(type_1_Button); + atomTypesPanel.add(type_2_Button); + atomTypesPanel.add(type_3_Button); + atomTypesPanel.add(type_4_Button); + atomTypesPanel.add(type_5_Button); + atomTypesPanel.add(type_6_Button); + atomTypesPanel.add(type_7_Button); + + getContentPane().add(panel1); + panel1.add(ePanel, BorderLayout.NORTH); + panel1.add(atomTypesPanel, BorderLayout.CENTER); + panel1.add(secondP, BorderLayout.SOUTH); + atomTypesButtons.add(type_1_Button); + atomTypesButtons.add(type_2_Button); + atomTypesButtons.add(type_3_Button); + atomTypesButtons.add(type_4_Button); + atomTypesButtons.add(type_5_Button); + atomTypesButtons.add(type_6_Button); + atomTypesButtons.add(type_7_Button); + defaultAtomTypeColor = new Color(type_7_Button.getForeground().getRed(), + type_7_Button.getForeground().getGreen(), + type_7_Button.getForeground().getBlue(), + type_7_Button.getForeground().getAlpha()); + + type_1_Button.setIcon(AtomGeometry.ATOM_ICON); + type_1_Button.setText("Atom"); + type_1_Button.setEnabled(true); + type_1_Button.setVisible(true); + type_1_Button.setForeground(defaultAtomTypeColor); + type_1_Button.validate(); + + AtomType_actionAdapter atad = new AtomType_actionAdapter(this); + for (int i = 0; i < atomTypesButtons.size(); i++) { + atomTypesButtons.get(i).addActionListener(atad); + } + + lastSelected = new int[ChemicalElements.getNumberOfElements()]; + for (int i = 0; i < lastSelected.length; i++) { + lastSelected[i] = -1; + } + + elementMapping = CCTAtomTypes.getElementMapping(); + currentElement = ChemicalElements.getElementSymbol(1); + this.selectElement(currentElement); + buttonGroup1.add(userDefBondLength); + buttonGroup1.add(covalentBondLength); + buttonGroup1.add(predefBondLength); + + Cancel.addActionListener(this); + + increaseFont.addActionListener(this); + decreaseFont.addActionListener(this); + fontMenu.add(increaseFont); + fontMenu.add(decreaseFont); + jMenuBar1.add(fontMenu); + + presentationMenu = new JMenu("Show Elements"); + asTable.addActionListener(this); + asCombobox.addActionListener(this); + presentationMenu.add(asTable); + presentationMenu.add(asCombobox); + jMenuBar1.add(presentationMenu); + + this.setJMenuBar(jMenuBar1); + } + + public void setAtomTypes(String element) { + Map atomTypes = (Map) elementMapping.get(element); + + int count = 0; + + int atomNumber = ChemicalElements.getAtomicNumber(element); + int selectedType = lastSelected[atomNumber]; + boolean selectDefault = true; + if (selectedType != -1) { + selectDefault = false; + } + + // --- Special setup for the first atom type (Atom) + + JButton butt = atomTypesButtons.get(count); + butt.setActionCommand(element); + if (atomTypes == null || selectedType == count) { + butt.setSelected(true); + } + else { + butt.setSelected(false); + } + butt.validate(); + ++count; + + if (atomTypes == null) { + for (int i = count; i < atomTypesButtons.size(); i++) { + butt = atomTypesButtons.get(i); + butt.setVisible(false); + butt.validate(); + } + return; + } + + Set set = atomTypes.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String typeName = me.getKey().toString(); + CCTAtomTypes type = (CCTAtomTypes) me.getValue(); + + logger.info("Modifying old button: " + type); + butt = atomTypesButtons.get(count); + butt.setIcon(type.getIcon()); + butt.setText(typeName); + butt.setActionCommand(typeName); + if (selectedType == count) { + butt.setSelected(true); + } + else { + butt.setSelected(false); + } + + if (selectDefault && type.isDefaultType()) { + butt.setSelected(true); + lastSelected[atomNumber] = count; + selectedType = count; + } + + butt.setEnabled(true); + butt.setVisible(true); + butt.setForeground(defaultAtomTypeColor); + butt.validate(); + ++count; + } + + for (int i = count; i < atomTypesButtons.size(); i++) { + butt = atomTypesButtons.get(i); + butt.setVisible(false); + butt.validate(); + } + + // --- Final check for selection + + if (selectedType == -1) { + butt = atomTypesButtons.get(1); + butt.setSelected(true); + lastSelected[atomNumber] = 1; + } + } + + @Override + public void actionPerformed(ActionEvent ae) { + String arg = ae.getActionCommand(); + if (ae.getSource() == OK) { + OKpressed = true; + setVisible(false); + } + else if (ae.getSource() == Cancel) { + OKpressed = false; + daddy.endProcessingSelectedAtoms(); + setVisible(false); + } + else if (ae.getSource() == increaseFont) { + Font font = ePanel.getElementsFont(); + Font newFont = new Font(font.getName(), font.getStyle(), font.getSize() + 1); + ePanel.setElementsFont(newFont); + this.pack(); + } + else if (ae.getSource() == decreaseFont) { + Font font = ePanel.getElementsFont(); + if (font.getSize() <= 8) { + return; + } + Font newFont = new Font(font.getName(), font.getStyle(), font.getSize() - 1); + ePanel.setElementsFont(newFont); + this.pack(); + } + else if (ae.getSource() == asTable) { + ePanel.showElementsAsTable(true); + this.pack(); + } + else if (ae.getSource() == asCombobox) { + ePanel.showElementsAsTable(false); + this.pack(); + } + + else if (arg.equals("OK")) { + } + + else { + currentElement = arg; + selectElement(currentElement); + } + } + + void selectElement(String element) { + selectedElem.setText(" Chemical Element Selected: " + element); + selectedElement = ChemicalElements.getAtomicNumber(element); + setAtomTypes(currentElement); + JButton butt = elementButtons.get(element); + /* + for (int i = 0; i < elButt.size(); i++) { + if ( (JButton) elButt.get(i) == ae.getSource()) { + butt = (JButton) elButt.get(i); + } + } + */ + if (butt != null) { + butt.setForeground(pressedColor); + } + if (Previous == null) { + Previous = butt; + } + else { + Previous.setForeground(oldColor); + Previous = butt; + } + //logger.info("Event: " + element); + + atomName.setText(element); + + } + + @Override + public void itemStateChanged(ItemEvent ie) { + //logger.info("Event: " + ie); + //logger.info("Event: getItem" + ie.getItem()); + //logger.info("Event: getItemSelectable" + ie.getItemSelectable()); + //String item = (String) ie.getItem(); + + if (ie.getSource() == predefBondLength) { + bondLength.setEnabled(predefBondLength.isSelected()); + bondLength.setEnabled(predefBondLength.isSelected()); + } + else if (ie.getSource() == drawBond) { + this.processDrawBondState(); + } + /* + if (ie.getStateChange() == ItemEvent.SELECTED) { + int n = bondLength.getSelectedIndex(); + bLength.setText(bondLength.getSelectedItem()); + } + */ + repaint(); + } + + private JPanel buildSecondPanel() { + GridLayout gridLayout = new GridLayout(4, 1); + JPanel P = new JPanel(); + P.setLayout(gridLayout); + + // --- Add info about selected element + + if (currentElement == null) { + selectedElem.setText(" Chemical Element Selected: "); + } + else { + selectedElem.setText(" Chemical Element Selected: " + currentElement); + } + + P.add(selectedElem); + + // + + JPanel PP = new JPanel(new FlowLayout(FlowLayout.LEFT)); + + PP.add(new JLabel(" Atom Name: ")); + PP.add(atomName); + PP.add(drawBond); + drawBond.addItemListener(this); + PP.validate(); + + P.add(PP); + + // + + PP = new JPanel(new FlowLayout(FlowLayout.LEFT)); + PP.add(userDefBondLength); + PP.add(covalentBondLength); + PP.add(predefBondLength); + predefBondLength.addItemListener(this); + if (predefBondLength.isSelected()) { + bondLength.setEnabled(true); + } + else { + bondLength.setEnabled(false); + } + PP.add(bondLength); + + processDrawBondState(); + + PP.validate(); + + P.add(PP); + P.validate(); + + PP = new JPanel(new FlowLayout(FlowLayout.CENTER)); + PP.add(Cancel); + PP.add(Help); + Help.setEnabled(false); + + P.add(PP); + + return P; + } + + JButton getHelpButton() { + return Help; + } + + void processDrawBondState() { + userDefBondLength.setEnabled(drawBond.isSelected()); + covalentBondLength.setEnabled(drawBond.isSelected()); + predefBondLength.setEnabled(drawBond.isSelected()); + } + + public void setOKVisible(boolean enable) { + OK.setVisible(enable); + } + + public void setCancelVisible(boolean enable) { + Cancel.setVisible(enable); + } + + public void setTargetClass(Java3dUniverse parent) { + daddy = parent; + } + + public String getAtomType() { + if (lastSelected[getElement()] < 1) { + return null; + } + JButton butt = atomTypesButtons.get(lastSelected[getElement()]); + return butt.getActionCommand(); + } + + public int getElement() { + return selectedElement; + } + + public boolean isUseBondLength() { + return predefBondLength.isSelected(); + } + + public boolean isCovalentBondLength() { + return covalentBondLength.isSelected(); + } + + public String getBondLength() { + return bondLength.getSelectedItem().toString(); + } + + public boolean isDrawBond() { + return drawBond.isSelected(); + } + + public String getSelectedAtomType() { + for (int i = 0; i < atomTypesButtons.size(); i++) { + JButton butt = atomTypesButtons.get(i); + if (!butt.isVisible()) { + break; + } + if (!butt.isSelected()) { + return butt.getActionCommand(); + } + } + return null; + } + + void selectAtomType(JButton button) { + for (int i = 0; i < atomTypesButtons.size(); i++) { + JButton butt = atomTypesButtons.get(i); + if (!butt.isVisible()) { + break; + } + if (button == butt) { + butt.setSelected(true); + butt.setForeground(selectedAtomTypeColor); + butt.validate(); + } + else { + butt.setSelected(false); + butt.setForeground(defaultAtomTypeColor); + butt.validate(); + } + } + + } + + public String getAtomName() { + return atomName.getText().trim(); + } + + public void changeAtomType(ActionEvent e) { + + for (int i = 0; i < atomTypesButtons.size(); i++) { + JButton butt = atomTypesButtons.get(i); + if (!butt.isVisible()) { + break; + } + if (e.getSource() == butt) { + lastSelected[selectedElement] = i; + selectAtomType(butt); + } + + } + } + + private class AtomType_actionAdapter + implements ActionListener { + private JAtomTypeDialog adaptee; + AtomType_actionAdapter(JAtomTypeDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.changeAtomType(e); + } + } + +} diff --git a/src/main/java/cct/dialogs/JAtomTypesPanel.java b/src/main/java/cct/dialogs/JAtomTypesPanel.java new file mode 100644 index 0000000..c97dd23 --- /dev/null +++ b/src/main/java/cct/dialogs/JAtomTypesPanel.java @@ -0,0 +1,217 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import cct.resources.images.ImageResources; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionListener; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class JAtomTypesPanel + extends JPanel { + + static ImageIcon emptyIcon = new ImageIcon(ImageResources.class.getResource( + "icons48x48/emptyTransparent.png")); + java.util.List buttons = new ArrayList(); + int activeButtons = 0; + ActionListener listener; + FlowLayout flowLayout1 = new FlowLayout(FlowLayout.LEFT); + static final Logger logger = Logger.getLogger(JAtomTypesPanel.class.getCanonicalName()); + + public JAtomTypesPanel(ActionListener l) { + listener = l; + try { + jbInit(); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + + public JAtomTypesPanel() { + + } + + public void setAtomTypes(Map atomTypes) { + activeButtons = 0; + + if (buttons.size() > atomTypes.size()) { + for (int i = buttons.size() - 1; i >= atomTypes.size(); i--) { + JButton butt = (JButton) buttons.get(i); + butt.removeActionListener(listener); + butt.setEnabled(false); + butt.setVisible(false); + butt.validate(); + } + } + + int count = 0; + Set set = atomTypes.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + ++activeButtons; + Map.Entry me = (Map.Entry) iter.next(); + String type = me.getKey().toString(); + ImageIcon image = (ImageIcon) me.getValue(); + + if (count >= buttons.size()) { + logger.info("Adding new button: " + type); + JButton temp = new JButton(type, image); + temp.setHorizontalAlignment(SwingConstants.CENTER); + temp.setHorizontalTextPosition(SwingConstants.CENTER); + temp.setVerticalAlignment(SwingConstants.CENTER); + temp.setVerticalTextPosition(SwingConstants.CENTER); + temp.setMargin(new Insets(0, 0, 0, 0)); + temp.setSize(50, 50); + temp.setPreferredSize(new Dimension(50, 50)); + temp.setFont(new Font("Monospaced", Font.BOLD, 12)); + temp.setActionCommand(type); + temp.addActionListener(listener); + buttons.add(temp); + add(temp); + temp.validate(); + } + else { + logger.info("Modifying old button: " + type); + JButton butt = (JButton) buttons.get(count); + butt.setIcon(image); + butt.setText(type); + butt.setActionCommand(type); + butt.setSelected(false); + butt.setEnabled(true); + butt.setVisible(true); + butt.addActionListener(listener); + butt.validate(); + } + ++count; + } + validate(); + } + + public void setSelectedButton(int n) { + if (n >= buttons.size()) { + System.err.println(getClass().getCanonicalName() + + ": n >= buttons.size():" + n + " & " + buttons.size() + + " Ignored"); + return; + } + + for (int i = 0; i < activeButtons; i++) { + JButton butt = (JButton) buttons.get(i); + if (i == n) { + butt.setSelected(true); + } + else { + butt.setSelected(false); + } + } + } + + public void setSelectedButton(String actionCom) { + + for (int i = 0; i < activeButtons; i++) { + JButton butt = (JButton) buttons.get(i); + if (actionCom.equalsIgnoreCase(butt.getActionCommand())) { + butt.setSelected(true); + butt.validate(); + } + else { + butt.setSelected(false); + butt.validate(); + } + } + + } + + private void jbInit() throws Exception { + this.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + + JButton temp = new JButton(emptyIcon); + temp.setHorizontalAlignment(SwingConstants.CENTER); + temp.setHorizontalTextPosition(SwingConstants.CENTER); + temp.setMargin(new Insets(0, 0, 0, 0)); + temp.setVerticalAlignment(SwingConstants.CENTER); + temp.setVerticalTextPosition(SwingConstants.CENTER); + temp.setSize(50, 50); + temp.setFont(new Font("Monospaced", Font.BOLD, 12)); + temp.setPreferredSize(new Dimension(50, 50)); + //temp.setActionCommand(type); + temp.addActionListener(listener); + buttons.add(temp); + this.add(temp); + + for (int i = 0; i < 5; i++) { + temp = new JButton(emptyIcon); + temp.setHorizontalAlignment(SwingConstants.CENTER); + temp.setHorizontalTextPosition(SwingConstants.CENTER); + temp.setMargin(new Insets(0, 0, 0, 0)); + temp.setVerticalAlignment(SwingConstants.CENTER); + temp.setVerticalTextPosition(SwingConstants.CENTER); + temp.setSize(50, 50); + temp.setFont(new Font("Monospaced", Font.BOLD, 12)); + temp.setPreferredSize(new Dimension(50, 50)); + //temp.setActionCommand(type); + temp.addActionListener(listener); + temp.setVisible(false); + buttons.add(temp); + add(temp); + + } + //validate(); + + } +} diff --git a/src/main/java/cct/dialogs/JChoiceDialog.java b/src/main/java/cct/dialogs/JChoiceDialog.java new file mode 100644 index 0000000..ba922cc --- /dev/null +++ b/src/main/java/cct/dialogs/JChoiceDialog.java @@ -0,0 +1,186 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.WindowConstants; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class JChoiceDialog + extends JDialog implements ActionListener { + //JList itemList = new JList(); + boolean OKpressed = false; + JComboBox itemList = new JComboBox(); + JPanel panel1 = new JPanel(); + JPanel panel2 = new JPanel(); + JPanel panel3 = new JPanel(); + JPanel mainPanel = new JPanel(); + JButton OK = new JButton("Ok"); + JButton Cancel = new JButton("Cancel"); + + BorderLayout borderLayout1 = new BorderLayout(); + FlowLayout flowLayout1 = new FlowLayout(); + FlowLayout flowLayout2 = new FlowLayout(); + FlowLayout flowLayout3 = new FlowLayout(); + GridLayout gridLayout1 = new GridLayout(2, 1); + + public JChoiceDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + //setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent we) { + //setLabel("Thwarted user attempt to close window."); + } + }); + + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JChoiceDialog() { + this(new Frame(), "JChoiceDialog", false); + } + + private void jbInit() throws Exception { + JLabel header = new JLabel("Select Item(s)"); + itemList.setMinimumSize(new Dimension(60, 19)); + itemList.setMaximumRowCount(20); + panel1.add(header); + + panel2.add(itemList); + + OK.addActionListener(this); + Cancel.addActionListener(this); + + panel3.add(OK); + panel3.add(Cancel); + + panel1.setLayout(flowLayout3); + panel2.setLayout(flowLayout3); + panel2.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + panel3.setLayout(flowLayout3); + + //mainPanel.add(panel1); + mainPanel.add(panel2); + mainPanel.add(panel3); + + mainPanel.setLayout(gridLayout1); + mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 30, 10, 30)); + getContentPane().add(mainPanel); + + //add(panel1); + //add(panel2); + //add(panel3); + + } + + public void addItem(Object item) { + itemList.addItem(item); + } + + public void addItem(String item) { + itemList.addItem(item); + } + + public void selectIndex(int index) { + if (index < 0 || index >= itemList.getItemCount()) { + return; + } + itemList.setSelectedIndex(index); + } + + public int getSelectedIndex() { + return itemList.getSelectedIndex(); + } + + public boolean isApproveOption() { + return OKpressed; + } + + /** + * Close the dialog on a button event. + * + * @param actionEvent ActionEvent + */ + @Override + public void actionPerformed(ActionEvent actionEvent) { + if (actionEvent.getSource() == OK) { + OKpressed = true; + setVisible(false); + } + else if (actionEvent.getSource() == Cancel) { + OKpressed = false; + setVisible(false); + } + + } + +} diff --git a/src/main/java/cct/dialogs/JEditorFrame.java b/src/main/java/cct/dialogs/JEditorFrame.java new file mode 100644 index 0000000..5ed7da9 --- /dev/null +++ b/src/main/java/cct/dialogs/JEditorFrame.java @@ -0,0 +1,27 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.dialogs; + +/** + * + * @author Vlad + * @deprecated Use JamberooFrame instead + */ +@Deprecated +public class JEditorFrame extends JamberooFrame { + + public JEditorFrame(String title) { + super(title); + } + + public JEditorFrame(String[] args) { + super(args); + } + + public JEditorFrame(String title, String[] args) { + super(title, args); + } +} diff --git a/src/main/java/cct/dialogs/JEditorFrame_AboutBox.java b/src/main/java/cct/dialogs/JEditorFrame_AboutBox.java new file mode 100644 index 0000000..5dab1fb --- /dev/null +++ b/src/main/java/cct/dialogs/JEditorFrame_AboutBox.java @@ -0,0 +1,247 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.dialogs; + +import cct.GlobalSettings; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class JEditorFrame_AboutBox + extends JDialog implements ActionListener, FocusListener, MouseListener { + + private JPanel panel1 = new JPanel(); + private JPanel panel2 = new JPanel(); + private JPanel insetsPanel1 = new JPanel(); + private JPanel insetsPanel2 = new JPanel(); + private JPanel insetsPanel3 = new JPanel(); + private JButton button1 = new JButton(); + private JLabel imageLabel = new JLabel(); + private JLabel label1 = new JLabel(); + private JLabel label2 = new JLabel(); + private JLabel homePageLabel = new JLabel(); + private JLabel emailLabel = new JLabel(); + private ImageIcon image1 = new ImageIcon(); + private BorderLayout borderLayout1 = new BorderLayout(); + private BorderLayout borderLayout2 = new BorderLayout(); + private FlowLayout flowLayout1 = new FlowLayout(); + private GridLayout gridLayout1 = new GridLayout(); + private String product = "Jamberoo - open-source project since 2005"; + private String version = "Version 0.7 build 0626"; + private String copyright = "Jamberoo Home Page"; + private String comments = "Send e-mail for help"; + private String Version, Build; + + public JEditorFrame_AboutBox(Frame parent, String version, String build) { + super(parent); + Version = version; + Build = build; + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JEditorFrame_AboutBox() { + this(null, "07", "0526"); + } + + /** + * Component initialization. + * + * @throws Exception + */ + private void jbInit() throws Exception { + version = "Version " + Version + " build " + Build; + image1 = new ImageIcon(JamberooFrame.class.getResource( + "cct/images/jmoleditor-128x128.png")); + //"images/about-32x32.gif")); + imageLabel.setIcon(image1); + setTitle("About"); + panel1.setLayout(borderLayout1); + panel2.setLayout(borderLayout2); + insetsPanel1.setLayout(flowLayout1); + insetsPanel2.setLayout(flowLayout1); + insetsPanel2.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + gridLayout1.setRows(4); + gridLayout1.setColumns(1); + label1.setToolTipText(""); + label1.setText(product); + label2.setText(version); + + homePageLabel.setText(copyright); + homePageLabel.setToolTipText("Go to the Jamberoo Home Page using default browser"); + homePageLabel.addMouseListener(this); + + emailLabel.setToolTipText("Send e-mail request using default e-mail client"); + emailLabel.setText(comments); + emailLabel.addMouseListener(this); + + insetsPanel3.setLayout(gridLayout1); + insetsPanel3.setBorder(BorderFactory.createEmptyBorder(10, 60, 10, 10)); + button1.setText("OK"); + button1.addActionListener(this); + insetsPanel2.add(imageLabel, null); + panel2.add(insetsPanel2, BorderLayout.WEST); + getContentPane().add(panel1, null); + insetsPanel3.add(label1, null); + insetsPanel3.add(label2, null); + insetsPanel3.add(homePageLabel, null); + insetsPanel3.add(emailLabel, null); + panel2.add(insetsPanel3, BorderLayout.CENTER); + insetsPanel1.add(button1, null); + panel1.add(insetsPanel1, BorderLayout.SOUTH); + panel1.add(panel2, BorderLayout.NORTH); + setResizable(true); + } + + /** + * Close the dialog on a button event. + * + * @param actionEvent ActionEvent + */ + @Override + public void actionPerformed(ActionEvent actionEvent) { + if (actionEvent.getSource() == button1) { + dispose(); + } + } + + /** + * Invoked when a component gains the keyboard focus. + * @param e + */ + public void focusGained(FocusEvent e) { + System.out.println("Got focus"); + if (e.getSource() == homePageLabel) { + homePageLabel.setForeground(Color.BLUE); + } + } + + public void focusLost(FocusEvent e) { + if (e.getSource() == homePageLabel) { + homePageLabel.setForeground(Color.BLACK); + } + } + + /** + * Invoked when the mouse button has been clicked (pressed and released) on a component. + * @param e + */ + public void mouseClicked(MouseEvent e) { + } + + /** + * Invoked when the mouse enters a component. + * @param e + */ + public void mouseEntered(MouseEvent e) { + //System.out.println("Got focus"); + if (e.getSource() == homePageLabel) { + homePageLabel.setForeground(Color.BLUE); + } else if (e.getSource() == emailLabel) { + emailLabel.setForeground(Color.BLUE); + } + } + + /** + * Invoked when the mouse exits a component. + * @param e + */ + public void mouseExited(MouseEvent e) { + if (e.getSource() == homePageLabel) { + homePageLabel.setForeground(Color.BLACK); + } else if (e.getSource() == emailLabel) { + emailLabel.setForeground(Color.BLACK); + } + } + + /** + * Invoked when a mouse button has been pressed on a component. + * @param e + */ + public void mousePressed(MouseEvent e) { + if (e.getSource() == homePageLabel) { + try { + GlobalSettings.showInDefaultBrowser(GlobalSettings.getProperty(GlobalSettings.URL_HOME_PAGE)); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + } else if (e.getSource() == emailLabel) { + try { + GlobalSettings.mailUsingDefaultClient(GlobalSettings.getProperty(GlobalSettings.HELP_EMAIL), "Jamberoo request", ""); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + System.err.println(ex.getMessage()); + } + } + + } + + public void mouseReleased(MouseEvent e) { + } +} diff --git a/src/main/java/cct/dialogs/JElementsPanel.java b/src/main/java/cct/dialogs/JElementsPanel.java new file mode 100644 index 0000000..57010cc --- /dev/null +++ b/src/main/java/cct/dialogs/JElementsPanel.java @@ -0,0 +1,658 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.Rectangle; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.ArrayList; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; + +import cct.modelling.ChemicalElements; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +enum ELEMENTS_PRESENTATION { + SHOW_AS_TABLE, SHOW_AS_COMBOBOX +} + +public class JElementsPanel + extends JPanel implements ActionListener, ItemListener { + BorderLayout borderLayout1 = new BorderLayout(); + java.util.List Buttons; + java.util.List buttonStore = new ArrayList (110); + JComboBox elementsCombobox = new JComboBox(); + + JButton selectedButton = null; + JPanel tablePanel = null; + JPanel comboboxPanel = null; + + public JElementsPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + + createButtons(); + adjustButtons(); + + //Buttons = buildTableForMainElements(tablePanel); + tablePanel = buildTableForMainElements(tablePanel); + buildComboxBox(); + + this.add(tablePanel); + } + + void createButtons() { + Insets buttonInsets = new Insets(2, 1, 2, 1); + + for (int i = 0; i < ChemicalElements.getNumberOfElements(); i++) { + JButton elemButton = new JButton(ChemicalElements.getElementSymbol(i)); + buttonStore.add(elemButton); + elemButton.setMargin(buttonInsets); + elemButton.addActionListener(this); + elemButton.validate(); + } + } + + void adjustButtons() { + Insets buttonInsets = new Insets(2, 1, 2, 1); + Dimension maxMin = new Dimension(0, 0); + + for (int i = 0; i < buttonStore.size(); i++) { + JButton elemButton = buttonStore.get(i); + Dimension min = elemButton.getMinimumSize(); + if (min.height > maxMin.height) { + maxMin.height = min.height; + } + if (min.width > maxMin.width) { + maxMin.width = min.width; + } + } + if (maxMin.width < maxMin.height) { + maxMin.width = maxMin.height; + } + else { + maxMin.height = maxMin.width; + } + //logger.info("height: " + maxMin.height + " width: " + + // maxMin.width); + + for (int i = 0; i < buttonStore.size(); i++) { + JButton elemButton = buttonStore.get(i); + elemButton.setMargin(buttonInsets); + elemButton.setPreferredSize(maxMin); + elemButton.setMaximumSize(maxMin); + elemButton.setMinimumSize(maxMin); + } + + } + + void buildComboxBox() { + elementsCombobox.removeAllItems(); + elementsCombobox.addItemListener(this); + + for (int i = 0; i < buttonStore.size(); i++) { + JButton elemButton = buttonStore.get(i); + elementsCombobox.addItem(ChemicalElements.getElementSymbol(i) + " - " + ChemicalElements.getElementName(i)); + } + + comboboxPanel = new JPanel(); + comboboxPanel.add(new JLabel("Elements: ")); + comboboxPanel.add(elementsCombobox); + + FlowLayout flowLayout1 = new FlowLayout(FlowLayout.LEFT); + comboboxPanel.setLayout(flowLayout1); + } + + public void showElementsAsTable(boolean show) { + Component[] comp = this.getComponents(); + for (int i = 0; i < comp.length; i++) { + if (comp[i] == comboboxPanel) { + if (!show) { + return; + } + this.remove(comboboxPanel); + this.add(tablePanel); + this.validate(); + return; + } + else if (comp[i] == tablePanel) { + if (show) { + return; + } + this.remove(tablePanel); + this.add(comboboxPanel); + this.validate(); + return; + + } + } + } + + //public ArrayList buildTableForMainElements(JPanel P) { + public JPanel buildTableForMainElements(JPanel P) { + java.util.List buttons = new ArrayList(); + String tooltip; + int elem, hight; + Dimension dim; + + if (P == null) { + P = new JPanel(); + } + + // java.awt.Insets[top=4,left=16,bottom=4,right=16] + + JLabel label; + JButton button; + GridBagLayout gridbag = new GridBagLayout(); + P.setLayout(gridbag); + GridBagConstraints c; + + // --- Build group number labels + + c = new GridBagConstraints(); + c.gridx = 0; + c.gridy = 0; + c.gridwidth = 1; + c.gridheight = 1; + //c.weightx = 1; + //c.weighty = 1; + //c.fill = GridBagConstraints.BOTH; + c.fill = GridBagConstraints.CENTER; + c.insets = new Insets(1, 1, 1, 1); + + label = new JLabel("Group"); + gridbag.setConstraints(label, c); + P.add(label); + + for (c.gridx = 1; c.gridx < 19; c.gridx++) { + label = new JLabel(String.valueOf(c.gridx), + javax.swing.SwingConstants.CENTER); + gridbag.setConstraints(label, c); + P.add(label); + } + + // --- Add "Period" label + + c.gridx = 0; + c.gridy += c.gridheight; + label = new JLabel("Period"); + gridbag.setConstraints(label, c); + P.add(label); + + // --- Add first period of elements + + c.gridx = 0; + c.gridy += c.gridheight; + label = new JLabel("1", javax.swing.SwingConstants.CENTER); + gridbag.setConstraints(label, c); + P.add(label); + + c.gridx = 1; + //symbol = ChemicalElements.getElementSymbol(1); + button = buttonStore.get(1); //new JButton(symbol); + tooltip = ChemicalElements.getElementName(1) + " " + String.valueOf(1) + + " " + ChemicalElements.getAtomicWeight(1); + button.setToolTipText(tooltip); + //button.setMargin(buttonInsets); + hight = button.getMinimumSize().height; + //button.setSize(hight,hight); + dim = button.getMinimumSize(); + dim.width = hight; + //button.setPreferredSize(dim); + //button.setMaximumSize(dim); + //button.setPreferredSize(maxMin); + //button.setMaximumSize(maxMin); + Rectangle r = button.getBounds(); + Insets ins = button.getInsets(); + //logger.info("dim min: " + dim + " bounds: " + r + " Hight: " + + // hight + " insets: " + ins); + //button.setMaximumSize(d); + //button.setSize(d); + gridbag.setConstraints(button, c); + P.add(button); + buttons.add(button); + + c.gridx = 18; + //symbol = ChemicalElements.getElementSymbol(2); + button = buttonStore.get(2); //new JButton(symbol); + tooltip = ChemicalElements.getElementName(2) + " " + String.valueOf(2) + + " " + ChemicalElements.getAtomicWeight(2); + button.setToolTipText(tooltip); + + //button.setMargin(buttonInsets); + //button.setPreferredSize(dim); + //button.setPreferredSize(maxMin); + //button.setMaximumSize(dim); + //button.setMaximumSize(maxMin); + //button.setMinimumSize(maxMin); + + + gridbag.setConstraints(button, c); + P.add(button); + buttons.add(button); + + // --- Add second period of elements + + c.gridx = 0; + c.gridy += c.gridheight; + label = new JLabel("2", javax.swing.SwingConstants.CENTER); + gridbag.setConstraints(label, c); + P.add(label); + + for (c.gridx = 1, elem = 3; c.gridx < 3; c.gridx++, elem++) { + //symbol = ChemicalElements.getElementSymbol(elem); + button = buttonStore.get(elem); //new JButton(symbol); + tooltip = ChemicalElements.getElementName(elem) + " " + + String.valueOf(elem) + " " + + ChemicalElements.getAtomicWeight(elem); + button.setToolTipText(tooltip); + + //button.setMargin(buttonInsets); + //button.setPreferredSize(dim); + //button.setPreferredSize(maxMin); + //button.setMaximumSize(dim); + //button.setMaximumSize(maxMin); + //button.setMinimumSize(maxMin); + + + gridbag.setConstraints(button, c); + P.add(button); + buttons.add(button); + } + + for (c.gridx = 13, elem = 5; c.gridx < 19; c.gridx++, elem++) { + //symbol = ChemicalElements.getElementSymbol(elem); + button = buttonStore.get(elem); //new JButton(symbol); + tooltip = ChemicalElements.getElementName(elem) + " " + + String.valueOf(elem) + " " + + ChemicalElements.getAtomicWeight(elem); + button.setToolTipText(tooltip); + + //button.setMargin(buttonInsets); + //button.setPreferredSize(dim); + //button.setPreferredSize(maxMin); + //button.setMaximumSize(dim); + //button.setMaximumSize(maxMin); + //button.setMinimumSize(maxMin); + + + gridbag.setConstraints(button, c); + P.add(button); + buttons.add(button); + } + + // --- Add the third period of elements + + c.gridx = 0; + c.gridy += c.gridheight; + label = new JLabel("3", javax.swing.SwingConstants.CENTER); + gridbag.setConstraints(label, c); + P.add(label); + + for (c.gridx = 1, elem = 11; c.gridx < 3; c.gridx++, elem++) { + //symbol = ChemicalElements.getElementSymbol(elem); + button = buttonStore.get(elem); //new JButton(symbol); + tooltip = ChemicalElements.getElementName(elem) + " " + + String.valueOf(elem) + " " + + ChemicalElements.getAtomicWeight(elem); + button.setToolTipText(tooltip); + + //button.setMargin(buttonInsets); + //button.setPreferredSize(dim); + //button.setPreferredSize(maxMin); + //button.setMaximumSize(dim); + //button.setMaximumSize(maxMin); + + gridbag.setConstraints(button, c); + P.add(button); + buttons.add(button); + } + + for (c.gridx = 13, elem = 13; c.gridx < 19; c.gridx++, elem++) { + //symbol = ChemicalElements.getElementSymbol(elem); + button = buttonStore.get(elem); //new JButton(symbol); + tooltip = ChemicalElements.getElementName(elem) + " " + + String.valueOf(elem) + " " + + ChemicalElements.getAtomicWeight(elem); + button.setToolTipText(tooltip); + + //button.setMargin(buttonInsets); + //button.setPreferredSize(dim); + //button.setPreferredSize(maxMin); + //button.setMaximumSize(dim); + //button.setMaximumSize(maxMin); + + gridbag.setConstraints(button, c); + P.add(button); + buttons.add(button); + } + + // --- Add the forth period of elements + + c.gridx = 0; + c.gridy += c.gridheight; + label = new JLabel("4", javax.swing.SwingConstants.CENTER); + gridbag.setConstraints(label, c); + P.add(label); + + for (c.gridx = 1, elem = 19; c.gridx < 19; c.gridx++, elem++) { + //symbol = ChemicalElements.getElementSymbol(elem); + button = buttonStore.get(elem); //new JButton(symbol); + tooltip = ChemicalElements.getElementName(elem) + " " + + String.valueOf(elem) + " " + + ChemicalElements.getAtomicWeight(elem); + button.setToolTipText(tooltip); + + //button.setMargin(buttonInsets); + //button.setPreferredSize(dim); + //button.setPreferredSize(maxMin); + //button.setMaximumSize(dim); + //button.setMaximumSize(maxMin); + + gridbag.setConstraints(button, c); + P.add(button); + buttons.add(button); + } + + // --- Add the fifth period of elements + + c.gridx = 0; + c.gridy += c.gridheight; + label = new JLabel("5", javax.swing.SwingConstants.CENTER); + gridbag.setConstraints(label, c); + P.add(label); + + for (c.gridx = 1, elem = 37; c.gridx < 19; c.gridx++, elem++) { + //symbol = ChemicalElements.getElementSymbol(elem); + button = buttonStore.get(elem); //new JButton(symbol); + tooltip = ChemicalElements.getElementName(elem) + " " + + String.valueOf(elem) + " " + + ChemicalElements.getAtomicWeight(elem); + button.setToolTipText(tooltip); + + //button.setMargin(buttonInsets); + //button.setPreferredSize(dim); + //button.setPreferredSize(maxMin); + //button.setMaximumSize(dim); + //button.setMaximumSize(maxMin); + + gridbag.setConstraints(button, c); + P.add(button); + buttons.add(button); + } + + // --- Add the sixth period of elements + + c.gridx = 0; + c.gridy += c.gridheight; + label = new JLabel("6", javax.swing.SwingConstants.CENTER); + gridbag.setConstraints(label, c); + P.add(label); + + for (c.gridx = 1, elem = 55; c.gridx < 4; c.gridx++, elem++) { + //symbol = ChemicalElements.getElementSymbol(elem); + button = buttonStore.get(elem); //new JButton(symbol); + tooltip = ChemicalElements.getElementName(elem) + " " + + String.valueOf(elem) + " " + + ChemicalElements.getAtomicWeight(elem); + button.setToolTipText(tooltip); + + //button.setMargin(buttonInsets); + //button.setPreferredSize(dim); + //button.setPreferredSize(maxMin); + //button.setMaximumSize(dim); + //button.setMaximumSize(maxMin); + + gridbag.setConstraints(button, c); + P.add(button); + buttons.add(button); + } + // --- Skip Lanthanides + for (c.gridx = 4, elem = 72; c.gridx < 19; c.gridx++, elem++) { + //symbol = ChemicalElements.getElementSymbol(elem); + button = buttonStore.get(elem); //new JButton(symbol); + tooltip = ChemicalElements.getElementName(elem) + " " + + String.valueOf(elem) + " " + + ChemicalElements.getAtomicWeight(elem); + button.setToolTipText(tooltip); + + //button.setMargin(buttonInsets); + //button.setPreferredSize(dim); + //button.setPreferredSize(maxMin); + //button.setMaximumSize(dim); + //button.setMaximumSize(maxMin); + + gridbag.setConstraints(button, c); + P.add(button); + buttons.add(button); + } + + // --- Add the seventh period of elements + + c.gridx = 0; + c.gridy += c.gridheight; + label = new JLabel("7", javax.swing.SwingConstants.CENTER); + gridbag.setConstraints(label, c); + P.add(label); + + for (c.gridx = 1, elem = 87; c.gridx < 4; c.gridx++, elem++) { + //symbol = ChemicalElements.getElementSymbol(elem); + button = buttonStore.get(elem); //new JButton(symbol); + tooltip = ChemicalElements.getElementName(elem) + " " + + String.valueOf(elem) + " " + + ChemicalElements.getAtomicWeight(elem); + button.setToolTipText(tooltip); + + //button.setMargin(buttonInsets); + //button.setPreferredSize(dim); + //button.setPreferredSize(maxMin); + //button.setMaximumSize(dim); + //button.setMaximumSize(maxMin); + + gridbag.setConstraints(button, c); + P.add(button); + buttons.add(button); + } + // --- Skip Actinides + for (c.gridx = 4, elem = 104; + c.gridx < 19 && elem < ChemicalElements.getNumberOfElements(); + c.gridx++, elem++) { + //symbol = ChemicalElements.getElementSymbol(elem); + button = buttonStore.get(elem); //new JButton(symbol); + tooltip = ChemicalElements.getElementName(elem) + " " + + String.valueOf(elem) + " " + + ChemicalElements.getAtomicWeight(elem); + button.setToolTipText(tooltip); + + //button.setMargin(buttonInsets); + //button.setPreferredSize(dim); + //button.setPreferredSize(maxMin); + //button.setMaximumSize(dim); + //button.setMaximumSize(maxMin); + + gridbag.setConstraints(button, c); + P.add(button); + buttons.add(button); + } + + // --- Add Lanthanides + + c.gridx = 1; + c.gridwidth = 2; + c.gridy += c.gridheight + 1; + label = new JLabel("Lanthanide:", javax.swing.SwingConstants.RIGHT); + gridbag.setConstraints(label, c); + P.add(label); + + c.gridwidth = 1; + + for (c.gridx = 4, elem = 58; c.gridx < 18; c.gridx++, elem++) { + //symbol = ChemicalElements.getElementSymbol(elem); + button = buttonStore.get(elem); //new JButton(symbol); + tooltip = ChemicalElements.getElementName(elem) + " " + + String.valueOf(elem) + " " + + ChemicalElements.getAtomicWeight(elem); + button.setToolTipText(tooltip); + + //button.setMargin(buttonInsets); + //button.setPreferredSize(dim); + //button.setPreferredSize(maxMin); + //button.setMaximumSize(dim); + //button.setMaximumSize(maxMin); + + gridbag.setConstraints(button, c); + P.add(button); + buttons.add(button); + } + + // --- Add Actinide + + c.gridx = 1; + c.gridwidth = 2; + c.gridy += c.gridheight; + label = new JLabel("Actinide:", javax.swing.SwingConstants.RIGHT); + gridbag.setConstraints(label, c); + P.add(label); + + c.gridwidth = 1; + + for (c.gridx = 4, elem = 90; c.gridx < 18; c.gridx++, elem++) { + //symbol = ChemicalElements.getElementSymbol(elem); + button = buttonStore.get(elem); //new JButton(symbol); + tooltip = ChemicalElements.getElementName(elem) + " " + + String.valueOf(elem) + " " + + ChemicalElements.getAtomicWeight(elem); + button.setToolTipText(tooltip); + + //button.setMargin(buttonInsets); + //button.setPreferredSize(dim); + //button.setPreferredSize(maxMin); + //button.setMaximumSize(dim); + //button.setMaximumSize(maxMin); + + gridbag.setConstraints(button, c); + P.add(button); + buttons.add(button); + } + + //return buttons; + return P; + } + + public Font getElementsFont() { + JButton elemButton = buttonStore.get(0); + return elemButton.getFont(); + } + + public void setElementsFont(Font newFont) { + for (int i = 0; i < buttonStore.size(); i++) { + JButton elemButton = buttonStore.get(i); + elemButton.setFont(newFont); + } + + adjustButtons(); + this.validate(); + + } + + public java.util.List getButtons() { + //return Buttons; + return buttonStore; + } + + @Override + public void actionPerformed(ActionEvent ae) { + selectedButton = (JButton) ae.getSource(); + int index = buttonStore.indexOf(selectedButton); + if (index == -1) { + index = 0; + } + if (elementsCombobox.isEnabled()) { + elementsCombobox.setEnabled(false); + elementsCombobox.setSelectedIndex(index); + elementsCombobox.setEnabled(true); + } + } + + @Override + public void itemStateChanged(ItemEvent e) { + if (!elementsCombobox.isEnabled()) { + return; + } + if (e.getStateChange() == ItemEvent.DESELECTED) { + return; + } + elementsCombobox.setEnabled(false); + int index = elementsCombobox.getSelectedIndex(); + selectedButton = buttonStore.get(index); + selectedButton.doClick(); + elementsCombobox.setEnabled(true); + } +} diff --git a/src/main/java/cct/dialogs/JModifyAngleDialog.java b/src/main/java/cct/dialogs/JModifyAngleDialog.java new file mode 100644 index 0000000..b9cfeef --- /dev/null +++ b/src/main/java/cct/dialogs/JModifyAngleDialog.java @@ -0,0 +1,691 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.dialogs; + +import cct.j3d.Java3dUniverse; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.GridLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.HashMap; +import java.util.Map; + +import javax.swing.BorderFactory; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JSlider; +import javax.swing.JTextField; +import javax.swing.SwingConstants; +import javax.swing.border.Border; +import javax.swing.border.TitledBorder; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +import cct.modelling.MolecularEditor; +import cct.modelling.OperationsOnAtoms; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +/** + *

+ * Title: Picking

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005

+ * + *

+ * Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class JModifyAngleDialog + extends JDialog implements OperationsOnAtoms { + + JPanel mainPanel = new JPanel(); + JPanel DisplPanel = new JPanel(); + JPanel Atom_1 = new JPanel(); + JPanel Atom_3 = new JPanel(); + JPanel Atom_2 = new JPanel(); + Border border1 = BorderFactory.createLineBorder(Color.lightGray, 1); + Border border2 = new TitledBorder(border1, "Atom 2 Displacement"); + ButtonGroup buttonGroup1 = new ButtonGroup(); + ButtonGroup buttonGroup2 = new ButtonGroup(); + ButtonGroup buttonGroup3 = new ButtonGroup(); + JRadioButton Fixed_1 = new JRadioButton(); + JRadioButton Rotate_atom_1 = new JRadioButton(); + JRadioButton Translate_group_1 = new JRadioButton(); + JRadioButton Rotate_group_1 = new JRadioButton(); + JRadioButton Translate_group_2 = new JRadioButton(); + JRadioButton Translate_atom_2 = new JRadioButton(); + JRadioButton Fixed_2 = new JRadioButton(); + JRadioButton Rotate_group_3 = new JRadioButton(); + JRadioButton Translate_group_3 = new JRadioButton(); + JRadioButton Rotate_atom_3 = new JRadioButton(); + JRadioButton Fixed_3 = new JRadioButton(); + GridLayout gridLayout1 = new GridLayout(); + JPanel InfoPanel = new JPanel(); + JLabel maxAngle = new JLabel(); + JLabel minAngle = new JLabel(); + JTextField currentAngle = new JTextField(); + JLabel jLabel1 = new JLabel(); + JLabel jLabel2 = new JLabel(); + JPanel changeAnglePanel = new JPanel(); + JSlider changeAngle = new JSlider(); + // --- My variables + + Map Labels = new HashMap(); + JPanel anglePanel = new JPanel(); + MolecularEditor daddy = null; + float oldAngle; + float maxAngleValue = 180.0f; + boolean setOnlySlider = false; + JPanel buttonPanel = new JPanel(); + FlowLayout flowLayout1 = new FlowLayout(); + JButton Finish = new JButton(); + JCheckBox instantView = new JCheckBox(); + JButton undoLastSelection = new JButton(); + JButton Ok = new JButton(); + JButton Reset = new JButton(); + BorderLayout borderLayout1 = new BorderLayout(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + GridBagLayout gridBagLayout2 = new GridBagLayout(); + GridBagLayout gridBagLayout3 = new GridBagLayout(); + GridBagLayout gridBagLayout4 = new GridBagLayout(); + BorderLayout borderLayout2 = new BorderLayout(); + GridBagLayout gridBagLayout5 = new GridBagLayout(); + JButton helpButton = new JButton(); + + public JModifyAngleDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + this.addWindowListener(new WindowAdapter() { + + @Override + public void windowClosing(WindowEvent we) { + CloseWindowGracefully(); + } + }); + //setDefaultCloseOperation(HIDE_ON_CLOSE); + jbInit(); + pack(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JModifyAngleDialog() { + this(new Frame(), "JModifyAngleDialog", false); + try { + jbInit(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + private void jbInit() throws Exception { + Labels.put(0, "0.0"); + Labels.put(50, "90.0"); + Labels.put(100, "180.0"); + + mainPanel.setLayout(borderLayout1); + DisplPanel.setBorder(null); + DisplPanel.setLayout(gridLayout1); + Atom_1.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color.lightGray, 1), "Atom 1 Displacement")); + Atom_1.setLayout(gridBagLayout1); + Atom_2.setBorder(border2); + Atom_2.setLayout(gridBagLayout2); + Atom_3.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color.lightGray, 1), "Atom 3 Displacement")); + Atom_3.setLayout(gridBagLayout3); + Fixed_1.setText("Fixed"); + Fixed_1.addChangeListener(new JModifyAngleDialog_Fixed_1_changeAdapter(this)); + Rotate_atom_1.setSelected(false); + Rotate_atom_1.setText("Rotate Atom"); + Rotate_atom_1.addChangeListener(new JModifyAngleDialog_Rotate_atom_1_changeAdapter(this)); + Translate_group_1.setEnabled(true); + Translate_group_1.setToolTipText(""); + Translate_group_1.setRolloverSelectedIcon(null); + Translate_group_1.setSelected(false); + Translate_group_1.setText("Translate Group"); + Translate_group_1.addChangeListener(new JModifyAngleDialog_Translate_group_1_changeAdapter(this)); + Rotate_group_1.setSelected(true); + Rotate_group_1.setText("Rotate Group"); + Translate_group_2.setEnabled(false); + Translate_group_2.setToolTipText(""); + Translate_group_2.setText("Translate Group"); + Translate_atom_2.setEnabled(false); + Translate_atom_2.setText("Translate Atom"); + Fixed_2.setEnabled(true); + Fixed_2.setSelected(true); + Fixed_2.setText("Fixed"); + Fixed_2.addChangeListener(new JModifyAngleDialog_Fixed_2_changeAdapter(this)); + Rotate_group_3.setToolTipText(""); + Rotate_group_3.setSelected(true); + Rotate_group_3.setText("Rotate Group"); + Translate_group_3.setEnabled(true); + Translate_group_3.setToolTipText(""); + Translate_group_3.setSelected(false); + Translate_group_3.setText("Translate Group"); + Rotate_atom_3.setText("Rotate Atom"); + Fixed_3.setText("Fixed"); + Fixed_3.addChangeListener(new JModifyAngleDialog_Fixed_3_changeAdapter(this)); + maxAngle.setToolTipText(""); + maxAngle.setHorizontalAlignment(SwingConstants.RIGHT); + maxAngle.setHorizontalTextPosition(SwingConstants.RIGHT); + maxAngle.setText("180.0"); + minAngle.setHorizontalAlignment(SwingConstants.LEFT); + minAngle.setHorizontalTextPosition(SwingConstants.LEFT); + minAngle.setText("0.0"); + currentAngle.setToolTipText(""); + currentAngle.setText("90.0"); + currentAngle.setColumns(8); + currentAngle.setHorizontalAlignment(SwingConstants.CENTER); + currentAngle.addActionListener(new JModifyAngleDialog_currentAngle_actionAdapter(this)); + InfoPanel.setLayout(gridBagLayout5); + jLabel1.setToolTipText(""); + jLabel1.setText(""); + jLabel2.setText(""); + changeAnglePanel.setInputVerifier(null); + changeAnglePanel.setLayout(borderLayout2); + changeAngle.setLabelTable(null); + changeAngle.setMajorTickSpacing(36); + changeAngle.setMaximum(360); + changeAngle.setPaintTicks(true); + changeAngle.addChangeListener(new JModifyAngleDialog_changeAngle_changeAdapter(this)); + anglePanel.setLayout(gridBagLayout4); + buttonPanel.setLayout(flowLayout1); + Finish.setToolTipText("Accept current editing and Finish"); + Finish.setText("Finish"); + Finish.addActionListener(new JModifyAngleDialog_Finish_actionAdapter(this)); + instantView.setToolTipText(""); + instantView.setSelected(true); + instantView.setText("Instant View"); + undoLastSelection.setToolTipText("Deselect last selected atom"); + undoLastSelection.setText("Undo Last Selection"); + undoLastSelection.addActionListener(new JModifyAngleDialog_undoLastSelection_actionAdapter(this)); + Ok.setToolTipText("Accept current editing and start a new one"); + Ok.setText("Accept"); + Ok.addActionListener(new JModifyAngleDialog_Ok_actionAdapter(this)); + Reset.setToolTipText("Reset geometry"); + Reset.setText("Reset"); + Reset.addActionListener(new JModifyAngleDialog_Reset_actionAdapter(this)); + helpButton.setEnabled(false); + helpButton.setToolTipText("Accept current editing and Finish"); + helpButton.setText("Help"); + //changeAngle.setLabelTable(Labels); + getContentPane().add(mainPanel); + DisplPanel.add(Atom_1, null); + DisplPanel.add(Atom_2); + DisplPanel.add(Atom_3, null); + buttonPanel.add(Ok); + buttonPanel.add(Reset); + buttonPanel.add(Finish); + buttonPanel.add(undoLastSelection); + buttonPanel.add(helpButton); + buttonGroup1.add(Fixed_1); + buttonGroup1.add(Rotate_atom_1); + buttonGroup1.add(Translate_group_1); + buttonGroup1.add(Rotate_group_1); + + buttonGroup2.add(Fixed_2); + buttonGroup2.add(Translate_group_2); + buttonGroup2.add(Translate_atom_2); + + buttonGroup3.add(Fixed_3); + buttonGroup3.add(Rotate_atom_3); + buttonGroup3.add(Translate_group_3); + buttonGroup3.add(Rotate_group_3); + mainPanel.add(DisplPanel, BorderLayout.NORTH); + mainPanel.add(buttonPanel, BorderLayout.SOUTH); + mainPanel.add(anglePanel, BorderLayout.CENTER); + Atom_1.add(Translate_group_1, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + Atom_1.add(Rotate_group_1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + Atom_1.add(Rotate_atom_1, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + Atom_2.add(Translate_group_2, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + Atom_2.add(Translate_atom_2, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + Atom_2.add(Fixed_2, new GridBagConstraints(0, 2, 1, 1, 0.0, 1.0, GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + Atom_3.add(Rotate_group_3, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + Atom_3.add(Translate_group_3, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + Atom_3.add(Rotate_atom_3, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + Atom_3.add(Fixed_3, new GridBagConstraints(0, 3, 1, 1, 0.0, 1.0, GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + Atom_1.add(Fixed_1, new GridBagConstraints(0, 3, 1, 1, 0.0, 1.0, GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 62, 0)); + anglePanel.add(changeAnglePanel, + new GridBagConstraints(0, 2, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, + GridBagConstraints.BOTH, + new Insets(0, 0, 0, 0), 190, 0)); + anglePanel.add(instantView, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + anglePanel.add(InfoPanel, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + changeAnglePanel.add(changeAngle, BorderLayout.NORTH); + InfoPanel.add(jLabel1, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + InfoPanel.add(jLabel2, new GridBagConstraints(3, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + InfoPanel.add(maxAngle, new GridBagConstraints(4, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + InfoPanel.add(currentAngle, new GridBagConstraints(2, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + InfoPanel.add(minAngle, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + } + + public void setTargetClass(MolecularEditor target) { + daddy = target; + } + + public void setAngle(float angle) { + oldAngle = angle; + setOnlySlider = true; + setTextAreaOnly(angle); + setSliderOnly(angle); + setOnlySlider = false; + } + + public void modifyAngle(float angle) { + int I_status = FIXED_ATOM; + if (Rotate_group_1.isSelected()) { + I_status = ROTATE_GROUP; + } else if (Translate_group_1.isSelected()) { + I_status = TRANSLATE_GROUP; + } else if (Rotate_atom_1.isSelected()) { + I_status = ROTATE_ATOM; + } + + int J_status = 0; + if (Translate_group_2.isSelected()) { + J_status = TRANSLATE_GROUP; + } else if (Translate_atom_2.isSelected()) { + J_status = TRANSLATE_ATOM; + } + + int K_status = FIXED_ATOM; + if (Rotate_group_3.isSelected()) { + K_status = ROTATE_GROUP; + } else if (Translate_group_3.isSelected()) { + K_status = TRANSLATE_GROUP; + } else if (Rotate_atom_3.isSelected()) { + K_status = ROTATE_ATOM; + } + + daddy.changeAngleBetweenSelectedAtoms(angle, I_status, + J_status, K_status); + } + + private void setTextAreaOnly(float value) { + currentAngle.setText(String.format("%8.4f", value)); + } + + private void setSliderOnly(float value) { + boolean store = instantView.isSelected(); + instantView.setSelected(false); + changeAngle.setValueIsAdjusting(true); + float max = changeAngle.getMaximum(); + changeAngle.setValue((int) (value / maxAngleValue * max)); + changeAngle.setValueIsAdjusting(false); + instantView.setSelected(store); + } + + public void CloseWindowGracefully() { + Java3dUniverse target = (Java3dUniverse) daddy; + //target.processSelectedAtoms(); + target.endProcessingSelectedAtoms(); + setVisible(false); + + } + + public void Finish_actionPerformed(ActionEvent e) { + CloseWindowGracefully(); + } + + public void changeAngle_stateChanged(ChangeEvent e) { + float value = changeAngle.getValue(); + float max = changeAngle.getMaximum(); + float min = changeAngle.getMinimum(); + oldAngle = (value - min) / max * maxAngleValue; + //logger.info("Value: "+value+" Curr Bond: "+currentBond+" min: "+min+" max: "+max); + + if (setOnlySlider) { + return; + } + + setTextAreaOnly(oldAngle); + + if (changeAngle.getValueIsAdjusting() && !instantView.isSelected()) { //doing adjusting + + } else { //done adjusting + modifyAngle(oldAngle); + } + } + + public void Fixed_1_stateChanged(ChangeEvent e) { + if (Fixed_1.isSelected()) { + if (Fixed_2.isSelected()) { + Fixed_3.setEnabled(false); + } + if (Fixed_3.isSelected()) { + Fixed_2.setEnabled(false); + } + } else { + Fixed_2.setEnabled(true); + Fixed_3.setEnabled(true); + } + } + + public void Fixed_2_stateChanged(ChangeEvent e) { + if (Fixed_2.isSelected()) { + if (Fixed_1.isSelected()) { + Fixed_3.setEnabled(false); + } + if (Fixed_3.isSelected()) { + Fixed_1.setEnabled(false); + } + } else { + Fixed_1.setEnabled(true); + Fixed_3.setEnabled(true); + } + } + + public void Fixed_3_stateChanged(ChangeEvent e) { + if (Fixed_3.isSelected()) { + if (Fixed_1.isSelected()) { + Fixed_2.setEnabled(false); + } + if (Fixed_2.isSelected()) { + Fixed_1.setEnabled(false); + } + } else { + Fixed_1.setEnabled(true); + Fixed_2.setEnabled(true); + } + + } + + public void Translate_group_1_stateChanged(ChangeEvent e) { + //Fixed_2.setEnabled(true); + //Fixed_3.setEnabled(true); + } + + public void Rotate_atom_1_stateChanged(ChangeEvent e) { + //Fixed_2.setEnabled(true); + //Fixed_3.setEnabled(true); + } + + public void undoLastSelection_actionPerformed(ActionEvent e) { + daddy.undoLastSelection(); + } + + public void Ok_actionPerformed(ActionEvent e) { + daddy.confirmChanges(); + } + + public void Reset_actionPerformed(ActionEvent e) { + daddy.resetGeometry(); + } + + public void currentAngle_actionPerformed(ActionEvent e) { + String new_value = currentAngle.getText(); + float value; + try { + value = Float.parseFloat(new_value); + } catch (NumberFormatException ex) { + JOptionPane.showMessageDialog(this, + "Wrong input for angle value: " + + currentAngle.getText(), + "Error", + JOptionPane.ERROR_MESSAGE); + currentAngle.setText(String.valueOf(oldAngle)); + return; + } + + // Second test + if (value < 0 || value > 180.0) { + JOptionPane.showMessageDialog(this, + "Angle value should be in the range from 0 to 180 degrees", + "Error", + JOptionPane.ERROR_MESSAGE); + currentAngle.setText(String.valueOf(oldAngle)); + + return; + } + + // -- now set slider + oldAngle = value; + setOnlySlider = true; + setSliderOnly(oldAngle); + modifyAngle(oldAngle); + setOnlySlider = false; + } + + public JButton getHelpButton() { + return helpButton; + } +} + +class JModifyAngleDialog_currentAngle_actionAdapter + implements ActionListener { + + private JModifyAngleDialog adaptee; + + JModifyAngleDialog_currentAngle_actionAdapter(JModifyAngleDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.currentAngle_actionPerformed(e); + } +} + +class JModifyAngleDialog_Reset_actionAdapter + implements ActionListener { + + private JModifyAngleDialog adaptee; + + JModifyAngleDialog_Reset_actionAdapter(JModifyAngleDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Reset_actionPerformed(e); + } +} + +class JModifyAngleDialog_Ok_actionAdapter + implements ActionListener { + + private JModifyAngleDialog adaptee; + + JModifyAngleDialog_Ok_actionAdapter(JModifyAngleDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Ok_actionPerformed(e); + } +} + +class JModifyAngleDialog_undoLastSelection_actionAdapter + implements ActionListener { + + private JModifyAngleDialog adaptee; + + JModifyAngleDialog_undoLastSelection_actionAdapter(JModifyAngleDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.undoLastSelection_actionPerformed(e); + } +} + +class JModifyAngleDialog_Rotate_atom_1_changeAdapter + implements ChangeListener { + + private JModifyAngleDialog adaptee; + + JModifyAngleDialog_Rotate_atom_1_changeAdapter(JModifyAngleDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.Rotate_atom_1_stateChanged(e); + } +} + +class JModifyAngleDialog_Fixed_3_changeAdapter + implements ChangeListener { + + private JModifyAngleDialog adaptee; + + JModifyAngleDialog_Fixed_3_changeAdapter(JModifyAngleDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.Fixed_3_stateChanged(e); + } +} + +class JModifyAngleDialog_Fixed_2_changeAdapter + implements ChangeListener { + + private JModifyAngleDialog adaptee; + + JModifyAngleDialog_Fixed_2_changeAdapter(JModifyAngleDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.Fixed_2_stateChanged(e); + } +} + +class JModifyAngleDialog_Fixed_1_changeAdapter + implements ChangeListener { + + private JModifyAngleDialog adaptee; + + JModifyAngleDialog_Fixed_1_changeAdapter(JModifyAngleDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.Fixed_1_stateChanged(e); + } +} + +class JModifyAngleDialog_Translate_group_1_changeAdapter + implements ChangeListener { + + private JModifyAngleDialog adaptee; + + JModifyAngleDialog_Translate_group_1_changeAdapter(JModifyAngleDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.Translate_group_1_stateChanged(e); + } +} + +class JModifyAngleDialog_changeAngle_changeAdapter + implements ChangeListener { + + private JModifyAngleDialog adaptee; + + JModifyAngleDialog_changeAngle_changeAdapter(JModifyAngleDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.changeAngle_stateChanged(e); + } +} + +class JModifyAngleDialog_Finish_actionAdapter + implements ActionListener { + + private JModifyAngleDialog adaptee; + + JModifyAngleDialog_Finish_actionAdapter(JModifyAngleDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Finish_actionPerformed(e); + } +} diff --git a/src/main/java/cct/dialogs/JModifyAtomDialog.java b/src/main/java/cct/dialogs/JModifyAtomDialog.java new file mode 100644 index 0000000..e9b0192 --- /dev/null +++ b/src/main/java/cct/dialogs/JModifyAtomDialog.java @@ -0,0 +1,564 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import cct.interfaces.GraphicsRendererInterface; +import cct.j3d.Java3dUniverse; +import cct.resources.images.ImageResources; + +import javax.swing.*; +import javax.swing.border.TitledBorder; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class JModifyAtomDialog + extends JDialog implements ActionListener { + + GraphicsRendererInterface renderer = null; + + // For reset + int originalElement = 0; + float originalRadius = 0.2f; + String originalLabel = ""; + String originalAtomType = ""; + int originalRed = 255; + int originalGreen = 255; + int originalBlue = 255; + Map originalAtomTypes = null; + JPanel P = new JPanel(); + JButton OK = new JButton(); + JButton Cancel = new JButton(); + JButton Reset = new JButton(); + + java.util.List buttons = new ArrayList(); + boolean internalUpdate = true; + Object daddy = null; + int oldElement = 0; + Color current_color = new Color(1, 1, 1); + JModifyAtomPanel jModifyAtomPanel1 = new JModifyAtomPanel(); + JAtomTypesPanel jAtomTypesPanel1 = new JAtomTypesPanel(this); + JPanel atomTypesPanel = new JPanel(); + JButton type_1_Button = new JButton(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + BorderLayout borderLayout1 = new BorderLayout(); + FlowLayout flowLayout1 = new FlowLayout(); + JButton type_2_Button = new JButton(); + static ImageIcon emptyIcon = new ImageIcon(ImageResources.class.getResource( + "icons48x48/emptyTransparent.png")); + JButton type_3_Button = new JButton(); + JButton type_4_Button = new JButton(); + JButton type_5_Button = new JButton(); + JButton type_6_Button = new JButton(); + JButton type_7_Button = new JButton(); + JButton helpButton = new JButton(); + static final Logger logger = Logger.getLogger(JModifyAtomDialog.class.getCanonicalName()); + + public JModifyAtomDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + this.pack(); + } + + public JModifyAtomDialog() { + this(new Frame(), "Modify Atoms", false); + } + + private void jbInit() throws Exception { + OK.setText("OK"); + OK.setHorizontalAlignment(SwingConstants.LEADING); + OK.setHorizontalTextPosition(SwingConstants.LEADING); + //OK.setVisible(false); + OK.setText("OK"); + OK.setVisible(false); + + Cancel.setText("Finish"); + Cancel.addActionListener(new JModifyAtomDialog_Cancel_actionAdapter(this)); + Reset.setText("Reset"); + Reset.addActionListener(new JModifyAtomDialog_Reset_actionAdapter(this)); + Reset.setVisible(true); + jAtomTypesPanel1.setBorder(new TitledBorder(BorderFactory. + createEtchedBorder(Color. + white, new Color(165, 163, 151)), "Available Atom Types")); + this.setDefaultCloseOperation(javax.swing.WindowConstants. + DO_NOTHING_ON_CLOSE); + this.getContentPane().setLayout(borderLayout1); + type_1_Button.setVisible(true); + type_1_Button.setPreferredSize(new Dimension(50, 50)); + type_1_Button.setToolTipText(""); + type_1_Button.setHorizontalTextPosition(SwingConstants.CENTER); + type_1_Button.setMargin(new Insets(0, 0, 0, 0)); + type_1_Button.setText("Atom"); + type_1_Button.addActionListener(new + JModifyAtomDialog_type_1_Button_actionAdapter(this)); + type_1_Button.setIcon(emptyIcon); + atomTypesPanel.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + type_2_Button.setPreferredSize(new Dimension(50, 50)); + type_2_Button.setToolTipText(""); + type_2_Button.setHorizontalTextPosition(SwingConstants.CENTER); + type_2_Button.setIcon(emptyIcon); + type_2_Button.setMargin(new Insets(0, 0, 0, 0)); + type_2_Button.setText("Atom"); + type_2_Button.addActionListener(new + JModifyAtomDialog_type_2_Button_actionAdapter(this)); + type_3_Button.setPreferredSize(new Dimension(50, 50)); + type_3_Button.setToolTipText(""); + type_3_Button.setHorizontalTextPosition(SwingConstants.CENTER); + type_3_Button.setMargin(new Insets(0, 0, 0, 0)); + type_3_Button.setText("Atom"); + type_3_Button.addActionListener(new + JModifyAtomDialog_type_3_Button_actionAdapter(this)); + type_3_Button.setIcon(emptyIcon); + type_4_Button.setPreferredSize(new Dimension(50, 50)); + type_4_Button.setToolTipText(""); + type_4_Button.setHorizontalTextPosition(SwingConstants.CENTER); + type_4_Button.setMargin(new Insets(0, 0, 0, 0)); + type_4_Button.setText("Atom"); + type_4_Button.addActionListener(new + JModifyAtomDialog_type_4_Button_actionAdapter(this)); + type_4_Button.setIcon(emptyIcon); + type_5_Button.setPreferredSize(new Dimension(50, 50)); + type_5_Button.setToolTipText(""); + type_5_Button.setHorizontalTextPosition(SwingConstants.CENTER); + type_5_Button.setMargin(new Insets(0, 0, 0, 0)); + type_5_Button.setText("Atom"); + type_5_Button.addActionListener(new + JModifyAtomDialog_type_5_Button_actionAdapter(this)); + type_5_Button.setIcon(emptyIcon); + type_6_Button.setPreferredSize(new Dimension(50, 50)); + type_6_Button.setToolTipText(""); + type_6_Button.setHorizontalTextPosition(SwingConstants.CENTER); + type_6_Button.setMargin(new Insets(0, 0, 0, 0)); + type_6_Button.setText("Atom"); + type_6_Button.addActionListener(new + JModifyAtomDialog_type_6_Button_actionAdapter(this)); + type_7_Button.setPreferredSize(new Dimension(50, 50)); + type_7_Button.setToolTipText(""); + type_7_Button.setHorizontalTextPosition(SwingConstants.CENTER); + type_7_Button.setMargin(new Insets(0, 0, 0, 0)); + type_7_Button.setText("Atom"); + type_7_Button.addActionListener(new + JModifyAtomDialog_type_7_Button_actionAdapter(this)); + helpButton.setEnabled(false); + helpButton.setToolTipText(""); + helpButton.setText("Help"); + //jModifyAtomPanel1.setLayout(gridBagLayout1); + P.add(OK); + P.add(Reset); + P.add(Cancel); + P.add(helpButton); + atomTypesPanel.add(type_1_Button); + atomTypesPanel.add(type_2_Button); + atomTypesPanel.add(type_3_Button); + atomTypesPanel.add(type_4_Button); + atomTypesPanel.add(type_5_Button); + atomTypesPanel.add(type_6_Button); + atomTypesPanel.add(type_7_Button); + this.getContentPane().add(P, BorderLayout.SOUTH); + this.getContentPane().add(atomTypesPanel, BorderLayout.CENTER); + this.getContentPane().add(jModifyAtomPanel1, BorderLayout.NORTH); + + buttons.add(type_1_Button); + buttons.add(type_2_Button); + buttons.add(type_3_Button); + buttons.add(type_4_Button); + buttons.add(type_5_Button); + buttons.add(type_6_Button); + buttons.add(type_7_Button); + for (int i = 1; i < buttons.size(); i++) { + JButton butt = (JButton) buttons.get(i); + butt.setVisible(false); + } + } + + public JButton getHelpButton() { + return helpButton; + } + + public void setTargetClass(Object target) { + daddy = target; + } + + public void selectElement(int elem) { + jModifyAtomPanel1.Element.setEnabled(false); + jModifyAtomPanel1.Element.setSelectedIndex(elem); + originalElement = elem; + jModifyAtomPanel1.Element.setEnabled(true); + logger.info(getClass().getCanonicalName() + ": select element: " + + elem); + } + + public void setLabel(String label) { + jModifyAtomPanel1.Label.setEnabled(false); + jModifyAtomPanel1.Label.setText(label); + originalLabel = label; + jModifyAtomPanel1.Label.setEnabled(true); + logger.info(getClass().getCanonicalName() + ": set label: " + + label); + } + + public void setElements(String[] elements) { + jModifyAtomPanel1.Element.setEnabled(false); + for (int i = 0; i < elements.length; i++) { + jModifyAtomPanel1.Element.addItem(elements[i]); + } + jModifyAtomPanel1.Element.setSelectedIndex(0); + jModifyAtomPanel1.Element.setEnabled(true); + + } + + public void setX(float x) { + //jModifyAtomPanel1.Xcoord.removeAllItems(); + jModifyAtomPanel1.Xcoord.setText(String.valueOf(x)); + } + + public void setY(float x) { + //jModifyAtomPanel1.Ycoord.removeAllItems(); + jModifyAtomPanel1.Ycoord.setText(String.valueOf(x)); + } + + public void setZ(float x) { + //jModifyAtomPanel1.Zcoord.removeAllItems(); + jModifyAtomPanel1.Zcoord.setText(String.valueOf(x)); + } + + public void setColor(Color c) { + setColor(c.getRed(), c.getGreen(), c.getBlue()); + } + + public void setAtomTypes(Map atomTypes) { + /* Old stuff + jAtomTypesPanel1.setAtomTypes(atomTypes); + */ + + int count = 0; + Set set = atomTypes.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String type = me.getKey().toString(); + ImageIcon image = (ImageIcon) me.getValue(); + + logger.info("Modifying old button: " + type); + JButton butt = (JButton) buttons.get(count); + butt.setIcon(image); + butt.setText(type); + butt.setActionCommand(type); + butt.setSelected(false); + butt.setEnabled(true); + butt.setVisible(true); + butt.validate(); + ++count; + } + + for (int i = count; i < buttons.size(); i++) { + JButton butt = (JButton) buttons.get(i); + butt.setVisible(false); + butt.validate(); + } + + originalAtomTypes = atomTypes; + } + + private void setSelectedAtomType(int n) { + internalUpdate = true; + jAtomTypesPanel1.setSelectedButton(n); + internalUpdate = false; + logger.info(getClass().getCanonicalName() + ": set atom type: " + + n); + } + + public void setSelectedAtomType(String atomType) { + internalUpdate = true; + + //jAtomTypesPanel1.setSelectedButton(atomType); + + for (int i = 0; i < buttons.size(); i++) { + JButton butt = (JButton) buttons.get(i); + if (!butt.isVisible()) { + break; + } + if (atomType.equalsIgnoreCase(butt.getActionCommand())) { + butt.setSelected(true); + butt.validate(); + } + else { + butt.setSelected(false); + butt.validate(); + } + } + + internalUpdate = false; + originalAtomType = atomType; + + logger.info(getClass().getCanonicalName() + ": set atom type: " + + atomType); + validate(); + } + + public void setColor(int red, int green, int blue) { + jModifyAtomPanel1.Red.setEnabled(false); + jModifyAtomPanel1.Green.setEnabled(false); + jModifyAtomPanel1.Blue.setEnabled(false); + + jModifyAtomPanel1.Red.setValue(red); + jModifyAtomPanel1.Green.setValue(green); + jModifyAtomPanel1.Blue.setValue(blue); + originalRed = red; + originalGreen = green; + originalBlue = blue; + + jModifyAtomPanel1.Red.setEnabled(true); + jModifyAtomPanel1.Green.setEnabled(true); + jModifyAtomPanel1.Blue.setEnabled(true); + } + + public void setRadius(float r) { + jModifyAtomPanel1.Radius.setEnabled(false); + jModifyAtomPanel1.Radius.setValue(r); + jModifyAtomPanel1.Radius.setEnabled(true); + originalRadius = r; + logger.info(getClass().getCanonicalName() + ": set radius: " + r); + } + + public void setGraphicsRenderer(GraphicsRendererInterface r) { + renderer = r; + jModifyAtomPanel1.setGraphicsRenderer(r); + } + + public void Cancel_actionPerformed(ActionEvent e) { + if (daddy instanceof Java3dUniverse) { + Java3dUniverse target = (Java3dUniverse) daddy; + target.endProcessingSelectedAtoms(); + setVisible(false); + } + } + + /** + * For listening the JAtomTypesPanel only + * @param actionEvent ActionEvent + */ + @Override + public void actionPerformed(ActionEvent actionEvent) { + if (internalUpdate) { + return; + } + internalUpdate = true; + String store = originalAtomType; + jAtomTypesPanel1.setSelectedButton(actionEvent.getActionCommand()); + originalAtomType = store; + renderer.setAtomTypeForSelectedAtoms(actionEvent.getActionCommand()); + internalUpdate = false; + } + + public void Reset_actionPerformed(ActionEvent e) { + renderer.setElementForSelectedAtoms(originalElement); + renderer.setColorForSelectedAtoms(new Color(originalRed, originalGreen, + originalBlue)); + renderer.setLabelForSelectedAtoms(originalLabel); + renderer.setRadiusForSelectedAtoms(originalRadius); + renderer.setAtomTypeForSelectedAtoms(originalAtomType); + setSelectedAtomType(originalAtomType); + validate(); + } + + public void typeButtons_actionPerformed(ActionEvent e) { + if (internalUpdate) { + return; + } + + for (int i = 0; i < buttons.size(); i++) { + JButton butt = (JButton) buttons.get(i); + if (!butt.isVisible()) { + break; + } + if (e.getActionCommand().equalsIgnoreCase(butt.getActionCommand())) { + butt.setSelected(true); + butt.validate(); + } + else { + butt.setSelected(false); + butt.validate(); + } + } + + renderer.setAtomTypeForSelectedAtoms(e.getActionCommand()); + } +} + +class JModifyAtomDialog_type_7_Button_actionAdapter + implements ActionListener { + private JModifyAtomDialog adaptee; + JModifyAtomDialog_type_7_Button_actionAdapter(JModifyAtomDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.typeButtons_actionPerformed(e); + } +} + +class JModifyAtomDialog_type_6_Button_actionAdapter + implements ActionListener { + private JModifyAtomDialog adaptee; + JModifyAtomDialog_type_6_Button_actionAdapter(JModifyAtomDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.typeButtons_actionPerformed(e); + } +} + +class JModifyAtomDialog_type_1_Button_actionAdapter + implements ActionListener { + private JModifyAtomDialog adaptee; + JModifyAtomDialog_type_1_Button_actionAdapter(JModifyAtomDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.typeButtons_actionPerformed(e); + } +} + +class JModifyAtomDialog_type_2_Button_actionAdapter + implements ActionListener { + private JModifyAtomDialog adaptee; + JModifyAtomDialog_type_2_Button_actionAdapter(JModifyAtomDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.typeButtons_actionPerformed(e); + } +} + +class JModifyAtomDialog_type_3_Button_actionAdapter + implements ActionListener { + private JModifyAtomDialog adaptee; + JModifyAtomDialog_type_3_Button_actionAdapter(JModifyAtomDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.typeButtons_actionPerformed(e); + } +} + +class JModifyAtomDialog_type_4_Button_actionAdapter + implements ActionListener { + private JModifyAtomDialog adaptee; + JModifyAtomDialog_type_4_Button_actionAdapter(JModifyAtomDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.typeButtons_actionPerformed(e); + } +} + +class JModifyAtomDialog_type_5_Button_actionAdapter + implements ActionListener { + private JModifyAtomDialog adaptee; + JModifyAtomDialog_type_5_Button_actionAdapter(JModifyAtomDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.typeButtons_actionPerformed(e); + } +} + +class JModifyAtomDialog_Reset_actionAdapter + implements ActionListener { + private JModifyAtomDialog adaptee; + JModifyAtomDialog_Reset_actionAdapter(JModifyAtomDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Reset_actionPerformed(e); + } +} + +class JModifyAtomDialog_Cancel_actionAdapter + implements ActionListener { + private JModifyAtomDialog adaptee; + JModifyAtomDialog_Cancel_actionAdapter(JModifyAtomDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Cancel_actionPerformed(e); + } +} diff --git a/src/main/java/cct/dialogs/JModifyAtomPanel.java b/src/main/java/cct/dialogs/JModifyAtomPanel.java new file mode 100644 index 0000000..6394144 --- /dev/null +++ b/src/main/java/cct/dialogs/JModifyAtomPanel.java @@ -0,0 +1,462 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import cct.interfaces.AtomInterface; +import cct.interfaces.GraphicsRendererInterface; +import cct.j3d.ChemicalElementsColors; +import cct.modelling.ChemicalElements; +import org.scijava.vecmath.Color3f; + +import javax.swing.*; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class JModifyAtomPanel + extends JPanel { + + GraphicsRendererInterface renderer = null; + Color colorBuffer = new Color(0, 0, 0); + + JPanel jPanel1 = new JPanel(); + JLabel jLabel1 = new JLabel(); + JComboBox Element = new JComboBox(ChemicalElements.getAllElements()); + JLabel jLabel2 = new JLabel(); + JTextField Label = new JTextField(); + FlowLayout flowLayout1 = new FlowLayout(); + JPanel jPanel2 = new JPanel(); + JTextField Zcoord = new JTextField(); + JLabel Z = new JLabel(); + FlowLayout flowLayout2 = new FlowLayout(); + JTextField Ycoord = new JTextField(); + JTextField Xcoord = new JTextField(); + JLabel Y = new JLabel(); + JLabel X = new JLabel(); + JPanel jPanel3 = new JPanel(); + FlowLayout flowLayout3 = new FlowLayout(); + JLabel jLabel3 = new JLabel(); + JLabel jLabel4 = new JLabel(); + JLabel jLabel5 = new JLabel(); + JButton Choose_color = new JButton(); + JLabel jLabel6 = new JLabel(); + + JSpinner Radius = new JSpinner(new SpinnerNumberModel(1.2, 0.01, 5.0, 0.1)); + JSpinner Red = new JSpinner(new SpinnerNumberModel(1, 0, 255, 1)); + JSpinner Green = new JSpinner(new SpinnerNumberModel(1, 0, 255, 1)); + JSpinner Blue = new JSpinner(new SpinnerNumberModel(1, 0, 255, 1)); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + + public JModifyAtomPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(gridBagLayout1); + jLabel1.setHorizontalTextPosition(SwingConstants.LEFT); + jLabel1.setText("Element: "); + jLabel2.setPreferredSize(new Dimension(50, 15)); + jLabel2.setHorizontalAlignment(SwingConstants.RIGHT); + jLabel2.setHorizontalTextPosition(SwingConstants.RIGHT); + jLabel2.setText("Label: "); + Element.setMinimumSize(new Dimension(48, 40)); + Element.setPreferredSize(new Dimension(60, 19)); + Element.setEditable(false); + Element.addItemListener(new JModifyAtomPanel_Element_itemAdapter(this)); + Element.setToolTipText("Select Element Symbol"); + jPanel1.setLayout(flowLayout1); + jPanel1.setMinimumSize(new Dimension(376, 30)); + jPanel1.setPreferredSize(new Dimension(372, 30)); + flowLayout1.setAlignment(FlowLayout.LEFT); + Label.setPreferredSize(new Dimension(80, 19)); + Label.setToolTipText("Type Atom\'s Name and Press Enter"); + Label.addActionListener(new JModifyAtomPanel_Label_actionAdapter(this)); + Z.setHorizontalAlignment(SwingConstants.RIGHT); + Z.setHorizontalTextPosition(SwingConstants.RIGHT); + Z.setText("Z: "); + jPanel2.setLayout(flowLayout2); + flowLayout2.setAlignment(FlowLayout.LEFT); + Zcoord.setEnabled(false); + Zcoord.setPreferredSize(new Dimension(100, 19)); + Zcoord.setToolTipText("Z-coordinate"); + Ycoord.setEnabled(false); + Ycoord.setPreferredSize(new Dimension(100, 19)); + Ycoord.setToolTipText("Y-coordinate"); + Xcoord.setEnabled(false); + Xcoord.setPreferredSize(new Dimension(100, 19)); + Xcoord.setToolTipText("X-coordinate"); + Y.setHorizontalAlignment(SwingConstants.RIGHT); + Y.setHorizontalTextPosition(SwingConstants.RIGHT); + Y.setText("Y: "); + X.setHorizontalAlignment(SwingConstants.RIGHT); + X.setHorizontalTextPosition(SwingConstants.RIGHT); + X.setText("X: "); + jPanel3.setLayout(flowLayout3); + jLabel3.setText("Color: Red: "); + jLabel4.setText("Green: "); + jLabel5.setText("Blue: "); + flowLayout3.setAlignment(FlowLayout.LEFT); + Choose_color.setText("Choose Color"); + Choose_color.addActionListener(new + JModifyAtomPanel_Choose_color_actionAdapter(this)); + jLabel6.setText("Radius: "); + jLabel6.setPreferredSize(new Dimension(50, 15)); + jLabel6.setHorizontalAlignment(SwingConstants.RIGHT); + jLabel6.setHorizontalTextPosition(SwingConstants.RIGHT); + Red.addChangeListener(new JModifyAtomPanel_Red_changeAdapter(this)); + Green.addChangeListener(new JModifyAtomPanel_Green_changeAdapter(this)); + Blue.addChangeListener(new JModifyAtomPanel_Blue_changeAdapter(this)); + Radius.addChangeListener(new JModifyAtomPanel_Radius_changeAdapter(this)); + jPanel1.add(jLabel1, null); + jPanel1.add(Element, null); + jPanel1.add(jLabel2, null); + jPanel1.add(Label, null); + jPanel1.add(jLabel6); + jPanel1.add(Radius); + jPanel2.add(X); + jPanel2.add(Xcoord); + jPanel2.add(Y); + jPanel2.add(Ycoord); + jPanel2.add(Z); + jPanel2.add(Zcoord); + + jPanel3.add(jLabel3); + jPanel3.add(Red); + jPanel3.add(jLabel4); + jPanel3.add(Green); + jPanel3.add(jLabel5); + jPanel3.add(Blue); + jPanel3.add(Choose_color); + + this.add(jPanel2, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.BOTH, + new Insets(0, 0, 0, 0), 0, 0)); + this.add(jPanel3, new GridBagConstraints(0, 2, 1, 1, 1.0, 1.0 + , GridBagConstraints.CENTER, + GridBagConstraints.BOTH, + new Insets(0, 0, 0, 0), 0, 0)); + this.add(jPanel1, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.BOTH, + new Insets(0, 0, 0, 0), 0, 0)); + } + + public void jComboBox1_actionPerformed(ActionEvent e) { + + } + + public void setGraphicsRenderer(GraphicsRendererInterface r) { + renderer = r; + } + + public void Element_itemStateChanged(ItemEvent e) { + if (renderer == null) { + showRendererError(); + return; + } + if (e.getStateChange() == ItemEvent.DESELECTED) { + return; + } + + if (!Element.isEnabled()) { + return; + } + Element.setEnabled(false); + int element = Element.getSelectedIndex(); + this.Label.setText(ChemicalElements.getElementSymbol(element)); + Double radius = new Double(ChemicalElements.getCovalentRadius(element)); + radius *= AtomInterface.COVALENT_TO_GRADIUS_FACTOR; + + renderer.setElementForSelectedAtoms(element); + renderer.setLabelForSelectedAtoms(ChemicalElements.getElementSymbol(element)); + + //Radius.setEnabled(false); + SpinnerNumberModel smodel = (SpinnerNumberModel) Radius.getModel(); + if (smodel.getMaximum().compareTo(radius) >= 0 && smodel.getMinimum().compareTo(radius) <= 0) { + smodel.setValue(radius); + } + + Red.setEnabled(false); + Green.setEnabled(false); + Blue.setEnabled(false); + + Color3f color = ChemicalElementsColors.getElementColor(element); + Color new_color = new Color(color.x, color.y, color.z); + renderer.setColorForSelectedAtoms(new_color); + + Red.setValue(new_color.getRed()); + Green.setValue(new_color.getGreen()); + Blue.setValue(new_color.getBlue()); + + Red.setEnabled(true); + Green.setEnabled(true); + Blue.setEnabled(true); + + //smodel.getValue(); + //Radius.setEnabled(true); + + Element.setEnabled(true); + } + + void showRendererError() { + JOptionPane.showMessageDialog(this, + "Internal ERROR: Graphis Renderer is not set!", + "Error", + JOptionPane.ERROR_MESSAGE); + } + + public void Choose_color_actionPerformed(ActionEvent e) { + if (renderer == null) { + showRendererError(); + return; + } + + Red.setEnabled(false); + Green.setEnabled(false); + Blue.setEnabled(false); + + Color c; + + String red = Red.getValue().toString(); + String green = Green.getValue().toString(); + String blue = Blue.getValue().toString(); + + Color initialColor = new Color(Integer.parseInt(red), + Integer.parseInt(green), + Integer.parseInt(blue)); + + c = JColorChooser.showDialog(this.getParent(), "Choose Atom Color", + initialColor); + if (c != null) { + + renderer.setColorForSelectedAtoms(c); + + Red.setValue(c.getRed()); + Green.setValue(c.getGreen()); + Blue.setValue(c.getBlue()); + } + + Red.setEnabled(true); + Green.setEnabled(true); + Blue.setEnabled(true); + + } + + private void changeColor() { + String red = Red.getValue().toString(); + String green = Green.getValue().toString(); + String blue = Blue.getValue().toString(); + + Color c = new Color(Integer.parseInt(red), + Integer.parseInt(green), + Integer.parseInt(blue)); + renderer.setColorForSelectedAtoms(c); + validate(); + } + + public void Red_stateChanged(ChangeEvent e) { + if (!Red.isEnabled()) { + return; + } + if (renderer == null) { + showRendererError(); + return; + } + changeColor(); + } + + public void Green_stateChanged(ChangeEvent e) { + if (!Green.isEnabled()) { + return; + } + if (renderer == null) { + showRendererError(); + return; + } + changeColor(); + } + + public void Blue_stateChanged(ChangeEvent e) { + if (!Blue.isEnabled()) { + return; + } + if (renderer == null) { + showRendererError(); + return; + } + changeColor(); + } + + public void Label_actionPerformed(ActionEvent e) { + if (!Label.isEnabled()) { + return; + } + if (renderer == null) { + showRendererError(); + return; + } + renderer.setLabelForSelectedAtoms(Label.getText()); + validate(); + } + + public void Radius_stateChanged(ChangeEvent e) { + if (!Radius.isEnabled()) { + return; + } + + Radius.setEnabled(false); + float radius = Float.parseFloat(Radius.getValue().toString()); + Radius.setEnabled(true); + renderer.setRadiusForSelectedAtoms(radius); + validate(); + } + + private class JModifyAtomPanel_Label_actionAdapter + implements ActionListener { + private JModifyAtomPanel adaptee; + JModifyAtomPanel_Label_actionAdapter(JModifyAtomPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Label_actionPerformed(e); + } + } + + private class JModifyAtomPanel_Radius_changeAdapter + implements ChangeListener { + private JModifyAtomPanel adaptee; + JModifyAtomPanel_Radius_changeAdapter(JModifyAtomPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.Radius_stateChanged(e); + } + } + +} + +class JModifyAtomPanel_Blue_changeAdapter + implements ChangeListener { + private JModifyAtomPanel adaptee; + JModifyAtomPanel_Blue_changeAdapter(JModifyAtomPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.Blue_stateChanged(e); + } +} + +class JModifyAtomPanel_Choose_color_actionAdapter + implements ActionListener { + private JModifyAtomPanel adaptee; + JModifyAtomPanel_Choose_color_actionAdapter(JModifyAtomPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Choose_color_actionPerformed(e); + } +} + +class JModifyAtomPanel_Red_changeAdapter + implements ChangeListener { + private JModifyAtomPanel adaptee; + JModifyAtomPanel_Red_changeAdapter(JModifyAtomPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.Red_stateChanged(e); + } +} + +class JModifyAtomPanel_Green_changeAdapter + implements ChangeListener { + private JModifyAtomPanel adaptee; + JModifyAtomPanel_Green_changeAdapter(JModifyAtomPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.Green_stateChanged(e); + } +} + +class JModifyAtomPanel_Element_itemAdapter + implements ItemListener { + private JModifyAtomPanel adaptee; + JModifyAtomPanel_Element_itemAdapter(JModifyAtomPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void itemStateChanged(ItemEvent e) { + adaptee.Element_itemStateChanged(e); + } +} diff --git a/src/main/java/cct/dialogs/JModifyAtomPanel.jbx b/src/main/java/cct/dialogs/JModifyAtomPanel.jbx new file mode 100644 index 0000000..6e493a3 --- /dev/null +++ b/src/main/java/cct/dialogs/JModifyAtomPanel.jbx @@ -0,0 +1,35 @@ +[PropertyInfo] +Blue,javax.swing.JSpinner,false,false, , ,false, +Choose_color,javax.swing.JButton,false,false, , ,false, +colorBuffer,java.awt.Color,false,false, , ,false, +Element,javax.swing.JComboBox,false,false, , ,false, +flowLayout1,java.awt.FlowLayout,false,false, , ,false, +flowLayout2,java.awt.FlowLayout,false,false, , ,false, +flowLayout3,java.awt.FlowLayout,false,false, , ,false, +graphicsRenderer,cct.interfaces.GraphicsRendererInterface,false,false, , ,true, +Green,javax.swing.JSpinner,false,false, , ,false, +gridBagLayout1,java.awt.GridBagLayout,false,false, , ,false, +JLabel1,javax.swing.JLabel,false,false, , ,false, +JLabel2,javax.swing.JLabel,false,false, , ,false, +JLabel3,javax.swing.JLabel,false,false, , ,false, +JLabel4,javax.swing.JLabel,false,false, , ,false, +JLabel5,javax.swing.JLabel,false,false, , ,false, +JLabel6,javax.swing.JLabel,false,false, , ,false, +JPanel1,javax.swing.JPanel,false,false, , ,false, +JPanel2,javax.swing.JPanel,false,false, , ,false, +JPanel3,javax.swing.JPanel,false,false, , ,false, +Label,javax.swing.JTextField,false,false, , ,false, +Radius,javax.swing.JSpinner,false,false, , ,false, +Red,javax.swing.JSpinner,false,false, , ,false, +renderer,cct.interfaces.GraphicsRendererInterface,false,false, , ,false, +X,javax.swing.JLabel,false,false, , ,false, +Xcoord,javax.swing.JTextField,false,false, , ,false, +Y,javax.swing.JLabel,false,false, , ,false, +Ycoord,javax.swing.JTextField,false,false, , ,false, +Z,javax.swing.JLabel,false,false, , ,false, +Zcoord,javax.swing.JTextField,false,false, , ,false, +[IconNames] + + + + diff --git a/src/main/java/cct/dialogs/JModifyBondDialog.java b/src/main/java/cct/dialogs/JModifyBondDialog.java new file mode 100644 index 0000000..0b2b10f --- /dev/null +++ b/src/main/java/cct/dialogs/JModifyBondDialog.java @@ -0,0 +1,706 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.dialogs; + +import cct.interfaces.MoleculeInterface; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.GridLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; + +import javax.swing.BorderFactory; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JSlider; +import javax.swing.JTextField; +import javax.swing.SwingConstants; +import javax.swing.border.TitledBorder; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +import cct.j3d.Java3dUniverse; +import cct.modelling.MolecularEditor; +import cct.modelling.Molecule; +import java.awt.Window; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import javax.swing.WindowConstants; + +/** + *

+ * Title: Picking

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005

+ * + *

+ * Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class JModifyBondDialog + extends JDialog { + + JPanel mainPanel = new JPanel(); + JPanel Displ_panel = new JPanel(); + ButtonGroup Atom_1 = new ButtonGroup(); + JRadioButton Fixed_1 = new JRadioButton(); + JRadioButton translateAtom_1 = new JRadioButton(); + JRadioButton translateGroup_1 = new JRadioButton(); + ButtonGroup Atom_2 = new ButtonGroup(); + JRadioButton translateGroup_2 = new JRadioButton(); + JRadioButton Fixed_2 = new JRadioButton(); + JRadioButton translateAtom_2 = new JRadioButton(); + JPanel Displace_1 = new JPanel(); + + JPanel Displace_2 = new JPanel(); + JPanel changeBondPanel = new JPanel(); + JSlider bondLengthSlider = new JSlider(); + JPanel bondInfoPanel = new JPanel(); + JLabel minBond = new JLabel(); + JLabel maxBond = new JLabel(); + JTextField currentBondLength = new JTextField(); + GridLayout gridLayout1 = new GridLayout(); + JLabel jLabel1 = new JLabel(); + JLabel jLabel2 = new JLabel(); + JPanel bondPanel = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JPanel buttonsPanel = new JPanel(); + JButton Cancel = new JButton(); + public JButton Help = new JButton(); + JButton Ok = new JButton(); + JCheckBox drawBond = new JCheckBox(); + + // --- My variables + MolecularEditor daddy = null; + float bondMin = 0.001f; + float bondMax = 10.0f; + float currentBond = 5.0f; + boolean setSlideOnly = false; + + // --- Store variables + float oldBondLength = 0.0f; + boolean oldDrawBond = true; + JPanel checkboxesPanel = new JPanel(); + JCheckBox instantView = new JCheckBox(); + GridLayout gridLayout2 = new GridLayout(); + JButton undoLastSelection = new JButton(); + JButton Reset = new JButton(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + GridBagLayout gridBagLayout2 = new GridBagLayout(); + BorderLayout borderLayout2 = new BorderLayout(); + BorderLayout borderLayout3 = new BorderLayout(); + GridBagLayout gridBagLayout3 = new GridBagLayout(); + + public JModifyBondDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + this.addWindowListener(new WindowAdapter() { + + @Override + public void windowClosing(WindowEvent we) { + CloseWindowGracefully(); + } + }); + //setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); + jbInit(); + pack(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JModifyBondDialog() { + this(new Frame(), "JModifyBondDialog", false); + try { + jbInit(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + private void jbInit() throws Exception { + mainPanel.setLayout(gridBagLayout3); + Fixed_1.setText("jRadioButton1"); + translateAtom_1.setToolTipText("Translate only Selected Atom"); + translateAtom_1.setText("Translate this Atom only"); + translateAtom_1.addChangeListener(new JModifyBondDialog_translateAtom_1_changeAdapter(this)); + translateGroup_1.setToolTipText("Translate Atom and Group it belongs to"); + translateGroup_1.setSelected(true); + translateGroup_1.setText("Translate group"); + translateGroup_1.addChangeListener(new JModifyBondDialog_translateGroup_1_changeAdapter(this)); + translateGroup_2.setToolTipText("Translate Atom and Group it belongs to"); + translateGroup_2.setSelected(true); + translateGroup_2.setText("Translate Group"); + translateGroup_2.addChangeListener(new JModifyBondDialog_translateGroup_2_changeAdapter(this)); + Fixed_2.setToolTipText("Keep Atom position fixed"); + Fixed_2.setText("Fixed Atom Position"); + Fixed_2.addChangeListener(new JModifyBondDialog_Fixed_2_changeAdapter(this)); + translateAtom_2.setToolTipText("Translate only Selected Atom"); + translateAtom_2.setText("Translate this Atom only"); + translateAtom_2.addChangeListener(new JModifyBondDialog_translateAtom_2_changeAdapter(this)); + Displace_1.setLayout(gridBagLayout2); + Fixed_1.setToolTipText("Keep Atom position fixed"); + Fixed_1.setActionCommand("Fixed_1"); + Fixed_1.setText("Fixed Atom Position"); + Fixed_1.addChangeListener(new JModifyBondDialog_Fixed_1_changeAdapter(this)); + Displace_2.setLayout(gridBagLayout1); + Displace_1.setBorder(new TitledBorder(BorderFactory.createLineBorder( + Color.lightGray, 1), "Atom 1 Displacement")); + Displace_2.setBorder(new TitledBorder(BorderFactory.createLineBorder( + Color.lightGray, 1), "Atom 2 Displacement")); + changeBondPanel.setLayout(borderLayout2); + bondLengthSlider.setMajorTickSpacing(10); + bondLengthSlider.setPaintLabels(false); + bondLengthSlider.setPaintTicks(true); + bondLengthSlider.setToolTipText("Drag the slider to update Bond Length"); + bondLengthSlider.addChangeListener(new JModifyBondDialog_bondLengthSlider_changeAdapter(this)); + //bondLengthSlider.addChangeListener(new + // JModifyBondDialog_bondLengthSlider_changeAdapter(this)); + bondInfoPanel.setLayout(gridLayout1); + minBond.setToolTipText("Minimal Bond Length Value"); + minBond.setHorizontalAlignment(SwingConstants.LEFT); + minBond.setText("0.0"); + maxBond.setToolTipText("Maximal Bond Length Available"); + maxBond.setHorizontalAlignment(SwingConstants.RIGHT); + maxBond.setText("10"); + currentBondLength.setText("5"); + currentBondLength.setToolTipText( + "Current Bond Length; Type and press Enter for Value"); + currentBondLength.setColumns(8); + currentBondLength.setHorizontalAlignment(SwingConstants.CENTER); + currentBondLength.addActionListener(new JModifyBondDialog_currentBondLength_actionAdapter(this)); + gridLayout1.setHgap(10); + jLabel1.setText(""); + jLabel2.setText(""); + bondPanel.setLayout(borderLayout3); + bondPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color.lightGray, 1), "Bond Length Control")); + bondPanel.setToolTipText( + "Bond Length Contols; For longer Bond Length type its value in textbox"); + Displ_panel.setLayout(borderLayout1); + Cancel.setToolTipText("Exit Bond Editing"); + Cancel.setText("Finish"); + Cancel.addActionListener(new JModifyBondDialog_Cancel_actionAdapter(this)); + Help.setEnabled(false); + Help.setText("Help"); + Ok.setText("Accept"); + Ok.setVisible(true); + Ok.setToolTipText("Accept Changes and start new selection"); + Ok.addActionListener(new JModifyBondDialog_Ok_actionAdapter(this)); + drawBond.setSelected(true); + drawBond.setText("Connect Atoms with Bond"); + drawBond.addChangeListener(new JModifyBondDialog_drawBond_changeAdapter(this)); + checkboxesPanel.setLayout(gridLayout2); + instantView.setToolTipText("See changes in bond length while drugging"); + instantView.setHorizontalAlignment(SwingConstants.RIGHT); + instantView.setSelected(true); + instantView.setText("Instant View"); + undoLastSelection.setToolTipText("Deselect last selected Atom"); + undoLastSelection.setText("Undo Last Selection"); + undoLastSelection.addActionListener(new JModifyBondDialog_undoLastSelection_actionAdapter(this)); + Reset.setToolTipText("Undo all editing"); + Reset.setText("Reset"); + Reset.addActionListener(new JModifyBondDialog_Reset_actionAdapter(this)); + getContentPane().add(mainPanel); + checkboxesPanel.add(drawBond, null); + checkboxesPanel.add(instantView); + buttonsPanel.add(Ok); + buttonsPanel.add(Reset); + buttonsPanel.add(Cancel); + buttonsPanel.add(undoLastSelection); + buttonsPanel.add(Help); + Displ_panel.add(Displace_2, BorderLayout.EAST); + Displ_panel.add(Displace_1, BorderLayout.WEST); + bondInfoPanel.add(minBond, null); + bondInfoPanel.add(jLabel1); + bondInfoPanel.add(currentBondLength, null); + bondInfoPanel.add(jLabel2); + bondInfoPanel.add(maxBond, null); + Atom_1.add(translateGroup_1); + Atom_1.add(translateAtom_1); + Atom_1.add(Fixed_1); + + Atom_2.add(translateGroup_2); + Atom_2.add(translateAtom_2); + Atom_2.add(Fixed_2); + Displace_2.add(translateGroup_2, + new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); //minBond.setText(String.valueOf(bondMin)); + Displace_2.add(translateAtom_2, + new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + Displace_2.add(Fixed_2, new GridBagConstraints(0, 2, 1, 1, 0.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + Displace_1.add(translateGroup_1, + new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + Displace_1.add(translateAtom_1, + new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + Displace_1.add(Fixed_1, new GridBagConstraints(0, 2, 1, 1, 0.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + changeBondPanel.add(bondLengthSlider, BorderLayout.NORTH); + bondPanel.add(changeBondPanel, BorderLayout.CENTER); + bondPanel.add(bondInfoPanel, BorderLayout.NORTH); + mainPanel.add(Displ_panel, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + mainPanel.add(checkboxesPanel, + new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + mainPanel.add(bondPanel, new GridBagConstraints(0, 2, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + mainPanel.add(buttonsPanel, new GridBagConstraints(0, 3, 1, 1, 1.0, 1.0, GridBagConstraints.NORTH, GridBagConstraints.BOTH, + new Insets(5, 5, 5, 5), 0, 0)); + setNewBondBounds(); + + } + + public void bondLengthSlider_stateChanged(ChangeEvent e) { + + //bondLengthSlider.removeChangeListener(bondLengthSlider_changeAdapter); + float value = bondLengthSlider.getValue(); + float max = bondLengthSlider.getMaximum(); + float min = bondLengthSlider.getMinimum(); + currentBond = bondMin + (value - min) / max * (bondMax - bondMin); + //logger.info("Value: "+value+" Curr Bond: "+currentBond+" min: "+min+" max: "+max); + + if (setSlideOnly) { + return; + } + + currentBondLength.setText(String.format("%8.4f", currentBond)); + + if (bondLengthSlider.getValueIsAdjusting() && !instantView.isSelected()) { //doing adjusting + + } else { //done adjusting + + setNewDistance(currentBond); + } + + } + + void setNewDistance(float new_bond) { + int I_status = 0; + if (translateAtom_1.isSelected()) { + I_status = 1; + } else if (translateGroup_1.isSelected()) { + I_status = 2; + } + + int J_status = 0; + if (translateAtom_2.isSelected()) { + J_status = 1; + } else if (translateGroup_2.isSelected()) { + J_status = 2; + } + + if (daddy instanceof Java3dUniverse) { + Java3dUniverse target = (Java3dUniverse) daddy; + target.changeDistanceBetweenSelectedAtoms(new_bond, I_status, J_status); + } + } + + public void setTargetClass(MolecularEditor target) { + daddy = target; + } + + public void setBondLenght(float length) { + setSlideOnly = true; + oldBondLength = length; + currentBond = length; + bondMax = currentBond * 2.0f; + setNewBondBounds(); + setSlideOnly = false; + } + + public void setDrawBond(boolean draw) { + drawBond.setSelected(draw); + } + + private void setNewBondBounds() { + maxBond.setText(String.valueOf(bondMax)); + currentBondLength.setText(String.valueOf(currentBond)); + setSlider(currentBond); + } + + private void setSlider(float value) { + boolean store = instantView.isSelected(); + instantView.setSelected(false); + bondLengthSlider.setValueIsAdjusting(true); + bondLengthSlider.setValue((int) (value / bondMax * 100.0f)); + bondLengthSlider.setValueIsAdjusting(false); + instantView.setSelected(store); + + //bondLengthSlider.setValue( (int) ( (value - bondMin) / bondMax * + // 100.0f)); + } + + public void Ok_actionPerformed(ActionEvent e) { + daddy.confirmChanges(); + } + + public void CloseWindowGracefully() { + daddy.endProcessingSelectedAtoms(); + setVisible(false); + + } + + public void Cancel_actionPerformed(ActionEvent e) { + CloseWindowGracefully(); + } + + public void Fixed_1_stateChanged(ChangeEvent e) { + if (Fixed_1.isSelected()) { + Fixed_2.setEnabled(false); + } else { + Fixed_2.setEnabled(true); + } + } + + public void Fixed_2_stateChanged(ChangeEvent e) { + if (Fixed_2.isSelected()) { + Fixed_1.setEnabled(false); + } else { + Fixed_1.setEnabled(true); + } + } + + public void translateGroup_2_itemStateChanged(ItemEvent e) { + if (translateGroup_2.isSelected()) { + Fixed_1.setEnabled(true); + } + } + + public void translateAtom_2_itemStateChanged(ItemEvent e) { + if (translateAtom_2.isSelected()) { + Fixed_1.setEnabled(true); + } + } + + public void drawBond_itemStateChanged(ItemEvent e) { + if (daddy instanceof Java3dUniverse) { + Java3dUniverse target = (Java3dUniverse) daddy; + target.drawBondBetweenSelectedAtoms(drawBond.isSelected()); + } + } + + public void translateAtom_1_stateChanged(ChangeEvent e) { + if (translateAtom_1.isSelected()) { + Fixed_2.setEnabled(true); + } + } + + public void translateGroup_1_stateChanged(ChangeEvent e) { + if (translateGroup_1.isSelected()) { + Fixed_2.setEnabled(true); + } + } + + public void translateGroup_2_stateChanged(ChangeEvent e) { + if (translateGroup_2.isSelected()) { + Fixed_1.setEnabled(true); + } + } + + public void translateAtom_2_stateChanged(ChangeEvent e) { + if (translateAtom_2.isSelected()) { + Fixed_1.setEnabled(true); + } + + } + + public void drawBond_stateChanged(ChangeEvent e) { + if (daddy instanceof Java3dUniverse) { + Java3dUniverse target = (Java3dUniverse) daddy; + target.drawBondBetweenSelectedAtoms(drawBond.isSelected()); + } + + } + + public void currentBondLength_actionPerformed(ActionEvent e) { + + String new_value = currentBondLength.getText(); + float value; + try { + value = Float.parseFloat(new_value); + } catch (NumberFormatException ex) { + + return; + } + + if (value >= bondMax) { + setBondLenght(value); + } else if (value < 0.001f) { + value = 0.001f; + } + + // -- now set slider + setSlideOnly = true; + setSlider(value); + setSlideOnly = false; + + setNewDistance(value); + //currentBondLength.setText(String.format("%8.4f", value)); + } + + public void undoLastSelection_actionPerformed(ActionEvent e) { + daddy.undoLastSelection(); + } + + public void Reset_actionPerformed(ActionEvent e) { + daddy.resetGeometry(); + setBondLenght(oldBondLength); + } +} + +class JModifyBondDialog_undoLastSelection_actionAdapter + implements ActionListener { + + private JModifyBondDialog adaptee; + + JModifyBondDialog_undoLastSelection_actionAdapter(JModifyBondDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.undoLastSelection_actionPerformed(e); + } +} + +class JModifyBondDialog_currentBondLength_actionAdapter + implements ActionListener { + + private JModifyBondDialog adaptee; + + JModifyBondDialog_currentBondLength_actionAdapter(JModifyBondDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + + adaptee.currentBondLength_actionPerformed(e); + } +} + +class JModifyBondDialog_drawBond_changeAdapter + implements ChangeListener { + + private JModifyBondDialog adaptee; + + JModifyBondDialog_drawBond_changeAdapter(JModifyBondDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.drawBond_stateChanged(e); + } +} + +class JModifyBondDialog_translateAtom_2_changeAdapter + implements ChangeListener { + + private JModifyBondDialog adaptee; + + JModifyBondDialog_translateAtom_2_changeAdapter(JModifyBondDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.translateAtom_2_stateChanged(e); + } +} + +class JModifyBondDialog_translateGroup_2_changeAdapter + implements ChangeListener { + + private JModifyBondDialog adaptee; + + JModifyBondDialog_translateGroup_2_changeAdapter(JModifyBondDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.translateGroup_2_stateChanged(e); + } +} + +class JModifyBondDialog_translateGroup_1_changeAdapter + implements ChangeListener { + + private JModifyBondDialog adaptee; + + JModifyBondDialog_translateGroup_1_changeAdapter(JModifyBondDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.translateGroup_1_stateChanged(e); + } +} + +class JModifyBondDialog_Fixed_2_changeAdapter + implements ChangeListener { + + private JModifyBondDialog adaptee; + + JModifyBondDialog_Fixed_2_changeAdapter(JModifyBondDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.Fixed_2_stateChanged(e); + } +} + +class JModifyBondDialog_Fixed_1_changeAdapter + implements ChangeListener { + + private JModifyBondDialog adaptee; + + JModifyBondDialog_Fixed_1_changeAdapter(JModifyBondDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.Fixed_1_stateChanged(e); + } +} + +class JModifyBondDialog_Cancel_actionAdapter + implements ActionListener { + + private JModifyBondDialog adaptee; + + JModifyBondDialog_Cancel_actionAdapter(JModifyBondDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Cancel_actionPerformed(e); + } +} + +class JModifyBondDialog_Ok_actionAdapter + implements ActionListener { + + private JModifyBondDialog adaptee; + + JModifyBondDialog_Ok_actionAdapter(JModifyBondDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Ok_actionPerformed(e); + } +} + +class JModifyBondDialog_Reset_actionAdapter + implements ActionListener { + + private JModifyBondDialog adaptee; + + JModifyBondDialog_Reset_actionAdapter(JModifyBondDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Reset_actionPerformed(e); + } +} + +// --- End of Class +class JModifyBondDialog_bondLengthSlider_changeAdapter + implements ChangeListener { + + private JModifyBondDialog adaptee; + + JModifyBondDialog_bondLengthSlider_changeAdapter(JModifyBondDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + + adaptee.bondLengthSlider_stateChanged(e); + } +} + +class JModifyBondDialog_translateAtom_1_changeAdapter + implements ChangeListener { + + private JModifyBondDialog adaptee; + + JModifyBondDialog_translateAtom_1_changeAdapter(JModifyBondDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.translateAtom_1_stateChanged(e); + } +} diff --git a/src/main/java/cct/dialogs/JModifyTorsionDialog.java b/src/main/java/cct/dialogs/JModifyTorsionDialog.java new file mode 100644 index 0000000..e1d6342 --- /dev/null +++ b/src/main/java/cct/dialogs/JModifyTorsionDialog.java @@ -0,0 +1,493 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JSlider; +import javax.swing.JTextField; +import javax.swing.SwingConstants; +import javax.swing.border.TitledBorder; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +import cct.modelling.MolecularEditor; +import cct.modelling.OperationsOnAtoms; + +/** + * + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class JModifyTorsionDialog + extends JDialog implements OperationsOnAtoms { + JPanel mainPanel = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JPanel displPanel = new JPanel(); + JPanel jAtom_1 = new JPanel(); + JPanel Atom_2 = new JPanel(); + ButtonGroup buttonGroup1 = new ButtonGroup(); + ButtonGroup buttonGroup2 = new ButtonGroup(); + JRadioButton Fixed_1 = new JRadioButton(); + JRadioButton rotateAtom_1 = new JRadioButton(); + JRadioButton rotateGroup_1 = new JRadioButton(); + JRadioButton rotateAtom_4 = new JRadioButton(); + JRadioButton rotateGroup_4 = new JRadioButton(); + JRadioButton Fixed_4 = new JRadioButton(); + BorderLayout borderLayout2 = new BorderLayout(); + GridLayout gridLayout1 = new GridLayout(); + BorderLayout borderLayout3 = new BorderLayout(); + JPanel buttonPanel = new JPanel(); + JButton Reset = new JButton(); + JButton Undo = new JButton(); + JButton Finish = new JButton(); + JButton OK_button = new JButton(); + JPanel centralPanel = new JPanel(); + JCheckBox instantView = new JCheckBox(); + JPanel sliderPanel = new JPanel(); + JSlider changeAngle = new JSlider(); + JPanel viewPanel = new JPanel(); + JPanel valuesPanel = new JPanel(); + GridLayout gridLayout2 = new GridLayout(); + FlowLayout flowLayout1 = new FlowLayout(); + GridLayout gridLayout3 = new GridLayout(); + JLabel jLabel1 = new JLabel(); + JLabel jLabel2 = new JLabel(); + JLabel jLabel3 = new JLabel(); + JLabel jLabel4 = new JLabel(); + JTextField angleValue = new JTextField(); + GridLayout gridLayout4 = new GridLayout(); + JPanel jPanel1 = new JPanel(); + BorderLayout borderLayout4 = new BorderLayout(); + + MolecularEditor daddy; + float oldAngle; + boolean setOnlySlider = false; + JButton helpButton = new JButton(); + + public JModifyTorsionDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JModifyTorsionDialog() { + this(new Frame(), "JModifyTorsionDialog", false); + } + + private void jbInit() throws Exception { + mainPanel.setLayout(borderLayout1); + jAtom_1.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color. + lightGray, 1), "Atom 1 Displacement")); + jAtom_1.setLayout(borderLayout2); + Atom_2.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color. + lightGray, 1), "Atom 4 Displacement")); + Atom_2.setLayout(borderLayout3); + Fixed_1.setText("Fixed"); + Fixed_1.addChangeListener(new JModifyTorsionDialog_Fixed_1_changeAdapter(this)); + rotateAtom_1.setToolTipText(""); + rotateAtom_1.setSelected(true); + rotateAtom_1.setText("Rotate Atom"); + rotateGroup_1.setToolTipText(""); + rotateGroup_1.setSelected(true); + rotateGroup_1.setText("Rotate Group"); + rotateAtom_4.setToolTipText(""); + rotateAtom_4.setSelected(false); + rotateAtom_4.setText("Rotate Atom"); + rotateGroup_4.setToolTipText(""); + rotateGroup_4.setSelected(true); + rotateGroup_4.setText("Rotate Group"); + Fixed_4.setText("Fixed"); + Fixed_4.addChangeListener(new JModifyTorsionDialog_Fixed_4_changeAdapter(this)); + displPanel.setLayout(gridLayout1); + Reset.setText("Reset"); + Reset.addActionListener(new JModifyTorsionDialog_Reset_actionAdapter(this)); + Undo.setText("Undo last selection"); + Undo.addActionListener(new JModifyTorsionDialog_Undo_actionAdapter(this)); + Finish.setToolTipText("Finish Editing"); + Finish.setText("Finish"); + Finish.addActionListener(new JModifyTorsionDialog_Finish_actionAdapter(this)); + OK_button.setText("Accept"); + OK_button.addActionListener(new + JModifyTorsionDialog_OK_button_actionAdapter(this)); + instantView.setHorizontalAlignment(SwingConstants.LEFT); + instantView.setSelected(true); + instantView.setText("Instant View"); + changeAngle.setMajorTickSpacing(10); + changeAngle.setMaximum(360); + changeAngle.setPaintTicks(true); + changeAngle.addChangeListener(new + JModifyTorsionDialog_changeAngle_changeAdapter(this)); + centralPanel.setLayout(gridLayout2); + gridLayout2.setColumns(1); + gridLayout2.setRows(3); + viewPanel.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + sliderPanel.setLayout(gridLayout3); + jLabel1.setToolTipText(""); + jLabel1.setHorizontalAlignment(SwingConstants.RIGHT); + jLabel1.setText("180 "); + jLabel1.setVerticalAlignment(SwingConstants.BOTTOM); + jLabel4.setText(" -180"); + jLabel4.setVerticalAlignment(SwingConstants.BOTTOM); + angleValue.setToolTipText("Torsional Angle Value"); + angleValue.setText("0.0"); + angleValue.setColumns(8); + angleValue.setHorizontalAlignment(SwingConstants.CENTER); + angleValue.addActionListener(new + JModifyTorsionDialog_angleValue_actionAdapter(this)); + valuesPanel.setLayout(gridLayout4); + jPanel1.setLayout(borderLayout4); + this.setDefaultCloseOperation(javax.swing.WindowConstants. + DO_NOTHING_ON_CLOSE); + helpButton.setEnabled(false); + helpButton.setToolTipText(""); + helpButton.setText("Help"); + getContentPane().add(mainPanel); + jAtom_1.add(rotateGroup_1, BorderLayout.NORTH); + jAtom_1.add(rotateAtom_1, BorderLayout.CENTER); + jAtom_1.add(Fixed_1, BorderLayout.SOUTH); + displPanel.add(jAtom_1, null); + displPanel.add(Atom_2, null); + buttonGroup1.add(rotateGroup_1); + Atom_2.add(rotateAtom_4, BorderLayout.CENTER); + buttonGroup1.add(rotateAtom_1); + buttonGroup1.add(Fixed_1); + Atom_2.add(Fixed_4, BorderLayout.SOUTH); + Atom_2.add(rotateGroup_4, BorderLayout.NORTH); + buttonGroup2.add(rotateAtom_4); + buttonGroup2.add(Fixed_4); + buttonGroup2.add(rotateGroup_4); + this.getContentPane().add(buttonPanel, BorderLayout.SOUTH); + buttonPanel.add(OK_button); + buttonPanel.add(Reset); + buttonPanel.add(Finish); + buttonPanel.add(Undo); + buttonPanel.add(helpButton); + this.getContentPane().add(centralPanel, BorderLayout.CENTER); + centralPanel.add(viewPanel, null); + viewPanel.add(instantView); + centralPanel.add(valuesPanel); + valuesPanel.add(jLabel4); + valuesPanel.add(jLabel2); + valuesPanel.add(jPanel1); + valuesPanel.add(jLabel3); + valuesPanel.add(jLabel1); + centralPanel.add(sliderPanel, null); + sliderPanel.add(changeAngle); + this.getContentPane().add(displPanel, BorderLayout.NORTH); + jPanel1.add(angleValue, BorderLayout.SOUTH); + } + + public void setTargetClass(MolecularEditor target) { + daddy = target; + } + + public void setAngle(double angle) { + setAngle( (float) angle); + } + + public void setAngle(float angle) { + + if (angle < -180.0f || angle > 180.0f) { + angle -= Math.floor( (angle + 180.0f) / 360.0f) * 360.0f - 180.f; + } + + oldAngle = angle; + setOnlySlider = true; + setTextAreaOnly(angle); + setSliderOnly(angle); + setOnlySlider = false; + } + + private void setTextAreaOnly(float value) { + angleValue.setText(String.format("%8.4f", value)); + } + + /** + * values should be always within -180 - 180 interval + * @param value float + */ + private void setSliderOnly(float value) { + boolean store = instantView.isSelected(); + instantView.setSelected(false); + changeAngle.setValueIsAdjusting(true); + float max = changeAngle.getMaximum(); + changeAngle.setValue( (int) ( (value + 180.0f) / 360.0f * max)); + changeAngle.setValueIsAdjusting(false); + instantView.setSelected(store); + } + + public void OK_button_actionPerformed(ActionEvent e) { + daddy.confirmChanges(); + } + + public void Undo_actionPerformed(ActionEvent e) { + daddy.undoLastSelection(); + } + + public void Reset_actionPerformed(ActionEvent e) { + daddy.resetGeometry(); + } + + public void Finish_actionPerformed(ActionEvent e) { + //daddy.processSelectedAtoms(); + daddy.endProcessingSelectedAtoms(); + setVisible(false); + } + + public void Fixed_1_stateChanged(ChangeEvent e) { + if (Fixed_1.isSelected()) { + Fixed_4.setEnabled(false); + } + else { + Fixed_4.setEnabled(true); + } + } + + public void Fixed_4_stateChanged(ChangeEvent e) { + if (Fixed_4.isSelected()) { + Fixed_1.setEnabled(false); + } + else { + Fixed_1.setEnabled(true); + } + } + + public void angleValue_actionPerformed(ActionEvent e) { + String new_value = angleValue.getText(); + float value; + try { + value = Float.parseFloat(new_value); + } + catch (NumberFormatException ex) { + JOptionPane.showMessageDialog(this, "Wrong input for dihedral angle value: " + angleValue.getText(), "Error", + JOptionPane.ERROR_MESSAGE); + angleValue.setText(String.valueOf(oldAngle)); + return; + } + + // -- now set slider + + oldAngle = value; + setOnlySlider = true; + setSliderOnly(oldAngle); + modifyAngle(oldAngle); + setOnlySlider = false; + + } + + public void modifyAngle(float angle) { + int I_status = FIXED_ATOM; + if (rotateGroup_1.isSelected()) { + I_status = ROTATE_GROUP; + } + else if (rotateAtom_1.isSelected()) { + I_status = ROTATE_ATOM; + } + + int L_status = FIXED_ATOM; + if (rotateGroup_4.isSelected()) { + L_status = ROTATE_GROUP; + } + else if (rotateAtom_4.isSelected()) { + L_status = ROTATE_ATOM; + } + + daddy.changeDihedralForSelectedAtoms(angle, I_status, L_status); + } + + public void changeAngle_stateChanged(ChangeEvent e) { + float value = changeAngle.getValue(); + float max = changeAngle.getMaximum(); + float min = changeAngle.getMinimum(); + oldAngle = (value - min) / max * 360.0f - 180.0f; + //logger.info("Value: "+value+" Curr Bond: "+currentBond+" min: "+min+" max: "+max); + + if (setOnlySlider) { + return; + } + + setTextAreaOnly(oldAngle); + + if (changeAngle.getValueIsAdjusting() && !instantView.isSelected()) { //doing adjusting + + } + else { //done adjusting + modifyAngle(oldAngle); + } + + } + + public JButton getHelpButton() { + return helpButton; + } +} + +class JModifyTorsionDialog_changeAngle_changeAdapter + implements ChangeListener { + private JModifyTorsionDialog adaptee; + JModifyTorsionDialog_changeAngle_changeAdapter(JModifyTorsionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.changeAngle_stateChanged(e); + } +} + +class JModifyTorsionDialog_angleValue_actionAdapter + implements ActionListener { + private JModifyTorsionDialog adaptee; + JModifyTorsionDialog_angleValue_actionAdapter(JModifyTorsionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.angleValue_actionPerformed(e); + } +} + +class JModifyTorsionDialog_Fixed_4_changeAdapter + implements ChangeListener { + private JModifyTorsionDialog adaptee; + JModifyTorsionDialog_Fixed_4_changeAdapter(JModifyTorsionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.Fixed_4_stateChanged(e); + } +} + +class JModifyTorsionDialog_Fixed_1_changeAdapter + implements ChangeListener { + private JModifyTorsionDialog adaptee; + JModifyTorsionDialog_Fixed_1_changeAdapter(JModifyTorsionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.Fixed_1_stateChanged(e); + } +} + +class JModifyTorsionDialog_Reset_actionAdapter + implements ActionListener { + private JModifyTorsionDialog adaptee; + JModifyTorsionDialog_Reset_actionAdapter(JModifyTorsionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Reset_actionPerformed(e); + } +} + +class JModifyTorsionDialog_Finish_actionAdapter + implements ActionListener { + private JModifyTorsionDialog adaptee; + JModifyTorsionDialog_Finish_actionAdapter(JModifyTorsionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Finish_actionPerformed(e); + } +} + +class JModifyTorsionDialog_Undo_actionAdapter + implements ActionListener { + private JModifyTorsionDialog adaptee; + JModifyTorsionDialog_Undo_actionAdapter(JModifyTorsionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Undo_actionPerformed(e); + } +} + +class JModifyTorsionDialog_OK_button_actionAdapter + implements ActionListener { + private JModifyTorsionDialog adaptee; + JModifyTorsionDialog_OK_button_actionAdapter(JModifyTorsionDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.OK_button_actionPerformed(e); + } +} diff --git a/src/main/java/cct/dialogs/JModifyTorsionDialog.jbx b/src/main/java/cct/dialogs/JModifyTorsionDialog.jbx new file mode 100644 index 0000000..fcec9d1 --- /dev/null +++ b/src/main/java/cct/dialogs/JModifyTorsionDialog.jbx @@ -0,0 +1,8 @@ +[PropertyInfo] +borderLayout1,java.awt.BorderLayout,false,false, , ,false, +panel1,javax.swing.JPanel,false,false, , ,false, +[IconNames] + + + + diff --git a/src/main/java/cct/dialogs/JMoleculeSelectorDialog.java b/src/main/java/cct/dialogs/JMoleculeSelectorDialog.java new file mode 100644 index 0000000..6fefa43 --- /dev/null +++ b/src/main/java/cct/dialogs/JMoleculeSelectorDialog.java @@ -0,0 +1,179 @@ +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.ListSelectionModel; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; + +import cct.interfaces.MoleculeSelectorInterface; +import cct.j3d.Java3dUniverse; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2009 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class JMoleculeSelectorDialog + extends JDialog { + public static final int OK = 0, CANCEL = 1; + private JPanel panel1 = new JPanel(); + private BorderLayout borderLayout1 = new BorderLayout(); + private JPanel graphicsPanel = new JPanel(); + private JPanel jPanel2 = new JPanel(); + private JButton helpButton = new JButton(); + private JButton cancelButton = new JButton(); + private JButton okButton = new JButton(); + private BorderLayout borderLayout2 = new BorderLayout(); + private JScrollPane jScrollPane1 = new JScrollPane(); + private JList molDescrList = new JList(); + + private MoleculeSelectorInterface moleculeSelector; + private Java3dUniverse java3d = null; + private int outcome = CANCEL; + + public JMoleculeSelectorDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JMoleculeSelectorDialog() { + this(new Frame(), "MoleculeSelectorDialog", false); + } + + public void set3DRenderer(Java3dUniverse j3d) { + if (java3d != null) { + graphicsPanel.remove(java3d.getCanvas3D()); + } + java3d = j3d; + java3d.getCanvas3D().setMaximumSize(new Dimension(300, 200)); + java3d.getCanvas3D().setPreferredSize(new Dimension(300, 200)); + graphicsPanel.add(java3d.getCanvas3D(), BorderLayout.CENTER); + this.validate(); + this.pack(); + } + + public void setMoleculeSelector(MoleculeSelectorInterface mSelector) { + moleculeSelector = mSelector; + int n = moleculeSelector.countMolecules(); + if (n < 1) { + System.err.println(this.getClass().getCanonicalName() + " : setMoleculeSelector: MoleculeSelector has no molecules..."); + return; + } + + molDescrList.removeAll(); + Object[] list = new Object[n]; + for (int i = 0; i < n; i++) { + try { + list[i] = moleculeSelector.getMoleculeDescription(i); + } + catch (Exception ex) {} + } + molDescrList.setListData(list); + molDescrList.setSelectedIndex(0); + update3DStructure(); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + helpButton.setToolTipText(""); + helpButton.setText(" Help "); + cancelButton.setToolTipText(""); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + cancelButton_actionPerformed(e); + } + }); + okButton.setToolTipText(""); + okButton.setText(" OK "); + okButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + okButton_actionPerformed(e); + } + }); + graphicsPanel.setLayout(borderLayout2); + jScrollPane1.setMaximumSize(new Dimension(32767, 100)); + jScrollPane1.setMinimumSize(new Dimension(0, 100)); + jScrollPane1.setPreferredSize(new Dimension(0, 100)); + molDescrList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + molDescrList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + molDescrList_valueChanged(e); + } + }); + graphicsPanel.setMinimumSize(new Dimension(200, 100)); + getContentPane().add(panel1); + panel1.add(graphicsPanel, BorderLayout.CENTER); + jScrollPane1.getViewport().add(molDescrList); + panel1.add(jPanel2, BorderLayout.SOUTH); + jPanel2.add(okButton); + jPanel2.add(cancelButton); + jPanel2.add(helpButton); + graphicsPanel.add(jScrollPane1, BorderLayout.SOUTH); + } + + public void molDescrList_valueChanged(ListSelectionEvent e) { + update3DStructure(); + } + + private void update3DStructure() { + int index = molDescrList.getSelectedIndex(); + if (index == -1) { + return; + } + try { + java3d.addMolecule(moleculeSelector.getMolecule(index)); + } + catch (Exception ex) {} + } + + public int showDialog() { + if (graphicsPanel.getSize().getHeight() < 200) { + graphicsPanel.setSize(graphicsPanel.getSize().width, 200); + } + this.pack(); + setVisible(true); + return outcome; + } + + public void okButton_actionPerformed(ActionEvent e) { + outcome = OK; + setVisible(false); + } + + public void cancelButton_actionPerformed(ActionEvent e) { + outcome = CANCEL; + setVisible(false); + } + + public int getSelectedIndex() { + return molDescrList.getSelectedIndex(); + } +} diff --git a/src/main/java/cct/dialogs/JQuickSelectionPanel.java b/src/main/java/cct/dialogs/JQuickSelectionPanel.java new file mode 100644 index 0000000..bc4bf4e --- /dev/null +++ b/src/main/java/cct/dialogs/JQuickSelectionPanel.java @@ -0,0 +1,112 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.GridLayout; +import java.awt.SystemColor; +import java.util.HashMap; +import java.util.Map; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JPanel; +import javax.swing.border.Border; +import javax.swing.border.TitledBorder; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class JQuickSelectionPanel + extends JPanel { + JButton Invert = new JButton(); + JButton Undo = new JButton(); + JButton Clear = new JButton(); + JButton All = new JButton(); + GridLayout gridLayout1 = new GridLayout(); + Border border1 = BorderFactory.createLineBorder(SystemColor.controlText, 1); + Border border2 = new TitledBorder(border1, "Quick Selection"); + + Map Controls = new HashMap(); + + public JQuickSelectionPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(gridLayout1); + Invert.setToolTipText("Invert Selection"); + Invert.setText("Invert"); + Undo.setEnabled(false); + Undo.setToolTipText("Undo last Selection"); + Undo.setText("Undo"); + Clear.setToolTipText("Clear Selection"); + Clear.setText("Clear"); + All.setToolTipText("Select all atoms"); + All.setText("All"); + this.setBorder(border2); + this.setToolTipText("Quick Selection Panel"); + this.add(All, null); + this.add(Clear, null); + this.add(Invert, null); + this.add(Undo, null); + + Controls.put("All", All); + Controls.put("Clear", Clear); + Controls.put("Invert", Invert); + Controls.put("Undo", Undo); + + } + + public Map getControls() { + return Controls; + } +} diff --git a/src/main/java/cct/dialogs/JSelectAtomTypesDialog.java b/src/main/java/cct/dialogs/JSelectAtomTypesDialog.java new file mode 100644 index 0000000..b7d80f8 --- /dev/null +++ b/src/main/java/cct/dialogs/JSelectAtomTypesDialog.java @@ -0,0 +1,219 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Arrays; +import java.util.Iterator; +import java.util.Set; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.border.TitledBorder; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class JSelectAtomTypesDialog + extends JDialog { + JPanel mainPanel = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JList Elements = new JList(); + JList atomNames = new JList(); + JPanel buttonPanel = new JPanel(); + JButton OK = new JButton(); + JButton Cancel = new JButton(); + JButton Help = new JButton(); + JPanel P1 = new JPanel(); + boolean okPressed = false; + GridLayout gridLayout1 = new GridLayout(); + JScrollPane jScrollPane1 = new JScrollPane(); + JScrollPane jScrollPane2 = new JScrollPane(); + + public JSelectAtomTypesDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JSelectAtomTypesDialog(String title, boolean modal) { + this(new Frame(), title, modal); + } + + public JSelectAtomTypesDialog() { + this(new Frame(), "JSelectAtomTypesDialog", false); + } + + private void jbInit() throws Exception { + mainPanel.setLayout(borderLayout1); + OK.setText("OK"); + OK.addActionListener(new JSelectAtomTypesDialog_OK_actionAdapter(this)); + Cancel.setText("Cancel"); + Cancel.addActionListener(new JSelectAtomTypesDialog_Cancel_actionAdapter(this)); + Help.setToolTipText(""); + Help.setText("Help"); + Elements.setBorder(BorderFactory.createEmptyBorder()); + Elements.setMaximumSize(new Dimension(0, 200)); + Elements.setVisibleRowCount(10); + atomNames.setBorder(BorderFactory.createEmptyBorder()); + atomNames.setMaximumSize(new Dimension(200, 200)); + atomNames.setVisibleRowCount(10); + this.setDefaultCloseOperation(javax.swing.WindowConstants. + DO_NOTHING_ON_CLOSE); + P1.setLayout(gridLayout1); + P1.setMaximumSize(new Dimension(32767, 200)); + gridLayout1.setColumns(2); + jScrollPane1.setBorder(new TitledBorder(BorderFactory.createLineBorder( + Color.lightGray, 1), "Atom Names")); + jScrollPane2.setBorder(new TitledBorder(BorderFactory.createLineBorder(new + Color(127, 157, 185), 1), "Elements")); + getContentPane().add(mainPanel); + buttonPanel.add(OK); + buttonPanel.add(Cancel); + buttonPanel.add(Help); + mainPanel.add(buttonPanel, BorderLayout.SOUTH); + mainPanel.add(P1, BorderLayout.NORTH); + P1.add(jScrollPane2); + jScrollPane2.getViewport().add(Elements); + P1.add(jScrollPane1); + jScrollPane1.getViewport().add(atomNames); + + } + + public void setupElements(Set elements) { + Elements.removeAll(); + Iterator i = elements.iterator(); + String el[] = new String[elements.size()]; + int count = 0; + while (i.hasNext()) { + el[count] = i.next(); + ++count; + } + Arrays.sort(el); + Elements.setListData(el); + Elements.updateUI(); + this.pack(); + } + + public void setupAtomNames(Set atom_names) { + atomNames.removeAll(); + Iterator i = atom_names.iterator(); + String el[] = new String[atom_names.size()]; + int count = 0; + while (i.hasNext()) { + el[count] = i.next(); + ++count; + } + Arrays.sort(el); + atomNames.setListData(el); + this.pack(); + } + + public void OK_actionPerformed(ActionEvent e) { + okPressed = true; + setVisible(false); + } + + public void Cancel_actionPerformed(ActionEvent e) { + okPressed = false; + setVisible(false); + } + + public boolean isOK() { + return okPressed; + } + + public Object[] getSelectedElements() { + return Elements.getSelectedValues(); + } + + public Object[] getSelectedAtomNames() { + return atomNames.getSelectedValues(); + } +} + +class JSelectAtomTypesDialog_Cancel_actionAdapter + implements ActionListener { + private JSelectAtomTypesDialog adaptee; + JSelectAtomTypesDialog_Cancel_actionAdapter(JSelectAtomTypesDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Cancel_actionPerformed(e); + } +} + +class JSelectAtomTypesDialog_OK_actionAdapter + implements ActionListener { + private JSelectAtomTypesDialog adaptee; + JSelectAtomTypesDialog_OK_actionAdapter(JSelectAtomTypesDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.OK_actionPerformed(e); + } +} diff --git a/src/main/java/cct/dialogs/JSelectMonomersDialog.java b/src/main/java/cct/dialogs/JSelectMonomersDialog.java new file mode 100644 index 0000000..6663d47 --- /dev/null +++ b/src/main/java/cct/dialogs/JSelectMonomersDialog.java @@ -0,0 +1,210 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Arrays; +import java.util.Iterator; +import java.util.Set; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JList; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.border.TitledBorder; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class JSelectMonomersDialog + extends JDialog { + JPanel mainPanel = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JPanel buttonsPanel = new JPanel(); + JButton Help = new JButton(); + JButton Cancel = new JButton(); + JButton OK = new JButton(); + JList Monomers = new JList(); + boolean okPressed = false; + Frame owner = null; + JScrollPane jScrollPane1 = new JScrollPane(); + + public JSelectMonomersDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + this.owner = owner; + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JSelectMonomersDialog(String title, boolean modal) { + this(new Frame(), title, modal); + } + + public JSelectMonomersDialog() { + this(new Frame(), "JSelectMonomersDialog", false); + } + + private void jbInit() throws Exception { + mainPanel.setLayout(borderLayout1); + this.setDefaultCloseOperation(javax.swing.WindowConstants. + DO_NOTHING_ON_CLOSE); + Help.setText("Help"); + Help.addActionListener(new JSelectMonomersDialog_Help_actionAdapter(this)); + Cancel.setText("Cancel"); + Cancel.addActionListener(new JSelectMonomersDialog_Cancel_actionAdapter(this)); + OK.setText("Ok"); + OK.addActionListener(new JSelectMonomersDialog_OK_actionAdapter(this)); + jScrollPane1.setBorder(new TitledBorder(BorderFactory.createLineBorder( + Color.lightGray, 1), "Monomers")); + getContentPane().add(mainPanel); + mainPanel.add(buttonsPanel, BorderLayout.SOUTH); + buttonsPanel.add(OK); + buttonsPanel.add(Cancel); + buttonsPanel.add(Help); + mainPanel.add(jScrollPane1, BorderLayout.NORTH); + jScrollPane1.getViewport().add(Monomers); + } + + public void OK_actionPerformed(ActionEvent e) { + okPressed = true; + setVisible(false); + } + + public void Cancel_actionPerformed(ActionEvent e) { + okPressed = false; + setVisible(false); + } + + public void Help_actionPerformed(ActionEvent e) { + if (owner == null) { + owner = new JFrame(); + } + JOptionPane.showMessageDialog(owner, + "Select Monomer(s) from the list\n" + + "For multiple selection use Shift and/or Ctrl keys", + "Help", + JOptionPane.INFORMATION_MESSAGE); + + } + + public void setupMonomers(Set elements) { + Monomers.removeAll(); + Iterator i = elements.iterator(); + String el[] = new String[elements.size()]; + int count = 0; + while (i.hasNext()) { + el[count] = i.next(); + ++count; + } + Arrays.sort(el); + Monomers.setListData(el); + //Monomers.updateUI(); + this.pack(); + } + + public boolean isOK() { + return okPressed; + } + + public Object[] getSelectedMonomers() { + return Monomers.getSelectedValues(); + } + +} + +class JSelectMonomersDialog_Help_actionAdapter + implements ActionListener { + private JSelectMonomersDialog adaptee; + JSelectMonomersDialog_Help_actionAdapter(JSelectMonomersDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Help_actionPerformed(e); + } +} + +class JSelectMonomersDialog_Cancel_actionAdapter + implements ActionListener { + private JSelectMonomersDialog adaptee; + JSelectMonomersDialog_Cancel_actionAdapter(JSelectMonomersDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Cancel_actionPerformed(e); + } +} + +class JSelectMonomersDialog_OK_actionAdapter + implements ActionListener { + private JSelectMonomersDialog adaptee; + JSelectMonomersDialog_OK_actionAdapter(JSelectMonomersDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.OK_actionPerformed(e); + } +} diff --git a/src/main/java/cct/dialogs/JSelectSubstructureDialog.java b/src/main/java/cct/dialogs/JSelectSubstructureDialog.java new file mode 100644 index 0000000..c262570 --- /dev/null +++ b/src/main/java/cct/dialogs/JSelectSubstructureDialog.java @@ -0,0 +1,217 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Iterator; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JList; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.border.TitledBorder; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class JSelectSubstructureDialog + extends JDialog { + JPanel mainPanel = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JScrollPane jScrollPane1 = new JScrollPane(); + JPanel buttonPanel = new JPanel(); + JButton Cancel = new JButton(); + JButton OK = new JButton(); + JButton Help = new JButton(); + JList Substructure = new JList(); + + boolean okPressed = true; + Frame owner = null; + + public JSelectSubstructureDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + this.owner = owner; + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JSelectSubstructureDialog(String title, boolean modal) { + this(new Frame(), title, modal); + } + + public JSelectSubstructureDialog() { + this(new Frame(), "JSelectSubstructureDialog", false); + } + + private void jbInit() throws Exception { + mainPanel.setLayout(borderLayout1); + this.setDefaultCloseOperation(javax.swing.WindowConstants. + DO_NOTHING_ON_CLOSE); + jScrollPane1.setBorder(new TitledBorder(BorderFactory.createLineBorder( + Color.lightGray, 1), "Substructure")); + Cancel.setToolTipText("Cancel Selection"); + Cancel.setText("Cancel"); + Cancel.addActionListener(new + JSelectSubstructureDialog_Cancel_actionAdapter(this)); + OK.setToolTipText("Confirm Selection"); + OK.setText("Ok"); + OK.addActionListener(new JSelectSubstructureDialog_OK_actionAdapter(this)); + Help.setToolTipText(""); + Help.setText("Help"); + Help.addActionListener(new JSelectSubstructureDialog_Help_actionAdapter(this)); + Substructure.setToolTipText(""); + Substructure.setVisibleRowCount(15); + getContentPane().add(mainPanel); + mainPanel.add(buttonPanel, BorderLayout.SOUTH); + buttonPanel.add(OK); + buttonPanel.add(Cancel); + buttonPanel.add(Help); + mainPanel.add(jScrollPane1, BorderLayout.NORTH); + jScrollPane1.getViewport().add(Substructure); + + } + + public void OK_actionPerformed(ActionEvent e) { + okPressed = true; + setVisible(false); + } + + public void Cancel_actionPerformed(ActionEvent e) { + okPressed = false; + setVisible(false); + } + + public void Help_actionPerformed(ActionEvent e) { + if (owner == null) { + owner = new JFrame(); + } + JOptionPane.showMessageDialog(owner, + "Select Monomer(s) from the list\n" + + "For multiple selection use Shift and/or Ctrl keys", + "Help", + JOptionPane.INFORMATION_MESSAGE); + } + + public void setupSubstructure(java.util.List elements) { + Substructure.removeAll(); + Iterator i = elements.iterator(); + String el[] = new String[elements.size()]; + int count = 0; + while (i.hasNext()) { + el[count] = i.next() + " " + String.valueOf(count + 1); + ++count; + } + //Arrays.sort(el); + Substructure.setListData(el); + //Monomers.updateUI(); + this.pack(); + } + + public boolean isOK() { + return okPressed; + } + + public int[] getSelectedMonomers() { + return Substructure.getSelectedIndices(); + } + +} + +class JSelectSubstructureDialog_Help_actionAdapter + implements ActionListener { + private JSelectSubstructureDialog adaptee; + JSelectSubstructureDialog_Help_actionAdapter(JSelectSubstructureDialog + adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Help_actionPerformed(e); + } +} + +class JSelectSubstructureDialog_Cancel_actionAdapter + implements ActionListener { + private JSelectSubstructureDialog adaptee; + JSelectSubstructureDialog_Cancel_actionAdapter(JSelectSubstructureDialog + adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Cancel_actionPerformed(e); + } +} + +class JSelectSubstructureDialog_OK_actionAdapter + implements ActionListener { + private JSelectSubstructureDialog adaptee; + JSelectSubstructureDialog_OK_actionAdapter(JSelectSubstructureDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.OK_actionPerformed(e); + } +} diff --git a/src/main/java/cct/dialogs/JSelectTreeDialog.java b/src/main/java/cct/dialogs/JSelectTreeDialog.java new file mode 100644 index 0000000..bcc24d0 --- /dev/null +++ b/src/main/java/cct/dialogs/JSelectTreeDialog.java @@ -0,0 +1,263 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTree; +import javax.swing.WindowConstants; +import javax.swing.event.TreeSelectionEvent; +import javax.swing.event.TreeSelectionListener; +import javax.swing.tree.DefaultMutableTreeNode; + +import cct.interfaces.TreeSelectorInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class JSelectTreeDialog + extends JFrame { + + TreeSelectorInterface parent = null; + JScrollPane jScrollPane1 = new JScrollPane(); + JPanel jPanel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JButton finishButton = new JButton(); + JButton addFragButton = new JButton(); + JButton helpButton = new JButton(); + JTree fragmentsTree = null; + Map referenceTable = new HashMap(); + String rootNodeName = ""; + + public JSelectTreeDialog(String title, String rootnodeName, Map fragTree, TreeSelectorInterface p) { + super(title); + parent = p; + rootNodeName = rootnodeName; + + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(fragTree); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + + } + + private void jbInit(Map fragTree) throws Exception { + + DefaultMutableTreeNode top = + new DefaultMutableTreeNode(rootNodeName); + createNodes(top, fragTree); + JTree jTree1 = new JTree(top); + //jTree1.setSelectionModel(TreeSelectionModel.SINGLE_TREE_SELECTION); + fragmentsTree = jTree1; + + jScrollPane1.setMinimumSize(new Dimension(300, 150)); + + //jScrollPane1. + this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); + this.getContentPane().setLayout(borderLayout1); + finishButton.setToolTipText(""); + finishButton.setText("Cancel"); + finishButton.addActionListener(new + JSelectTreeDialog_finishButton_actionAdapter(this)); + addFragButton.setText("Ok"); + addFragButton.addActionListener(new + JSelectTreeDialog_addFragButton_actionAdapter(this)); + helpButton.setEnabled(false); + helpButton.setToolTipText(""); + helpButton.setText("Help"); + jTree1.addTreeSelectionListener(new + JSelectTreeDialog_jTree1_treeSelectionAdapter(this)); + this.getContentPane().add(jScrollPane1, BorderLayout.CENTER); + this.getContentPane().add(jPanel1, BorderLayout.SOUTH); + jPanel1.add(addFragButton); + jPanel1.add(finishButton); + jPanel1.add(helpButton); + jScrollPane1.getViewport().add(jTree1); + } + + private void createNodes(DefaultMutableTreeNode top, Map fragTree) { + + DefaultMutableTreeNode lastDic = top; + + Set set = fragTree.entrySet(); + Iterator iter = set.iterator(); + + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String dicName = me.getKey().toString(); + Object obj = me.getValue(); + + if (obj instanceof Map) { + DefaultMutableTreeNode dictionary = new DefaultMutableTreeNode( + dicName); + top.add(dictionary); + //LinkedHashMap dic = (LinkedHashMap)obj; + createNodes(dictionary, (Map) obj); + lastDic = dictionary; + } + else if (obj instanceof String) { + DefaultMutableTreeNode fragment = new DefaultMutableTreeNode( + dicName); + lastDic.add(fragment); + String spec = (String) obj; + referenceTable.put(fragment, spec); + } + } + } + + public void setParent(TreeSelectorInterface p) { + parent = p; + } + + public void jTree1_valueChanged(TreeSelectionEvent e) { + /* + if (!fragmentsTree.isEnabled()) { + return; + } + fragmentsTree.setEnabled(false); + + DefaultMutableTreeNode node = (DefaultMutableTreeNode) fragmentsTree. + getLastSelectedPathComponent(); + if (node == null) { + return; + } + + Object nodeInfo = node.getUserObject(); + + if (node.isLeaf()) { + String spec = (String) referenceTable.get(node); + //java3d.loadFragment((String)nodeInfo ); + parent.getSelectedBranch(spec); + } + + fragmentsTree.setEnabled(true); + */ + } + + public void addFragButton_actionPerformed(ActionEvent e) { + DefaultMutableTreeNode node = (DefaultMutableTreeNode) fragmentsTree. + getLastSelectedPathComponent(); + if (node == null) { + JOptionPane.showMessageDialog(null, + "Select Item First!", + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + Object nodeInfo = node.getUserObject(); + + if (node.isLeaf()) { + String spec = (String) referenceTable.get(node); + //java3d.loadFragment((String)nodeInfo ); + setVisible(false); + parent.getSelectedBranch(spec); + } + + } + + public void finishButton_actionPerformed(ActionEvent e) { + setVisible(false); + parent.cancelTreeSelection(); + } + + class JSelectTreeDialog_finishButton_actionAdapter + implements ActionListener { + private JSelectTreeDialog adaptee; + JSelectTreeDialog_finishButton_actionAdapter(JSelectTreeDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.finishButton_actionPerformed(e); + } + } + + class JSelectTreeDialog_addFragButton_actionAdapter + implements ActionListener { + private JSelectTreeDialog adaptee; + JSelectTreeDialog_addFragButton_actionAdapter(JSelectTreeDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.addFragButton_actionPerformed(e); + } + } + + class JSelectTreeDialog_jTree1_treeSelectionAdapter + implements TreeSelectionListener { + private JSelectTreeDialog adaptee; + JSelectTreeDialog_jTree1_treeSelectionAdapter(JSelectTreeDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void valueChanged(TreeSelectionEvent e) { + adaptee.jTree1_valueChanged(e); + } + } + +} diff --git a/src/main/java/cct/dialogs/JSelectionRulePanel.java b/src/main/java/cct/dialogs/JSelectionRulePanel.java new file mode 100644 index 0000000..141a6b8 --- /dev/null +++ b/src/main/java/cct/dialogs/JSelectionRulePanel.java @@ -0,0 +1,112 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.SystemColor; +import java.util.HashMap; +import java.util.Map; + +import javax.swing.BorderFactory; +import javax.swing.ButtonGroup; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.border.Border; +import javax.swing.border.TitledBorder; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class JSelectionRulePanel + extends JPanel { + BorderLayout borderLayout1 = new BorderLayout(); + ButtonGroup buttonGroup1 = new ButtonGroup(); + JRadioButton Difference = new JRadioButton(); + JRadioButton Intersection = new JRadioButton(); + JRadioButton Union = new JRadioButton(); + Border border1 = BorderFactory.createLineBorder(SystemColor.controlText, 1); + Border border2 = new TitledBorder(border1, "Selection Rule"); + + Map Controls = new HashMap(); + + public JSelectionRulePanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + this.setBorder(border2); + this.setToolTipText(""); + Difference.setToolTipText("Subtract from Selection"); + Difference.setText("Difference"); + Intersection.setToolTipText("Intersect with Selection"); + Intersection.setText("Intersection"); + Union.setToolTipText("Add to Selection"); + Union.setSelected(true); + Union.setText("Union"); + this.add(Difference, BorderLayout.CENTER); + this.add(Intersection, BorderLayout.SOUTH); + this.add(Union, BorderLayout.NORTH); + + buttonGroup1.add(Difference); + buttonGroup1.add(Intersection); + buttonGroup1.add(Union); + + Controls.put("Difference", Difference); + Controls.put("Intersection", Intersection); + Controls.put("Union", Union); + } + + public Map getControls() { + return Controls; + } +} diff --git a/src/main/java/cct/dialogs/JSelectionTypePanel.java b/src/main/java/cct/dialogs/JSelectionTypePanel.java new file mode 100644 index 0000000..29721f7 --- /dev/null +++ b/src/main/java/cct/dialogs/JSelectionTypePanel.java @@ -0,0 +1,115 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.SystemColor; +import java.util.HashMap; +import java.util.Map; + +import javax.swing.BorderFactory; +import javax.swing.ButtonGroup; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.border.Border; +import javax.swing.border.TitledBorder; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class JSelectionTypePanel + extends JPanel { + BorderLayout borderLayout1 = new BorderLayout(); + ButtonGroup buttonGroup1 = new ButtonGroup(); + JRadioButton Atom = new JRadioButton(); + JRadioButton Monomer = new JRadioButton(); + JRadioButton Molecule = new JRadioButton(); + Border border1 = BorderFactory.createLineBorder(SystemColor.controlText, 2); + Border border2 = new TitledBorder(border1, "Selection"); + + Map Controls = new HashMap(); + Border border3 = BorderFactory.createLineBorder(SystemColor.controlText, 1); + Border border4 = new TitledBorder(border3, "Selection"); + + public JSelectionTypePanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + Atom.setToolTipText("Select Atom"); + Atom.setSelected(true); + Atom.setText("Atom"); + Monomer.setToolTipText("Select all atoms in monomer"); + Monomer.setText("Monomer"); + Molecule.setToolTipText("Select all atoms in Molecule"); + Molecule.setText("Molecule"); + this.setBorder(border4); + this.setToolTipText("Choose type of Selection"); + + buttonGroup1.add(Monomer); + buttonGroup1.add(Molecule); + buttonGroup1.add(Atom); + + this.add(Atom, BorderLayout.NORTH); + this.add(Monomer, BorderLayout.CENTER); + this.add(Molecule, BorderLayout.SOUTH); + + Controls.put("Atom", Atom); + Controls.put("Monomer", Monomer); + Controls.put("Molecule", Molecule); + } + + public Map getControls() { + return Controls; + } +} diff --git a/src/main/java/cct/dialogs/JSimpleAtomSelectionDialog.java b/src/main/java/cct/dialogs/JSimpleAtomSelectionDialog.java new file mode 100644 index 0000000..ccb454f --- /dev/null +++ b/src/main/java/cct/dialogs/JSimpleAtomSelectionDialog.java @@ -0,0 +1,179 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.WindowConstants; + +import cct.j3d.Java3dUniverse; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class JSimpleAtomSelectionDialog + extends JDialog implements ActionListener { + + JLabel message; + JButton OK, Cancel; + boolean OKpressed = false; + Object daddy = null; + + JPanel panel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + + public JSimpleAtomSelectionDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JSimpleAtomSelectionDialog() { + this(new Frame(), "JSimpleAtomSelectionDialog", false); + } + + private void jbInit() throws Exception { + + panel1.setBorder(BorderFactory.createEmptyBorder(10, 30, 10, 30)); + panel1.setLayout(borderLayout1); + + message = new JLabel("Your message is here ", + javax.swing.SwingConstants.CENTER); + //add(message, FlowLayout.CENTER ); + panel1.add(message, BorderLayout.CENTER); + + JPanel p = new JPanel(); + p.setLayout(new FlowLayout()); + OK = new JButton("OK"); + p.add(OK); + OK.addActionListener(this); + + Cancel = new JButton("Cancel"); + p.add(Cancel); + Cancel.addActionListener(this); + + //panel1.add(message, BorderLayout.NORTH ); + panel1.add(p, BorderLayout.SOUTH); + + getContentPane().add(panel1); + } + + @Override + public void actionPerformed(ActionEvent actionEvent) { + if (actionEvent.getSource() == OK) { + OKpressed = true; + //setVisible(false); + if (daddy instanceof Java3dUniverse) { + Java3dUniverse target = (Java3dUniverse) daddy; + target.enableMousePicking(false); + //target.processSelectedAtoms(); + target.endProcessingSelectedAtoms(); + } + else { + JOptionPane.showMessageDialog(this, + "Internal ERROR: JSimpleAtomSelectionDialog: Unknown instance!", + "Error", + JOptionPane.ERROR_MESSAGE); + + } + } + else if (actionEvent.getSource() == Cancel) { + OKpressed = false; + if (daddy instanceof Java3dUniverse) { + Java3dUniverse target = (Java3dUniverse) daddy; + target.selectAllAtoms(false); + target.enableMousePicking(false); + //target.processSelectedAtoms(); + target.endProcessingSelectedAtoms(); + } + else { + JOptionPane.showMessageDialog(this, + "Internal ERROR: JSimpleAtomSelectionDialog: Unknown instance!", + "Error", + JOptionPane.ERROR_MESSAGE); + + } + + //setVisible(false); + } + + } + + public void setTargetClass(Object parent) { + daddy = parent; + } + + public boolean pressedOK() { + return OKpressed; + } // May be used in modal dialog + + public void setMessage(String mess) { + message.setText(mess); + pack(); + } + + public void setOKVisible(boolean enable) { + OK.setVisible(enable); + } + +} diff --git a/src/main/java/cct/dialogs/JSolvateShellDialog.java b/src/main/java/cct/dialogs/JSolvateShellDialog.java new file mode 100644 index 0000000..bde10d7 --- /dev/null +++ b/src/main/java/cct/dialogs/JSolvateShellDialog.java @@ -0,0 +1,425 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import javax.swing.BorderFactory; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JTextField; +import javax.swing.SwingConstants; +import javax.swing.border.TitledBorder; + +import cct.modelling.ui.OpenFile; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class JSolvateShellDialog + extends JDialog { + boolean OK_pressed = false; + OpenFile openFile = null; + JPanel panel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JPanel solventPanel = new JPanel(); + JPanel paramPanel = new JPanel(); + JPanel buttonPanel = new JPanel(); + JButton jButton1 = new JButton(); + JButton jButton2 = new JButton(); + JButton SolvateButton = new JButton(); + JTextField jTextField1 = new JTextField(); + JLabel jLabel1 = new JLabel(); + FlowLayout flowLayout1 = new FlowLayout(); + JLabel jLabel2 = new JLabel(); + JTextField jTextField2 = new JTextField(); + JLabel jLabel3 = new JLabel(); + JLabel jLabel4 = new JLabel(); + JButton browseButton = new JButton(); + JComboBox jComboBox1 = new JComboBox(); + JRadioButton predefinedRadioButton = new JRadioButton(); + JRadioButton userDefinedRadioButton = new JRadioButton(); + ButtonGroup buttonGroup1 = new ButtonGroup(); + JTextField fileTextField = new JTextField(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + + Object[] customObjects = null; + + public JSolvateShellDialog(Frame owner, String title, boolean modal, + java.util.List simpleList) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + for (int i = 0; i < simpleList.size(); i++) { + jComboBox1.addItem(simpleList.get(i)); + } + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JSolvateShellDialog(Frame owner, String title, boolean modal, Map simpleList) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + + Set set = simpleList.entrySet(); + Iterator iter = set.iterator(); + + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String dicName = me.getKey().toString(); + jComboBox1.addItem(dicName); + } + + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + this.setDefaultCloseOperation(javax.swing.WindowConstants. + DO_NOTHING_ON_CLOSE); + jButton1.setEnabled(false); + jButton1.setToolTipText("Get Help about Solvation parameters"); + jButton1.setText("Help"); + jButton2.setToolTipText(""); + jButton2.setText("Cancel"); + jButton2.addActionListener(new JSolvateShellDialog_jButton2_actionAdapter(this)); + SolvateButton.setToolTipText(""); + SolvateButton.setText("Solvate"); + SolvateButton.addActionListener(new + JSolvateShellDialog_SolvateButton_actionAdapter(this)); + jTextField1.setToolTipText(""); + jTextField1.setText("1.0"); + jTextField1.setColumns(6); + jTextField1.setHorizontalAlignment(SwingConstants.CENTER); + jTextField1.addActionListener(new + JSolvateShellDialog_jTextField1_actionAdapter(this)); + jLabel1.setToolTipText(""); + jLabel1.setText(" Closeness: "); + paramPanel.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + flowLayout1.setVgap(15); + jLabel2.setToolTipText("Radius of Solvent Sphere"); + jLabel2.setText("Radius: "); + jTextField2.setToolTipText("Enter Radius of solvation and press Enter"); + jTextField2.setText("5.0"); + jTextField2.setColumns(6); + jTextField2.setHorizontalAlignment(SwingConstants.CENTER); + jTextField2.addActionListener(new + JSolvateShellDialog_jTextField2_actionAdapter(this)); + solventPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder( + Color.GRAY, 1), "Solvent")); + solventPanel.setLayout(gridBagLayout1); + jLabel3.setToolTipText(""); + jLabel3.setText(" User Defined: "); + jLabel4.setToolTipText(""); + jLabel4.setText("Predefined: "); + browseButton.setToolTipText(""); + browseButton.setText("Browse"); + browseButton.addActionListener(new JSolvateShellDialog_browseButton_actionAdapter(this)); + predefinedRadioButton.setToolTipText(""); + predefinedRadioButton.setSelected(true); + predefinedRadioButton.setText("Predefined"); + predefinedRadioButton.addItemListener(new JSolvateShellDialog_predefinedRadioButton_itemAdapter(this)); + userDefinedRadioButton.setToolTipText(""); + userDefinedRadioButton.setText("User Defined"); + fileTextField.setToolTipText(""); + fileTextField.setEditable(false); + fileTextField.setColumns(50); + getContentPane().add(panel1); + paramPanel.add(jLabel2); + paramPanel.add(jTextField2); + paramPanel.add(jLabel1); + paramPanel.add(jTextField1); + panel1.add(buttonPanel, BorderLayout.SOUTH); + buttonPanel.add(SolvateButton); + buttonPanel.add(jButton2); + buttonPanel.add(jButton1); + buttonGroup1.add(userDefinedRadioButton); + buttonGroup1.add(predefinedRadioButton); + solventPanel.add(fileTextField, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); + solventPanel.add(browseButton, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + solventPanel.add(jComboBox1, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + solventPanel.add(userDefinedRadioButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + solventPanel.add(predefinedRadioButton, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + solventPanel.add(jLabel4, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + solventPanel.add(jLabel3, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + panel1.add(paramPanel, BorderLayout.CENTER); + panel1.add(solventPanel, BorderLayout.NORTH); + + // --- My stuff + + jComboBox1.setEnabled(predefinedRadioButton.isSelected()); + fileTextField.setEnabled(!predefinedRadioButton.isSelected()); + browseButton.setEnabled(!predefinedRadioButton.isSelected()); + } + + public int getSelectedIndex() { + return jComboBox1.getSelectedIndex(); + } + + public Object getSelectedItem() { + return jComboBox1.getSelectedItem(); + } + + public String getCustomSolventFile() { + return fileTextField.getText().trim(); + } + + public JButton getHelpButton() { + return jButton1; + } + + public boolean isOKpressed() { + return OK_pressed; + } + + public boolean isPredefinedSolvent() { + return predefinedRadioButton.isSelected(); + } + + public float getCloseness() throws Exception { + return getFloat(jTextField1.getText()); + } + + public String getClosenessAsText() { + return jTextField1.getText(); + } + + public float getRadius() throws Exception { + return getFloat(jTextField2.getText()); + } + + public String getRadiusAsText() { + return jTextField2.getText(); + } + + public void jTextField2_actionPerformed(ActionEvent e) { + try { + getFloat(jTextField2.getText()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "ERROR: Wrong value for radius: " + + jTextField2.getText() + " " + + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + } + + float getFloat(String value) throws Exception { + float f = 0; + try { + f = Float.parseFloat(value.trim()); + } + catch (Exception ex) { + throw ex; + } + return f; + } + + public void jTextField1_actionPerformed(ActionEvent e) { + try { + getFloat(jTextField1.getText()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "ERROR: Wrong value for closeness: " + jTextField1.getText() + " " + + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + } + + } + + class JSolvateShellDialog_jTextField1_actionAdapter + implements ActionListener { + private JSolvateShellDialog adaptee; + JSolvateShellDialog_jTextField1_actionAdapter(JSolvateShellDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.jTextField1_actionPerformed(e); + } + } + + public void SolvateButton_actionPerformed(ActionEvent e) { + OK_pressed = true; + setVisible(false); + } + + public void jButton2_actionPerformed(ActionEvent e) { + OK_pressed = false; + setVisible(false); + } + + public void predefinedRadioButton_itemStateChanged(ItemEvent e) { + jComboBox1.setEnabled(predefinedRadioButton.isSelected()); + fileTextField.setEnabled(!predefinedRadioButton.isSelected()); + browseButton.setEnabled(!predefinedRadioButton.isSelected()); + } + + public Object[] getCustomObjects() { + return customObjects; + } + + public void browseButton_actionPerformed(ActionEvent e) { + if (openFile == null) { + openFile = new OpenFile(); + } + try { + customObjects = openFile.loadMolecule(null, null); + fileTextField.setText(openFile.getFileName()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error opening file: " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + } + } + + private class JSolvateShellDialog_jTextField2_actionAdapter + implements ActionListener { + private JSolvateShellDialog adaptee; + JSolvateShellDialog_jTextField2_actionAdapter(JSolvateShellDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.jTextField2_actionPerformed(e); + } + } + + private class JSolvateShellDialog_SolvateButton_actionAdapter + implements ActionListener { + private JSolvateShellDialog adaptee; + JSolvateShellDialog_SolvateButton_actionAdapter(JSolvateShellDialog + adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.SolvateButton_actionPerformed(e); + } + } + + private class JSolvateShellDialog_jButton2_actionAdapter + implements ActionListener { + private JSolvateShellDialog adaptee; + JSolvateShellDialog_jButton2_actionAdapter(JSolvateShellDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.jButton2_actionPerformed(e); + } + } + +} + +class JSolvateShellDialog_browseButton_actionAdapter + implements ActionListener { + private JSolvateShellDialog adaptee; + JSolvateShellDialog_browseButton_actionAdapter(JSolvateShellDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.browseButton_actionPerformed(e); + } +} + +class JSolvateShellDialog_predefinedRadioButton_itemAdapter + implements ItemListener { + private JSolvateShellDialog adaptee; + JSolvateShellDialog_predefinedRadioButton_itemAdapter(JSolvateShellDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void itemStateChanged(ItemEvent e) { + adaptee.predefinedRadioButton_itemStateChanged(e); + } + +} diff --git a/src/main/java/cct/dialogs/JSpecialSelectionPanel.java b/src/main/java/cct/dialogs/JSpecialSelectionPanel.java new file mode 100644 index 0000000..0326b4b --- /dev/null +++ b/src/main/java/cct/dialogs/JSpecialSelectionPanel.java @@ -0,0 +1,125 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.Dimension; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.util.HashMap; +import java.util.Map; + +import javax.swing.JButton; +import javax.swing.JPanel; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class JSpecialSelectionPanel + extends JPanel { + JButton Sets = new JButton(); + JButton substructure = new JButton(); + JButton monomer_types = new JButton(); + JButton Sphere_selection = new JButton(); + JButton atom_types = new JButton(); + + Map Controls = new HashMap(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + + public JSpecialSelectionPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(gridBagLayout1); + this.setMinimumSize(new Dimension(0, 0)); + Sets.setToolTipText("Select Atoms in Set(s)"); + Sets.setText("Sets"); + substructure.setToolTipText("Select Atoms in Substructure"); + substructure.setVerifyInputWhenFocusTarget(false); + substructure.setText("Substructure"); + monomer_types.setToolTipText("Select all Atoms of particular Monomers"); + monomer_types.setVerifyInputWhenFocusTarget(false); + monomer_types.setText("Monomer Types"); + Sphere_selection.setToolTipText( + "Select all Atoms within specified radius"); + Sphere_selection.setText("Sphere"); + atom_types.setToolTipText("Select Atoms of particular Type"); + atom_types.setText("Atom Types"); + this.add(atom_types, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(monomer_types, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(substructure, new GridBagConstraints(0, 2, 1, 1, 1.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(Sets, new GridBagConstraints(0, 3, 1, 1, 1.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(Sphere_selection, new GridBagConstraints(0, 4, 1, 1, 1.0, 1.0 + , GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + Controls.put("atom_types", atom_types); + Controls.put("monomer_types", monomer_types); + Controls.put("substructure", substructure); + Controls.put("Sets", Sets); + Controls.put("Sphere_selection", Sphere_selection); + } + + public Map getControls() { + return Controls; + } +} diff --git a/src/main/java/cct/dialogs/JThreeButtonsPanel.java b/src/main/java/cct/dialogs/JThreeButtonsPanel.java new file mode 100644 index 0000000..0b2b27c --- /dev/null +++ b/src/main/java/cct/dialogs/JThreeButtonsPanel.java @@ -0,0 +1,82 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.FlowLayout; + +import javax.swing.JButton; +import javax.swing.JPanel; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class JThreeButtonsPanel + extends JPanel { + FlowLayout flowLayout1 = new FlowLayout(); + public JButton OK = new JButton(); + public JButton Cancel = new JButton(); + public JButton Help = new JButton(); + + public JThreeButtonsPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(flowLayout1); + OK.setText("OK"); + Cancel.setText("Cancel"); + Help.setText("Help"); + this.add(OK); + add(Cancel); + add(Help); + } +} diff --git a/src/main/java/cct/dialogs/JamberooChangeEvent.java b/src/main/java/cct/dialogs/JamberooChangeEvent.java new file mode 100644 index 0000000..27bad79 --- /dev/null +++ b/src/main/java/cct/dialogs/JamberooChangeEvent.java @@ -0,0 +1,50 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.dialogs; + +import javax.swing.event.ChangeEvent; + +/** + * + * @author vvv900 + */ +public class JamberooChangeEvent extends ChangeEvent { + + public JamberooChangeEvent(Object source) { + super(source); + } +} diff --git a/src/main/java/cct/dialogs/JamberooCore.java b/src/main/java/cct/dialogs/JamberooCore.java new file mode 100644 index 0000000..ad81c27 --- /dev/null +++ b/src/main/java/cct/dialogs/JamberooCore.java @@ -0,0 +1,160 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.dialogs; + +import cct.GlobalSettings; +import cct.interfaces.GraphicsObjectInterface; +import cct.interfaces.HelperInterface; +import cct.interfaces.JamberooCoreInterface; +import cct.j3d.Java3dUniverse; +import cct.j3d.ui.GraphicsObjectPropertiesFrame; +import cct.tools.filebrowser.ShadowSFTPManager; +import java.awt.Component; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JOptionPane; + +/** + * + * @author vvv900 + */ +public class JamberooCore implements JamberooCoreInterface { + + static private HelperInterface helper = null; + private Java3dUniverse java3dUniverse = new Java3dUniverse(); + private GraphicsObjectPropertiesFrame gopDialog = null; + private AtomSelectionDialog jAtomSelectionDialog = null; + private ShadowSFTPManager shadowSFTPManager = null; + private Component componet = null; + + public Component getComponet() { + return componet; + } + + public void setComponet(Component componet) { + this.componet = componet; + } + + public ShadowSFTPManager getShadowSFTPManager() { + if (shadowSFTPManager == null) { + shadowSFTPManager = new ShadowSFTPManager(); + shadowSFTPManager.setExitOnAllClose(false); + } + return shadowSFTPManager; + } + + public Java3dUniverse getJamberooRenderer() { + return java3dUniverse; + } + + public HelperInterface getHelper() { + return helper; + } + + public void setHelper(HelperInterface helper) { + JamberooCore.helper = helper; + } + + public void updateGraphicsObjectsDialog() { + if (gopDialog != null) { + gopDialog.updateTree(); + } + } + + public void showGraphicsObjectsDialog(boolean visible) { + if (gopDialog == null) { + gopDialog = new GraphicsObjectPropertiesFrame(); + gopDialog.setIconImage(GlobalSettings.ICON_16x16_JAVA_FILE.getImage()); + if (componet != null) { + gopDialog.setLocationRelativeTo(componet); + } + } + if (helper != null) { + JButton h = gopDialog.getHelpButton(); + h.setEnabled(true); + helper.setHelpIDString(h, HelperInterface.JMD_MANAGE_GRAPHICS_OBJECTS_ID); + helper.displayHelpFromSourceActionListener(h); + } + java.util.List gops = java3dUniverse.getGraphicsObjects(); + gopDialog.setTree(gops); + gopDialog.setVisible(visible); + } + + public boolean setupAtomSelectionDialog(Java3dUniverse j3d, int jobType, int mode, + boolean select_and_process) { + + // --- Common for all selections + + if (j3d.getMoleculeInterface() == null) { + JOptionPane.showMessageDialog(null, "Load Molecule first!", "Warning", JOptionPane.WARNING_MESSAGE); + return false; + } + + if (j3d.getMousePickingStatus()) { + JOptionPane.showMessageDialog(null, "Another Selection is already in progress!", "Error", + JOptionPane.ERROR_MESSAGE); + return false; + } + + if (jAtomSelectionDialog == null) { + jAtomSelectionDialog = new AtomSelectionDialog(null, "Atom Selection", false); + jAtomSelectionDialog.setTargetClass(j3d); + //jAtomSelectionDialog.setLocationRelativeTo(); + if (helper != null) { + JButton h = jAtomSelectionDialog.getHelpButton(); + h.setEnabled(true); + helper.setHelpIDString(h, HelperInterface.JMD_SELECT_ATOMS_ID); + helper.displayHelpFromSourceActionListener(h); + } + } + + jAtomSelectionDialog.setNextDialog(null); + + j3d.enableMousePicking(true); + j3d.selectedMode = mode; + j3d.setJobType(jobType); + j3d.selectAndProcessDialog = select_and_process; + + return true; + } + + public void openAtomSelectionDialog(Java3dUniverse j3d, int jobType, + int mode, boolean select_and_process, JDialog nextDialog) { + + if (!setupAtomSelectionDialog(j3d, jobType, mode, select_and_process)) { + return; + } + + if (nextDialog != null) { + jAtomSelectionDialog.setNextDialog(nextDialog); + //nextDialog.setLocationRelativeTo(this); + } + + jAtomSelectionDialog.setVisible(true); + } + + public void openAtomSelectionDialog(Java3dUniverse j3d, int jobType, + int mode, boolean select_and_process) { + + if (!setupAtomSelectionDialog(j3d, jobType, mode, select_and_process)) { + return; + } + + jAtomSelectionDialog.setVisible(true); + } + + public void openAtomSelectionDialog(Java3dUniverse j3d, int jobType, int mode, boolean select_and_process, JComponent component) { + if (!setupAtomSelectionDialog(j3d, jobType, mode, select_and_process)) { + return; + } + + if (component != null) { + jAtomSelectionDialog.addUserComponent(component); + } + + jAtomSelectionDialog.setVisible(true); + } +} diff --git a/src/main/java/cct/dialogs/JamberooFrame.java b/src/main/java/cct/dialogs/JamberooFrame.java new file mode 100644 index 0000000..b240d88 --- /dev/null +++ b/src/main/java/cct/dialogs/JamberooFrame.java @@ -0,0 +1,1349 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + Jamberoo - Java Molecules Editor + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK ***** + */ +package cct.dialogs; + +import cct.GlobalSettings; +import cct.gaussian.GaussianCube; +import cct.gaussian.ui.ManageCubesFrame; +import cct.help.JavaHelp; +import cct.interfaces.*; +import cct.interfaces.MoleculeEventObject.MOLECULE_EVENT; +import cct.j3d.Java3dUniverse; +import cct.j3d.VibrationsRenderer; +import cct.modelling.*; +import cct.modelling.ui.VibrationsControlFrame; +import cct.resources.images.ImageResources; +import cct.tools.GridProviders; +import cct.tools.ui.JShowText; + +import javax.swing.*; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.util.ArrayList; +import java.util.Properties; +import java.util.ResourceBundle; +import java.util.logging.Logger; + +/** + * + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

This is the main interface for the Jamberoo (JMolEditor) By default, is redirected to the internal + * window. To disable this feature set cct.dialogs.JamberooFrame@redirectStderr = false in the cct.properties file + * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + * + */ +public class JamberooFrame + extends JFrame implements OperationsOnAtoms, AtomProperties, ActionListener, ChangeListener, MoleculeChangeListener { + + private static String version = "15"; + private static String build = "0804"; + private static final String ENABLE_DATABASE = "enableDatabase"; + private static final String ERROR_MESSAGE = "Error"; + private static final String LICENSE_FILE = "Jamberoo-license.txt"; + private boolean useTabbedPane = false; + private J3DTabbedWorld j3dTabbedWorld = null; + private JPanel contentPane; + private BorderLayout borderLayout1 = new BorderLayout(); + private JMenuBar jamberooMenuBar = new JMenuBar(); + private JMenu jMenuFile = new JMenu(); + private JMenu jMenuGrid = new JMenu("Grid"); + private JMenuItem jMenuFileExit = new JMenuItem(); + private JMenuItem postSuggestionMenuItem = new JMenuItem("Post Your Suggestion"); + private JMenuItem postBugMenuItem = new JMenuItem("Post a Bug"); + private JMenu jMenuEdit = new JMenu("Edit"); + private JMenu jMenuView = new JMenu("View"); + private JMenu jMenuDatabase = new JMenu("Database"); + private JMenu jMenuSetup; // = new JMenu("Setup"); + private JMenu jMenuHelp = new JMenu(); + private JMenu jMenuAnalyze = new JMenu("Analyze"); + private JMenuItem jMenuHelpAbout = new JMenuItem(); + private JMenuItem jMenuHelpLicense = new JMenuItem("License"); + private JMenuItem jMenuDBLogin = new JMenuItem("Login"); + private JMenuItem jMenuDBLogout = new JMenuItem("Logout"); + private JMenuItem loadGaussianCube = new JMenuItem("Load Gaussian Cube"); + private JMenuItem manageGaussianCubes = new JMenuItem("Manage Gaussian Cubes"); + private java.util.List volumeDataList = new ArrayList(); + private ManageCubesFrame manageCubesDialog = null; + private JMenuItem jMenuItemHelp = new JMenuItem("Help"); + private JToolBar mainToolbar = new JToolBar(); + private JToolBar jFileToolBar = new JToolBar("File"); + private JToolBar jEditToolBar = new JToolBar("Edit"); + private JToolBar jDBToolBar = new JToolBar("Database"); + private JButton openFileButton = new JButton(); + private JButton deleteMoleculeButton = new JButton(); + private JButton jButton3 = new JButton(); + private JButton trackingHelpButton = new JButton(); + private JButton modifyBondsButton = new JButton(); + private JButton modifyAnglesButton = new JButton(); + private JButton modifyDihedralsButton = new JButton(); + private JMenuItem vibrationalAnalysis = new JMenuItem("Frequencies"); + protected JMenuItem trajectoryAnalysis = new JMenuItem("Analyse MD Trajectory"); + protected TrajectoryAnalysisDialog trajectoryAnalysisDialog = null; + private ImageIcon tableImage = new ImageIcon(cct.resources.Resources.class.getResource( + "/cct/images/icons16x16/table_selection_all.png")); + private ImageIcon image2 = new ImageIcon(JamberooFrame.class.getResource("/cct/images/closeFile.png")); + private ImageIcon image3 = new ImageIcon(JamberooFrame.class.getResource("/cct/images/help.png")); + private ImageIcon exitImage = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/door2.gif")); + private ImageIcon docPulseImage = new ImageIcon(cct.resources.Resources.class.getResource("/cct/images/icons16x16/document_pulse.png")); + private ImageIcon dbImage = new ImageIcon(JamberooFrame.class.getResource("/cct/images/db-16x16.gif")); + private JButton jAddAtoms = new JButton(); + private JButton jAddFragments = new JButton(); + private JButton jAddMoleculeButton = new JButton(); + private ImageIcon addAtomsImage = new ImageIcon(JamberooFrame.class.getResource("/cct/images/add-atom.gif")); + private ImageIcon getHelpOn = new ImageIcon(ImageResources.class.getResource("/cct/images/icons16x16/getHelpOn.png")); + private JButton jDeleteAtoms = new JButton(); + private JButton jModifyAtoms = new JButton(); + private JButton jDBLogin = new JButton(); + private JLabel statusBar = new JLabel(); + private VibrationsControlFrame vcFrame = null; + private Java3dUniverse java3dUniverse; + private JEditorFrame_jMenuAnalyze_ActionAdapter processAnalyzeMenu; + //private JEditorFrame_jMenuDB_ActionAdapter processDBMenu; + private JScrollBar jScrollBar1 = new JScrollBar(); + private JScrollBar jScrollBar2 = new JScrollBar(); + private JPanel lowerPanel = new JPanel(); + private BorderLayout borderLayout2 = new BorderLayout(); + private Component dad = this; + private FileMenu fileMenu = null; + private EditMenu editMenu = null; + static final Logger logger = Logger.getLogger(JamberooFrame.class.getCanonicalName()); + private JamberooCore jamberooCore = new JamberooCore(); + private ResourceBundle messages; + + public JamberooFrame(String title, String[] args) { + super(title); + processArguments(args); + try { + setDefaultCloseOperation(EXIT_ON_CLOSE); + initializeJamberooFrame(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JamberooFrame(String[] args) { + processArguments(args); + try { + setDefaultCloseOperation(EXIT_ON_CLOSE); + initializeJamberooFrame(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JamberooFrame(String title) { + super(title); + try { + setDefaultCloseOperation(EXIT_ON_CLOSE); + initializeJamberooFrame(); + } catch (Exception exception) { + exception.printStackTrace(); + } + + } + + void processArguments(final String[] args) { + if (args == null) { + return; + } + for (int i = 0; i < args.length; i++) { + if (args[i].equals("-v")) { + logger.info(version + "." + build); + System.exit(0); + } else if (args[i].equals("-V")) { + logger.info("Version " + version + " build " + build); + System.exit(0); + } + + } + + } + + public void setDefaultHelper() { + String helpHS = "JMolEditorHelpSet.hs"; + JavaHelp javahelp = null; + try { + javahelp = new JavaHelp(helpHS); + setHelper(javahelp); + } catch (Exception ex) { + System.err.println("Activating Help System: " + ex.getMessage()); + } + + } + + /** + * Component initialization. + * + * @throws Exception + */ + private void initializeJamberooFrame() throws Exception { + // Get System Properties + JPopupMenu.setDefaultLightWeightPopupEnabled(false); + ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false); + + jamberooCore.setComponet(this); + + messages = GlobalSettings.getResourceBundle(); + + boolean enableDatabase = false; + //URL custom = null; + String className = this.getClass().getCanonicalName(); + try { + //custom = JamberooFrame.class.getClassLoader().getResource(CCT_PROPERTY_FILE); + Properties props = GlobalSettings.getProperties(); + //props.load(custom.openStream()); + + //--- Whether redirect stderr ?... + String customCommand = ""; + + //--- Whether to enable database facility ?... + customCommand = props.getProperty(className + GlobalSettings.DIVIDER + ENABLE_DATABASE, String.valueOf(enableDatabase)); + if (customCommand != null) { + try { + enableDatabase = Boolean.parseBoolean(customCommand); + } catch (Exception exx) { + System.err.println("Error parsing " + className + GlobalSettings.DIVIDER + ENABLE_DATABASE + " value from " + GlobalSettings.CCT_PROPERTY_FILE + + " file. Ignored..."); + } + } + + } catch (Exception ex) { + System.err.println("Warning: cannot open " + GlobalSettings.CCT_PROPERTY_FILE + " : " + ex.getMessage()); + } + + // --- Init memory monitor + //memorymonitor = new MemoryMonitor(); + GridProviders.setParentComponent(this); + + // --- create event processing + //processViewMenu = new JEditorFrame_jMenuView_ActionAdapter(this); + //processDBMenu = new JEditorFrame_jMenuDB_ActionAdapter(this); + processAnalyzeMenu = new JEditorFrame_jMenuAnalyze_ActionAdapter(this); + + contentPane = (JPanel) getContentPane(); + contentPane.setLayout(borderLayout1); + + java3dUniverse = jamberooCore.getJamberooRenderer(); + //setLayout(new BorderLayout()); + //Canvas3D canvas3D = java3dUniverse.getCanvas3D(); + + //add("Center",canvas3D); + // Comment this line before starting Design !!! + if (useTabbedPane) { + j3dTabbedWorld = new J3DTabbedWorld((useTabbedPane ? J3DTabbedWorld.MULTIPLE_MOLECULES : J3DTabbedWorld.SINGLE_MOLECULE)); + getContentPane().add(j3dTabbedWorld.getComponent()); + validate(); + } else { + logger.info("Double Buffer Available: " + java3dUniverse.getCanvas3D().getDoubleBufferAvailable()); + logger.info("Double Buffer Enable: " + java3dUniverse.getCanvas3D().getDoubleBufferEnable()); + getContentPane().add(java3dUniverse.getCanvas3D()); + } + + JPopupMenu.setDefaultLightWeightPopupEnabled(false); + + statusBar.setText("Hold down Left mouse button for Rotation, Middle button for Zooming and Right button for Translation: "); + + fileMenu = new FileMenu(jamberooCore); + fileMenu.addMoleculeChangeListener(this); + //shadowSFTPManager = fileMenu.getShadowSFTPManager(); + vcFrame = fileMenu.getVcFrame(); + jMenuFile = fileMenu; + jamberooMenuBar.add(jMenuFile); + + jMenuFile.setText(messages != null ? messages.getString("file_menu") : "File"); + jMenuFile.setMnemonic(KeyEvent.VK_F); + + jMenuFileExit.setText("Exit"); + jMenuFileExit.setMnemonic(KeyEvent.VK_X); + jMenuFileExit.setIcon(exitImage); + jMenuFileExit.addActionListener(new JEditorFrame_jMenuFileExit_ActionAdapter(this)); + + jScrollBar1.setOrientation(JScrollBar.HORIZONTAL); + jScrollBar1.setValue(50); + jScrollBar1.setEnabled(false); + lowerPanel.setLayout(borderLayout2); + deleteMoleculeButton.addActionListener(new JEditorFrame_deleteMoleculeButton_actionAdapter(this)); + jScrollBar2.setEnabled(false); + jScrollBar2.setForeground(Color.orange); // --- Assemble menu bar + //openFileButton.addActionListener(new JEditorFrame_openFileButton_actionAdapter(this)); // --- File Menu + openFileButton.addActionListener(this); // --- File Menu + jButton3.addActionListener(new JEditorFrame_jButton3_actionAdapter(this)); + + jMenuFile.add(jMenuFileExit); + + // --- Edit Menu + editMenu = new EditMenu(jamberooCore); + editMenu.addMoleculeChangeListener(this); + editMenu.setParentComponent(this); + editMenu.setVolumeDataList(volumeDataList); + editMenu.setManageCubesDialog(manageCubesDialog); + editMenu.createMenu(); + jMenuEdit = editMenu; + + jamberooMenuBar.add(jMenuEdit); + + jMenuEdit.setMnemonic(KeyEvent.VK_E); + jMenuEdit.setText(messages != null ? messages.getString("edit_menu") : "Edit"); + + // --- View Menu + ViewMenu viewMenu = new ViewMenu(jamberooCore); + viewMenu.createMenu(); + jMenuView = viewMenu; + jMenuView.setText(messages != null ? messages.getString("view_menu") : "View"); + jMenuView.setMnemonic(KeyEvent.VK_V); + + jamberooMenuBar.add(jMenuView); + + // --- Calculate menu + CalculateMenu calculateMenu = new CalculateMenu(this.jamberooCore); + calculateMenu.setParentComponent(this); + calculateMenu.createMenu(); + calculateMenu.setText(messages != null ? messages.getString("calculate_menu") : "Calculate"); + calculateMenu.setMnemonic(KeyEvent.VK_C); + + jamberooMenuBar.add(calculateMenu); + + // --- Database Menu + if (enableDatabase) { + jMenuDBLogin.setToolTipText("Login Database"); + jMenuDatabase.add(jMenuDBLogin); + jMenuDBLogin.addActionListener(this); + jMenuDBLogout.setEnabled(false); + jMenuDatabase.add(jMenuDBLogout); + jMenuDBLogout.addActionListener(this); + jamberooMenuBar.add(jMenuDatabase); + } + + // --- Grid menu + jMenuGrid.setMnemonic(KeyEvent.VK_G); + jMenuGrid.setText(messages != null ? messages.getString("grid_menu") : "Grid"); + + JMenuItem jMenuItem; + if (GridProviders.isJobStatusDialogAvailable()) { + jMenuItem = new JMenuItem("Job Status"); + jMenuItem.addActionListener(GridProviders.getActionListener()); + GridProviders.addActionListener(jMenuItem, GridProviders.JOB_STATUS_DIALOG); + GridProviders.setMolecularViewer(this.java3dUniverse); + jMenuGrid.add(jMenuItem); + } + + if (jMenuGrid.getItemCount() > 0) { + jamberooMenuBar.add(jMenuGrid); + } + + // --- Analyze Menu + jMenuAnalyze.setMnemonic(KeyEvent.VK_A); + jMenuAnalyze.setText(messages != null ? messages.getString("analyze_menu") : "Analyze"); + buildAnalyzeMenu(); + jMenuAnalyze.setEnabled(true); + jamberooMenuBar.add(jMenuAnalyze); + + // --- Tools menu + ToolsMenu toolsMenu = new ToolsMenu(this.jamberooCore); + toolsMenu.setParentComponent(this); + toolsMenu.createMenu(); + toolsMenu.setText(messages != null ? messages.getString("tools_menu") : "Tools"); + toolsMenu.setMnemonic(KeyEvent.VK_T); + + jamberooMenuBar.add(toolsMenu); + + // --- Setup Menu + SetupMenu setupMenu = new SetupMenu(this.jamberooCore); + setupMenu.setParentComponent(this); + setupMenu.createMenu(); + jMenuSetup = setupMenu; + jMenuSetup.setText(messages != null ? messages.getString("setup_menu") : "Setup"); + jMenuSetup.setMnemonic(KeyEvent.VK_S); + + jamberooMenuBar.add(jMenuSetup); + + // --- Help Menu + jMenuHelp.setText(messages != null ? messages.getString("help_menu") : "Help"); + jMenuHelp.setMnemonic(KeyEvent.VK_H); + + jMenuHelpAbout.setText("About"); + jMenuHelpAbout.setIcon(new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons16x16/help2.png"))); + jMenuHelpAbout.addActionListener(new JEditorFrame_jMenuHelpAbout_ActionAdapter(this)); + + jMenuHelpLicense.setIcon(new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons16x16/document_certificate.png"))); + + jMenuHelpLicense.addActionListener(new ActionListener() { + + private JShowText showLicense = new JShowText("Jamberoo License agreement"); + private boolean init = true; + + public void actionPerformed(ActionEvent e) { + if (init) { + showLicense.enableTextEditing(false); + showLicense.setSize(600, 640); + showLicense.setLocationByPlatform(true); + showLicense.setText(cct.tools.Utils.getResourceAsString(LICENSE_FILE)); + init = false; + } + showLicense.setVisible(true); + } + }); + + postSuggestionMenuItem.addActionListener(new ActionListener() { + + public void actionPerformed(ActionEvent e) { + + try { + GlobalSettings.mailUsingDefaultClient(GlobalSettings.getProperty(GlobalSettings.HELP_EMAIL), "Suggestion for Jamberoo", + "Please, type your suggestion(s) here..."); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + System.err.println(ex.getMessage()); + } + /* + * if (postSuggestionDialog == null) { postSuggestionDialog = new PostMessageDialog(thisFrame, "Post Your Suggestion", + * false); PostMessageType type = PostMessageType.SUGGESTION; postSuggestionDialog.setDialogType(type); + * postSuggestionDialog.validate(); postSuggestionDialog.pack(); postSuggestionDialog.setLocationRelativeTo(thisFrame); } + * postSuggestionDialog.setVisible(true); + */ + } + }); + postBugMenuItem.addActionListener(new ActionListener() { + + public void actionPerformed(ActionEvent e) { + + try { + GlobalSettings.mailUsingDefaultClient(GlobalSettings.getProperty(GlobalSettings.HELP_EMAIL), "Jamberoo Bug", + "Please, report a bug here.\nTell exactly what you did\n" + + "Which GUI controls you selected and what order you selected them in.\n" + + "If the program reads from a file, you will probably need to send a copy of the file.\n" + + "Above all, be precise. Programmers like precision... :-)"); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + System.err.println(ex.getMessage()); + } + /* + * if (postABugDialog == null) { postABugDialog = new PostMessageDialog(thisFrame, "Post A Bug", false); + * postABugDialog.setEmailImportance(PostMessageDialog.EMAIL_IS_OPTIONAL_BUT_WARN); PostMessageType type = + * PostMessageType.BUG_REPORT; postABugDialog.setDialogType(type); postABugDialog.validate(); postABugDialog.pack(); + * postABugDialog.setLocationRelativeTo(thisFrame); } postABugDialog.setVisible(true); + */ + } + }); + + jMenuItemHelp.setIcon(new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons16x16/help-file.png"))); + + jMenuHelp.add(jMenuItemHelp); + jMenuItemHelp.setEnabled(false); + + postSuggestionMenuItem.setIcon(new ImageIcon(ImageResources.class.getResource("/cct/images/icons16x16/document_edit.png"))); + jMenuHelp.add(postSuggestionMenuItem); + + postBugMenuItem.setIcon(new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons16x16/bug_red.png"))); + jMenuHelp.add(postBugMenuItem); + + jMenuHelp.addSeparator(); + jMenuHelp.add(jMenuHelpLicense); + jMenuHelp.add(jMenuHelpAbout); + + jamberooMenuBar.add(Box.createHorizontalGlue()); + + jamberooMenuBar.add(jMenuHelp); + + setJMenuBar(jamberooMenuBar); + + // --- Make "File" toolbar + openFileButton.setIcon(GlobalSettings.ICON_16x16_OPEN_FILE); + openFileButton.setToolTipText("Open File"); + openFileButton.setInheritsPopupMenu(true); + deleteMoleculeButton.setIcon(image2); + deleteMoleculeButton.setToolTipText("Erase Molecule"); + jButton3.setIcon(image3); + jButton3.setToolTipText("Help"); + jFileToolBar.add(openFileButton); + jFileToolBar.add(deleteMoleculeButton); + jFileToolBar.add(jButton3); + + jFileToolBar.addSeparator(); + + jFileToolBar.add(fileMenu.getSnapshotButton()); + + // --- Make "Edit" toolbar + jAddAtoms.setIcon(addAtomsImage); + jAddAtoms.setToolTipText(EditMenu.ADD_ATOMS_MESSAGE); + jAddAtoms.setActionCommand(EditMenu.EDIT_MENU_ACTIONS.ADD_ATOMS.name()); + jAddAtoms.addActionListener(editMenu); + jEditToolBar.add(jAddAtoms); + + jAddFragments.setIcon(GlobalSettings.ICON_16x16_ADD_FRAGMENT); + jAddFragments.setToolTipText("Add Fragments"); + jAddFragments.setActionCommand(EditMenu.EDIT_MENU_ACTIONS.ADD_FRAGMENT.name()); + jAddFragments.addActionListener(editMenu); + jEditToolBar.add(jAddFragments); + + jAddMoleculeButton.setIcon(GlobalSettings.ICON_16x16_MOLECULE); + jAddMoleculeButton.setToolTipText(EditMenu.ADD_MOLECULE_MESSAGE); + jAddMoleculeButton.setActionCommand(EditMenu.EDIT_MENU_ACTIONS.ADD_MOLECULE.name()); + jAddMoleculeButton.addActionListener(editMenu); + jEditToolBar.add(jAddMoleculeButton); + + jEditToolBar.addSeparator(); + + jDeleteAtoms.setIcon(GlobalSettings.ICON_16x16_CUT); + jDeleteAtoms.setToolTipText(EditMenu.DELETE_ATOMS_MESSAGE); + jDeleteAtoms.setActionCommand(EditMenu.EDIT_MENU_ACTIONS.DELETE_ATOMS.name()); + jDeleteAtoms.addActionListener(editMenu); + jEditToolBar.add(jDeleteAtoms); + + jEditToolBar.addSeparator(); + + jModifyAtoms.setIcon(GlobalSettings.ICON_16x16_ATOM); + jModifyAtoms.setToolTipText(EditMenu.MODIFY_ATOMS_MESSAGE); + jModifyAtoms.setActionCommand(EditMenu.EDIT_MENU_ACTIONS.MODIFY_ATOMS.name()); + jModifyAtoms.addActionListener(editMenu); + jEditToolBar.add(jModifyAtoms); + + modifyBondsButton.setIcon(GlobalSettings.ICON_16x16_BOND); + modifyBondsButton.setToolTipText("Modify Interatomic Distances"); + modifyBondsButton.setActionCommand(EditMenu.EDIT_MENU_ACTIONS.MODIFY_BONDS.name()); + modifyBondsButton.addActionListener(editMenu); + jEditToolBar.add(modifyBondsButton); + + modifyAnglesButton.setIcon(GlobalSettings.ICON_16x16_ANGLE); + modifyAnglesButton.setToolTipText("Modify Angles between atoms"); + modifyAnglesButton.setActionCommand(EditMenu.EDIT_MENU_ACTIONS.MODIFY_ANGLES.name()); + modifyAnglesButton.addActionListener(editMenu); + jEditToolBar.add(modifyAnglesButton); + + modifyDihedralsButton.setIcon(GlobalSettings.ICON_16x16_DIHEDRAL); + modifyDihedralsButton.setToolTipText("Modify Dihedral angles"); + modifyDihedralsButton.setActionCommand(EditMenu.EDIT_MENU_ACTIONS.MODIFY_TORSIONS.name()); + modifyDihedralsButton.addActionListener(editMenu); + jEditToolBar.add(modifyDihedralsButton); + + // --- Make database toolbar + if (enableDatabase) { + jDBLogin.setIcon(dbImage); + jDBLogin.setToolTipText("Login/Logout Database"); + jDBLogin.addActionListener(this); + jDBToolBar.add(jDBLogin); + } + + mainToolbar.add(jFileToolBar); + mainToolbar.add(jEditToolBar); + if (enableDatabase) { + mainToolbar.add(jDBToolBar); + } + trackingHelpButton.setIcon(getHelpOn); + trackingHelpButton.setToolTipText("Tracking Help"); + mainToolbar.addSeparator(); + mainToolbar.add(trackingHelpButton); + + /* + * Test button JButton temp = new JButton("Ca",tetra); temp.setHorizontalAlignment(SwingConstants.CENTER); + * temp.setHorizontalTextPosition(SwingConstants.CENTER); temp.setVerticalAlignment(SwingConstants.CENTER); + * temp.setVerticalTextPosition(SwingConstants.CENTER); temp.setSize(35,35); temp.setFont(new Font("Monospaced", Font.BOLD, + * 16)); + * + * mainToolbar.add(temp); + */ + jScrollBar2.setValue(50); + contentPane.add(jScrollBar2, BorderLayout.EAST); + contentPane.add(lowerPanel, BorderLayout.SOUTH); + lowerPanel.add(statusBar, BorderLayout.SOUTH); + lowerPanel.add(jScrollBar1, BorderLayout.CENTER); + contentPane.add(mainToolbar, BorderLayout.NORTH); + + // Comment this line before starting Design !!! + //contentPane.add(graphicsPanel, java.awt.BorderLayout.CENTER); + //contentPane.add(canvas3D, java.awt.BorderLayout.CENTER); + } + + public void setHelper(HelperInterface h) { + jamberooCore.setHelper(h); + HelperInterface helper = jamberooCore.getHelper(); + JRootPane rootpane = this.getRootPane(); + + java3dUniverse.setHelper(jamberooCore.getHelper()); + + // --- Set help for root pane + //helper.enableHelpKey(rootpane, "top"); + jamberooCore.getHelper().enableHelpKey(rootpane, "top", "javax.help.SecondaryWindow", null); + //helper.enableHelpKey(rootpane, "top", "javax.help.Popup", null); + + // --- Set help for menues + helper.setHelpIDString(jamberooMenuBar, "menues.top"); + helper.setHelpIDString(jMenuFile, "menues.file"); + helper.setHelpIDString(jMenuEdit, "menues.edit"); + helper.setHelpIDString(jMenuView, "menues.view"); + helper.setHelpIDString(jMenuAnalyze, "menues.analyze"); + helper.setHelpIDString(jMenuSetup, "menues.setup"); + + // --- Main help in tool bar + helper.setHelpIDString(jButton3, "top"); + helper.displayHelpFromSourceActionListener(jButton3); + + helper.setHelpIDString(this.jAddAtoms, HelperInterface.JMD_ADD_ATOM_ID); + //helper.displayHelpFromSourceActionListener(jAddAtoms); + + helper.setHelpIDString(this.jAddFragments, HelperInterface.JMD_ADD_FRAGMENT_ID); + //helper.displayHelpFromSourceActionListener(jAddFragments); + + helper.setHelpIDString(this.jAddMoleculeButton, HelperInterface.JMD_ADD_MOLECULE_ID); + //helper.displayHelpFromSourceActionListener(jAddMoleculeButton); + + helper.setHelpIDString(this.modifyBondsButton, HelperInterface.JMD_MODIFY_BOND_ID); + + helper.setHelpIDString(this.modifyAnglesButton, HelperInterface.JMD_MODIFY_ANGLE_ID); + + helper.setHelpIDString(this.modifyDihedralsButton, HelperInterface.JMD_MODIFY_TORSION_ID); + + jMenuItemHelp.setEnabled(true); + helper.setHelpIDString(jMenuItemHelp, "top"); + helper.displayHelpFromSourceActionListener(jMenuItemHelp); + + helper.addActionListenerForTracking(trackingHelpButton); + } + + /** + * Checks whether molecule loaded or not + * + * @return boolean "true" if loaded and "false" otherwise + */ + public boolean isMoleculeLoaded() { + MoleculeInterface m = java3dUniverse.getMolecule(); + if (m == null) { + JOptionPane.showMessageDialog(this, "Load Molecule first!", "Warning", + JOptionPane.WARNING_MESSAGE); + return false; + } + return true; + } + + void jMenuAnalyze_actionPerformed(ActionEvent actionEvent) { + String arg = actionEvent.getActionCommand(); + + // --- process menues + if (arg.equals("Measure Bond Length")) { + //java3dUniverse.enableMousePicking(true); // Enable mouse picking + } else if (actionEvent.getSource() == vibrationalAnalysis) { + if (java3dUniverse.getMolecule() == null + || java3dUniverse.getMolecule().getNumberOfAtoms() < 1) { + JOptionPane.showMessageDialog(this, "Load Molecule first!", ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + MoleculeInterface mol = java3dUniverse.getMoleculeInterface(); + Object obj = mol.getProperty(MoleculeInterface.OUTPUT_RESULTS); + if (obj == null || (!(obj instanceof OutputResultsInterface))) { + if (!(obj instanceof OutputResultsInterface) && obj != null) { + System.err.println("Possible internal inconsistency: ! (obj instanceof OutputResultsInterface)"); + } + JOptionPane.showMessageDialog(this, "No frequencies information for a molecule", ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + OutputResultsInterface results = (OutputResultsInterface) obj; + if (!results.hasDisplacementVectors() && results.countSpectra() == 0) { + JOptionPane.showMessageDialog(this, "No frequencies information for a molecule", ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + obj = mol.getProperty(MoleculeInterface.VIBRATION_RENDERER); + VibrationsRenderer vRenderer = null; + if (obj == null) { + try { + vRenderer = new VibrationsRenderer(mol, results, java3dUniverse); + mol.addProperty(MoleculeInterface.VIBRATION_RENDERER, vRenderer); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Cannot initialize vibration renderer", ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); + return; + } + } else { + vRenderer = (VibrationsRenderer) obj; + } + + if (vcFrame == null || (!vcFrame.isVisible())) { + vcFrame = new VibrationsControlFrame(); + vcFrame.setTitle("Vibrations Control"); + vcFrame.setVibrationsRendererProvider(vRenderer); + vcFrame.setSpectraProvider(results); + vcFrame.pack(); + vcFrame.setLocationRelativeTo(this); + vcFrame.setVisible(true); + } else { + vcFrame.toFront(); + } + } else if (actionEvent.getSource() == trajectoryAnalysis) { + if (java3dUniverse.getMolecule() == null + || java3dUniverse.getMolecule().getNumberOfAtoms() < 1) { + JOptionPane.showMessageDialog(this, "Load Molecule first!", + ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + return; + } + + if (this.trajectoryAnalysisDialog == null) { + trajectoryAnalysisDialog = new TrajectoryAnalysisDialog(this, + "MD Trajectory Analysis", false); + trajectoryAnalysisDialog.setLocationRelativeTo(this); + trajectoryAnalysisDialog.setDefaultCloseOperation(HIDE_ON_CLOSE); + } + trajectoryAnalysisDialog.setRenderer(java3dUniverse); + trajectoryAnalysisDialog.setVisible(true); + } else if (actionEvent.getSource() == loadGaussianCube) { + String fileName = fileMenu.chooseFileDialog(MolecularFileFormats.gaussian03Cube, + "Load Gaussian G03 Cube File (*.cub;*.cube)", + JFileChooser.OPEN_DIALOG); + if (fileName == null) { + return; + } + + GaussianCube gCube = new GaussianCube(); + try { + MoleculeInterface mol = new Molecule(); + gCube.parseVolumetricData(fileName); + gCube.getMolecule(mol); + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, + CCTAtomTypes.getElementMapping()); + //MoleculeInterface m2 = Molecule.divideIntoMolecules(mol); + java3dUniverse.addMolecule(mol); + volumeDataList.add(gCube); + + JOptionPane.showMessageDialog(this, gCube.getTitle() + "\n" + + gCube.getCubeDescription() + "\n" + "Number of atoms: " + + mol.getNumberOfAtoms() + "\n" + "Number of cubes: " + + gCube.countCubes(), "Gaussian cube info", + JOptionPane.INFORMATION_MESSAGE); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, + "Error Loading Gaussian Cube file : " + + ex.getMessage(), ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + return; + } + + } else if (actionEvent.getSource() == manageGaussianCubes) { + if (manageCubesDialog == null) { + manageCubesDialog = new ManageCubesFrame("Manage Volumetric Data (Cubes)", this.volumeDataList); + //if (gopDialog == null) { + // initGraphObjDialog(this.java3dUniverse); + //} + jamberooCore.showGraphicsObjectsDialog(false); + + //manageCubesDialog.setGraphicsObjectPropertiesFrame(gopDialog); + manageCubesDialog.setJamberooCore(jamberooCore); + if (jamberooCore.getHelper() != null) { + JButton h = manageCubesDialog.getHelpButton(); + h.setEnabled(true); + jamberooCore.getHelper().setHelpIDString(h, HelperInterface.JMD_MANAGE_GAUSSIAN_CUBES_ID); + jamberooCore.getHelper().displayHelpFromSourceActionListener(h); + } + //manageCubesDialog.setJava3dUniverse(java3dUniverse); + manageCubesDialog.pack(); + manageCubesDialog.setLocationRelativeTo(this); + } else { + manageCubesDialog.setCubeList(volumeDataList); + } + //if (gopDialog != null) { + // gopDialog.setVisible(false); + //} + manageCubesDialog.setVisible(true); + } + + } + + void jMenuDB_actionPerformed(ActionEvent actionEvent) { + if (jMenuDBLogin == actionEvent.getSource() || jDBLogin == actionEvent.getSource()) { + + if (java3dUniverse.connectToDatabase()) { + jMenuDBLogin.setText("Save/Retrieve Data"); + jMenuDBLogin.setToolTipText( + "Save/Retrieve Data to/from Database"); + jMenuDBLogout.setEnabled(true); + } + } else if (jMenuDBLogout == actionEvent.getSource()) { + java3dUniverse.logoutDatabase(); + jMenuDBLogin.setText("Login Database"); + jMenuDBLogin.setToolTipText("Login Database"); + jMenuDBLogout.setEnabled(false); + } + } + + public Component getComponent() { + return this; + } + + void buildAnalyzeMenu() { + + JMenuItem jMenuItem; + + /* + * // --- "Measure Bond Length" item jMenuItem = new JMenuItem("Measure Bond Length", new ImageIcon(cct.dialogs. + * JamberooFrame.class. getResource( "/images/empty-transp-16x16.png"))); + * + * jMenuItem.addActionListener(processAnalyzeMenu); jMenuAnalyze.add(jMenuItem); + */ + // --- Molecular geometry + jMenuItem = new JMenuItem("Geometry", GlobalSettings.ICON_16x16_DOCUMENT_INFO); + jMenuItem.addActionListener(new ActionListener() { + + public void actionPerformed(ActionEvent e) { + if (java3dUniverse.getMolecule() == null + || java3dUniverse.getMoleculeInterface().getNumberOfAtoms() + < 1) { + JOptionPane.showMessageDialog(null, "Load molecule first", + ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + return; + } + if (java3dUniverse.getMoleculeInterface().getNumberOfAtoms() + > 100) { + int n = JOptionPane.showConfirmDialog(dad, + "Molecule has " + + java3dUniverse.getMoleculeInterface(). + getNumberOfAtoms() + + " - output could be lengthy.\n" + + "Do you want to continue?\n", + "Output could be lengthy", + JOptionPane.YES_NO_OPTION); + if (n == JOptionPane.NO_OPTION + || n == JOptionPane.CLOSED_OPTION) { + return; + } + } + + JShowText showResume = new JShowText("Molecular Geometry"); + showResume.setIconImage(GlobalSettings.ICON_16x16_DOCUMENT_INFO.getImage()); + showResume.enableTextEditing(false); + showResume.setSize(600, 640); + showResume.setLocationRelativeTo(dad); + showResume.setText(Molecule.geometryAsString(java3dUniverse.getMoleculeInterface())); + showResume.setDefaultFileName("geometry.txt"); + showResume.setVisible(true); + } + }); + jMenuAnalyze.add(jMenuItem); + + // --- Interatomic distances + jMenuItem = new JMenuItem("Interatomic Distances", tableImage); + jMenuItem.addActionListener(new ActionListener() { + + public void actionPerformed(ActionEvent e) { + if (java3dUniverse.getMolecule() == null + || java3dUniverse.getMoleculeInterface().getNumberOfAtoms() + < 1) { + JOptionPane.showMessageDialog(null, "Load molecule first", + ERROR_MESSAGE, + JOptionPane.ERROR_MESSAGE); + return; + } + if (java3dUniverse.getMoleculeInterface().getNumberOfAtoms() + > 100) { + int n = JOptionPane.showConfirmDialog(dad, + "Molecule has " + + java3dUniverse.getMoleculeInterface(). + getNumberOfAtoms() + + " - output could be lengthy.\n" + + "Do you want to continue?\n", + "Output could be lengthy", + JOptionPane.YES_NO_OPTION); + if (n == JOptionPane.NO_OPTION + || n == JOptionPane.CLOSED_OPTION) { + return; + } + } + + JShowText showResume = new JShowText("Interatomic Distances"); + showResume.setIconImage(tableImage.getImage()); + showResume.enableTextEditing(false); + showResume.setSize(600, 640); + showResume.setLocationRelativeTo(dad); + showResume.setText(Molecule.distancesAsString(java3dUniverse.getMoleculeInterface())); + showResume.setDefaultFileName("distances.txt"); + showResume.setVisible(true); + } + }); + jMenuAnalyze.add(jMenuItem); + + // --- Frequencies + vibrationalAnalysis.setIcon(docPulseImage); + jMenuAnalyze.add(vibrationalAnalysis); + vibrationalAnalysis.addActionListener(processAnalyzeMenu); + + // --- MD Trajectories + trajectoryAnalysis.setIcon(new ImageIcon(cct.resources.Resources.class.getResource( + "/cct/images/icons16x16/line-chart.png"))); + trajectoryAnalysis.addActionListener(processAnalyzeMenu); + + jMenuAnalyze.add(trajectoryAnalysis); + jMenuAnalyze.addSeparator(); + + // --- Load Gaussian cube + ImageIcon cubeIcon = new ImageIcon(cct.resources.Resources.class.getResource( + "/cct/images/icons16x16/gaussian-cube-16x16.png")); + loadGaussianCube.setIcon(cubeIcon); + loadGaussianCube.addActionListener(processAnalyzeMenu); + jMenuAnalyze.add(loadGaussianCube); + + manageGaussianCubes.setIcon(cubeIcon); + manageGaussianCubes.addActionListener(processAnalyzeMenu); + jMenuAnalyze.add(manageGaussianCubes); + + } + + /** + * File | Exit action performed. + * + * @param actionEvent ActionEvent + */ + void jMenuFileExit_actionPerformed(ActionEvent actionEvent) { + int whatToDo = this.getDefaultCloseOperation(); + switch (whatToDo) { + case JFrame.EXIT_ON_CLOSE: + System.exit(0); + break; + case JFrame.DISPOSE_ON_CLOSE: + this.dispose(); + break; + case JFrame.DO_NOTHING_ON_CLOSE: + break; + case JFrame.HIDE_ON_CLOSE: + setVisible(false); + break; + } + + } + + /** + * Help | About action performed. + * + * @param actionEvent ActionEvent + */ + void jMenuHelpAbout_actionPerformed(ActionEvent actionEvent) { + JEditorFrame_AboutBox dlg = new JEditorFrame_AboutBox(this, version, + build); + Dimension dlgSize = dlg.getPreferredSize(); + Dimension frmSize = getSize(); + Point loc = getLocation(); + dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, + (frmSize.height - dlgSize.height) / 2 + loc.y); + dlg.setModal(true); + dlg.pack(); + dlg.setVisible(true); + } + + public void deleteMoleculeButton_actionPerformed(ActionEvent e) { + Molecule m = new Molecule(); + java3dUniverse.addMolecule(m); + } + + /** + * Program tries to guess and open all supported molecular file formats + * + * @param e ActionEvent + */ + //public void openFileButton_actionPerformed(ActionEvent e) { + // guessAndOpenFile(java3dUniverse); + //} + //@Deprecated + //boolean guessAndOpenFile(Java3dUniverse j3d) { + // JFileChooser chooser = new JFileChooser(); + // FileFilterImpl filter = new FileFilterImpl(); + // String extensions = MolecularFileFormats.allMolecularExtensions; + // String temp[] = extensions.split(";"); + // for (int i = 0; i < temp.length; i++) { + // filter.addExtension(temp[i]); + // } + // filter.setDescription(MolecularFileFormats.allMolecularFormats); + // chooser.setFileFilter(filter); + // chooser.setDialogType(JFileChooser.OPEN_DIALOG); + // chooser.setDialogTitle("Open Molecular Modeling File"); + // File currentWorkingDirectory = GlobalSettings.getCurrentWorkingDirectory(); + // if (currentWorkingDirectory != null) { + // chooser.setCurrentDirectory(currentWorkingDirectory); + // } + // int returnVal = chooser.showOpenDialog(this); + // if (returnVal == JFileChooser.APPROVE_OPTION) { + // String fileName = chooser.getSelectedFile().getPath(); + // currentWorkingDirectory = chooser.getCurrentDirectory(); + // GlobalSettings.setCurrentWorkingDirectory(currentWorkingDirectory); + // logger.info("You chose to open this file: " + // + fileName); + // String extension = FileFilterImpl.getExtension(fileName); + // int fileFormat = MolecularFileFormats.guessMolecularFileFormat( + // fileName, extension); + // if (fileFormat == MolecularFileFormats.formatUnknown) { + // JOptionPane.showMessageDialog(this, "Unknown Molecular Modeling File Format", ERROR_MESSAGE, + // JOptionPane.ERROR_MESSAGE); + // return false; + // } + // j3d.openMolecularModelingFile(fileFormat, fileName); + // return true; + // } + // return false; + //} + /** + * Transforms coordinates of atoms of the arbitrary molecule into current virtual world space + * + * @param molec MoleculeInterface - Molecule + * @return float[][] - cartesian coordinates float[number_of_atoms][3] + */ + public float[][] getVirtualWorldCoordinates(MoleculeInterface molec) { + return java3dUniverse.getVirtualWorldCoordinates(molec); + } + + public String addMenuItem(String menuName, JMenuItem menuItem) { + for (int i = 0; i < jamberooMenuBar.getMenuCount(); i++) { + JMenu menu = jamberooMenuBar.getMenu(i); + //logger.info("Name: "+menu.getName()+" ActionCommand: "+menu.getActionCommand()); + if (menuName.equalsIgnoreCase(menu.getActionCommand())) { + menu.add(menuItem); + return null; + } + } + return "No menu with name " + menuName; + } + + public JToolBar getJToolBar() { + return mainToolbar; + } + + public void stateChanged(ChangeEvent e) { + + } + + public void moleculeChanged(MoleculeEventObject event) { + if (event.getMoleculeEvent() == MOLECULE_EVENT.MOLECULE_DELETED) { + this.setTitle(""); + } else if (event.getMoleculeEvent() == MOLECULE_EVENT.MOLECULE_LOADED) { + this.setTitle(event.getUrlString()); + } + } + + public void actionPerformed(ActionEvent actionEvent) { + Object source = actionEvent.getSource(); + + if (jMenuDBLogin == source || jDBLogin == source) { + + if (java3dUniverse.connectToDatabase()) { + jMenuDBLogin.setText("Save/Retrieve Data"); + jMenuDBLogin.setToolTipText("Save/Retrieve Data to/from Database"); + jMenuDBLogout.setEnabled(true); + } + } else if (jMenuDBLogout == actionEvent.getSource()) { + java3dUniverse.logoutDatabase(); + jMenuDBLogin.setText("Login Database"); + jMenuDBLogin.setToolTipText("Login Database"); + jMenuDBLogout.setEnabled(false); + } + + if (source == openFileButton) { + fileMenu.openMoleculeFile("Open Molecule file", this.java3dUniverse, GlobalSettings.ADD_MOLECULE_MODE.SET); + //fileMenu.o + return; + } + + String eventName = ""; + if (source instanceof JMenuItem) { + JMenuItem jMenuItem = (JMenuItem) source; + eventName = jMenuItem.getName(); + } + + // --- Open Molecule Menuitem + if (false) { + } + } + + /** + * Check whether menu with ActionCommand "menuName" has menu item with ActionCommand "menuItemName" + * + * @param menuName String - menu ActionCommand name + * @param menuItemName String menu item ActionCommand name + * @return boolean true - a menu has a given menu item, false otherwise + * @throws Exception if there is no such menu in menubar + */ + public boolean hasMenuItem(String menuName, String menuItemName) throws + Exception { + for (int i = 0; i < jamberooMenuBar.getMenuCount(); i++) { + JMenu menu = jamberooMenuBar.getMenu(i); + //logger.info("Name: "+menu.getName()+" ActionCommand: "+menu.getActionCommand()); + if (menuName.equalsIgnoreCase(menu.getActionCommand())) { + for (int j = 0; j < menu.getItemCount(); j++) { + JMenuItem item = menu.getItem(j); + if (menuItemName.equalsIgnoreCase(item.getActionCommand())) { + return true; + } + } + return false; + } + } + throw new Exception("No menu " + menuName + " in menu bar"); + } + + /** + * Gets menu item with ActionCommand name "menuItemName" from the menu with ActionCommand name "menuName" + * + * @param menuName String + * @param menuItemName String + * @return JMenuItem + * @throws Exception + */ + public JMenuItem getMenuItem(String menuName, String menuItemName) throws + Exception { + for (int i = 0; i < jamberooMenuBar.getMenuCount(); i++) { + JMenu menu = jamberooMenuBar.getMenu(i); + + if (menuName.equalsIgnoreCase(menu.getActionCommand())) { + for (int j = 0; j < menu.getItemCount(); j++) { + Object obj = null; + try { + obj = menu.getItem(j); + //logger.info("Name: " + obj.getClass().getSimpleName()); + } catch (Exception ex) { + //System.err.println(ex.getMessage()); + continue; + } + + if (obj instanceof JMenuItem) { + final JMenuItem item = (JMenuItem) obj; + + if (menuItemName.equalsIgnoreCase(item.getActionCommand())) { + return item; + } + } + } + throw new Exception("No menu item " + menuItemName + + " in menu " + menuName); + //return null; + } + } + throw new Exception("No menu " + menuName + " in menu bar"); + } + + public JMenuItem removeMenuItem(String menuName, String menuItemName) throws + Exception { + for (int i = 0; i < jamberooMenuBar.getMenuCount(); i++) { + final JMenu menu = jamberooMenuBar.getMenu(i); + + if (menuName.equalsIgnoreCase(menu.getActionCommand())) { + for (int j = 0; j < menu.getItemCount(); j++) { + Object obj = null; + try { + obj = menu.getItem(j); + //logger.info("Name: " + obj.getClass().getSimpleName()); + } catch (Exception ex) { + //System.err.println(ex.getMessage()); + continue; + } + + if (obj instanceof JMenuItem) { + JMenuItem item = (JMenuItem) obj; + + if (menuItemName.equalsIgnoreCase(item.getActionCommand())) { + menu.remove(item); + return item; + } + } + } + throw new Exception("No menu item " + menuItemName + + " in menu " + menuName); + //return null; + } + } + throw new Exception("No menu " + menuName + " in menu bar"); + } + + public JMenu getMenu(String menuName) throws Exception { + for (int i = 0; i < jamberooMenuBar.getMenuCount(); i++) { + JMenu menu = jamberooMenuBar.getMenu(i); + if (menuName.equalsIgnoreCase(menu.getActionCommand())) { + return menu; + } + } + return null; + } + + public MoleculeInterface getMolecule() { + return java3dUniverse.getMolecule(); + } + + public Java3dUniverse getJ3DUniverse() { + return java3dUniverse; + } + + public void setMolecule(Molecule m) { + java3dUniverse.addMolecule(m); + } + + public void setMolecule(MoleculeInterface m) { + java3dUniverse.addMolecule(m); + } + + public java.util.List getVolumeDataList() { + return volumeDataList; + } + + public void jButton3_actionPerformed(ActionEvent e) { + //JavaHelp jh = new JavaHelp(); + //jh.showHelp(); + } + + class JEditorFrame_jButton3_actionAdapter + implements ActionListener { + + private JamberooFrame adaptee; + + JEditorFrame_jButton3_actionAdapter(JamberooFrame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.jButton3_actionPerformed(e); + } + } + + //class JEditorFrame_openFileButton_actionAdapter + // implements ActionListener { + // private JamberooFrame adaptee; + // JEditorFrame_openFileButton_actionAdapter(JamberooFrame adaptee) { + // this.adaptee = adaptee; + // } + // public void actionPerformed(ActionEvent e) { + // adaptee.openFileButton_actionPerformed(e); + // } + //} + class JEditorFrame_jMenuFileExit_ActionAdapter + implements ActionListener { + + JamberooFrame adaptee; + + JEditorFrame_jMenuFileExit_ActionAdapter(JamberooFrame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent actionEvent) { + adaptee.jMenuFileExit_actionPerformed(actionEvent); + } + } + + /** + * + *

+ * Title: Picking

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005

+ * + *

+ * Company:

+ * + * @author not attributable + * @version 1.0 + */ + class JEditorFrame_jMenuAnalyze_ActionAdapter + implements ActionListener { + + JamberooFrame adaptee; + + JEditorFrame_jMenuAnalyze_ActionAdapter(JamberooFrame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent actionEvent) { + adaptee.jMenuAnalyze_actionPerformed(actionEvent); + } + } + + class JEditorFrame_jMenuHelpAbout_ActionAdapter + implements ActionListener { + + JamberooFrame adaptee; + + JEditorFrame_jMenuHelpAbout_ActionAdapter(JamberooFrame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent actionEvent) { + adaptee.jMenuHelpAbout_actionPerformed(actionEvent); + } + } + + //class JEditorFrame_jMenuDB_ActionAdapter + // implements ActionListener { + // + // JamberooFrame adaptee; + // JEditorFrame_jMenuDB_ActionAdapter(JamberooFrame adaptee) { + // this.adaptee = adaptee; + // } + // public void actionPerformed(ActionEvent actionEvent) { + // adaptee.jMenuDB_actionPerformed(actionEvent); + // } + //} + class JEditorFrame_deleteMoleculeButton_actionAdapter + implements + ActionListener { + + private JamberooFrame adaptee; + + JEditorFrame_deleteMoleculeButton_actionAdapter(JamberooFrame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.deleteMoleculeButton_actionPerformed(e); + } + } +} diff --git a/src/main/java/cct/dialogs/MainPopupMenu.java b/src/main/java/cct/dialogs/MainPopupMenu.java new file mode 100644 index 0000000..0e36505 --- /dev/null +++ b/src/main/java/cct/dialogs/MainPopupMenu.java @@ -0,0 +1,136 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.dialogs; + +import java.awt.Component; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.util.logging.Logger; + +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; + +import cct.interfaces.JamberooCoreInterface; +import cct.j3d.Java3dUniverse; + +/** + * + * @author vvv900 + */ +public class MainPopupMenu extends JPopupMenu implements ActionListener { + + private Java3dUniverse j3d = null; + private int currX = 0, currY = 0; + private Component component; + private JamberooCoreInterface jamberooCore; + static final Logger logger = Logger.getLogger(MainPopupMenu.class.getCanonicalName()); + + public MainPopupMenu(JamberooCoreInterface jamberooCore) { + this.jamberooCore = jamberooCore; + j3d = jamberooCore.getJamberooRenderer(); + } + + public void createPopupMenu() { + JMenuItem menuItem; + + //Create the popup menu. + JPopupMenu popup = new JPopupMenu("Jamberoo Controls"); + + try { + FileMenu fm = new FileMenu(jamberooCore); + fm.setText("File"); + popup.add(fm); + } catch (Exception ex) { + ex.printStackTrace(); + } + + EditMenu em = new EditMenu(jamberooCore); + em.createMenu(); + em.setText("Edit"); + popup.add(em); + + ViewMenu vm = new ViewMenu(jamberooCore); + vm.createMenu(); + vm.setText("View"); + popup.add(vm); + + CalculateMenu cm = new CalculateMenu(jamberooCore); + cm.setParentComponent(this); + cm.createMenu(); + cm.setText("Calculate"); + popup.add(cm); + + ToolsMenu tm = new ToolsMenu(jamberooCore); + tm.createMenu(); + tm.setText("Tools"); + popup.add(tm); + + SetupMenu sm = new SetupMenu(jamberooCore); + sm.createMenu(); + sm.setText("Setup"); + popup.add(sm); + + //Add listener to the text area so the popup menu can come up. + MouseListener popupListener = new PopupListener(popup); + j3d.getCanvas3D().addMouseListener(popupListener); + //this.addMouseListener(popupListener); + } + + @Override + public void actionPerformed(ActionEvent ae) { + } + + public JPopupMenu createFilePopupMenu() { + JMenuItem menuItem; + //Create the popup menu. + JPopupMenu popup = new JPopupMenu("File"); + menuItem = new JMenuItem("Open File"); + menuItem.addActionListener(this); + popup.add(menuItem); + menuItem = new JMenuItem("Save As"); + menuItem.addActionListener(this); + popup.add(menuItem); + + //Add listener to the text area so the popup menu can come up. + //MouseListener popupListener = new PopupListener(popup); + //j3d.getCanvas3D().addMouseListener(popupListener); + //this.addMouseListener(popupListener); + return popup; + } + + class PopupListener extends MouseAdapter { + + JPopupMenu popup; + + PopupListener(JPopupMenu popupMenu) { + + popup = popupMenu; + } + + @Override + public void mousePressed(MouseEvent e) { + logger.info("mousePressed"); + currX = e.getX(); + currY = e.getY(); + component = e.getComponent(); + maybeShowPopup(e); + } + + @Override + public void mouseReleased(MouseEvent e) { + logger.info("mouseReleased"); + maybeShowPopup(e); + } + + private void maybeShowPopup(MouseEvent e) { + if (e.isPopupTrigger()) { + popup.show(e.getComponent(), e.getX(), e.getY()); + } + } + } +} diff --git a/src/main/java/cct/dialogs/MoleculeSelectorDialog.java b/src/main/java/cct/dialogs/MoleculeSelectorDialog.java new file mode 100644 index 0000000..fab7493 --- /dev/null +++ b/src/main/java/cct/dialogs/MoleculeSelectorDialog.java @@ -0,0 +1,206 @@ +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JTree; +import javax.swing.event.TreeSelectionEvent; +import javax.swing.event.TreeSelectionListener; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreeSelectionModel; + +import cct.interfaces.MoleculeInterface; +import cct.interfaces.MoleculeRendererInterface; +import cct.j3d.Java3dUniverse; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2009 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class MoleculeSelectorDialog + extends JDialog { + + private Java3dUniverse java3d = null; + private MoleculeRendererInterface parent = null; + private Map molecules = null; + private Map referenceTable = new HashMap (); + private String topName = "Molecules"; + + private JPanel panel1 = new JPanel(); + private BorderLayout borderLayout1 = new BorderLayout(); + private JSplitPane jSplitPane1 = new JSplitPane(); + private BorderLayout borderLayout2 = new BorderLayout(); + private JButton cancelButton = new JButton(); + private JPanel jPanel1 = new JPanel(); + private JButton loadButton = new JButton(); + private JScrollPane jScrollPane1 = new JScrollPane(); + private JTree moleculeTree = new JTree(); + + public MoleculeSelectorDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public MoleculeSelectorDialog() { + this(new Frame(), "MoleculeSelectorDialog", false); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + this.getContentPane().setLayout(borderLayout2); + cancelButton.setText(" Cancel "); + cancelButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + cancelButton_actionPerformed(e); + } + }); + loadButton.setToolTipText(""); + loadButton.setText("Load Molecule"); + loadButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + loadButton_actionPerformed(e); + } + }); + jSplitPane1.setOrientation(JSplitPane.VERTICAL_SPLIT); + moleculeTree.addTreeSelectionListener(new TreeSelectionListener() { + @Override + public void valueChanged(TreeSelectionEvent e) { + moleculeTree_valueChanged(e); + } + }); + this.setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); + jPanel1.add(loadButton); + jPanel1.add(cancelButton); + panel1.add(jPanel1, BorderLayout.SOUTH); + panel1.add(jSplitPane1, BorderLayout.CENTER); + this.getContentPane().add(panel1, BorderLayout.CENTER); + jSplitPane1.add(jScrollPane1, JSplitPane.TOP); + jScrollPane1.getViewport().add(moleculeTree); + jScrollPane1.setMinimumSize(new Dimension(300, 150)); + moleculeTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); + + } + + public void setJ3DRenderer(Java3dUniverse renderer) { + java3d = renderer; + java3d.getCanvas3D().setMaximumSize(new Dimension(300, 200)); + jSplitPane1.add(java3d.getCanvas3D(), JSplitPane.BOTTOM); + } + + public void setJ3DParent(MoleculeRendererInterface parent) { + this.parent = parent; + } + + public void setMoleculeTree(Map molecules) { + DefaultMutableTreeNode top = new DefaultMutableTreeNode(topName); + createNodes(top, molecules); + moleculeTree.removeAll(); + jScrollPane1.getViewport().remove(moleculeTree); + moleculeTree = new JTree(top); + moleculeTree.addTreeSelectionListener(new TreeSelectionListener() { + @Override + public void valueChanged(TreeSelectionEvent e) { + moleculeTree_valueChanged(e); + } + }); + jScrollPane1.getViewport().add(moleculeTree); + } + + private void createNodes(DefaultMutableTreeNode top, Map molecules) { + + DefaultMutableTreeNode lastDic = top; + + Set set = molecules.entrySet(); + Iterator iter = set.iterator(); + + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String dicName = me.getKey().toString(); + Object obj = me.getValue(); + + if (obj instanceof Map) { + DefaultMutableTreeNode dictionary = new DefaultMutableTreeNode(dicName); + top.add(dictionary); + createNodes(dictionary, (Map) obj); + lastDic = dictionary; + } + else if (obj instanceof MoleculeInterface) { + DefaultMutableTreeNode fragment = new DefaultMutableTreeNode(dicName); + lastDic.add(fragment); + MoleculeInterface mol = (MoleculeInterface) obj; + referenceTable.put(fragment, mol); + } + } + + } + + public void moleculeTree_valueChanged(TreeSelectionEvent e) { + if (!moleculeTree.isEnabled()) { + return; + } + moleculeTree.setEnabled(false); + + DefaultMutableTreeNode node = (DefaultMutableTreeNode) moleculeTree.getLastSelectedPathComponent(); + if (node == null) { + moleculeTree.setEnabled(true); + return; + } + + Object nodeInfo = node.getUserObject(); + + if (node.isLeaf()) { + MoleculeInterface mol = referenceTable.get(node); + if (java3d != null) { + java3d.addMolecule(mol); + } + } + + moleculeTree.setEnabled(true); + } + + public void loadButton_actionPerformed(ActionEvent e) { + if (java3d == null || parent == null) { + return; + } + MoleculeInterface mol = java3d.getMoleculeInterface(); + if (mol == null || mol.getNumberOfAtoms() < 1) { + return; + } + parent.addMolecule(mol); + { + } + } + + public void cancelButton_actionPerformed(ActionEvent e) { + setVisible(false); + } +} diff --git a/src/main/java/cct/dialogs/SaveXYZDialog.java b/src/main/java/cct/dialogs/SaveXYZDialog.java new file mode 100644 index 0000000..3b54564 --- /dev/null +++ b/src/main/java/cct/dialogs/SaveXYZDialog.java @@ -0,0 +1,191 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.SystemColor; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +import javax.swing.BorderFactory; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.border.TitledBorder; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class SaveXYZDialog + extends JDialog { + + boolean okPressed = false; + + JPanel panel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JPanel atomTypesPanel = new JPanel(); + JPanel jPanel2 = new JPanel(); + JPanel unitsPanel = new JPanel(); + ButtonGroup atomsButtonGroup = new ButtonGroup(); + JRadioButton numberRadioButton = new JRadioButton(); + FlowLayout flowLayout1 = new FlowLayout(); + JRadioButton symbolRadioButton = new JRadioButton(); + ButtonGroup unitsButtonGroup = new ButtonGroup(); + JRadioButton angstromRadioButton = new JRadioButton(); + FlowLayout flowLayout2 = new FlowLayout(); + JRadioButton bohrRadioButton = new JRadioButton(); + JButton cancelButton = new JButton(); + JButton okButton = new JButton(); + + public SaveXYZDialog(Frame owner, String title) { + super(owner, title, true); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public SaveXYZDialog() { + this(new Frame(), "SaveXYZDialog"); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + this.setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); + numberRadioButton.setToolTipText(""); + numberRadioButton.setText("Element Numbers"); + atomTypesPanel.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + symbolRadioButton.setToolTipText(""); + symbolRadioButton.setSelected(true); + symbolRadioButton.setText("Element Symbols"); + atomTypesPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder(SystemColor.controlDkShadow, 1), "Atom Type Format")); + unitsPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder(SystemColor.controlDkShadow, 1), "Units")); + unitsPanel.setLayout(flowLayout2); + angstromRadioButton.setToolTipText(""); + angstromRadioButton.setSelected(true); + angstromRadioButton.setText("Angstroms"); + flowLayout2.setAlignment(FlowLayout.LEFT); + bohrRadioButton.setToolTipText(""); + bohrRadioButton.setText("Bohrs"); + cancelButton.setToolTipText(""); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + cancelButton_actionPerformed(e); + } + }); + okButton.setToolTipText(""); + okButton.setText(" OK "); + okButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + okButton_actionPerformed(e); + } + }); + getContentPane().add(panel1); + panel1.add(jPanel2, BorderLayout.SOUTH); + jPanel2.add(okButton); + jPanel2.add(cancelButton); + panel1.add(unitsPanel, BorderLayout.CENTER); + unitsPanel.add(angstromRadioButton); + unitsPanel.add(bohrRadioButton); + panel1.add(atomTypesPanel, BorderLayout.NORTH); + atomTypesPanel.add(symbolRadioButton); + atomTypesPanel.add(numberRadioButton); + atomsButtonGroup.add(symbolRadioButton); + atomsButtonGroup.add(numberRadioButton); + unitsButtonGroup.add(angstromRadioButton); + unitsButtonGroup.add(bohrRadioButton); + + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent we) { + okPressed = false; + we.getWindow().setVisible(false); + } + }); + + } + + public void okButton_actionPerformed(ActionEvent e) { + okPressed = true; + setVisible(false); + } + + public void cancelButton_actionPerformed(ActionEvent e) { + okPressed = false; + setVisible(false); + } + + public boolean isAtomicNumbers() { + return numberRadioButton.isSelected(); + } + + public boolean isAtomicSymbols() { + return this.symbolRadioButton.isSelected(); + } + + public boolean isInAngstroms() { + return this.angstromRadioButton.isSelected(); + } + + public boolean isInBohrs() { + return this.bohrRadioButton.isSelected(); + } +} diff --git a/src/main/java/cct/dialogs/SelectColorDialog.java b/src/main/java/cct/dialogs/SelectColorDialog.java new file mode 100644 index 0000000..502c025 --- /dev/null +++ b/src/main/java/cct/dialogs/SelectColorDialog.java @@ -0,0 +1,141 @@ +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; + +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JDialog; +import javax.swing.JPanel; + +import cct.interfaces.ColorChangerInterface; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class SelectColorDialog + extends JDialog implements ColorChangerInterface { + private JPanel panel1 = new JPanel(); + private BorderLayout borderLayout1 = new BorderLayout(); + private JPanel jPanel1 = new JPanel(); + private SelectColorPanel selectColorPanel1 = new SelectColorPanel(); + private JButton hideButton = new JButton(); + private JButton resetButton = new JButton(); + private ColorChangerInterface colorChangerInterface = null; + private JCheckBox previewCheckBox = new JCheckBox(); + private Color finalColor = null; + + public SelectColorDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public SelectColorDialog() { + this(new Frame(), "SelecColorDialog", false); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + hideButton.setToolTipText(""); + hideButton.setText(" Hide "); + hideButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + hideButton_actionPerformed(e); + } + }); + resetButton.setToolTipText(""); + resetButton.setText("Reset"); + resetButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + jButton2_actionPerformed(e); + } + }); + previewCheckBox.setToolTipText(""); + previewCheckBox.setSelected(true); + previewCheckBox.setText("Preview"); + previewCheckBox.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + previewCheckBox_itemStateChanged(e); + } + }); + getContentPane().add(panel1); + panel1.add(jPanel1, BorderLayout.SOUTH); + jPanel1.add(resetButton); + jPanel1.add(hideButton); + panel1.add(selectColorPanel1, BorderLayout.NORTH); + panel1.add(previewCheckBox, BorderLayout.CENTER); + + selectColorPanel1.setColorChangerInterface(this); + } + + public void setColorChangerInterface(ColorChangerInterface cci) { + colorChangerInterface = cci; + } + + @Override + public void setColor(Color newColor) { + finalColor = newColor; + if (colorChangerInterface != null && previewCheckBox.isSelected()) { + colorChangerInterface.setColor(finalColor); + } + } + + @Override + public void reset() { + if (colorChangerInterface != null) { + colorChangerInterface.reset(); + } + } + + @Override + public void stop() { + if (colorChangerInterface != null) { + colorChangerInterface.stop(); + } + } + + public void jButton2_actionPerformed(ActionEvent e) { + reset(); + } + + public void hideButton_actionPerformed(ActionEvent e) { + if (colorChangerInterface != null && !previewCheckBox.isSelected()) { + colorChangerInterface.setColor(finalColor); + } + stop(); + this.setVisible(false); + } + + public void previewCheckBox_itemStateChanged(ItemEvent e) { + if (e.getStateChange() == ItemEvent.SELECTED) { + if (colorChangerInterface != null && finalColor != null) { + colorChangerInterface.setColor(finalColor); + } + } + } + +} diff --git a/src/main/java/cct/dialogs/SelectColorPanel.java b/src/main/java/cct/dialogs/SelectColorPanel.java new file mode 100644 index 0000000..d8d4aad --- /dev/null +++ b/src/main/java/cct/dialogs/SelectColorPanel.java @@ -0,0 +1,58 @@ +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.Color; + +import javax.swing.JColorChooser; +import javax.swing.JPanel; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +import cct.interfaces.ColorChangerInterface; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class SelectColorPanel + extends JPanel implements ChangeListener { + private BorderLayout borderLayout1 = new BorderLayout(); + private JColorChooser jColorChooser1 = new JColorChooser(); + private ColorChangerInterface colorChangerInterface = null; + + public SelectColorPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + this.add(jColorChooser1, BorderLayout.NORTH); + jColorChooser1.getSelectionModel().addChangeListener(this); + } + + public void setColorChangerInterface(ColorChangerInterface cci) { + colorChangerInterface = cci; + } + + @Override + public void stateChanged(ChangeEvent e) { + Color newColor = jColorChooser1.getColor(); + if (colorChangerInterface != null) { + colorChangerInterface.setColor(newColor); + } + } + +} diff --git a/src/main/java/cct/dialogs/SelectListDialog.java b/src/main/java/cct/dialogs/SelectListDialog.java new file mode 100644 index 0000000..93b3518 --- /dev/null +++ b/src/main/java/cct/dialogs/SelectListDialog.java @@ -0,0 +1,174 @@ +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JList; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.ListSelectionModel; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class SelectListDialog + extends JDialog { + private JPanel panel1 = new JPanel(); + private BorderLayout borderLayout1 = new BorderLayout(); + private JScrollPane jScrollPane1 = new JScrollPane(); + private JList jList1 = new JList(); + private JPanel jPanel2 = new JPanel(); + private JButton cancelButton = new JButton(); + private JButton okButton = new JButton(); + + private boolean ok = false; + private JButton helpButton = new JButton(); + + public SelectListDialog(Frame owner, String title) { + super(owner, title, true); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public boolean showDialog() { + setVisible(true); + return ok; + } + + public void setList(Object[] list) { + jList1.setListData(list); + this.pack(); + } + + /** + * Sets selection mode for the JList. Determines whether single-item or multiple-item selections are allowed. + * @param mode int - selection mode. Can be + * ListSelectionModel.SINGLE_SELECTION - Only one list index can be selected at a time. + * In this mode the setSelectionInterval and addSelectionInterval methods are equivalent, + * and only the second index argument is used. + * ListSelectionModel.SINGLE_INTERVAL_SELECTION - One contiguous index interval can be selected at a time. In this mode setSelectionInterval and addSelectionInterval are equivalent. + * ListSelectionModel.MULTIPLE_INTERVAL_SELECTION - In this mode, there's no restriction on what can be selected. This is the default. + */ + public void setSelectionMode(int mode) { + jList1.setSelectionMode(mode); + } + + public SelectListDialog() { + this(new Frame(), "SelectListDialog"); + } + + public int getSelectedIndex() { + return jList1.getSelectedIndex(); + } + + public int[] getSelectedIndeces() { + return jList1.getSelectedIndices(); + } + + public Object[] getSelectedValues() { + if (!ok) { + return null; + } + if (jList1.getSelectionMode() == ListSelectionModel.SINGLE_SELECTION) { + if (jList1.getSelectedValue() == null) { + return null; + } + return new Object[] { + jList1.getSelectedValue()}; + } + if (jList1.getSelectedValues() == null || jList1.getSelectedValues().length < 1) { + return null; + } + return jList1.getSelectedValues(); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + cancelButton.setToolTipText("Cancel Selection"); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + cancelButton_actionPerformed(e); + } + }); + okButton.setToolTipText("Confirm Selection"); + okButton.setText(" OK "); + okButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + okButton_actionPerformed(e); + } + }); + helpButton.setToolTipText("Get Quick Help forl Selection"); + helpButton.setActionCommand("help"); + helpButton.setText(" Help "); + helpButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + helpButton_actionPerformed(e); + } + }); + getContentPane().add(panel1); + panel1.add(jScrollPane1, BorderLayout.CENTER); + jScrollPane1.getViewport().add(jList1); + jPanel2.add(okButton); + jPanel2.add(cancelButton); + jPanel2.add(helpButton); + panel1.add(jPanel2, BorderLayout.SOUTH); + } + + public void okButton_actionPerformed(ActionEvent e) { + ok = true; + setVisible(false); + } + + public void cancelButton_actionPerformed(ActionEvent e) { + ok = false; + setVisible(false); + } + + public void helpButton_actionPerformed(ActionEvent e) { + if (jList1.getSelectionMode() == ListSelectionModel.SINGLE_SELECTION) { + JOptionPane.showMessageDialog(this, + "Only one list value can be selected at a time\n" + + "OK - to confirm selection\nCancel - to cancel selection", "Help", + JOptionPane.INFORMATION_MESSAGE); + } + else if (jList1.getSelectionMode() == ListSelectionModel.SINGLE_INTERVAL_SELECTION) { + JOptionPane.showMessageDialog(this, + "One contiguous index interval can be selected at a time.\n" + + "Use mouse in combination with Shift and Ctrl keys to select/unselect blocks of values\n" + + "OK - to confirm selection\nCancel - to cancel selection", "Help", + JOptionPane.INFORMATION_MESSAGE); + } + else if (jList1.getSelectionMode() == ListSelectionModel.MULTIPLE_INTERVAL_SELECTION) { + JOptionPane.showMessageDialog(this, + "There's no restriction on what can be selected.\n" + + "Use mouse in combination with Shift and Ctrl keys to select/unselect blocks of values\n" + + "OK - to confirm selection\nCancel - to cancel selection", "Help", + JOptionPane.INFORMATION_MESSAGE); + } + + } +} diff --git a/src/main/java/cct/dialogs/SelectPropShowDialog.java b/src/main/java/cct/dialogs/SelectPropShowDialog.java new file mode 100644 index 0000000..99b1fbd --- /dev/null +++ b/src/main/java/cct/dialogs/SelectPropShowDialog.java @@ -0,0 +1,286 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.SystemColor; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JDialog; +import javax.swing.JPanel; +import javax.swing.border.TitledBorder; + +import cct.interfaces.OutputResultsInterface; +import cct.modelling.VIBRATIONAL_SPECTRUM; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class SelectPropShowDialog + extends JDialog { + private JPanel panel1 = new JPanel(); + private BorderLayout borderLayout1 = new BorderLayout(); + private JCheckBox jobSummaryCheckBox = new JCheckBox(); + private JPanel jPanel1 = new JPanel(); + private BorderLayout borderLayout2 = new BorderLayout(); + private JCheckBox mdCheckBox = new JCheckBox(); + private BorderLayout borderLayout3 = new BorderLayout(); + private JPanel vibrationsPanel = new JPanel(); + private JCheckBox vcdCheckBox = new JCheckBox(); + private JCheckBox uDepolCheckBox = new JCheckBox(); + private JCheckBox pDepolCheckBox = new JCheckBox(); + private JCheckBox ramanCheckBox = new JCheckBox(); + private JCheckBox infraredCheckBox = new JCheckBox(); + private GridBagLayout gridBagLayout1 = new GridBagLayout(); + private JPanel buttonsPanel = new JPanel(); + private JButton cancelButton = new JButton(); + private JButton okButton = new JButton(); + + private Map refTable = new HashMap (); + + java.util.List freq = new ArrayList (); + private boolean okPressed = true; + + public SelectPropShowDialog(Frame owner, String title) { + super(owner, title, true); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public SelectPropShowDialog() { + this(new Frame(), "SelectPropShowDialog"); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + this.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); + this.getContentPane().setLayout(borderLayout2); + jobSummaryCheckBox.setText("Show Job Summary"); + mdCheckBox.setToolTipText(""); + mdCheckBox.setText("Show Interactive Chart for MD/Minimization"); + jPanel1.setLayout(borderLayout3); + vibrationsPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder(SystemColor.controlDkShadow, 1), + "Vibrational Spectra")); + vibrationsPanel.setLayout(gridBagLayout1); + vcdCheckBox.setToolTipText(""); + vcdCheckBox.setText("VCD Rotational Strength Spectrum"); + uDepolCheckBox.setToolTipText(""); + uDepolCheckBox.setText("U-Depolarization Spectrum"); + pDepolCheckBox.setToolTipText(""); + pDepolCheckBox.setText("P-Depolarization Spectrum"); + ramanCheckBox.setToolTipText(""); + ramanCheckBox.setText("Raman Spectrum"); + infraredCheckBox.setToolTipText(""); + infraredCheckBox.setText("Infrared Spectrum"); + cancelButton.setToolTipText(""); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + cancelButton_actionPerformed(e); + } + }); + okButton.setToolTipText(""); + okButton.setText(" OK "); + okButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + okButton_actionPerformed(e); + } + }); + panel1.add(jPanel1, BorderLayout.CENTER); + this.getContentPane().add(panel1, BorderLayout.CENTER); + jPanel1.add(vibrationsPanel, BorderLayout.CENTER); + jPanel1.add(mdCheckBox, BorderLayout.NORTH); + vibrationsPanel.add(ramanCheckBox, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + vibrationsPanel.add(pDepolCheckBox, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + vibrationsPanel.add(uDepolCheckBox, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + vibrationsPanel.add(infraredCheckBox, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + vibrationsPanel.add(vcdCheckBox, new GridBagConstraints(0, 4, 1, 1, 0.0, 1.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + panel1.add(jobSummaryCheckBox, BorderLayout.NORTH); + panel1.add(buttonsPanel, BorderLayout.SOUTH); + buttonsPanel.add(okButton); + buttonsPanel.add(cancelButton); + + freq.add(vcdCheckBox); + freq.add(uDepolCheckBox); + freq.add(pDepolCheckBox); + freq.add(ramanCheckBox); + freq.add(infraredCheckBox); + + refTable.put(infraredCheckBox, VIBRATIONAL_SPECTRUM.INFRARED_SPECTRUM); + refTable.put(ramanCheckBox, VIBRATIONAL_SPECTRUM.RAMAN_SPECTRUM); + refTable.put(pDepolCheckBox, VIBRATIONAL_SPECTRUM.P_DEPOLARIZATION_SPECTRUM); + refTable.put(uDepolCheckBox, VIBRATIONAL_SPECTRUM.U_DEPOLARIZATION_SPECTRUM); + refTable.put(vcdCheckBox, VIBRATIONAL_SPECTRUM.VCD_ROTATIONAL_STRENGTH_SPECTRUM); + } + + /** + * Dialog should be shown using this function (not by using setVisible(true)) + * @return boolean - "true" - OK button was pressed, "false" - Cancel one + */ + public boolean showDialog() { + boolean toShow = false; + // --- First decide to show or not vibrational spectra panel + for (int i = 0; i < freq.size(); i++) { + JCheckBox jCheckBox = freq.get(i); + toShow |= jCheckBox.isSelected(); + jCheckBox.setVisible(jCheckBox.isSelected()); + } + vibrationsPanel.setVisible(toShow); + + // Show other checkboxes? + + toShow |= jobSummaryCheckBox.isSelected(); + jobSummaryCheckBox.setVisible(jobSummaryCheckBox.isSelected()); + + toShow |= mdCheckBox.isSelected(); + mdCheckBox.setVisible(mdCheckBox.isSelected()); + + if (!toShow) { + return false; + } + + this.setVisible(true); + return okPressed; + } + + public void setControls(OutputResultsInterface res) { + enableSummary(res.hasJobSummary()); + enableInteractiveChart(res.hasInteractiveChart()); + enableVCDSpectrum(res.hasVCDSpectrum()); + enableUDepolSpectrum(res.hasUDepolSpectrum()); + enablePDepolSpectrum(res.hasPDepolSpectrum()); + enableRamanSpectrum(res.hasRamanSpectrum()); + enableInfraredSpectrum(res.hasInfraredSpectrum()); + } + + public void enableSummary(boolean enable) { + jobSummaryCheckBox.setSelected(enable); + } + + public boolean isShowSummary() { + return jobSummaryCheckBox.isSelected(); + } + + public VIBRATIONAL_SPECTRUM[] spectraToShow() { + java.util.List toShow = new ArrayList (); + for (int i = 0; i < freq.size(); i++) { + JCheckBox jCheckBox = freq.get(i); + if (jCheckBox.isSelected()) { + toShow.add(refTable.get(jCheckBox)); + } + } + if (toShow.size() < 1) { + return null; + } + VIBRATIONAL_SPECTRUM[] spectra = new VIBRATIONAL_SPECTRUM[toShow.size()]; + toShow.toArray(spectra); + return spectra; + } + + public void enableInteractiveChart(boolean enable) { + mdCheckBox.setSelected(enable); + } + + public boolean isShowInteractiveChart() { + return mdCheckBox.isSelected(); + } + + public void enableVCDSpectrum(boolean enable) { + vcdCheckBox.setSelected(enable); + } + + public void enableUDepolSpectrum(boolean enable) { + uDepolCheckBox.setSelected(enable); + } + + public void enablePDepolSpectrum(boolean enable) { + pDepolCheckBox.setSelected(enable); + } + + public void enableRamanSpectrum(boolean enable) { + ramanCheckBox.setSelected(enable); + } + + public void enableInfraredSpectrum(boolean enable) { + infraredCheckBox.setSelected(enable); + } + + public void okButton_actionPerformed(ActionEvent e) { + okPressed = true; + this.setVisible(false); + } + + public void cancelButton_actionPerformed(ActionEvent e) { + okPressed = false; + this.setVisible(false); + + } +} diff --git a/src/main/java/cct/dialogs/SetupMenu.java b/src/main/java/cct/dialogs/SetupMenu.java new file mode 100644 index 0000000..cb47191 --- /dev/null +++ b/src/main/java/cct/dialogs/SetupMenu.java @@ -0,0 +1,307 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.dialogs; + +import java.awt.Color; +import java.awt.Component; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.swing.ButtonGroup; +import javax.swing.JColorChooser; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JRadioButtonMenuItem; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +import cct.interfaces.JamberooCoreInterface; +import cct.j3d.ChemicalElementsColors; +import cct.j3d.Java3dUniverse; +import cct.tools.SwingLookAndFeel; + +/** + * + * @author vvv900 + */ +public class SetupMenu extends JMenu implements ActionListener { + + public enum SETUP_MENU_ACTIONS { + + UNKNOWN, ATOM_COLOR_SCHEME, LOOK_AND_FEEL, BACKGROUND_COLOR + } + private JamberooCoreInterface jamberooCore; + private Java3dUniverse java3dUniverse; + private Component parentComponent; + private JMenu jSubmenuAtomColorScheme = new JMenu(); + private JMenu jSubmenuLookAndFeel = new JMenu(); + private JMenu projectionMode = new JMenu("Projection Mode"); + private JMenuItem jBackgroundColor = new JMenuItem("Background Color"); + static final Logger logger = Logger.getLogger(SetupMenu.class.getCanonicalName()); + + public SetupMenu(JamberooCoreInterface core) { + super(); + jamberooCore = core; + java3dUniverse = jamberooCore.getJamberooRenderer(); + parentComponent = this; + } + + public void createMenu() { + + // --- Atom color scheme submenu + + ColorSchemeHamdler colorSchemeHamdler = new ColorSchemeHamdler(); + jSubmenuAtomColorScheme.setText("Atom Color Scheme"); + ChemicalElementsColors.retrieveAtomColorSchemePrefs(this.getClass()); + String atomScheme[] = ChemicalElementsColors.getAtomColorSchemeNames(); + String currentColorScheme = ChemicalElementsColors.getCurrentAtomColorScheme(); + ButtonGroup colorSchemeGroup = new ButtonGroup(); + for (int i = 0; i < atomScheme.length; i++) { + JRadioButtonMenuItem jRadio = new JRadioButtonMenuItem(atomScheme[i]); + //jRadio.setActionCommand(SETUP_MENU_ACTIONS.ATOM_COLOR_SCHEME.name()); + jRadio.setSelected(currentColorScheme.equals(atomScheme[i])); + jRadio.addActionListener(colorSchemeHamdler); + colorSchemeGroup.add(jRadio); + jSubmenuAtomColorScheme.add(jRadio); + } + + // --- Look and feel ubmenu + + LookAndFeelHamdler lookAndFeelHamdler = new LookAndFeelHamdler(); + jSubmenuLookAndFeel.setText("Look & Feel"); + String look = SwingLookAndFeel.retrieveLookAndFeelPrefs(this.getClass()); + String feels[] = SwingLookAndFeel.getAvailableLookAndFeels(); + ButtonGroup lookAndFeelGroup = new ButtonGroup(); + for (int i = 0; i < feels.length; i++) { + JRadioButtonMenuItem jRadio = new JRadioButtonMenuItem(); + + jRadio.setText(feels[i]); + + if (look != null && look.equalsIgnoreCase(feels[i])) { + jRadio.setSelected(true); + try { + SwingLookAndFeel.setLookAndFeel(look); + SwingUtilities.updateComponentTreeUI(this); + } catch (Exception ex) { + } + } else { + jRadio.setSelected(false); + } + //jRadio.setActionCommand(SETUP_MENU_ACTIONS.LOOK_AND_FEEL.name()); + jRadio.addActionListener(lookAndFeelHamdler); + lookAndFeelGroup.add(jRadio); + jSubmenuLookAndFeel.add(jRadio); + + if (look == null) { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (Exception exception) { + exception.printStackTrace(); + } + + } + } + + // --- Projection mode + + String[] prModes = java3dUniverse.getProjectionModes(); + ButtonGroup projectionModeGroup = new ButtonGroup(); + for (int i = 0; i < prModes.length; i++) { + JRadioButtonMenuItem jRadio = new JRadioButtonMenuItem(prModes[i]); + jRadio.setSelected(java3dUniverse.getProjectionModeAsString(). + equals(prModes[i])); + jRadio.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + JRadioButtonMenuItem mode = (JRadioButtonMenuItem) e.getSource(); + java3dUniverse.setProjection(mode.getText()); + } + }); + projectionModeGroup.add(jRadio); + projectionMode.add(jRadio); + } + + // --- Setup Background color + + jBackgroundColor.setActionCommand(SETUP_MENU_ACTIONS.BACKGROUND_COLOR.name()); + jBackgroundColor.addActionListener(this); + + // --- Setup atominfo popup + + JRadioButtonMenuItem atomInfo = new JRadioButtonMenuItem(); + atomInfo.setSelected(java3dUniverse.atomInfoPopupEnabled()); + if (atomInfo.isSelected()) { + atomInfo.setText("Atom Info Popup Enabled"); + } else { + atomInfo.setText("Atom Info Popup Disabled"); + } + atomInfo.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + JRadioButtonMenuItem atomInfo = (JRadioButtonMenuItem) e.getSource(); + java3dUniverse.enableAtomInfoPopup(atomInfo.isSelected()); + if (atomInfo.isSelected()) { + atomInfo.setText("Atom Info Popup Enabled"); + } else { + atomInfo.setText("Atom Info Popup Disabled"); + } + } + }); + + // --- Setup global logging level + + JRadioButtonMenuItem globalLogging = new JRadioButtonMenuItem(); + Level level = Logger.getLogger("").getLevel(); + globalLogging.setSelected(level.intValue() <= 800); // 800 is for the INFO level + if (globalLogging.isSelected()) { + globalLogging.setText("Verbose Logging"); + } else { + globalLogging.setText("Warnings and errors Logging"); + } + globalLogging.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + JRadioButtonMenuItem globalLogging = (JRadioButtonMenuItem) e.getSource(); + if (globalLogging.isSelected()) { + globalLogging.setText("Verbose Logging"); + Logger.getLogger("").setLevel(Level.INFO); + } else { + globalLogging.setText("Warnings and errors Logging"); + Logger.getLogger("").setLevel(Level.WARNING); + } + } + }); + + add(jSubmenuAtomColorScheme); + add(jSubmenuLookAndFeel); + add(projectionMode); + add(jBackgroundColor); + add(atomInfo); + add(globalLogging); + } + + @Override + public void actionPerformed(ActionEvent actionEvent) { + String actionCommand = actionEvent.getActionCommand(); + + // --- Get action command + + SETUP_MENU_ACTIONS action = SETUP_MENU_ACTIONS.UNKNOWN; + try { + action = SETUP_MENU_ACTIONS.valueOf(actionCommand); + } catch (Exception ex) { + logger.warning("Unknown setup menu action: " + actionCommand); + return; + } + String arg; + + switch (action) { + /* + case ATOM_COLOR_SCHEME: + jSubmenuAtomColorScheme.setEnabled(false); + arg = (String) actionEvent.getActionCommand(); + ChemicalElementsColors.setCurrentAtomColorScheme(arg); + ChemicalElementsColors.saveAtomColorSchemePrefs(this.getClass()); + if (java3dUniverse.getMoleculeInterface() == null) { + return; + } + java3dUniverse.updateAtomColorScheme(); + jSubmenuAtomColorScheme.setEnabled(true); + break; + * + */ + /* + case LOOK_AND_FEEL: + jSubmenuLookAndFeel.setEnabled(false); + arg = (String) actionEvent.getActionCommand(); + //arg = arg.substring(0, arg.indexOf("(")).trim(); + + try { + SwingLookAndFeel.setLookAndFeel(arg); + SwingUtilities.updateComponentTreeUI(this); + SwingLookAndFeel.saveLookAndFeelPrefs(this.getClass()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), "Error Changing L&F", JOptionPane.ERROR_MESSAGE); + } + jSubmenuLookAndFeel.setEnabled(true); + break; + * + */ + + case BACKGROUND_COLOR: + if (java3dUniverse == null) { + return; + } + Color bgColor = java3dUniverse.getBackgroundColor(); + if (bgColor == null) { + JOptionPane.showMessageDialog(this, "Cannot setup background color", "Error getting background color", + JOptionPane.ERROR_MESSAGE); + jBackgroundColor.setEnabled(false); + return; + } + Color c = JColorChooser.showDialog(this.getParent(), "Choose Background Color", bgColor); + if (c != null) { + java3dUniverse.setBackgroundColor(c.getRed(), c.getGreen(), c.getBlue()); + } + break; + } + } + + public Component getParentComponent() { + return parentComponent; + } + + public void setParentComponent(Component parentComponent) { + this.parentComponent = parentComponent; + } + + class ColorSchemeHamdler implements ActionListener { + + @Override + public void actionPerformed(ActionEvent actionEvent) { + if (!(actionEvent.getSource() instanceof JRadioButtonMenuItem)) { + return; + } + + jSubmenuAtomColorScheme.setEnabled(false); + String arg = actionEvent.getActionCommand(); + ChemicalElementsColors.setCurrentAtomColorScheme(arg); + ChemicalElementsColors.saveAtomColorSchemePrefs(this.getClass()); + if (java3dUniverse.getMoleculeInterface() == null) { + return; + } + java3dUniverse.updateAtomColorScheme(); + jSubmenuAtomColorScheme.setEnabled(true); + } + } + + class LookAndFeelHamdler implements ActionListener { + + @Override + public void actionPerformed(ActionEvent actionEvent) { + if (!(actionEvent.getSource() instanceof JRadioButtonMenuItem)) { + return; + } + + jSubmenuLookAndFeel.setEnabled(false); + String arg = actionEvent.getActionCommand(); + + try { + SwingLookAndFeel.setLookAndFeel(arg); + SwingUtilities.updateComponentTreeUI(parentComponent); + SwingLookAndFeel.saveLookAndFeelPrefs(this.getClass()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error Changing L&F", JOptionPane.ERROR_MESSAGE); + } + jSubmenuLookAndFeel.setEnabled(true); + } + } +} diff --git a/src/main/java/cct/dialogs/ToolsMenu.java b/src/main/java/cct/dialogs/ToolsMenu.java new file mode 100644 index 0000000..19f549a --- /dev/null +++ b/src/main/java/cct/dialogs/ToolsMenu.java @@ -0,0 +1,124 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.dialogs; + +import java.awt.Component; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.WindowConstants; + +import cct.GlobalSettings; +import cct.amber.Sander8Frame; +import cct.amber.Sander8JobControl; +import cct.interfaces.JamberooCoreInterface; +import cct.tools.ui.JShowText; +import cct.tools.ui.MemoryMonitorFrame; + +/** + * + * @author vvv900 + */ +public class ToolsMenu extends JMenu { + + private Sander8Frame sander8InputEditor = null; + private MemoryMonitorFrame memoryMonitorFrame = null; + private JamberooCoreInterface jamberooCore; + private Component parentComponent; + + public ToolsMenu(JamberooCoreInterface core) { + super(); + jamberooCore = core; + } + + public void createMenu() { + JMenuItem jMenuSFTBrowser = new JMenuItem("Sftp Browser"); + jMenuSFTBrowser.setIcon(GlobalSettings.ICON_16x16_SERVER_CLIENT); + jMenuSFTBrowser.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + jamberooCore.getShadowSFTPManager().startFileBrowser(); + } + }); + add(jMenuSFTBrowser); + + JMenuItem startSander8 = new JMenuItem("Amber: input file for Sander-8"); + startSander8.setIcon(GlobalSettings.ICON_16x16_DOCUMENT_GEAR); + startSander8.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + if (sander8InputEditor == null) { + sander8InputEditor = new Sander8Frame(new Sander8JobControl()); + sander8InputEditor.setLocationByPlatform(true); + sander8InputEditor.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); + } + sander8InputEditor.setVisible(true); + } + }); + add(startSander8); + + // --- Information stuff + + JMenuItem systemInfo = new JMenuItem("System Info"); + systemInfo.setIcon(GlobalSettings.ICON_16x16_DOCUMENT_INFO); + systemInfo.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + JShowText showResume = new JShowText("System Info"); + showResume.enableTextEditing(false); + showResume.setSize(600, 640); + showResume.setLocationByPlatform(true); + showResume.setText(cct.tools.Utils.getSystemInfoAsString()); + showResume.setVisible(true); + } + }); + + JMenuItem memoryMonitor = new JMenuItem("Memory Usage"); + memoryMonitor.setIcon(GlobalSettings.ICON_16x16_MEMORY_MONITOR); + memoryMonitor.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + if (memoryMonitorFrame == null) { + memoryMonitorFrame = new MemoryMonitorFrame(); + memoryMonitorFrame.setSize(300, 200); + memoryMonitorFrame.setLocationRelativeTo(getParentComponent()); + } + memoryMonitorFrame.setVisible(true); + } + }); + + JMenuItem garbageCollection = new JMenuItem("Free Unused Memory"); + garbageCollection.setIcon(GlobalSettings.ICON_16x16_RECYCLE); + garbageCollection.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + Runtime.getRuntime().gc(); + } + }); + + addSeparator(); + add(systemInfo); + add(memoryMonitor); + add(garbageCollection); + + } + + + public Component getParentComponent() { + return parentComponent == null ? this : parentComponent; + } + + public void setParentComponent(Component parentComponent) { + this.parentComponent = parentComponent; + } + +} diff --git a/src/main/java/cct/dialogs/TrajectoriesManagerPanel.java b/src/main/java/cct/dialogs/TrajectoriesManagerPanel.java new file mode 100644 index 0000000..0dbda5a --- /dev/null +++ b/src/main/java/cct/dialogs/TrajectoriesManagerPanel.java @@ -0,0 +1,363 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.logging.Logger; +import java.util.prefs.Preferences; + +import javax.swing.JButton; +import javax.swing.JFileChooser; +import javax.swing.JList; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.filechooser.FileFilter; + +import cct.interfaces.MoleculeInterface; +import cct.modelling.MolecularFileFormats; +import cct.modelling.StructureManager; +import cct.modelling.TRAJECTORY_FILE_FORMAT; +import cct.modelling.TrajectoryClientInterface; +import cct.tools.FileFilterImpl; +import cct.tools.ui.TaskProgessDialog; +import java.awt.Container; +import java.awt.Cursor; +import javax.accessibility.AccessibleContext; +import javax.swing.JComponent; +import javax.swing.SwingWorker; + +/** + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class TrajectoriesManagerPanel + extends JPanel { + + private static String lastPWDKey = "lastPWD"; + + enum JOB_TYPE { + + LOAD_TRAJECTORY + } + + protected BorderLayout borderLayout1 = new BorderLayout(); + protected JPanel jPanel1 = new JPanel(); + protected JPanel jPanel2 = new JPanel(); + protected JScrollPane jScrollPane1 = new JScrollPane(); + protected JList trajList = new JList(); + protected JButton loadButton = new JButton(); + protected JButton deleteButton = new JButton(); + protected JButton helpButton = new JButton(); + + protected JFileChooser fileChooser = null; + protected Preferences prefs = Preferences.userNodeForPackage(getClass()); + protected File currentWorkingDirectory = null; + + protected StructureManager structureManager = null; + protected Map validFormats = new LinkedHashMap(); + protected Map loadedTrajectories = new LinkedHashMap(); + protected TrajectoryClientInterface trajectoryClientInterface = null; + protected JButton delAllButton = new JButton(); + private TaskProgessDialog taskProgessDialog = null; + private TRAJECTORY_FILE_FORMAT format; + private String fileName; + static final Logger logger = Logger.getLogger(TrajectoriesManagerPanel.class.getCanonicalName()); + + public TrajectoriesManagerPanel(MoleculeInterface referenceStructure) { + structureManager = new StructureManager(referenceStructure); + try { + jbInit(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public TrajectoriesManagerPanel() { + try { + jbInit(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public void setTrajectoryClientInterface(TrajectoryClientInterface traj) { + trajectoryClientInterface = traj; + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + loadButton.setToolTipText("Load New Trajectory"); + loadButton.setText(" Load "); + loadButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + loadButton_actionPerformed(e); + } + }); + deleteButton.setToolTipText("Delete selected Trajectories from the List"); + deleteButton.setText("Delete Selected"); + helpButton.setToolTipText(""); + helpButton.setText(" Help "); + delAllButton.setToolTipText("Delete selected Trajectories from the List"); + delAllButton.setText("Delete All"); + delAllButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + delAllButton_actionPerformed(e); + } + }); + jPanel2.add(jScrollPane1); + jScrollPane1.getViewport().add(trajList); + this.add(jPanel1, BorderLayout.CENTER); + jPanel1.add(loadButton); + jPanel1.add(deleteButton); + jPanel1.add(delAllButton); + jPanel1.add(helpButton); + this.add(jPanel2, BorderLayout.NORTH); + } + + public void loadButton_actionPerformed(ActionEvent e) { + + if (fileChooser == null) { + fileChooser = new JFileChooser(); + FileFilterImpl[] filter = MolecularFileFormats.formTrajectoryFileFilters(); + validFormats = MolecularFileFormats.formTrajectoryFileRef(); + for (int i = 0; i < filter.length; i++) { + fileChooser.setFileFilter(filter[i]); + } + fileChooser.setDialogType(JFileChooser.OPEN_DIALOG); + fileChooser.setDialogTitle("Open Trajectory file"); + fileChooser.setAcceptAllFileFilterUsed(false); + + if (currentWorkingDirectory != null) { + fileChooser.setCurrentDirectory(currentWorkingDirectory); + } else { + String lastPWD = prefs.get(lastPWDKey, ""); + if (lastPWD.length() > 0) { + currentWorkingDirectory = new File(lastPWD); + if (currentWorkingDirectory.isDirectory() + && currentWorkingDirectory.exists()) { + fileChooser.setCurrentDirectory(currentWorkingDirectory); + } + } + } + + } + + int returnVal = JFileChooser.CANCEL_OPTION; + + returnVal = fileChooser.showOpenDialog(this); + + if (returnVal != JFileChooser.APPROVE_OPTION) { + return; + } + + fileName = fileChooser.getSelectedFile().getPath(); + currentWorkingDirectory = fileChooser.getCurrentDirectory(); + try { + prefs.put(lastPWDKey, currentWorkingDirectory.getAbsolutePath()); + } catch (Exception ex) { + System.err.println("Cannot save cwd: " + ex.getMessage() + " Ignored..."); + } + logger.info("You chose to open a file: " + fileName); + + FileFilter ff = fileChooser.getFileFilter(); + + format = validFormats.get(ff.getDescription()); + if (structureManager == null) { + JOptionPane.showMessageDialog(this, "Structure Manager is not set", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + initTaskProgressDialog(); + PerformTrajectoryTask task + = new PerformTrajectoryTask(this, taskProgessDialog, JOB_TYPE.LOAD_TRAJECTORY); + task.execute(); + + /* + try { + structureManager.parseTrajectoryFile(fileName, format); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + String[] files = structureManager.getAvailableTrajectories(); + trajList.removeAll(); + if (files != null) { + trajList.setListData(files); + } + + if (trajectoryClientInterface != null) { + trajectoryClientInterface.setSnapshotsCount(structureManager.getSnapshotsCount()); + } + */ + } + + public void initTaskProgressDialog() { + if (taskProgessDialog == null) { + java.awt.Frame parentFrame = null; + Object parentObj = null; + Container cont = this.getParent(); + while ((parentObj = cont) != null) { + if (parentObj instanceof java.awt.Frame) { + parentFrame = (java.awt.Frame) parentObj; + break; + } + cont = ((Container) parentObj).getParent(); + } + taskProgessDialog = new TaskProgessDialog(parentFrame, false); + taskProgessDialog.setLocationRelativeTo(this); + taskProgessDialog.showHelpButton(false); + taskProgessDialog.setAlwaysOnTop(true); + } else { + taskProgessDialog.setProgress(0); // Reset progress bar + } + } + + public StructureManager getStructureManager() { + return structureManager; + } + + public void delAllButton_actionPerformed(ActionEvent e) { + this.deleteAlltrajectories(); + } + + public void deleteAlltrajectories() { + String[] files = new String[0]; + trajList.removeAll(); + trajList.setListData(files); + structureManager.deleteAllTrajectories(); + if (trajectoryClientInterface != null) { + trajectoryClientInterface.setSnapshotsCount(structureManager.getSnapshotsCount()); + } + this.validate(); + } + + public void setReferenceMolecule(MoleculeInterface mol) { + if (structureManager == null) { + structureManager = new StructureManager(mol); + } else { + structureManager.setReferenceMolecule(mol); + } + } + + class PerformTrajectoryTask extends SwingWorker { + + JComponent jComponent; + TaskProgessDialog progress; + boolean done = false; + JOB_TYPE job; + + PerformTrajectoryTask(JComponent jComponent, TaskProgessDialog progress, JOB_TYPE job) { + //initialize + this.progress = progress; + this.job = job; + this.jComponent = jComponent; + + AccessibleContext accessibleContext = jComponent.getAccessibleContext(); + + } + + @Override + public Void doInBackground() { + jComponent.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + jComponent.setEnabled(false); + progress.setCanceled(false); + progress.setVisible(true); + try { + switch (job) { + case LOAD_TRAJECTORY: + try { + structureManager.parseTrajectoryFile(fileName, format, progress); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + String[] files = structureManager.getAvailableTrajectories(); + trajList.removeAll(); + if (files != null) { + trajList.setListData(files); + } + + if (trajectoryClientInterface != null) { + trajectoryClientInterface.setSnapshotsCount(structureManager.getSnapshotsCount()); + } + progress.setProgress(0); + if (progress.isCanceled()) { + JOptionPane.showMessageDialog(null, "Trajectory loading was cancelled. Not all snapshots might be loaded.", + "Warning", JOptionPane.WARNING_MESSAGE); + } + return null; + default: + JOptionPane.showMessageDialog(null, "Option " + job.toString() + " is not implemented yet", "Error", JOptionPane.ERROR_MESSAGE); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + @Override + public void done() { + //parentDialog.setEnabled(true); + jComponent.setEnabled(true); + jComponent.setCursor(null); + progress.setVisible(false); + progress.setCanceled(false); + done = true; + } + } + +} diff --git a/src/main/java/cct/dialogs/TrajectoryAnalysisDialog.java b/src/main/java/cct/dialogs/TrajectoryAnalysisDialog.java new file mode 100644 index 0000000..61d7b83 --- /dev/null +++ b/src/main/java/cct/dialogs/TrajectoryAnalysisDialog.java @@ -0,0 +1,332 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.dialogs; + +import cct.chart.ChartFrame; +import cct.chart.PropsToChartDialog; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.logging.Logger; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTabbedPane; +import javax.swing.border.Border; +import javax.swing.border.TitledBorder; + +import cct.interfaces.MoleculeInterface; +import cct.j3d.ImageSequenceManager; +import cct.j3d.Java3dUniverse; +import cct.modelling.StructureManager; +import cct.modelling.StructureManagerInterface; +import cct.modelling.TrajectoryClientInterface; +import cct.tools.DataSets; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.logging.Level; +import static javax.swing.JOptionPane.ERROR_MESSAGE; + +/** + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class TrajectoryAnalysisDialog + extends JDialog implements TrajectoryClientInterface, StructureManagerInterface, ItemListener, ActionListener { + + protected JPanel panel1 = new JPanel(); + protected BorderLayout borderLayout1 = new BorderLayout(); + protected JTabbedPane mainTabbedPane = new JTabbedPane(); + protected JPanel mainPanel = new JPanel(); + protected BorderLayout borderLayout2 = new BorderLayout(); + protected TrajectoriesManagerPanel trajectoriesManagerPanel = new TrajectoriesManagerPanel(); + protected AnimationPanel animationPanel = new AnimationPanel(this); + private ImageSequencePanel imageSequencePanel = new ImageSequencePanel(); + protected JPanel buttonPanel = new JPanel(); + protected JButton hideButton = new JButton(); + protected JButton plotButton = new JButton(); + protected Border border1 = BorderFactory.createLineBorder(Color.darkGray, 1); + protected Border border2 = new TitledBorder(border1, "Animation Controls"); + protected Border border3 = BorderFactory.createLineBorder(Color.darkGray, 1); + protected Border border4 = new TitledBorder(border3, "Loaded Trajectories"); + static final Logger logger = Logger.getLogger(TrajectoryAnalysisDialog.class.getCanonicalName()); + + private float[][] Coordinates = null; + private javax.swing.JCheckBox generateImageSeqCheckBox; + private javax.swing.JComboBox imageSeqFormatComboBox; + + //protected MoleculeInterface referenceStructure = null; + private Java3dUniverse java3dUniverse = null; + private ImageSequenceManager imageSequenceManager; + + public TrajectoryAnalysisDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public TrajectoryAnalysisDialog() { + this(new Frame(), "TrajectoryAnalysisDialog", false); + } + + public void setRenderer(Java3dUniverse j3d) { + java3dUniverse = j3d; + imageSequenceManager = new ImageSequenceManager(java3dUniverse); + + imageSequencePanel.setImageSeqFormatComboBox(imageSequenceManager.getAvailableFormats()); + imageSequencePanel.getImageSeqFormatComboBox().setSelectedIndex(0); + + trajectoriesManagerPanel.setReferenceMolecule(java3dUniverse.getMoleculeInterface()); + allocateCoordinates(java3dUniverse.getMoleculeInterface()); + } + + void allocateCoordinates(MoleculeInterface mol) { + if (mol == null || mol.getNumberOfAtoms() < 1) { + Coordinates = null; + } else { + Coordinates = new float[mol.getNumberOfAtoms()][3]; + } + } + + private void jbInit() throws Exception { + + animationPanel.setStructureManagerInterface(this); + + border4 = new TitledBorder(BorderFactory.createLineBorder(Color.darkGray, 1), "Loaded Trajectories"); + border2 = new TitledBorder(BorderFactory.createLineBorder(Color.darkGray, 1), "Animation Controls"); + panel1.setLayout(borderLayout1); + mainPanel.setLayout(borderLayout2); + animationPanel.setBorder(border2); + hideButton.setToolTipText("Hide Dialog"); + hideButton.setText(" Hide "); + hideButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + hideButton_actionPerformed(e); + } + }); + // --- + plotButton.setToolTipText("Select properties to Plot"); + plotButton.setText(" Plot "); + plotButton.addActionListener(this); + // --- + trajectoriesManagerPanel.setBorder(border4); + getContentPane().add(panel1); + panel1.add(mainTabbedPane, BorderLayout.CENTER); + mainPanel.add(animationPanel, BorderLayout.CENTER); + mainPanel.add(trajectoriesManagerPanel, BorderLayout.NORTH); + panel1.add(buttonPanel, BorderLayout.SOUTH); + + buttonPanel.add(plotButton); + buttonPanel.add(hideButton); + + mainTabbedPane.add(mainPanel, "Main"); + mainTabbedPane.add(this.imageSequencePanel, "Movie"); + + trajectoriesManagerPanel.setTrajectoryClientInterface(animationPanel); + // --- + animationPanel.addActionListener(this); + // --- Animation panel setup... + generateImageSeqCheckBox = imageSequencePanel.getGenerateImageSeqCheckBox(); + generateImageSeqCheckBox.addItemListener(this); + imageSequencePanel.getImageSeqFormatComboBox().removeAllItems(); + imageSeqFormatComboBox = imageSequencePanel.getImageSeqFormatComboBox(); + } + + public void itemStateChanged(ItemEvent e) { + if (generateImageSeqCheckBox == e.getSource()) { + if (!generateImageSeqCheckBox.isSelected()) { + return; + } + // --- + Object item = imageSequencePanel.getImageSeqFormatComboBox().getSelectedItem(); + if (item == null) { + JOptionPane.showMessageDialog(this, "Image Sequence format is not set!", "Warning", JOptionPane.WARNING_MESSAGE); + generateImageSeqCheckBox.setSelected(false); + return; + } + // --- + imageSequenceManager.setOutputFormat(item.toString()); + imageSequenceManager.initializeImageSequence(); + } + } + + public void actionPerformed(ActionEvent e) { + if (e.getSource() == animationPanel) { + if (AnimationPanel.ANIMATION_STARTED == e.getID()) { + + } else if (AnimationPanel.ANIMATION_FINISHED == e.getID()) { + imageSequencePanel.getGenerateImageSeqCheckBox().setSelected(false); + imageSequenceManager.finalizeImageSequence(); + } else { + logger.log(Level.WARNING, "Unknown AnimationPanel event" + e.getID()); + } + } else if (e.getSource() == plotButton) { + PropsToChartDialog propsToChartDialog = new PropsToChartDialog(new Frame(), true); + propsToChartDialog.setLocationRelativeTo(this); + propsToChartDialog.setDataRangePanelVisible(true); + + StructureManager sm = trajectoriesManagerPanel.getStructureManager(); + if (sm != null) { + propsToChartDialog.setStructureManager(sm); + } else { + JOptionPane.showMessageDialog(this, "No Properties to chert", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + propsToChartDialog.setVisible(true); + + if (!propsToChartDialog.isOkPressed()) { + return; + } + + ChartFrame jchartframe = null; + try { + jchartframe = new ChartFrame(); + jchartframe.setChartTitle("Property Change Along Trajectory"); + Object xAxis = propsToChartDialog.getXAxisValue(); + if (xAxis == null) { + xAxis = DataSets.DATA_ROW_NUMBER; + } + double x[] = sm.getDataAsDouble(xAxis.toString()); + Object[] yAxis = propsToChartDialog.getYAxisValues(); + for (Object yvalue : yAxis) { + double y[] = sm.getDataAsDouble(yvalue.toString()); + jchartframe.addDataSeries(x, y, xAxis.toString() + " vs " + yvalue); + } + + jchartframe.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + jchartframe.showChart(true); + } catch (Exception ex) { + Logger.getLogger(TrajectoryAnalysisDialog.class.getName()).log(Level.SEVERE, null, ex); + JOptionPane.showMessageDialog(this, "Error initializaing Chart Frame: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return; + } + jchartframe.setSize(1024, 600); + jchartframe.enableAnimationPanel(false); + } + } + + public void hideButton_actionPerformed(ActionEvent e) { + this.setVisible(false); + } + + @Override + public void setSnapshotsCount(int new_max) { + animationPanel.setSnapshotsCount(new_max); + } + + @Override + public void selectStructure(int number, String term) throws Exception { + selectStructure(number); + } + + @Override + public void selectStructure(int number) throws Exception { + MoleculeInterface referenceStructure = java3dUniverse.getMoleculeInterface(); + + MoleculeInterface mol = trajectoriesManagerPanel.getStructureManager().getReferenceMolecule(); + + if (mol == null) { + throw new Exception("Reference structure in Structure Manager is not set"); + } + + if (mol.getNumberOfAtoms() != referenceStructure.getNumberOfAtoms()) { + int answer = JOptionPane.showConfirmDialog(null, "Number of atoms in molecule does not match that for MD trajectory.\n" + + "Do you want to purge MD trajectories?", "Molecules mismatch", JOptionPane.YES_NO_OPTION); + if (answer == JOptionPane.OK_OPTION) { + trajectoriesManagerPanel.deleteAlltrajectories(); + trajectoriesManagerPanel.setReferenceMolecule(referenceStructure); + throw new Exception("Load trajectories first!"); + } + throw new Exception("Number of atoms in molecule does not match that for MD trajectory"); + } + + try { + trajectoriesManagerPanel.getStructureManager().getStructure(number, Coordinates); + } catch (Exception ex) { + throw ex; + } + + for (int i = 0; i < referenceStructure.getNumberOfAtoms(); i++) { + referenceStructure.getAtomInterface(i).setXYZ(Coordinates[i][0], Coordinates[i][1], Coordinates[i][2]); + } + long start = System.currentTimeMillis(); + java3dUniverse.updateMolecularGeometry(); + float secs = (System.currentTimeMillis() - start) / 1000.0f; + logger.info("Elapsed time for java3d update: " + secs); + imageSequenceManager.generateImage(java3dUniverse, number + 1); + + // --- Generate "image" if needed + if (generateImageSeqCheckBox.isSelected()) { + + } + } + + @Override + public float[][] getStructure(int n) { + return null; + } + + @Override + public float[][] getStructure(int n, String term) { + return null; + } + +} diff --git a/src/main/java/cct/dialogs/ViewMenu.java b/src/main/java/cct/dialogs/ViewMenu.java new file mode 100644 index 0000000..3379da2 --- /dev/null +++ b/src/main/java/cct/dialogs/ViewMenu.java @@ -0,0 +1,250 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.dialogs; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.logging.Logger; + +import javax.swing.ButtonGroup; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.JRadioButtonMenuItem; + +import cct.interfaces.JamberooCoreInterface; +import cct.j3d.ChangeAtomColors; +import cct.j3d.Java3dUniverse; +import cct.j3d.SuperCell; +import cct.modelling.OperationsOnAtoms; + +/** + * + * @author vvv900 + */ +public class ViewMenu extends JMenu implements ActionListener { + + public enum VIEW_MENU_ACTIONS { + + UNKNOWN_VIEW_ACTION, CENTER_MOLECULE, NEW_ROTATION_CENTER, DISPLAY_SELECTED_ATOMS, UNDISPLAY_SELECTED_ATOMS, + CHANGE_COLOR_FOR_SELECTED_ATOMS, LABEL_SELECTED_ATOMS, UNLABEL_SELECTED_ATOMS, LABELS_SIZE, LABELS_COLOR + } + private Java3dUniverse java3dUniverse; + private JamberooCoreInterface jamberooCore; + private JFrame crystalEditorDialog = null; + private SelectColorDialog selecColorDialog = null; + static final Logger logger = Logger.getLogger(EditMenu.class.getCanonicalName()); + + public ViewMenu(JamberooCoreInterface core) { + super(); + jamberooCore = core; + java3dUniverse = jamberooCore.getJamberooRenderer(); + } + + public void createMenu() { + + // --- Center molecule + + JMenuItem jMenuCenterMolecule = new JMenuItem("Center Molecule"); + jMenuCenterMolecule.setActionCommand(VIEW_MENU_ACTIONS.CENTER_MOLECULE.name()); + jMenuCenterMolecule.addActionListener(this); + add(jMenuCenterMolecule); + + + // --- New center of rotation + + JMenuItem jMenuItem = new JMenuItem("New Rotation Center"); + jMenuItem.setActionCommand(VIEW_MENU_ACTIONS.NEW_ROTATION_CENTER.name()); + jMenuItem.addActionListener(this); + add(jMenuItem); + + + // --- rendering styles + + JMenu jSubmenuRenderStyle = new JMenu("Rendering Styles"); + String[] styles = java3dUniverse.getRenderingStyles(); + if (styles.length > 0) { + ButtonGroup stylesGroup = new ButtonGroup(); + ActionListener stylesAL = new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + JRadioButtonMenuItem atomInfo = (JRadioButtonMenuItem) e.getSource(); + String arg = e.getActionCommand(); + try { + java3dUniverse.setGlobalRenderingStyle(arg); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + } + atomInfo.setSelected(true); + } + }; + for (int i = 0; i < styles.length; i++) { + JRadioButtonMenuItem jRadio = new JRadioButtonMenuItem(styles[i]); + jRadio.addActionListener(stylesAL); + stylesGroup.add(jRadio); + jSubmenuRenderStyle.add(jRadio); + } + add(jSubmenuRenderStyle); + } + + // --- Manage graphics object + + JMenuItem manageObjects = new JMenuItem("Manage Objects"); + manageObjects.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + //JEditorFrame.initGraphObjDialog(java3dUniverse); + jamberooCore.showGraphicsObjectsDialog(true); + //gopDialog.setVisible(true); + } + }); + manageObjects.setEnabled(true); + add(manageObjects); + + // --- Crystal editor menu + + addSeparator(); + JMenuItem crystalEditor = new JMenuItem("View Periodic Image"); + crystalEditor.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + if (crystalEditorDialog == null) { + crystalEditorDialog = new JFrame("Periodic Image View Control"); + ViewPeriodicImagePanel manager = new ViewPeriodicImagePanel(); + manager.setCellViewManager(new SuperCell(java3dUniverse)); + crystalEditorDialog.add(manager); + crystalEditorDialog.pack(); + crystalEditorDialog.setLocationRelativeTo(java3dUniverse.getCanvas3D()); + } + crystalEditorDialog.setVisible(true); + } + }); + + crystalEditor.setEnabled(true); + add(crystalEditor); + + addSeparator(); + + JMenuItem jMenuDisplayAtoms = new JMenuItem("Display Atoms"); + jMenuDisplayAtoms.setActionCommand(VIEW_MENU_ACTIONS.DISPLAY_SELECTED_ATOMS.name()); + jMenuDisplayAtoms.addActionListener(this); + add(jMenuDisplayAtoms); + + JMenuItem jMenuUndisplayAtoms = new JMenuItem("Undisplay Selected Atoms"); + jMenuUndisplayAtoms.setActionCommand(VIEW_MENU_ACTIONS.UNDISPLAY_SELECTED_ATOMS.name()); + jMenuUndisplayAtoms.addActionListener(this); + add(jMenuUndisplayAtoms); + + addSeparator(); + + JMenuItem jMenuAtomColors = new JMenuItem("Change Atom Colors"); + jMenuAtomColors.setActionCommand(VIEW_MENU_ACTIONS.CHANGE_COLOR_FOR_SELECTED_ATOMS.name()); + jMenuAtomColors.addActionListener(this); + add(jMenuAtomColors); + addSeparator(); + + JMenuItem jMenuLabelAtoms = new JMenuItem("Label Selected Atoms"); + jMenuLabelAtoms.setActionCommand(VIEW_MENU_ACTIONS.LABEL_SELECTED_ATOMS.name()); + jMenuLabelAtoms.addActionListener(this); + add(jMenuLabelAtoms); + + JMenuItem jMenuUnlabelAtoms = new JMenuItem("Unlabel Selected Atoms"); + jMenuUnlabelAtoms.setActionCommand(VIEW_MENU_ACTIONS.UNLABEL_SELECTED_ATOMS.name()); + jMenuUnlabelAtoms.addActionListener(this); + add(jMenuUnlabelAtoms); + + JMenuItem jMenuAtomLabelsSize = new JMenuItem("Change Atom Labels Size"); + jMenuAtomLabelsSize.setActionCommand(VIEW_MENU_ACTIONS.LABELS_SIZE.name()); + jMenuAtomLabelsSize.addActionListener(this); + add(jMenuAtomLabelsSize); + + JMenuItem jMenuAtomLabelsColor = new JMenuItem("Change Atom Labels Color"); + jMenuAtomLabelsColor.setActionCommand(VIEW_MENU_ACTIONS.LABELS_COLOR.name()); + jMenuAtomLabelsColor.addActionListener(this); + add(jMenuAtomLabelsColor); + + } + + @Override + public void actionPerformed(ActionEvent actionEvent) { + String actionCommand = actionEvent.getActionCommand(); + + logger.info("actionEvent.getActionCommand(): " + actionEvent.getActionCommand()); + + // --- Get action command + + VIEW_MENU_ACTIONS action = VIEW_MENU_ACTIONS.UNKNOWN_VIEW_ACTION; + try { + action = VIEW_MENU_ACTIONS.valueOf(actionCommand); + } catch (Exception ex) { + logger.warning("Unknown view menu action: " + actionCommand); + return; + } + + switch (action) { + case CENTER_MOLECULE: + + if (java3dUniverse.getMolecule() == null) { + return; + } + java3dUniverse.centerSceneOnScreen(); + break; + + case NEW_ROTATION_CENTER: + jamberooCore.openAtomSelectionDialog(java3dUniverse, OperationsOnAtoms.SELECTED_ROTATION_CENTER, + OperationsOnAtoms.SELECTION_UNLIMITED, false); + break; + + case DISPLAY_SELECTED_ATOMS: + jamberooCore.openAtomSelectionDialog(java3dUniverse, OperationsOnAtoms.SELECTED_DISPLAY_ATOMS, + OperationsOnAtoms.SELECTION_UNLIMITED, false); + break; + + case UNDISPLAY_SELECTED_ATOMS: + jamberooCore.openAtomSelectionDialog(java3dUniverse, OperationsOnAtoms.SELECTED_UNDISPLAY_ATOMS, + OperationsOnAtoms.SELECTION_UNLIMITED, false); + break; + + case CHANGE_COLOR_FOR_SELECTED_ATOMS: + if (selecColorDialog == null) { + selecColorDialog = new SelectColorDialog(null, "Select Color for Atoms", false); + } + ChangeAtomColors changeAtomColors = new ChangeAtomColors(java3dUniverse); + selecColorDialog.setColorChangerInterface(changeAtomColors); + jamberooCore.openAtomSelectionDialog(java3dUniverse, OperationsOnAtoms.SELECTED_CHANGE_ATOM_COLORS, + OperationsOnAtoms.SELECTION_UNLIMITED, false, + selecColorDialog); + break; + + case LABEL_SELECTED_ATOMS: + jamberooCore.openAtomSelectionDialog(java3dUniverse, OperationsOnAtoms.SELECTED_LABEL_ATOMS, OperationsOnAtoms.SELECTION_UNLIMITED, false); + break; + + case UNLABEL_SELECTED_ATOMS: + jamberooCore.openAtomSelectionDialog(java3dUniverse, OperationsOnAtoms.SELECTED_UNLABEL_ATOMS, + OperationsOnAtoms.SELECTION_UNLIMITED, false); + break; + + case LABELS_SIZE: + jamberooCore.openAtomSelectionDialog(java3dUniverse, OperationsOnAtoms.SELECTED_CHANGE_ATOM_LABELS_SIZE, OperationsOnAtoms.SELECTION_UNLIMITED, false); + break; + + case LABELS_COLOR: + jamberooCore.openAtomSelectionDialog(java3dUniverse, OperationsOnAtoms.SELECTED_CHANGE_ATOM_LABELS_COLOR, OperationsOnAtoms.SELECTION_UNLIMITED, false); + break; + } + } + + public Java3dUniverse getJava3dUniverse() { + return java3dUniverse; + } + + public void setJava3dUniverse(Java3dUniverse java3dUniverse) { + this.java3dUniverse = java3dUniverse; + } +} diff --git a/src/main/java/cct/dialogs/ViewPeriodicImagePanel.java b/src/main/java/cct/dialogs/ViewPeriodicImagePanel.java new file mode 100644 index 0000000..6ec2d95 --- /dev/null +++ b/src/main/java/cct/dialogs/ViewPeriodicImagePanel.java @@ -0,0 +1,315 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.dialogs; + +import java.awt.BorderLayout; +import java.awt.Font; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JSpinner; +import javax.swing.SpinnerModel; +import javax.swing.SpinnerNumberModel; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +import cct.interfaces.CellViewManagerInterface; +import cct.modelling.CELL_PARAMETER; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class ViewPeriodicImagePanel + extends JPanel implements ChangeListener { + + static final Map typeTable = new HashMap (); + static final Map directionTable = new HashMap (); + + private int minusMin = 0; + private int plusMin = 1; + private int max = 100; + private int step = 1; + private int initMinusValue = 0; + private int initPlusValue = 1; + private SpinnerModel minusModel_1 = new SpinnerNumberModel(initMinusValue, minusMin, max, step); + private SpinnerModel minusModel_2 = new SpinnerNumberModel(initMinusValue, minusMin, max, step); + private SpinnerModel minusModel_3 = new SpinnerNumberModel(initMinusValue, minusMin, max, step); + private SpinnerModel plusModel_1 = new SpinnerNumberModel(initPlusValue, plusMin, max, step); + private SpinnerModel plusModel_2 = new SpinnerNumberModel(initPlusValue, plusMin, max, step); + private SpinnerModel plusModel_3 = new SpinnerNumberModel(initPlusValue, plusMin, max, step); + + private BorderLayout borderLayout1 = new BorderLayout(); + private JPanel cellReplicationPanel = new JPanel(); + private JPanel buttonPanel = new JPanel(); + private JPanel abcPanel = new JPanel(); + private BorderLayout borderLayout2 = new BorderLayout(); + private JLabel jLabel1 = new JLabel(); + private JSpinner cSpinner = new JSpinner(); + private JLabel jLabel2 = new JLabel(); + private JLabel jLabel3 = new JLabel(); + private JLabel jLabel4 = new JLabel(); + private JLabel jLabel5 = new JLabel(); + private JSpinner cMinusSpinner = new JSpinner(); + private JSpinner bSpinner = new JSpinner(); + private JSpinner bMinusSpinner = new JSpinner(); + private JSpinner aSpinner = new JSpinner(); + private JSpinner aMinusSpinner = new JSpinner(); + private GridBagLayout gridBagLayout1 = new GridBagLayout(); + private JButton resetButton = new JButton(); + private JButton makeSupercellButton = new JButton(); + + private CellViewManagerInterface cellViewManager = null; + + public ViewPeriodicImagePanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + + if (typeTable.size() < 1) { + typeTable.put(aSpinner, CELL_PARAMETER.A); + directionTable.put(aSpinner, new Integer(1)); + + typeTable.put(aMinusSpinner, CELL_PARAMETER.A); + directionTable.put(aMinusSpinner, new Integer( -1)); + + typeTable.put(bSpinner, CELL_PARAMETER.B); + directionTable.put(bSpinner, new Integer(1)); + + typeTable.put(bMinusSpinner, CELL_PARAMETER.B); + directionTable.put(bMinusSpinner, new Integer( -1)); + + typeTable.put(cSpinner, CELL_PARAMETER.C); + directionTable.put(cSpinner, new Integer(1)); + + typeTable.put(cMinusSpinner, CELL_PARAMETER.C); + directionTable.put(cMinusSpinner, new Integer( -1)); + + } + } + + public void setCellViewManager(CellViewManagerInterface manager) { + cellViewManager = manager; + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + cellReplicationPanel.setLayout(borderLayout2); + jLabel1.setToolTipText(""); + jLabel1.setText("c"); + jLabel2.setToolTipText(""); + jLabel2.setText("b"); + jLabel3.setToolTipText(""); + jLabel3.setText("a"); + jLabel4.setToolTipText(""); + jLabel4.setText("+"); + jLabel5.setToolTipText(""); + jLabel5.setText("-"); + abcPanel.setLayout(gridBagLayout1); + resetButton.setText("Reset"); + resetButton.addActionListener(new ViewPeriodicImagePanel_resetButton_actionAdapter(this)); + makeSupercellButton.setToolTipText(""); + makeSupercellButton.setText("Make Supercell"); + aMinusSpinner.setModel(minusModel_1); + bMinusSpinner.setModel(minusModel_2); + cMinusSpinner.setModel(minusModel_3); + aSpinner.setModel(plusModel_1); + + aSpinner.addChangeListener(this); + aMinusSpinner.addChangeListener(this); + bSpinner.addChangeListener(this); + bMinusSpinner.addChangeListener(this); + cSpinner.addChangeListener(this); + cMinusSpinner.addChangeListener(this); + + bSpinner.setModel(plusModel_2); + cSpinner.setModel(plusModel_3); + this.add(cellReplicationPanel, BorderLayout.CENTER); + cellReplicationPanel.add(buttonPanel, BorderLayout.SOUTH); + buttonPanel.add(resetButton); + buttonPanel.add(makeSupercellButton); + cellReplicationPanel.add(abcPanel, BorderLayout.CENTER); + abcPanel.add(jLabel3, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + abcPanel.add(jLabel2, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + abcPanel.add(jLabel4, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + abcPanel.add(jLabel5, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + abcPanel.add(aMinusSpinner, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0)); + abcPanel.add(aSpinner, new GridBagConstraints(2, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), + 0, 0)); + abcPanel.add(bMinusSpinner, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0)); + abcPanel.add(bSpinner, new GridBagConstraints(2, 2, 1, 1, 1.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), + 0, 0)); + abcPanel.add(cSpinner, new GridBagConstraints(2, 3, 1, 1, 1.0, 1.0 + , GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), + 0, 0)); + abcPanel.add(cMinusSpinner, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0 + , GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0)); + abcPanel.add(jLabel1, new GridBagConstraints(0, 3, GridBagConstraints.REMAINDER, 1, 0.0, 0.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, + 0)); + + Font font = aSpinner.getEditor().getFont(); + if (font.getSize() < 15) { + Font new_font = new Font(font.getName(), font.getStyle(), 15); + aSpinner.getEditor().setFont(new_font); + } + } + + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } + catch (Exception exception) { + exception.printStackTrace(); + } + + JDialog diag = new JDialog(new Frame(), "Test dialog", true); + diag.add(new ViewPeriodicImagePanel()); + diag.pack(); + diag.setVisible(true); + System.exit(0); + } + }); + } + + @Override + public void stateChanged(ChangeEvent e) { + if (cellViewManager == null) { + return; + } + CELL_PARAMETER param = CELL_PARAMETER.A; + JSpinner spinner = (JSpinner) e.getSource(); + if (!spinner.isEnabled()) { + return; + } + + param = typeTable.get(spinner); + int direction = directionTable.get(spinner); + + SpinnerModel dateModel = spinner.getModel(); + + if (dateModel instanceof SpinnerNumberModel) { + int value = ( (SpinnerNumberModel) spinner.getModel()).getNumber().intValue(); + try { + cellViewManager.replicateCell(param, value * direction); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return; + } + } + + } + + private void enableSpinners(boolean enable) { + Set spinners = typeTable.keySet(); + Iterator iter = spinners.iterator(); + while (iter.hasNext()) { + iter.next().setEnabled(enable); + } + } + + private void resetSpinners() { + Set spinners = directionTable.keySet(); + Iterator iter = spinners.iterator(); + while (iter.hasNext()) { + JSpinner spinner = iter.next(); + if (directionTable.get(spinner) == -1) { + spinner.getModel().setValue(0); + } + else { + spinner.getModel().setValue(1); + } + } + + } + + public void resetButton_actionPerformed(ActionEvent e) { + resetSpinners(); + } +} + +class ViewPeriodicImagePanel_resetButton_actionAdapter + implements ActionListener { + private ViewPeriodicImagePanel adaptee; + ViewPeriodicImagePanel_resetButton_actionAdapter(ViewPeriodicImagePanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.resetButton_actionPerformed(e); + } +} diff --git a/src/main/java/cct/dialogs/package.html b/src/main/java/cct/dialogs/package.html new file mode 100644 index 0000000..0809a85 --- /dev/null +++ b/src/main/java/cct/dialogs/package.html @@ -0,0 +1,24 @@ + + + + +Begin with a one sentence summary about this package. +Follow with the remainder of your description. + +

Package Specification

+Collection of SWING dialogs... + + +

Related Documentation

+ + + + + diff --git a/src/main/java/cct/dialogs/tetrahedral.gif b/src/main/java/cct/dialogs/tetrahedral.gif new file mode 100644 index 0000000..d74b866 Binary files /dev/null and b/src/main/java/cct/dialogs/tetrahedral.gif differ diff --git a/src/main/java/cct/dynamics/Dynamics.java b/src/main/java/cct/dynamics/Dynamics.java new file mode 100644 index 0000000..98b7ca2 --- /dev/null +++ b/src/main/java/cct/dynamics/Dynamics.java @@ -0,0 +1,643 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2012 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.dynamics; + +import cct.Constants; +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.vecmath.Point3d; +import cct.vecmath.Point3f; +import java.util.ArrayList; +import java.util.List; + +/** + * + * @author Vlad + */ +public class Dynamics { + + public enum INITIAL_VELOCITIES { + + AMeanDistr, Restart + } + + public enum MDAlgorithm { + + HalfStepLeapFrog, VelocityVerlet + } + + INITIAL_VELOCITIES InitVel = INITIAL_VELOCITIES.AMeanDistr; + MDAlgorithm StepAlgorithm; // Defines a MD algorithm + private double T0 = 298, Tinit = 298; // - Reference and initial temperatures (in K) + private static double ToA = Constants.FROM_CAL_TO_J * 100.0; + private static double GasConst_kcal = Constants.GAS_CONSTANT / (4.1868 * 1000.); + double delta_t; // - Time step length (in ps) + double tauT; // - Temperature Coupling Time + private MoleculeInterface molecule; + private List dynamicAtoms; + int StartStep, MaxSteps, CurrentStep; + double Etot, Epot, Ekin, Tcurr; + double DegreesOfFreedom = 0; + private ForcesInterface forces; + private boolean CheckTemp; + private double HotSystemTempExceed = 100.0; + Point3d[] grads = null; + DynamicsProgressInterface progressInterface = null; + + public Dynamics(MoleculeInterface molecule) { + this.molecule = molecule; + dynamicAtoms = new ArrayList(molecule.getNumberOfAtoms()); + } + + public static void main(String[] args) { + } + + public void start() throws Exception { + double coeff = 0.8 / Math.PI * Constants.GAS_CONSTANT * Tinit; + double mean_vel, s; + + int natoms = molecule.getNumberOfAtoms(); + + dynamicAtoms.clear(); + + int number_of_interesting_atoms = 0; + DegreesOfFreedom = (double) (3 * natoms); + double Mass = 0.0; + for (int j = 0; j < natoms; j++) { + AtomInterface atom = molecule.getAtomInterface(j); + if (atom.getAtomicMass() < 0.0 || !atom.isDynamic()) { + DegreesOfFreedom -= 3.0; + } else { + AtomMD mda = new AtomMD(atom, j); + dynamicAtoms.add(mda); + Mass += atom.getAtomicMass(); + ++number_of_interesting_atoms; + } + } + System.out.println("Number of interesting (dynamic) atoms " + number_of_interesting_atoms); + + grads = new Point3d[dynamicAtoms.size()]; + for (Point3d p : grads) { + p = new Point3d(); + } + + //!!! if ( ImposeHolConstr ) DegreesOfFreedom -= (double)NHolConstr; + + DegreesOfFreedom -= 6.0; + if (natoms == 1) { + DegreesOfFreedom = 3.0; + } + if (natoms == 2) { + DegreesOfFreedom = 6.0; // --- !!! + } + System.out.println("Number of degrees of freedom " + String.format("%10.0f", DegreesOfFreedom)); + System.out.println("Atomic mass of dynamic atoms " + String.format("%10.1f", Mass)); + if ((DegreesOfFreedom < 3) && (number_of_interesting_atoms > 0)) { + DegreesOfFreedom = (double) (3 * number_of_interesting_atoms); + System.out.println("Adjusted Number of degrees of freedom " + String.format("%10.0f", DegreesOfFreedom)); + } else if (DegreesOfFreedom < 3) { + String msg = "Strange value of degrees of freedom: " + String.format("%10.0f", DegreesOfFreedom); + System.err.println(msg); + throw new Exception(msg); + } + + if (progressInterface != null) { + progressInterface.dynamicsStarted("Setting up initial velocities"); + } + + if (InitVel == INITIAL_VELOCITIES.AMeanDistr) { + forces.forces(grads); + + int count = 0; + for (AtomMD mda : dynamicAtoms) { + Point3d gr = grads[count]; + ++count; + + mean_vel = Math.sqrt(coeff / mda.atom.getAtomicMass()); // velocity corresponding Tinit + + mda.vOld.setX(mean_vel * (2.0 * Math.random() - 1.0)); + mda.vOld.setY(Math.sqrt(mean_vel * mean_vel - mda.vOld.getX() * mda.vOld.getX()) * (2.0 * Math.random() - 1.0)); + mda.vOld.setZ(SIGN(Math.sqrt(mean_vel * mean_vel - mda.vOld.getX() * mda.vOld.getX() - mda.vOld.getY() * mda.vOld.getY()), + 2.0 * Math.random() - 1.0)); + + mda.a.setX((float) (-ToA * gr.getX() / mda.atom.getAtomicMass())); + mda.a.setY((float) (-ToA * gr.getY() / mda.atom.getAtomicMass())); + mda.a.setZ((float) (-ToA * gr.getZ() / mda.atom.getAtomicMass())); + + mda.xOld.setXYZ(mda.atom); + } + + /* + * if (ExtendedPrint) { printf("\n\nInitial Accelerations:\n"); for (i = 0; i < natoms; i++) { printf("\n%3d %8.3lf %8.3lf + * %8.3lf", i + 1, a[i].x, a[i].y, a[i].z); } } + */ + + /* + * if (RemoveMomentum) { RemoveNetMomentum(xold, vold, amasses, int_reg, natoms); } + */ + + //ScaleVelocities(vold, amasses, int_reg, natoms, delta_t, delta_t, Tinit, DegreesOfFreedom); + ScaleVelocities(dynamicAtoms, delta_t, delta_t, Tinit, DegreesOfFreedom); + } else if (InitVel == INITIAL_VELOCITIES.Restart) { + /* + * ReadCoordAndVelocities(xold, vold, natoms); for (i = 0; i < natoms; i++) { xnew[i] = xold[i]; } } else { printf("\n\nDon't + * know how to set initial velocities\n\n"); exit(1); } + */ + } + + /* + * if (ntwe > 0) { NTWE = fopen(mden_res_file, "wt"); assert (NTWE); } + */ + + double Etot_average = 0.0, Etot_square = 0.0, Etot_lowest = 0, Etot_highest = 0; + double Epot_average = 0.0, Epot_square = 0.0, Epot_lowest = 0, Epot_highest = 0; + double Ekin_average = 0.0, Ekin_square = 0.0, Ekin_lowest = 0, Ekin_highest = 0; + double Temp_average = 0.0, Temp_square = 0.0, Temp_lowest = 0, Temp_highest = 0; + double Finish_time = 0.0; + double Elapsed_time = 0.0; + + int i = 0; + for (i = StartStep; i < MaxSteps; i++) { + CurrentStep = i; + + //!!!if ( Schedule ) SetSchedule(i); + + //!!!if ( NoSilent ) printf("\n\nStep: %d",i); + + switch (StepAlgorithm) { + case HalfStepLeapFrog: + //HalfStepLeapFrogStep(xnew, grad, amasses, int_reg, natoms, Forces,HolConstr, NHolConstr); + HalfStepLeapFrogStep(); + break; + case VelocityVerlet: + //VelocityVerletStep(xnew, grad, amasses, int_reg, natoms, Forces); + VelocityVerletStep(); + break; + } + + /* + * if ( StepAlgorithm == MDAlgorithm.HalfStepLeapFrog ) HalfStepLeapFrogStep(xnew, grad, amasses, int_reg, natoms, Forces, + * HolConstr, NHolConstr ); else if ( StepAlgorithm == MDAlgorithm.VelocityVerlet ) VelocityVerletStep(xnew, grad, amasses, + * int_reg, natoms, Forces ); + */ + + if (progressInterface != null) { + progressInterface.dynamicsProgressed(String.format("Step %d Etot=%10.2f Epot=%10.2f", i + 1, Etot, Epot)); + } + + + //!!!if ( !(i%ntwe) ) PrintEnergiesAndTemp(NTWE,i+1,Etot,Epot,Ekin,Tcurr); + + /* + * if ( (PrintCRD>0 ) && (!(i%PrintCRD)) ) { AppendToAmberCRDFile(xnew, natoms, crd_file); + * PrintEnergiesAndTemp(energy_file,i,Etot,Epot,Ekin,Tcurr); } + */ + + /* + * if ( (PrintMol2>0 ) && (!(i%PrintMol2)) ) { char fichier[20]; sprintf(fichier, "dyn%04d.mol2",i/PrintMol2); + * WriteMol2UsingPattern(fichier, mol2_file, xnew, natoms); } + */ + + if (i == 0) { + Etot_lowest = Etot; + Etot_highest = Etot; + Epot_lowest = Epot; + Epot_highest = Epot; + Ekin_lowest = Ekin; + Ekin_highest = Ekin; + Temp_lowest = Tcurr; + Temp_highest = Tcurr; + } + + Etot_average += Etot; + Etot_square += Power2(Etot); + if (Etot_lowest > Etot) { + Etot_lowest = Etot; + } else if (Etot_highest < Etot) { + Etot_highest = Etot; + } + + Epot_average += Epot; + Epot_square += Power2(Epot); + if (Epot_lowest > Epot) { + Epot_lowest = Epot; + } else if (Epot_highest < Epot) { + Epot_highest = Epot; + } + + Ekin_average += Ekin; + Ekin_square += Power2(Ekin); + if (Ekin_lowest > Ekin) { + Ekin_lowest = Ekin; + } else if (Ekin_highest < Ekin) { + Ekin_highest = Ekin; + } + + Temp_average += Tcurr; + Temp_square += Power2(Tcurr); + if (Temp_lowest > Tcurr) { + Temp_lowest = Tcurr; + } else if (Temp_highest < Tcurr) { + Temp_highest = Tcurr; + } + + /* + * if ( NoSilent ) { printf("\nEtot: %lf Epot: %lf Ekin: %lf T: %lf",Etot,Epot,Ekin,Tcurr); fflush(stdout); } + */ + + /* + * if ( mean_str ) for (j=0; j 0 ) fclose(energy_file); fclose(NTWE); + */ + + /* + * if ( JobName != NULL ) { strcpy(bufer,JobName); strcat(bufer,"-restart.res"); } else strcpy(bufer,"restart.res"); + * WriteCoordAndVel(xold,vold,natoms,i,bufer,"--- Normal termination"); + */ + + + if (i != MaxSteps) { + ++i; + } + System.out.println(i + " MD Steps have been done"); + double norm = (double) i; + Etot_average /= norm; + Epot_average /= norm; + Ekin_average /= norm; + Temp_average /= norm; + + /* + * if ( mean_str ) { for (j=0; j dynamicAtoms, double dfree) { + double ekin = 0.0; + for (AtomMD mda : dynamicAtoms) { + ekin += mda.atom.getAtomicMass() * (mda.vOld.getXSq() + mda.vOld.getYSq() + mda.vOld.getZSq()); + } + ekin *= 0.5 / ToA; + return (2.0) * ekin / (dfree * GasConst_kcal); + } + + public static double Power2(double a) { + return a * a; + } + + public static double SIGN(double A, double B) { + if (B >= 0.0) { + return A > 0.0 ? A : -A; + } else { + return A < 0.0 ? A : -A; + } + } + + public static void ScaleVelocities(List dynamicAtoms, double delta_t, double taut, double t0, double dfree) { + + double tcurr = KineticTemperature(dynamicAtoms, dfree); + double gamma = Math.sqrt(1.0 + delta_t / taut * (t0 / tcurr - 1.0)); + + for (AtomMD mda : dynamicAtoms) { + mda.vOld.multiply(gamma); + } + } + + void TimeDecomposition(double seconds) { + int days = (int) (seconds / 86400.); + if (days > 0) { + System.out.printf("%d days ", days); + } + int hours = (int) ((seconds - (double) days * 86400.) / 3600.); + if (hours > 0) { + System.out.printf("%d hours ", hours); + } + int minuits = (int) ((seconds - (double) days * 86400. - (double) hours * 3600.) / 60.); + if (minuits > 0) { + System.out.printf("%d min ", minuits); + } + double sec = seconds - (double) days * 86400. - (double) hours * 3600. + - (double) minuits * 60.; + System.out.printf("%f sec ", sec); + } + + protected void HalfStepLeapFrogStep() {// + //, Inter12 *constraints , int nc + + double dt2_2 = delta_t * delta_t / 2.0, dt_2 = delta_t / 2.0, gamma; + int j; + + Epot = forces.forces(grads); + + int count = 0; + for (AtomMD mda : dynamicAtoms) { + float amass = mda.atom.getAtomicMass(); + Point3d grad = grads[count]; + mda.a.setX(-ToA * grad.getX() / amass); + mda.a.setY(-ToA * grad.getY() / amass); + mda.a.setZ(-ToA * grad.getZ() / amass); + ++count; + } + + /* + * if ( ExtendedPrint ) { printf("\n\nAccelerations:\n"); for(j=0; j T0 + HotSystemTempExceed)) { System.err.printf("\n\nCheckTemp && (Tcurr > T0 + HotSystemTempExceed) + * are disabled...\n"); System.exit(1); System.out.printf("\nTcurr > T0 + %lf, Make correction for hot atoms...", + * HotSystemTempExceed); WriteCoordAndVel(xold, vnew, natoms, CurrentStep, "hot.res", " Hot atoms, Tcurr > T0 + ???"); //Ekin = + * CheckHotAtoms(amasses,int_reg,natoms); } + */ + +//Tcurr = (double)2.0 * Ekin / ( DegreesOfFreedom * GasConst_kcal ); +//gamma = sqrt((double)1.0 + delta_t/tauT *(T0/Tcurr - (double)1.0)); +//if ( NoSilent ) printf("\nVnew: Unscaled T: %8.3lf Gamma: %8.5lf",Tcurr, gamma); + +//for (j=0; j dynamicAtoms) { + double Ekin = 0.0; + for (AtomMD mda : dynamicAtoms) { + Ekin += mda.atom.getAtomicMass() * mda.vOld.squaredNorm(); + } + /* + * Implementation is above for (int j=0; j (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.dynamics; + +import cct.modelling.*; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.ForceFieldInterface; +import cct.interfaces.MinimizeProgressInterface; +import cct.interfaces.MoleculeInterface; +import cct.math.DFPMin; +import cct.math.MinimizerInterface; +import cct.tools.Utils; +import cct.vecmath.Point3d; +import cct.vecmath.VecmathTools; +import java.util.List; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class DynamicsObject implements ForcesInterface { + + static final Logger logger = Logger.getLogger(DynamicsObject.class.getCanonicalName()); + protected FFMolecule ffMolecule = null; + protected MoleculeInterface Molec = null; + protected Dynamics integrator = null; + MolecularEnergy molEnergy = null; + int exitCode; + DynamicsProgressInterface progressInterface = null; + ForceFieldInterface forceField = null; + + public DynamicsObject(MoleculeInterface mol) { + Molec = mol; + } + + public MoleculeInterface getMolecule() { + return Molec; + } + + public void setForceField(ForceFieldInterface ff) { + forceField = ff; + } + + public void setDynamicsProgressInterface(DynamicsProgressInterface mpi) { + this.progressInterface = mpi; + } + + void setupDynamics() throws Exception { + ffMolecule = new FFMolecule(Molec); + if (forceField != null) { + ffMolecule.applyForceField(forceField); + } + ffMolecule.formFFParameters(); + + integrator = new Dynamics(Molec); + integrator.setForces(this); + + int dynamicAtoms = 0; + for (int i = 0; i < Molec.getNumberOfAtoms(); i++) { + AtomInterface atom = Molec.getAtomInterface(i); + if (atom.isDynamic()) { + ++dynamicAtoms; + } + } + + logger.info("Number of dynamic atoms: " + dynamicAtoms + " # of atoms: " + + Molec.getNumberOfAtoms()); + } + + public int integrate() throws Exception { + + if (progressInterface != null) { + integrator.setProgressInterface(progressInterface); + } + + setupDynamics(); + + molEnergy = new MolecularEnergy(ffMolecule); + + integrator.start(); + //printMinimizationSummary(); + return exitCode; + } + + public void printMinimizationSummary() { + /* + * logger.info(minimizer.getExitCodeDescription(exitCode)); + * + * logger.info("RMS of gradients : " + VecmathTools.getRMS(minimizer.getGradients()) + " Maximum gradient: " + + * VecmathTools.getMaxAbsValue(minimizer.getGradients())); + */ + molEnergy.printEnergyDecomposition(); + } + + /* + * public int minimize(int method) throws Exception { + * + * setupMinimization(); + * + * molEnergy = new MolecularEnergy(ffMolecule); molEnergy.setIndexes(indexes); + * + * if (method == 1) { DFPMin minimizer = new DFPMin(); minimizer.setMaximumStep(0.5); minimizer.setGTolerance(0.01f); + * minimizer.minimizeFunction(nVar, Variables, molEnergy); } + * + * + * logger.info("Minimum function value: " + molEnergy.function(nVar, Variables)); + * + * if (method == 0) { molEnergy.enable14Energy(true); molEnergy.enable1NonbondEnergy(true); + * molEnergy.enableBondStretchEnergy(false); molEnergy.enableAngleBendEnergy(false); molEnergy.enableTorsionEnergy(false); + * + * molEnergy.enableNumericalGradients(true); molEnergy.function(nVar, Variables, Gradients); + * molEnergy.enableNumericalGradients(false); float g[] = new float[nVar]; molEnergy.function(nVar, Variables, g); + * Utils.printFloatVectors(nVar, Gradients, g); + * + * molEnergy.printEnergyDecomposition(); + * + * molEnergy.enable14Energy(true); molEnergy.enable1NonbondEnergy(true); molEnergy.enableAngleBendEnergy(true); + * molEnergy.enableBondStretchEnergy(true); molEnergy.enableTorsionEnergy(true); } + * + * return 0; } + */ + public double forces(Point3d[] grad) { + double energy = 0; + return energy; + } + + /* + * public static void main(String[] args) { MinimizeStructure minimizestructure = new MinimizeStructure(); } + */ +} diff --git a/src/main/java/cct/dynamics/DynamicsProgressInterface.java b/src/main/java/cct/dynamics/DynamicsProgressInterface.java new file mode 100644 index 0000000..76a115d --- /dev/null +++ b/src/main/java/cct/dynamics/DynamicsProgressInterface.java @@ -0,0 +1,65 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.dynamics; + +/** + * + * @author Vlad + */ +public interface DynamicsProgressInterface { + + void dynamicsStarted(String _started); + + boolean isDynamicsCancelled(); + + void dynamicsProgressed(String _progress); + + void dynamicsCompleted(); + + /** + * Frequency for updating optimized variables + * + * @return int + */ + int getDynamicsFrequencyUpdate(); + + void setDynamicsFrequencyUpdate(int n); +} diff --git a/src/main/java/cct/dynamics/ForcesInterface.java b/src/main/java/cct/dynamics/ForcesInterface.java new file mode 100644 index 0000000..b57e14f --- /dev/null +++ b/src/main/java/cct/dynamics/ForcesInterface.java @@ -0,0 +1,16 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.dynamics; + +import cct.vecmath.Point3d; +import java.util.List; + +/** + * + * @author Vlad + */ +public interface ForcesInterface { + double forces(Point3d[] grad); +} diff --git a/src/main/java/cct/dynamics/SnapshotSequenceAnalyzer.java b/src/main/java/cct/dynamics/SnapshotSequenceAnalyzer.java new file mode 100644 index 0000000..faaec97 --- /dev/null +++ b/src/main/java/cct/dynamics/SnapshotSequenceAnalyzer.java @@ -0,0 +1,46 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.dynamics; + +import cct.interfaces.MoleculeInterface; +import cct.modelling.StructureManager; + +/** + * + * @author vvv900 + */ +public class SnapshotSequenceAnalyzer { + + private StructureManager structureManager; + private MoleculeInterface referenceStructure; + + public SnapshotSequenceAnalyzer() { + + } + + public SnapshotSequenceAnalyzer(StructureManager structureManager) { + this.structureManager = structureManager; + } + + public StructureManager getStructureManager() { + return structureManager; + } + + public void setStructureManager(StructureManager structureManager) { + this.structureManager = structureManager; + } + + public void setReferenceMolecule(MoleculeInterface mol) { + referenceStructure = mol; + if (structureManager != null) { + structureManager.setReferenceMolecule(mol); + } + } + + public MoleculeInterface getReferenceMolecule() { + return referenceStructure; + } +} diff --git a/src/main/java/cct/experimental/AtomList.java b/src/main/java/cct/experimental/AtomList.java new file mode 100644 index 0000000..7325c34 --- /dev/null +++ b/src/main/java/cct/experimental/AtomList.java @@ -0,0 +1,226 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.experimental; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + * @author Vlad + */ +public class AtomList { + + public enum PREDEFINED_PROPERTY { + + ELEMENT, X, Y, Z, NAME, ATOMIC_MASS + } + private MoleculeInterface molecule; + private Set uniqueProperties; + private List uniquePropertiesList = new ArrayList(); + private List> atoms = new ArrayList>(); + private boolean showAtomNumber = true; + static final Logger logger = Logger.getLogger(AtomList.class.getCanonicalName()); + + public AtomList() { + } + + public AtomList(MoleculeInterface molecule) { + this.molecule = molecule; + } + + public void setMolecule(MoleculeInterface molecule) { + this.molecule = molecule; + } + + protected void addProperty(String name) { + uniqueProperties.add(name); + uniquePropertiesList.add(name); + } + + protected void removeProperty(String name) { + uniqueProperties.remove(name); + uniquePropertiesList.remove(name); + } + + public Set getProperties() { + return new LinkedHashSet(uniqueProperties); + } + + public List getPropertiesList() { + return new ArrayList(uniquePropertiesList); + } + + public void setPropertyValueAt(Object value, int atomIndex, int propIndex) { + atoms.get(atomIndex).get(uniquePropertiesList.get(propIndex)).setValue(value); + } + + public boolean isPropertyEditable(int atomIndex, int propIndex) { + return atoms.get(atomIndex).get(uniquePropertiesList.get(propIndex)).isEditable(); + } + + public void buildAtomList() { + + uniqueProperties = countUniqueAtomsProperties(molecule); + uniquePropertiesList.clear(); + uniquePropertiesList.addAll(uniqueProperties); + + atoms.clear(); + + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface atom = molecule.getAtomInterface(i); + Map props = new LinkedHashMap(); + AtomProperty ap = new AtomProperty(PREDEFINED_PROPERTY.ELEMENT.name(), atom.getAtomicNumber(), true); + props.put(PREDEFINED_PROPERTY.ELEMENT.name(), ap); + ap = new AtomProperty(PREDEFINED_PROPERTY.X.name(), atom.getX(), true); + props.put(PREDEFINED_PROPERTY.X.name(), ap); + ap = new AtomProperty(PREDEFINED_PROPERTY.Y.name(), atom.getY(), true); + props.put(PREDEFINED_PROPERTY.Y.name(), ap); + ap = new AtomProperty(PREDEFINED_PROPERTY.Z.name(), atom.getZ(), true); + props.put(PREDEFINED_PROPERTY.Z.name(), ap); + ap = new AtomProperty(PREDEFINED_PROPERTY.NAME.name(), atom.getName() == null ? "" : atom.getName(), true); + props.put(PREDEFINED_PROPERTY.NAME.name(), ap); + ap = new AtomProperty(PREDEFINED_PROPERTY.ATOMIC_MASS.name(), atom.getAtomicMass(), true); + props.put(PREDEFINED_PROPERTY.ATOMIC_MASS.name(), ap); + + for (String prop : uniqueProperties) { + if (atom.getProperty(prop) == null) { + continue; + } + ap = new AtomProperty(prop, atom.getProperty(prop), true); + props.put(prop, ap); + } + + atoms.add(props); + } + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, toString()); + } + } + + public Set countUniqueAtomsProperties(MoleculeInterface molecule) { + Set uProperties = new LinkedHashSet(); + + uProperties.add(PREDEFINED_PROPERTY.ELEMENT.name()); + uProperties.add(PREDEFINED_PROPERTY.X.name()); + uProperties.add(PREDEFINED_PROPERTY.Y.name()); + uProperties.add(PREDEFINED_PROPERTY.Z.name()); + uProperties.add(PREDEFINED_PROPERTY.NAME.name()); + uProperties.add(PREDEFINED_PROPERTY.ATOMIC_MASS.name()); + + Set temp = new HashSet(); + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface atom = molecule.getAtomInterface(i); + Map< String, Object> props = atom.getProperties(); + for (Map.Entry entry : props.entrySet()) { + if (!temp.contains(entry.getKey())) { + temp.add(entry.getKey()); + } + } + } + System.out.println("Found " + temp.size() + " non-predefined properties"); + + Object[] obj = temp.toArray(); + Arrays.sort(obj); + + int n = 0; + for (Object o : obj) { + uProperties.add(o.toString()); + System.out.println((n++) + ": " + o.toString()); + } + return uProperties; + } + + public int getPropertiesCount() { + if (uniqueProperties == null) { + return 0; + } + return this.uniqueProperties.size(); + } + + public String getPropertyName(int index) { + return uniquePropertiesList.get(index); + } + + public int getAtomCount() { + return atoms.size(); + } + + public Object getPropertyAt(int atomIndex, int propIndex) { + return atoms.get(atomIndex).get(uniquePropertiesList.get(propIndex)).getValue(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("Number of unique atomic properties: " + uniqueProperties.size() + "\n"); + int n = 1; + for (String prop : uniqueProperties) { + sb.append((n++) + ": " + prop + "\n"); + } + sb.append("\nNumber of atoms: " + atoms.size() + "\n"); + // + n = 1; + for (Map atom : atoms) { + + sb.append(String.format("%-3d", n++) + "\n"); + + for (Map.Entry entry : atom.entrySet()) { + sb.append(" " + entry.getKey() + ": " + entry.getValue().getValue() + " " + entry.getValue().isEditable() + "\n"); + } + + } + return sb.toString(); + } + + public boolean isShowAtomNumber() { + return showAtomNumber; + } + + public void setShowAtomNumber(boolean showAtomNumber) { + this.showAtomNumber = showAtomNumber; + } + + public class AtomProperty { + + String propertyTag; + Object value; + boolean editable; + + public AtomProperty(String propertyTag, Object value, boolean editable) { + this.propertyTag = propertyTag; + this.value = value; + this.editable = editable; + } + + public boolean isEditable() { + return editable; + } + + public void setEditable(boolean editable) { + this.editable = editable; + } + + public String getPropertyTag() { + return propertyTag; + } + + public void setPropertyTag(String propertyTag) { + this.propertyTag = propertyTag; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + } +} diff --git a/src/main/java/cct/experimental/AtomListFrame.form b/src/main/java/cct/experimental/AtomListFrame.form new file mode 100644 index 0000000..7f26aee --- /dev/null +++ b/src/main/java/cct/experimental/AtomListFrame.form @@ -0,0 +1,71 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+
+
+
+ diff --git a/src/main/java/cct/experimental/AtomListFrame.java b/src/main/java/cct/experimental/AtomListFrame.java new file mode 100644 index 0000000..3c19ee6 --- /dev/null +++ b/src/main/java/cct/experimental/AtomListFrame.java @@ -0,0 +1,202 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.experimental; + +import cct.dialogs.JamberooFrame; +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.j3d.Java3dUniverse; +import cct.modelling.Molecule; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import javax.swing.JMenuItem; +import javax.swing.JTable; + +/** + * + * @author Vlad + */ +public class AtomListFrame extends javax.swing.JFrame { + + /** + * Creates new form AtomListFrame + */ + public AtomListFrame() { + initComponents(); + } + + public void setAtomList(MoleculeInterface mol) { + try { + AtomList zMatrix = new AtomList(); + zMatrix.setMolecule(mol); + zMatrix.buildAtomList(); + AtomListTableModel atomListTableModel = new AtomListTableModel(zMatrix); + JTable jTable = new JTable(atomListTableModel); + jScrollPane3.remove(jTable2); + jScrollPane3.setViewportView(jTable); + this.validate(); + this.pack(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public void setAtomList(Java3dUniverse j3d) { + setAtomList(j3d.getMoleculeInterface()); + } + + /** + * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this + * method is always regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jPanel3 = new javax.swing.JPanel(); + jButton1 = new javax.swing.JButton(); + jButton2 = new javax.swing.JButton(); + jScrollPane3 = new javax.swing.JScrollPane(); + jTable2 = new JTable(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + + jButton1.setText("jButton1"); + jPanel3.add(jButton1); + + jButton2.setText("jButton2"); + jPanel3.add(jButton2); + + getContentPane().add(jPanel3, java.awt.BorderLayout.SOUTH); + + jTable2.setModel(new javax.swing.table.DefaultTableModel( + new Object [][] { + {null, null, null, null}, + {null, null, null, null}, + {null, null, null, null}, + {null, null, null, null} + }, + new String [] { + "Title 1", "Title 2", "Title 3", "Title 4" + } + )); + jScrollPane3.setViewportView(jTable2); + + getContentPane().add(jScrollPane3, java.awt.BorderLayout.CENTER); + + pack(); + }// //GEN-END:initComponents + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + /* Set the Nimbus look and feel */ + // + /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. + * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html + */ + try { + for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + javax.swing.UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (ClassNotFoundException ex) { + java.util.logging.Logger.getLogger(AtomListFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (InstantiationException ex) { + java.util.logging.Logger.getLogger(AtomListFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + java.util.logging.Logger.getLogger(AtomListFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (javax.swing.UnsupportedLookAndFeelException ex) { + java.util.logging.Logger.getLogger(AtomListFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + // + + /* Create and display the form */ + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + + MoleculeInterface mol = new Molecule(); + AtomInterface atom = mol.getNewAtomInstance(); + atom.setAtomicNumber(1); + atom.setXYZ(1.07f, 0f, 0f); + mol.addAtom(atom); + + atom = atom.getNewAtomInstance(); + atom.setAtomicNumber(6); + atom.setXYZ(0f, 0f, 0f); + mol.addAtom(atom); + + atom = atom.getNewAtomInstance(); + atom.setAtomicNumber(1); + atom.setXYZ(-0.357f, -0.504f, 0.874f); + mol.addAtom(atom); + + atom = atom.getNewAtomInstance(); + atom.setAtomicNumber(1); + atom.setXYZ(-0.357f, -0.504f, -0.874f); + mol.addAtom(atom); + + atom = atom.getNewAtomInstance(); + atom.setAtomicNumber(1); + atom.setXYZ(-0.357f, 1.009f, 0.0f); + mol.addAtom(atom); + + AtomListFrame frame = new AtomListFrame(); + frame.setAtomList(mol); + frame.pack(); + frame.setSize(800, 400); + frame.setVisible(true); + + if (1 < 0) { + String[] args = new String[0]; + final JamberooFrame editor = new JamberooFrame("Jamberoo - ZMatrix Test Window", args); + JMenuItem item = new JMenuItem("Edit Coordinates"); + + editor.addMenuItem("Edit", item); + + item.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + if (editor.getJ3DUniverse().getMoleculeInterface() == null) { + return; + } + AtomListFrame frame = new AtomListFrame(); + frame.setAtomList(editor.getJ3DUniverse()); + frame.setVisible(true); + } + }); + + editor.setSize(new Dimension(800, 600)); + + editor.addWindowListener(new WindowAdapter() { + + public void windowClosing(WindowEvent we) { + System.exit(0); + } + }); + + editor.setVisible(true); + + } + } + }); + + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton jButton1; + private javax.swing.JButton jButton2; + private javax.swing.JPanel jPanel3; + private javax.swing.JScrollPane jScrollPane2; + private javax.swing.JScrollPane jScrollPane3; + private JTable jTable2; + // End of variables declaration//GEN-END:variables +} diff --git a/src/main/java/cct/experimental/AtomListTableModel.java b/src/main/java/cct/experimental/AtomListTableModel.java new file mode 100644 index 0000000..25cb5de --- /dev/null +++ b/src/main/java/cct/experimental/AtomListTableModel.java @@ -0,0 +1,152 @@ +package cct.experimental; + +import cct.experimental.AtomList; +import java.util.*; +import javax.swing.table.*; +import javax.swing.JOptionPane; + +/** + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2008

+ * + *

+ * Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class AtomListTableModel extends AbstractTableModel { + + public static final double DEGREES_TO_RADIANS = Math.PI / 180.0; + public static final double RADIANS_TO_DEGREES = 180.0 / Math.PI; + private boolean showAtomNumber = false; + private boolean debug = true; + AtomList atomList = null; + + public AtomListTableModel() { + } + + public AtomListTableModel(AtomList atom_list) { + atomList = atom_list; + } + + public boolean isShowAtomNumber() { + return showAtomNumber; + } + + public void setShowAtomNumber(boolean showAtomNumber) { + this.showAtomNumber = showAtomNumber; + } + + public void setZMatrix(AtomList atom_list) { + atomList = atom_list; + this.fireTableDataChanged(); + } + + public String getColumnName(int column) { + if (showAtomNumber) { + if (column == 0) { + return "#"; + } + --column; + } + return atomList.getPropertyName(column); + } + + /** + * Returns the number of columns in the model. + * + * @return the number of columns in the model @todo Implement this javax.swing.table.TableModel method + */ + public int getColumnCount() { + return atomList.getPropertiesCount() + (showAtomNumber ? 1 : 0); + } + + /** + * Returns the number of rows in the model. + * + * @return the number of rows in the model @todo Implement this javax.swing.table.TableModel method + */ + public int getRowCount() { + return atomList.getAtomCount(); + } + + public Class getColumnClass(int c) { + try { + if (showAtomNumber) { + if (c == 0) { + System.err.println("# Col: " + c + " Class: " + new Integer(0).getClass().toString()); + return new Integer(0).getClass(); + } + --c; + } + System.err.println("Col: " + c + " Class: " + getValueAt(0, c).getClass().toString()); + return getValueAt(0, c).getClass(); + } catch (Exception ex) { + ex.printStackTrace(); + } + return new Object().getClass(); + } + + /** + * Returns the value for the cell at columnIndex and rowIndex. + * + * @param rowIndex the row whose value is to be queried + * @param columnIndex the column whose value is to be queried + * @return the value Object at the specified cell @todo Implement this javax.swing.table.TableModel method + */ + public Object getValueAt(int rowIndex, int columnIndex) { + if (showAtomNumber) { + if (columnIndex == 0) { + System.err.println("# Col: " + columnIndex + " Row: " + rowIndex + " Value: " + new Integer(rowIndex + 1)); + return new Integer(rowIndex + 1); + } + --columnIndex; + } + System.err.println("Col: " + columnIndex + " Row: " + rowIndex + " Value: " + atomList.getPropertyAt(rowIndex, columnIndex)); + return atomList.getPropertyAt(rowIndex, columnIndex); + } + + public boolean isCellEditable(int row, int col) { + //Note that the data/cell address is constant, + //no matter where the cell appears onscreen. + if (showAtomNumber) { + if (col == 0) { + return false; + } + --col; + } + return atomList.isPropertyEditable(row, col); + } + + /* + * Don't need to implement this method unless your table's data can change. + */ + public void setValueAt(Object value, int rowIndex, int col) { + if (showAtomNumber) { + if (col == 0) { + return; + } + --col; + } + + if (debug) { + System.out.println("Setting value at " + rowIndex + "," + col + " to " + value + " (an instance of " + value.getClass() + + ")"); + } + atomList.setPropertyValueAt(value, rowIndex, col); + + fireTableCellUpdated(rowIndex, col); + + if (debug) { + System.out.println("New value of data:" + value.toString()); + //printDebugData(); + } + } +} diff --git a/src/main/java/cct/experimental/Method.java b/src/main/java/cct/experimental/Method.java new file mode 100644 index 0000000..c28cb8b --- /dev/null +++ b/src/main/java/cct/experimental/Method.java @@ -0,0 +1,23 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.experimental; + +/** + * + * @author vvv900 + */ +public class Method { + + protected String name; + protected String basisSet; + protected String secondBasisSet; + protected boolean hasBasisSet = true; + +public Method() { + +} + +} diff --git a/src/main/java/cct/gamess/Gamess.java b/src/main/java/cct/gamess/Gamess.java new file mode 100644 index 0000000..c9365f2 --- /dev/null +++ b/src/main/java/cct/gamess/Gamess.java @@ -0,0 +1,3292 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.gamess; + +import cct.Constants; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.io.StreamTokenizer; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.math.PointGroup; +import cct.modelling.CCTAtomTypes; +import cct.modelling.ChemicalElements; +import cct.modelling.GeneralMolecularDataParser; +import cct.modelling.Molecule; +import cct.vecmath.Geometry3d; +import java.util.logging.Level; + +/** + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2006

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Gamess extends GeneralMolecularDataParser { + + static final double ONE_BOHR = Constants.ONE_BOHR; // In Angstrom + static final float DEGREES_TO_RADIANS = (float) (Math.PI / 180.0); + static final int LOOKING_FOR_SECTION = 0; + static final int LOOKING_FOR_SWITCH = 1; + static final int LOOKING_FOR_SWITCH_VALUE = 2; + static final int READING_COMMENT = 3; + static final String endSection = "$END"; + static final String commentSection = "!"; + static final int UNIQUE = 0; + static final int HINT = 1; + static final int CART = 2; + static final int ZMT = 3; + static final int ZMTMPC = 4; + static final String controlSection = "$CONTRL"; // chemical control data INPUTA:START + static final String systemSection = "$SYSTEM"; // computer related control data INPUTA:START + static final String basisSection = "$BASIS"; // basis set INPUTB:BASISS + static final String dataSection = "$DATA"; // molecule, basis set INPUTB:MOLE + static final String fmoxyzSection = "$FMOXYZ"; // atomic coordinates for FMO FMOIO :FMOXYZ + static final String zmatSection = "$ZMAT"; // coded z-matrix ZMATRX:ZMATIN + static final String libeSection = "$LIBE"; // linear bend data ZMATRX:LIBE + static final String scfSection = "$SCF"; // HF-SCF wavefunction control SCFLIB:SCFIN + static final String scfmiSection = "$SCFMI"; // SCF-MI input control data SCFMI :MIINP + static final String mp2Section = "$MP2"; // 2nd order Moller-Plesset MP2 :MP2INP + static final String guessSection = "$GUESS"; // initial orbital selection GUESS :GUESMO + static final String vecSection = "$VEC"; // orbitals (formatted) GUESS :READMO + // -- Potential energy surface options: + static final String statptSection = "$STATPT"; // geometry search control STATPT:SETSIG + static final String trudgeSection = "$TRUDGE"; // nongradient optimization TRUDGE:TRUINP + static final String trurstSection = "$TRURST"; // restart data for TRUDGE TRUDGE:TRUDGX + static final String forceSection = "$FORCE"; // hessian, normal coordinates HESS :HESSX + static final String cphfSection = "$CPHF"; // coupled-Hartree-Fock options CPHF :CPINP + static final String hessSection = "$HESS"; // force constant matrix (formatted) HESS :FCMIN + static final String gradSection = "$GRAD"; // gradient vector (formatted) HESS :EGIN + static final String dipdrSection = "$DIPDR"; // dipole deriv. matrix (formatted) HESS :DDMIN + static final String vibSection = "$VIB"; // HESSIAN restart data (formatted) HESS :HSSNUM + static final String massSection = "$MASS"; // isotope selection VIBANL:RAMS + static final String ircSection = "$IRC"; // intirisic reaction path RXNCRD:IRCX + static final String drcSection = "$DRC"; // dynamic reaction path DRC :DRCDRV + static final String surfSection = "$SURF"; // potential surface scan SURF :SRFINP + // --- Interpretation, properties: + static final String localSection = "$LOCAL"; // orbital localization control LOCAL :LMOINP + static final String twoeiSection = "$TWOEI"; // J,K integrals (formatted) LOCCD :TWEIIN + static final String elmonSection = "$ELMOM"; // electrostatic moments PRPLIB:INPELM + static final String elpotSection = "$ELPOT"; // electrostatic potential PRPLIB:INPELP + static final String eldensSection = "$ELDENS"; // electron density PRPLIB:INPELD + static final String elfldgSection = "$ELFLDG"; // electric field/gradient PRPLIB:INPELF + static final String pointsSection = "$POINTS"; // property calculation points PRPLIB:INPPGS + static final String gridSection = "$GRID"; // property calculation mesh PRPLIB:INPPGS + static final String pdcSection = "$PDC"; // MEP fitting mesh PRPLIB:INPPDC + static final String molgrfSection = "$MOLGRF"; // orbital plots PARLEY:PLTMEM + static final String stoneSection = "$STONE"; // distributed multipole analysis PRPPOP:STNRD + static final String morokmSection = "$MOROKM"; // Morokuma energy decomposition MOROKM:MOROIN + static final String ffcalcSection = "$FFCALC"; // finite field polarizabilities FFIELD:FFLDX + static final String tdhfSection = "$TDHF"; // time dependent HF NLO properties TDHF :TDHFX + // --- Solvation models: + static final String efragSection = "$EFRAG"; // effective fragment potentials EFINP :EFINP + static final String fragnameSection = "$FRAGNAME"; // specific named fragment pot. EFINP :RDSTFR + static final String fgrrplSection = "$FRGRPL"; // inter-fragment repulsion EFINP :RDDFRL + static final String pcmSection = "$PCM"; // polarizable continuum model PCM :PCMINP + static final String pcmcavSection = "$PCMCAV"; // PCM cavity generation PCM :MAKCAV + static final String newcavSection = "$NEWCAV"; // PCM escaped charge cavity PCM :DISREP + static final String disbsSection = "$DISBS"; // PCM dispersion basis set PCMDIS:ENLBS + static final String disrepSection = "$DISREP"; // PCM dispersion/repulsion PCMVCH:MORETS + static final String scrfSection = "$SCRF"; // self consistent reaction field SCRF :ZRFINP + // --- Integral and integral modification options: + static final String ecpSection = "$ECP"; // effective core potentials ECPLIB : ECPPAR + static final String efieldSection = "$EFIELD"; // external electric field PRPLIB : INPEF + static final String intgrlSection = "$INTGRL"; // format for 2e-integrals INT2A : INTIN + static final String transSection = "$TRANS"; // integral transformation TRANS : TRFIN + // --- MCSCF and CI wavefunctions, and their properties : + static final String ciinpSection = "$CIINP"; // control of CI process GAMESS : WFNCI + static final String detSection = "$DET"; // determinantal full CI for MCSCF ALDECI : DETINP + static final String cidetSection = "$CIDET"; // determinantal full CI ALDECI : DETINP + static final String drtSection = "$DRT"; // distinct row table for MCSCF GUGDRT : ORDORB + static final String cidrtSection = "$CIDRT"; // distinct row table for CI GUGDRT : ORDORB + static final String mcscfSection = "$MCSCF"; // parameters for MCSCF MCSCF : MCSCF + static final String mcqdptSection = "$MCQDPT"; // multireference pert.theory MCQDPT : MQREAD + static final String cisortSection = "$CISORT"; // integral sorting GUGSRT : GUGSRT + static final String gugemSection = "$GUGEM"; // Hamiltonian matrix formation GUGEM : GUGAEM + static final String gugdiaSection = "$GUGDIA"; // Hamiltonian eigenvalues / vectors GUGDGA : GUGADG + static final String gugdmSection = "$GUGDM"; // 1e-density matrix GUGDM : GUGADM + static final String gugdm2Section = "$GUGDM2"; // 2e-density matrix GUGDM2 : GUG2DM + static final String lagranSection = "$LAGRAN"; // CI lagrangian matrix LAGRAN : CILGRN + static final String trfdm2Section = "$TRFDM2"; // 2e-density backtransformation TRFDM2 : TRF2DM + static final String transtSection = "$TRANST"; // transition moments, spin - orbit TRNSTN : TRNSTX + static final Set validSections = new HashSet(); + static Map sectionVarsReference = new HashMap(); + static Map controlSwitches = null; + static Map basisSwitches = new HashMap(); + static Map systemSwitches = new HashMap(); + static final Set validSymmetrySymbols = new HashSet(); + static final Logger logger = Logger.getLogger(Gamess.class.getCanonicalName()); + + static { + validSections.add(controlSection); + validSections.add(systemSection); + validSections.add(basisSection); + validSections.add(dataSection); + validSections.add(zmatSection); + validSections.add(libeSection); + validSections.add(scfSection); + validSections.add(scfmiSection); + validSections.add(mp2Section); + validSections.add(guessSection); + validSections.add(vecSection); + + validSections.add(statptSection); + validSections.add(trudgeSection); + validSections.add(trurstSection); + validSections.add(forceSection); + validSections.add(cphfSection); + validSections.add(hessSection); + validSections.add(gradSection); + validSections.add(dipdrSection); + validSections.add(vibSection); + validSections.add(massSection); + validSections.add(ircSection); + validSections.add(drcSection); + validSections.add(surfSection); + + validSections.add(localSection); + validSections.add(twoeiSection); + validSections.add(elmonSection); + validSections.add(elpotSection); + validSections.add(eldensSection); + validSections.add(elfldgSection); + validSections.add(pointsSection); + validSections.add(gridSection); + validSections.add(pdcSection); + validSections.add(molgrfSection); + validSections.add(stoneSection); + validSections.add(morokmSection); + validSections.add(ffcalcSection); + validSections.add(tdhfSection); + + // --- Solvation models: + validSections.add(efragSection); + validSections.add(fragnameSection); + validSections.add(fgrrplSection); + validSections.add(pcmSection); + validSections.add(pcmcavSection); + validSections.add(newcavSection); + validSections.add(disbsSection); + validSections.add(disrepSection); + validSections.add(scrfSection); + + // --- Integral and integral modification options: + validSections.add(ecpSection); + validSections.add(efieldSection); + validSections.add(intgrlSection); + validSections.add(transSection); + + // --- MCSCF and CI wavefunctions, and their properties : + validSections.add(ciinpSection); + validSections.add(detSection); + validSections.add(cidetSection); + validSections.add(drtSection); + validSections.add(cidrtSection); + validSections.add(mcscfSection); + validSections.add(mcqdptSection); + validSections.add(cisortSection); + validSections.add(gugemSection); + validSections.add(gugdiaSection); + validSections.add(gugdmSection); + validSections.add(gugdm2Section); + validSections.add(lagranSection); + validSections.add(trfdm2Section); + validSections.add(transtSection); + + // --- Setup valid symmetry symbols + validSymmetrySymbols.add("C1"); + validSymmetrySymbols.add("CS"); + validSymmetrySymbols.add("CI"); + validSymmetrySymbols.add("CN"); + validSymmetrySymbols.add("S2N"); + validSymmetrySymbols.add("CNH"); + validSymmetrySymbols.add("NH"); + validSymmetrySymbols.add("CNV"); + validSymmetrySymbols.add("DN"); + validSymmetrySymbols.add("DNH"); + validSymmetrySymbols.add("DND"); + validSymmetrySymbols.add("T"); + validSymmetrySymbols.add("TH"); + validSymmetrySymbols.add("TD"); + validSymmetrySymbols.add("O"); + validSymmetrySymbols.add("OH"); + } + String Title = "No Title"; + String SymmetrySymbol = "c1"; + int AxisOrder = 1; + Map currentVars = new HashMap(); + List atoms = new ArrayList(); + //HashMap controlGroup = new HashMap(); + Map basisGroup = new HashMap(); + private boolean ignoreDataSection = false; + + public Gamess() { + initialize(); + } + + public void setLoggerLevel(Level level) { + logger.setLevel(level); + } + + private void initialize() { + + // --- Setup vars + //currentVars.put(controlSection, controlGroup); + //currentVars.put(basisSection, basisGroup); + // --- Initialize control switches + if (controlSwitches != null) { + return; + } + + controlSwitches = new HashMap(); + + GamessSwitch gSwitch = new GamessSwitch("SCFTYP", + "together with MPLEVL or CITYP specifies the wavefunction. You may choose from"); + gSwitch.addValue("RHF", + "Restricted Hartree Fock calculation (default)", true); + gSwitch.addValue("UHF", "Unrestricted Hartree Fock calculation"); + gSwitch.addValue("ROHF", + "Restricted open shell Hartree-Fock. (high spin, see GVB for low spin)"); + gSwitch.addValue("GVB", + "Generalized valence bond wavefunction or OCBSE type ROHF. (needs $SCF input)"); + gSwitch.addValue("MCSCF", + "Multiconfigurational SCF wavefunction (this requires $DET or $DRT input)"); + gSwitch.addValue("NONE", + "indicates a single point computation, rereading a converged SCF function. " + + "This option requires that you select CITYP=GUGA or ALDET, RUNTYP=ENERGY, " + + "TRANSITN, or SPINORBT, and GUESS=MOREAD."); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("ISPHER", "Spherical Harmonics option"); + gSwitch.setType(new Integer(-1)); + gSwitch.addValue("-1", + "Use Cartesian basis functions to construct symmetry-adapted linear combination (SALC) " + + "of basis functions. The SALC space is the linear variation space used. (default)", true); + gSwitch.addValue("0", + "Use spherical harmonic functions to create SALC functions, which are then expressed " + + "in terms of Cartesian functions. The contaminants are not dropped, hence this " + + "option has EXACTLY the same variational space as ISPHER=-1. The only benefit to " + + "obtain from this is a population analysis in terms of pure s,p,d,f,g functions."); + gSwitch.addValue("1", + "Same as ISPHER=0, but the function space is truncated to eliminate all contaminant " + + "Cartesian functions [3S(D), 3P(F), 4S(G), and 3D(G)] before constructing the SALC " + + "functions. The computation corresponds to the use of a spherical harmonic basis."); + + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("MPLEVL", + "chooses Moller-Plesset perturbation theory level, after the SCF. See $MP2 and $MCQDPT input groups."); + gSwitch.addValue("0", "skips the MP computation (default)", true); + gSwitch.addValue("2", + "performs a second order energy correction. MP2 is implemented only " + + "for RHF, UHF, ROHF, and MCSCF wave functions. Gradients are available " + + "only for RHF, so for the others you may pick from RUNTYP=ENERGY, TRUDGE, SURFACE, or FFIELD only."); + gSwitch.setType(new Integer(0)); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("CITYP", + "chooses CI computation after the SCF, for any SCFTYP except UHF."); + gSwitch.addValue("NONE", "skips the CI. (default)", true); + gSwitch.addValue("GUGA", + "runs the Unitary Group CI package, which requires $CIDRT input. Gradients are available only for RHF, " + + "so for other SCFTYPs, you may choose only RUNTYP=ENERGY, TRUDGE, SURFACE, FFIELD, TRANSITN, or SPINORBT."); + gSwitch.addValue("ALDET", + "runs the Ames Laboratory determinant full CI package, requiring $CIDET input. RUNTYP=ENERGY only."); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("RUNTYP", + "specifies the type of computation\n" + + "* * * * * * * * * * * * * * * * * * * * * * * * *\n" + + "Note that RUNTYPs involving the energy gradient,\n" + + "which are GRADIENT, HESSIAN, OPTIMIZE, SADPOINT, \n" + + "IRC, GRADEXTR, and DRC, cannot be used for any\n" + + "CI or MP2 computation, except when SCFTYP=RHF.\n" + + "* * * * * * * * * * * * * * * * * * * * * * * * *"); + gSwitch.addValue("ENERGY", "Molecular energy. (default)", true); + gSwitch.addValue("GRADIENT", "Molecular energy plus gradient."); + gSwitch.addValue("HESSIAN", + "Molecular energy plus gradient plus second derivatives, including harmonic " + + "harmonic vibrational analysis. See the $FORCE and $CPHF input groups."); + gSwitch.addValue("OPTIMIZE", + "Optimize the molecular geometry using analytic energy gradients. See $STATPT."); + gSwitch.addValue("TRUDGE", + "Non-gradient total energy minimization. See groups $TRUDGE and $TRURST."); + gSwitch.addValue("SADPOINT", + "Locate saddle point (transition state). See the $STATPT group."); + gSwitch.addValue("IRC", + "Follow intrinsic reaction coordinate. See the $IRC group."); + gSwitch.addValue("GRADEXTR", + "Trace gradient extremal. See the $GRADEX group."); + gSwitch.addValue("DRC", + "Follow dynamic reaction coordinate. See the $DRC group."); + gSwitch.addValue("SURFACE", + "Scan linear cross sections of the potential energy surface. See $SURF."); + gSwitch.addValue("PROP", "Properties will be calculated. A $DATA deck and converged $VEC group should be " + + "input. Optionally, orbital localization can be done. See $ELPOT, etc."); + gSwitch.addValue("MOROKUMA", + "Performs monomer energy decomposition. See the $MOROKM group."); + gSwitch.addValue("TRANSITN", + "Compute radiative transition moment. See the $TRANST group."); + gSwitch.addValue("SPINORBT", + "Compute spin-orbit coupling. See the $TRANST group."); + gSwitch.addValue("FFIELD", + "applies finite electric fields, most commonly to extract polarizabilities. See the $FFCALC group."); + gSwitch.addValue("TDHF", + "analytic computation of time dependent polarizabilities. See the $TDHF group."); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("EXETYP", ""); + gSwitch.addValue("RUN", "Actually do the run. (default)", true); + gSwitch.addValue("CHECK", + "Wavefunction and energy will not be evaluated. This lets you speedily check input and memory requirements. " + + "See the overview section for details."); + gSwitch.addValue("DEBUG", + "Massive amounts of output are printed, useful only if you hate trees."); + gSwitch.addValue("routine", + "Maximum output is generated by the routine named. Check the source for the routines this applies to."); // !!! + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("MAXIT", + "Maximum number of SCF iteration cycles. Pertains only to RHF, UHF, ROHF, or " + + "GVB runs. See also MAXIT in $MCSCF. (default = 30)", true); + gSwitch.addValue("30", "", true); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("ICHARG", + "Molecular charge. (default=0, neutral)", true); + gSwitch.addValue("0", "", true); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("MULT", + "Multiplicity of the electronic state. = 1 singlet (default)", true); + gSwitch.addValue("1", "", true); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("ECP", "effective core potential control."); + gSwitch.addValue("NONE", "all electron calculation (default).", true); + gSwitch.addValue("READ", "read the potentials in $ECP group."); + gSwitch.addValue("SBKJC", "use Stevens, Basch, Krauss, Jasien, Cundari potentials for all heavy atoms (Li-Rn are available)."); + gSwitch.addValue("HW", + "use Hay, Wadt potentials for all the heavy atoms (Na-Xe are available)."); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("COORD", + "choice for molecular geometry in $DATA.\n\n" + + "Note that the CART, ZMT, ZMTMPC choices require input of " + + "all atoms in the molecule. These three also orient the " + + "molecule, and then determine which atoms are unique. The " + + "reorientation is very likely to change the order of the " + + "atoms from what you input. When the point group contains " + + "a 3-fold or higher rotation axis, the degenerate moments " + + "of inertia often cause problems choosing correct symmetry " + + " unique axes, in which case you must use COORD=UNIQUE rather than Z-matrices.\n\n" + + "Note that the CART, ZMT, ZMTMPC choices require input of " + + "all atoms in the molecule. These three also orient the " + + "molecule, and then determine which atoms are unique. The " + + "reorientation is very likely to change the order of the " + + "atoms from what you input. When the point group contains " + + "a 3-fold or higher rotation axis, the degenerate moments " + + "of inertia often cause problems choosing correct symmetry " + + "unique axes, in which case you must use COORD=UNIQUE " + + "rather than Z-matrices.\n\n" + + "Warning: The reorientation into principal axes is done " + + "only for atomic coordinates, and is not applied to the " + + "axis dependent data in the following groups: $VEC, $HESS, " + + "$GRAD, $DIPDR, $VIB, nor Cartesian coords of effective " + + "fragments in $EFRAG. COORD=UNIQUE avoids reorientation, " + + "and thus is the safest way to read these.\n\n " + + "Note that the choices CART, ZMT, ZMTMPC require the use " + + "of a $BASIS group to define the basis set. The first " + + "two choices might or might not use $BASIS, as you wish."); + + gSwitch.addValue("UNIQUE", + "only the symmetry unique atoms will be given, in Cartesian coords (default).", true); + gSwitch.addValue("HINT", + "only the symmetry unique atoms will be given, in Hilderbrandt style internals."); + gSwitch.addValue("CART", "Cartesian coordinates will be input."); + gSwitch.addValue("ZMT", "GAUSSIAN style internals will be input."); + gSwitch.addValue("ZMTMPC", "MOPAC style internals will be input."); + gSwitch.addValue("FRAGONLY", + "means no part of the system is treated by ab initio means, hence $DATA is not " + + "given. The system is specified by $EFRAG."); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("UNITS", + "distance units, any angles must be in degrees."); + gSwitch.addValue("ANGS", "Angstroms (default)", true); + gSwitch.addValue("BOHR", "Bohr atomic units"); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("NZVAR", + "NZVAR refers mainly to the coordinates used by OPTIMIZE " + + "or SADPOINT runs, but may also print the internal's values for other run types. You can use internals to " + + "define the molecule, but Cartesians during optimizations! \n\n" + + "= 0 Use Cartesian coordinates (default).\n" + + "= M If COORD=ZMT or ZMTMPC and a $ZMAT is not given: the internal coordinates will be those defining " + + "the molecule in $DATA. In this case, $DATA must not contain any dummy atoms. M is usually 3N-6, or 3N-5 for linear.\n\n" + + "= M For other COORD choices, or if $ZMAT is given: the internal coordinates will be those defined " + + "in $ZMAT. This allows more sophisticated internal coordinate choices. M is ordinarily 3N-6 (3N-5), unless $ZMAT has linear bends.", true); + gSwitch.addValue("0", "Use Cartesian coordinates(default)", true); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("LOCAL", "controls orbital localization."); + gSwitch.addValue("NONE", "Skip localization (default).", true); + gSwitch.addValue("BOYS", "Do Foster-Boys localization."); + gSwitch.addValue("RUEDNBRG", "Do Edmiston-Ruedenberg localization."); + gSwitch.addValue("POP", + "Do Pipek-Mezey population localization. See the $LOCAL group. Localization " + + "does not work for SCFTYP=GVB or CITYP."); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("MOLPLT", + "flag that produces an input deck for a molecule " + + "drawing program distributed with GAMESS. (default is .FALSE.)", true); + gSwitch.setType(new Boolean(false)); + gSwitch.addValue("false", "", true); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("PLTORB", + "flag that produces an input deck for an orbital " + + "plotting program distributed with GAMESS. (default is .FALSE.)", true); + gSwitch.setType(new Boolean(false)); + gSwitch.addValue("false", "", true); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("AIMPAC", + "flag to create an input deck for Bader's atoms " + + "in molecules properties code. (default=.FALSE.)", true); + gSwitch.setType(new Boolean(false)); + gSwitch.addValue("false", "", true); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("RPAC", + "flag to create the input files for Bouman and " + + "Hansen 'sRPAC electronic excitation and NMR shieldings program.RPAC works only with " + + "RHF wavefunctions. (inactive)", true); + gSwitch.setType(new Boolean(false)); + gSwitch.addValue("false", "", true); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("FRIEND", + "string to prepare input to other quantum programs"); + gSwitch.addValue("HONDO", " for HONDO 8.2"); + gSwitch.addValue("MELDF", " for MELDF"); + gSwitch.addValue("GAMESSUK", " for GAMESS(UK Daresbury version)"); + gSwitch.addValue("GAUSSIAN", " for Gaussian 9x"); + gSwitch.addValue("ALL", " for all of the above"); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("NPRINT", + "Print / punch control flag. See also EXETYP for debug info. " + + "(options - 7to 5are primarily debug)"); + gSwitch.addValue("-7", "Extra printing from Boys localization."); + gSwitch.addValue("-6", "debug for geometry searches"); + gSwitch.addValue("-5", "minimal output"); + gSwitch.addValue("-4", "print 2e-contribution to gradient."); + gSwitch.addValue("-3", "print 1e-contribution to gradient."); + gSwitch.addValue("-2", "normal printing, no punch file"); + gSwitch.addValue("1", "extra printing for basis, symmetry, ZMAT"); + gSwitch.addValue("2", "extra printing for MO guess routines"); + gSwitch.addValue("3", "print out property and 1e-integrals"); + gSwitch.addValue("4", "print out 2e-integrals"); + gSwitch.addValue("5", + "print out SCF data for each cycle. (Fock and density matrices, current MOs"); + gSwitch.addValue("6", + "same as 7, but wider 132columns output. This option isn't perfect."); + gSwitch.addValue("7", "normal printing and punching(default)", true); + gSwitch.addValue("8", + "more printout than 7.The extra output is(AO) Mulliken and overlap population analysis, eigenvalues, Lagrangians, ..."); + gSwitch.addValue("9", + "everything in 8plus Lowdin population analysis, final density matrix."); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("NOSYM", ""); + gSwitch.addValue("0", "the symmetry specified in $DATA is used as much as possible in integrals, SCF, " + + "gradients, etc. (this is the default)", true); + gSwitch.addValue("1", + "the symmetry specified in the $DATA group is used to build the molecule, then " + + "symmetry is not used again.Some GVB or MCSCF runs(those without a totally " + + "symmetric charge density) require you request no symmetry."); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("INTTYP", ""); + gSwitch.addValue("POPLE", "use fast Pople - Hehre routines for sp integral blocks, and HONDO Rys polynomial code for " + + "all other integrals. (default)", true); + gSwitch.addValue("HONDO", " use HONDO / Rys integrals for all integrals. This option produces slightly more accurate " + + "integrals but is also slower."); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("NORMF", ""); + gSwitch.addValue("0", "normalize the basis functions(default)", true); + gSwitch.addValue("1", "no normalization"); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("NORMP", ""); + gSwitch.addValue("0", "input contraction coefficients refer to normalized Gaussian primitives. (default)", true); + gSwitch.addValue("1", "the opposite."); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("ITOL", + "primitive cutoff factor(default = 20)\n" + + "= n products of primitives whose exponential factor is less than 10**( -n) are skipped.", true); + gSwitch.addValue("20", "", true); + gSwitch.setType(new Integer(20)); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("ICUT", + " = n integrals less than 10.0**(-n) are not saved on disk. (default = 9)", true); + gSwitch.addValue("9", "", true); + gSwitch.setType(new Integer(9)); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("IREST", + "restart control options (for OPTIMIZE run restarts, see $STATPT)\n" + + "Note that this option is unreliable!"); + gSwitch.addValue("-1", "reuse dictionary file from previous run, useful with GEOM = DAF and / or GUESS = MOSAVED. " + + "Otherwise, this option is the same as 0."); + gSwitch.addValue("0", "normal run(default)", true); + gSwitch.addValue("1", "2e restart(1 - e integrals and MOs saved)"); + gSwitch.addValue("2", + "SCF restart(1 - , 2 - e integrls and MOs saved)"); + gSwitch.addValue("3", "1e gradient restart "); + gSwitch.addValue("4", "2e gradient restart"); + controlSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("GEOM", + "select where to obtain molecular geometry"); + gSwitch.addValue("INPUT", " from $DATA input(default for IREST = 0)"); /// !!! + gSwitch.addValue("DAF", "read from DICTNRY file(default otherwise)", true); + controlSwitches.put(gSwitch.getName(), gSwitch); + + // --- Setting up basis swithces + gSwitch = new GamessSwitch("GBASIS", + "GBASIS requests various Gaussian basis sets."); + gSwitch.addValue("MINI", + "Huzinaga's 3 gaussian minimal basis set.\nAvailable H-Rn."); + gSwitch.addValue("MIDI", + "Huzinaga's 21 split valence basis set.\nAvailable H-Rn."); + gSwitch.addValue("STO", + "Pople's STO-NG minimal basis set.\nAvailable H-Xe, for NGAUSS=2,3,4,5,6."); + gSwitch.addValue("N21", + "Pople's N-21G split valence basis set.\nAvailable H-Xe, for NGAUSS=3.\nAvailable H-Ar, for NGAUSS=6."); + gSwitch.addValue("N31", + "Pople's N-31G split valence basis set.\nAvailable H-Ne,P-Cl for NGAUSS=4.\n" + + "Available H-He,C-F for NGAUSS=5.\nAvailable H-Kr, for NGAUSS=6, note that the bases for K,Ca,Ga-Kr were changed 9/2006."); + gSwitch.addValue("N311", + "Pople's \"triple split\" N-311G basis set.\nAvailable H-Ne, for NGAUSS=6.\nSelecting N311 implies MC for Na-Ar."); + gSwitch.addValue("DZV", + "\"double zeta valence\" basis set. a synonym for DH for H,Li,Be-Ne,Al-Cl.\n" + + "(14s,9p,3d)/[5s,3p,1d] for K-Ca.\n(14s,11p,5d/[6s,4p,1d] for Ga-Kr."); + gSwitch.addValue("DH", "Dunning/Hay \"double zeta\" basis set.\n" + + "(3s)/[2s] for H.\n" + + "(9s,4p)/[3s,2p] for Li.\n" + + "(9s,5p)/[3s,2p] for Be-Ne.\n" + + "(11s,7p)/[6s,4p] for Al-Cl."); + gSwitch.addValue("TZV", "\"triple zeta valence\" basis set.\n" + + "(5s)/[3s] for H.\n" + + "(10s,3p)/[4s,3p] for Li.\n" + + "(10s,6p)/[5s,3p] for Be-Ne.\n" + + "a synonym for MC for Na-Ar.\n" + + "(14s,9p)/[8s,4p] for K-Ca." + + "(14s,11p,6d)/[10s,8p,3d] for Sc-Zn."); + + gSwitch.addValue("MC", "McLean/Chandler \"triple split\" basis.\n" + + "(12s,9p)/[6s,5p] for Na-Ar.\n" + + "Selecting MC implies 6-311G for H-Ne."); + gSwitch.addValue("CCD", + "Dunning-type Correlation Consistent basis sets, officially called cc-pVnZ." + + "Available for H-He, Li-Ne, Na-Ar, Ca, Ga-Kr"); + gSwitch.addValue("CCT", + "Dunning-type Correlation Consistent basis sets, officially called cc-pVnZ." + + "Available for H-He, Li-Ne, Na-Ar, Ca, Ga-Kr"); + gSwitch.addValue("CCQ", + "Dunning-type Correlation Consistent basis sets, officially called cc-pVnZ." + + "Available for H-He, Li-Ne, Na-Ar, Ca, Ga-Kr"); + gSwitch.addValue("CC5", + "Dunning-type Correlation Consistent basis sets, officially called cc-pVnZ." + + "Available for H-He, Li-Ne, Na-Ar, Ca, Ga-Kr"); + gSwitch.addValue("CC6", + "Dunning-type Correlation Consistent basis sets, officially called cc-pVnZ." + + "Available for H-He, Li-Ne, Na-Ar, Ca, Ga-Kr"); + //Use n = D,T,Q,5,6 to indicate the level of + //polarization. These provide a hierachy of + //basis sets suitable for recovering the + //correlation energy. + //Available for H - He, Li - Ne, Na - Ar, Ca, Ga - Kr + + gSwitch.addValue("ACCD", + "As CCD, but augmented with a set of diffuse functions, e.g.aug - cc - pVDZ."); + gSwitch.addValue("ACCT", + "As CCT, but augmented with a set of diffuse functions, e.g.aug - cc - pVTZ."); + gSwitch.addValue("ACCQ", + "As CCQ, but augmented with a set of diffuse functions, e.g.aug - cc - pVQZ."); + gSwitch.addValue("ACC5", + "As CC5, but augmented with a set of diffuse functions, e.g.aug - cc - pV5Z."); + gSwitch.addValue("ACC6", + "As CC6, but augmented with a set of diffuse functions, e.g.aug - cc - pV6Z."); + + gSwitch.addValue("CCDC", "As CCD, but augmented with tight functions for recovering core and core - valence " + + "correlation, e.g.cc - pCVDZ"); + gSwitch.addValue("CCTC", "As CCT, but augmented with tight functions for recovering core and core - valence " + + "correlation, e.g.cc - pCVTZ"); + gSwitch.addValue("CCQC", "As CCQ, but augmented with tight functions for recovering core and core - valence " + + "correlation, e.g.cc - pCVQZ"); + gSwitch.addValue("CC5C", "As CC5, but augmented with tight functions for recovering core and core - valence " + + "correlation, e.g.cc - pCV5Z"); + gSwitch.addValue("CC6C", "As CC6, but augmented with tight functions for recovering core and core - valence " + + "correlation, e.g.cc - pCV6Z"); + + gSwitch.addValue("ACCTC", "As CCT, but augmented with both tight and diffuse functions, e.g.aug - cc - pCVTZ."); + gSwitch.addValue("ACCDC", "As CCD, but augmented with both tight and diffuse functions, e.g.aug - cc - pCVDZ."); + gSwitch.addValue("ACCQC", "As CCQ, but augmented with both tight and diffuse functions, e.g.aug - cc - pCVQZ."); + gSwitch.addValue("ACC5C", "As CC5, but augmented with both tight and diffuse functions, e.g.aug - cc - pCV5Z."); + gSwitch.addValue("ACC6C", "As CC6, but augmented with both tight and diffuse functions, e.g.aug - cc - pCV6Z."); + + gSwitch.addValue("PC0", "Jensen Polarization Consistent basis sets.\n" + + "n = 0, 1, 2, 3, 4 indicates the level of polarization. (n = 0 is unpolarized, n = 1 is" + + "DZP, n = 2 is TZP, etc.)\n" + + "Available for H, C, N, O, F, Si, P, S, Cl"); + gSwitch.addValue("PC1", "Jensen Polarization Consistent basis sets.\n" + + "n = 0, 1, 2, 3, 4 indicates the level of polarization. (n = 0 is unpolarized, n = 1 is" + + "DZP, n = 2 is TZP, etc.)\n" + + "Available for H, C, N, O, F, Si, P, S, Cl"); + gSwitch.addValue("PC2", "Jensen Polarization Consistent basis sets.\n" + + "n = 0, 1, 2, 3, 4 indicates the level of polarization. (n = 0 is unpolarized, n = 1 is" + + "DZP, n = 2 is TZP, etc.)\n" + + "Available for H, C, N, O, F, Si, P, S, Cl"); + gSwitch.addValue("PC3", "Jensen Polarization Consistent basis sets.\n" + + "n = 0, 1, 2, 3, 4 indicates the level of polarization. (n = 0 is unpolarized, n = 1 is" + + "DZP, n = 2 is TZP, etc.)\n" + + "Available for H, C, N, O, F, Si, P, S, Cl"); + gSwitch.addValue("PC4", "Jensen Polarization Consistent basis sets.\n" + + "n = 0, 1, 2, 3, 4 indicates the level of polarization. (n = 0 is unpolarized, n = 1 is" + + "DZP, n = 2 is TZP, etc.)\n" + + "Available for H, C, N, O, F, Si, P, S, Cl"); + + gSwitch.addValue("APC0", + "As PC0, but augmented with a set of diffuse functions."); + gSwitch.addValue("APC1", + "As PC1, but augmented with a set of diffuse functions."); + gSwitch.addValue("APC2", + "As PC2, but augmented with a set of diffuse functions."); + gSwitch.addValue("APC3", + "As PC3, but augmented with a set of diffuse functions."); + gSwitch.addValue("APC4", + "As PC4, but augmented with a set of diffuse functions."); + + gSwitch.addValue("SBKJC", + "Stevens/Basch/Krauss/Jasien/Cundari valence basis set, for Li-Rn. This choice " + + "implies an unscaled -31G basis for H-He."); + gSwitch.addValue("HW", "Hay/Wadt valence basis.\n" + + "This is a -21 split, available Na-Xe, except for the transition metals.\n" + + "This implies a 3-21G basis for H-Ne."); + + gSwitch.addValue("MCP-DZP", + "double zeta quality valence basis set, which are akin to the " + + "correlation consistent sets, in that these include increasing levels of polarization (and so do not " + + "require \"supplements\" like NDFUNC or DIFFSP) and must be used as spherical harmonics (see ISPHER).\n" + + "These are available for main group atoms, Li-Rn."); + gSwitch.addValue("MCP-TZP", + "triple zeta quality valence basis set, which are akin to the " + + "correlation consistent sets, in that these include increasing levels of polarization (and so do not " + + "require \"supplements\" like NDFUNC or DIFFSP) and must be used as spherical harmonics (see ISPHER).\n" + + "These are available for main group atoms, Li-Rn."); + gSwitch.addValue("MCP-QZP", + "quadruple zeta quality valence basis set, which are akin to the " + + "correlation consistent sets, in that these include increasing levels of polarization (and so do not " + + "require \"supplements\" like NDFUNC or DIFFSP) and must be used as spherical harmonics (see ISPHER).\n" + + "These are available for main group atoms, Li-Rn."); + gSwitch.addValue("IMCP-SR1", "valence basis set to be used with the improved MCPs with scalar relativistic effects.\n" + + "These are available for transition metals except La, and the main group elements B-Ne, P-Ar, Ge, Kr, Sb, Xe, Rn.\n" + + "The 1 refer to addition of first polarization shell, so again don't use any of the \"supplements\" and do use spherical harmonics."); + gSwitch.addValue("IMCP-SR2", "valence basis set to be used with the improved MCPs with scalar relativistic effects.\n" + + "These are available for transition metals except La, and the main group elements B-Ne, P-Ar, Ge, Kr, Sb, Xe, Rn.\n" + + "The 2 refer to addition of second polarization shell, so again don't use any of the \"supplements\" and do use spherical harmonics."); + gSwitch.addValue("IMCP-NR1", + "valence basis set, but with nonrelativistic model core potentials."); + gSwitch.addValue("IMCP-NR2", + "valence basis set, but with nonrelativistic model core potentials."); + gSwitch.addValue("MNDO", "selects MNDO model hamiltonian"); + gSwitch.addValue("AM1", "selects AM1 model hamiltonian"); + gSwitch.addValue("PM3", "selects PM3 model hamiltonian"); + + basisSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("NGAUSS", + "the number of Gaussians (N). This parameter pertains only to GBASIS=STO, N21, N31, or N311."); + gSwitch.setType(new Integer(0)); + + basisSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("NDFUNC", + "number of heavy atom polarization functions to be used. These are usually d functions, except " + + "for MINI/MIDI. The term \"heavy\" means Na on up when GBASIS=STO, HW, or N21, and from Li on up " + + "otherwise. The value may not exceed 3. The variable POLAR selects the actual exponents to " + + " be used, see also SPLIT2 and SPLIT3. (default=0)"); + gSwitch.setType(new Integer(0)); + gSwitch.addValue("0", "", true); + gSwitch.addValue("1", ""); + gSwitch.addValue("2", ""); + gSwitch.addValue("3", ""); + + basisSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("NFFUNC", "number of heavy atom f type polarization functions to be used on Li-Cl. This may only " + + "be input as 0 or 1. (default=0)"); + gSwitch.setType(new Integer(0)); + gSwitch.addValue("0", "", true); + gSwitch.addValue("1", ""); + + basisSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("NPFUNC", "number of light atom, p type polarization functions to be used on H-He. This may not " + + "exceed 3, see also POLAR. (default=0)"); + gSwitch.setType(new Integer(0)); + gSwitch.addValue("0", "", true); + gSwitch.addValue("1", ""); + gSwitch.addValue("2", ""); + gSwitch.addValue("3", ""); + + basisSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("DIFFSP", + "flag to add diffuse sp(L) shell to heavy atoms.\n" + + "Heavy means Li - F, Na - Cl, Ga - Br, In - I, Tl - At.\n" + + "The default is .FALSE."); + gSwitch.setType(new Boolean(false)); + gSwitch.addValue(".FALSE.", "", true); + gSwitch.addValue(".TRUE.", ""); + + basisSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("DIFFS", + "flag to add diffuse s shell to hydrogens.\n" + + "The default is .FALSE."); + gSwitch.setType(new Boolean(false)); + gSwitch.addValue(".FALSE.", "", true); + gSwitch.addValue(".TRUE.", ""); + + basisSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("POLAR", "exponent of polarization functions"); + gSwitch.addValue("COMMON", "(default for GBASIS=STO,N21,HW,SBKJC)"); + gSwitch.addValue("POPN31", "(default for GBASIS=N31)"); + gSwitch.addValue("POPN311", "(default for GBASIS=N311, MC)"); + gSwitch.addValue("DUNNING", "(default for GBASIS=DH, DZV)"); + gSwitch.addValue("HUZINAGA", "(default for GBASIS=MINI, MIDI)"); + gSwitch.addValue("HONDO7", "(default for GBASIS=TZV)"); + + basisSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("SPLIT2", + "an array of splitting factors used when NDFUNC or NPFUNC is 2. Default=2.0,0.5"); + Float[] split2 = { + 2.0f, 0.5f}; + gSwitch.setType(split2); + gSwitch.addValue("2.0,0.5", "", true); + + basisSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("SPLIT3", "an array of splitting factors used when NDFUNC or NPFUNC is 3. Default=4.00,1.00,0.25"); + Float[] split3 = { + 4.00f, 1.00f, 0.25f}; + gSwitch.setType(split3); + gSwitch.addValue("4.00,1.00,0.25", "", true); + + basisSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("EXTFIL", + "a flag to read basis sets from an external file, defined by EXTBAS, rather than from a $DATA group.\n" + + "(default=.false.)"); + gSwitch.setType(new Boolean(false)); + gSwitch.addValue(".FALSE.", "", true); + gSwitch.addValue(".TRUE.", ""); + + basisSwitches.put(gSwitch.getName(), gSwitch); + + // --- $SYSTEM swithces + gSwitch = new GamessSwitch("MWORDS", + "The maximum replicated memory which your job can " + + "use, on every node. This is given in units of 1,000,000 words (as opposed to 1024*1024 words), " + + "where a word is defined as 64 bits. (default=1)\n" + + "(In case finer control over the memory is needed, this value can be given in units of words with " + + " the old keyword MEMORY instead of MWORDS.)", true); + gSwitch.setType(new Integer(1)); + gSwitch.addValue("1", "", true); + + gSwitch = new GamessSwitch("MEMORY", + "The maximum memory in units of words. Obsolete", true); + gSwitch.setType(new Integer(1)); + + systemSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("MEMDDI", + "The grand total memory needed for the distributed data interface (DDI) storage, given in units of " + + "1,000,000 words.\n" + + "note: the memory required on each processor for a run using p processors is therefore MEMDDI/p + MWORDS.\n" + + "The parallel runs that currently require MEMDDI are:\n" + + "SCFTYP=RHF MPLEVL=2 energy or gradient\n" + + "SCFTYP=UHF MPLEVL=2 energy or gradient\n" + + "SCFTYP=ROHF MPLEVL=2 OSPT=ZAPT energy or gradient\n" + + "SCFTYP=MCSCF MPLEVL=2 energy\n" + + "SCFTYP=MCSCF using the FULLNR or JACOBI convergers\n" + + "SCFTYP=MCSCF analytic hessian\n" + + "SCFTYP=any CITYP=ALDET, GENCI, ORMAS, FSOCI, GUGA\n" + + "SCFTYP=RHF CCTYP=CCSD or CCSD(T)\n" + + "All other parallel runs should enter MEMDDI=0, for they use only replicated memory.\n" + + "Some serial runs execute the parallel code (on just 1 CPU), for there is only a parallel code. These serial runs must " + + "give MEMDDI as a result:\n" + + "SCFTYP=ROHF MPLEVL=2 OSPT=ZAPT gradient/property run\n" + + "SCFTYP=MCSCF analytic hessian", true); + gSwitch.setType(new Integer(1)); + gSwitch.addValue("1", "", true); + + systemSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("TIMLIM", + "Time limit, in minutes. Set to about 95 percent of the time limit given to the batch job (if you " + + "use a queueing system) so that GAMESS can stop itself gently. (default=525600.0 minutes)", true); + gSwitch.setType(new Float(525600.0f)); + gSwitch.addValue("525600", "", true); + + systemSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("PARALL", + "A flag to cause the distributed data parallel MP2 program to execute the parallel algorithm, " + + "even if you are running on only one node. The main purpose of this is to allow you to " + + "do EXETYP=CHECK runs to learn what the correct value of MEMDDI needs to be."); + gSwitch.setType(new Boolean(false)); + gSwitch.addValue(".FALSE.", "", true); + + systemSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("KDIAG", "Diagonalization control switch"); + gSwitch.setType(new Integer(0)); + gSwitch.addValue("0", + "use a vectorized diagonalization routine if one is available on your machine, else use EVVRSP. (default)", true); + gSwitch.addValue("1", + "use EVVRSP diagonalization. This may be more accurate than KDIAG=0."); + gSwitch.addValue("2", + "use GIVEIS diagonalization (not as fast or reliable as EVVRSP)"); + gSwitch.addValue("3", + "use JACOBI diagonalization (this is the slowest method)"); + + systemSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("COREFL", "A flag to indicate whether or not GAMESS should produce a \"core\" file for debugging " + + "when subroutine ABRT is called to kill a job.This variable pertains only to UNIX operating systems. (default = .FALSE.)"); + gSwitch.setType(new Boolean(false)); + gSwitch.addValue(".FALSE.", "", true); + gSwitch.addValue(".TRUE.", ""); + + systemSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("BALTYP", "Parallel load balance scheme", true); + gSwitch.setType(new Integer(0)); + + systemSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("BALTYP", + "Parallel load balance scheme. LOOP uses static load balancing. NXTVAL uses dynamic load balancing(DLB).\n" + + "(default = NXTVAL)", true); + gSwitch.setType(new Integer(0)); + + systemSwitches.put(gSwitch.getName(), gSwitch); + + gSwitch = new GamessSwitch("NODEXT", + "Array specifying node extentions in GDDI for each file. " + + "Non - zero values force no extension.\n" + + "E.g., NODEXT(40) = 1 forces file 40 (file numbers are unit numbers used in GAMESS, " + + "see \"rungms\" or PROG.DOC) to have the name of $JOB.F40 on all nodes, rather than $JOB.F40, $JOB.F40 .001, " + + "$JOB.F40 .002etc.This is convenient for FMO restart jobs, so that the file name need not be " + + "changed for each node, when copying the restart file. Note that on machines when several CPUs use " + + "the same directory(e.g., SMP) NODEXT should be zero. (default: all zeros)", true); + systemSwitches.put(gSwitch.getName(), gSwitch); + + // --- Setup references + sectionVarsReference.put(controlSection, controlSwitches); + sectionVarsReference.put(basisSection, basisSwitches); + sectionVarsReference.put(systemSection, systemSwitches); + + } + + public void getMolecularInterface(MoleculeInterface molec) throws + Exception { + if (molec == null) { + throw new Exception(this.getClass().getCanonicalName() + + " : molec == null"); + } + if (atoms.size() < 1) { + throw new Exception(this.getClass().getCanonicalName() + + " : no GAMESS atoms"); + } + + molec.addMonomer("GAMESS"); + + for (int i = 0; i < atoms.size(); i++) { + GamessAtom ga = atoms.get(i); + AtomInterface atom = molec.getNewAtomInstance(); + atom.setName(ga.getName()); + atom.setAtomicNumber(ga.getAtomicNumber()); + atom.setXYZ(ga.getX(), ga.getY(), ga.getZ()); + molec.addAtom(atom); + } + } + + /** + * + * @param inputfile + * @throws Exception + * @deprecated + * + */ + @Deprecated + public void parseGamessInput(String inputfile) throws + Exception { + + int status = LOOKING_FOR_SECTION; + + try { + // Create the tokenizer to read from a file + FileReader rd = new FileReader(inputfile); + StreamTokenizer st = new StreamTokenizer(rd); + + // Prepare the tokenizer for Java-style tokenizing rules + //st.parseNumbers(); + st.wordChars('1', '9'); + st.wordChars('0', '0'); + st.wordChars('_', '_'); + st.wordChars('$', '$'); + st.wordChars('.', '.'); + + st.eolIsSignificant(true); + + // If whitespace is not to be discarded, make this call + //st.ordinaryChars(0, ' '); + st.whitespaceChars('=', '='); + //st.ordinaryChar('$'); + + // These calls caused comments to be discarded + st.slashSlashComments(true); + st.slashStarComments(true); + + // Parse the file + int token = st.nextToken(); + while (token != StreamTokenizer.TT_EOF) { + switch (token) { + + case StreamTokenizer.TT_EOL: + + // End of line character found + if (status == READING_COMMENT) { + status = LOOKING_FOR_SECTION; + } + break; + + case StreamTokenizer.TT_NUMBER: + + // A number was found; the value is in nval + break; + case StreamTokenizer.TT_WORD: + + if (status == READING_COMMENT) { + break; + } else if (status == LOOKING_FOR_SECTION) { + String word = st.sval.toUpperCase(); + if (!validSections.contains(word)) { + break; + //throw new Exception( + // "Error parsing GAMESS input file: unknown section: " + + // st.sval); + } + st.pushBack(); + parseGamessInputSection(st); + } + + // A word was found; the value is in sval + break; + case '"': + + // A double-quoted string was found; sval contains the contents + break; + case '\'': + + // A single-quoted string was found; sval contains the contents + break; + + case StreamTokenizer.TT_EOF: + + // End of file has been reached + break; + default: + + // A regular character was found; the value is the token itself + char ch = (char) st.ttype; + if (commentSection.startsWith(String.valueOf(ch))) { + status = READING_COMMENT; + } + + break; + } + + token = st.nextToken(); + + } + rd.close(); + + logger.info("Number of atoms: " + atoms.size()); + } catch (Exception e) { + throw new Exception("Error parsing GAMESS input file: " + e.getMessage()); + } + } + + /** + * + * @param inputfile + * @param fileType + * @throws Exception + * @deprecated Use parseData methods instead + */ + @Deprecated + public void parseGamessInput(String inputfile, int fileType) throws Exception { + + String line; + BufferedReader in = null; + ignoreDataSection = false; + + if (fileType == 0) { // Read from file + try { + in = new BufferedReader(new FileReader(inputfile)); + + } catch (Exception ex) { + throw ex; + } + } else if (fileType == 1) { // Read from String + in = new BufferedReader(new StringReader(inputfile)); + } else { + throw new Exception("parseGamessInput: INTERNAL ERROR: Unknown file type"); + } + parseData(in); + } + + private void printSection(String section, Map controls) { + logger.info("Section " + section + " variables"); + Set set = controls.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + logger.info(me.getKey().toString() + "=" + + me.getValue().toString()); + } + + } + + private Object parseGamessInputSection(StreamTokenizer st) throws + Exception { + + st.nextToken(); + String section = st.sval.toUpperCase(); + + Map references = sectionVarsReference.get(section); + Map current = currentVars.get(section); + + if (references != null && current == null + && sectionVarsReference.containsKey(section)) { + st.pushBack(); + current = new HashMap(); + parseControlSection(st, references, current); + currentVars.put(section, current); + //HashMap controls = getControlSection(); + Map controls = new HashMap(current); + logger.info("Section " + section + " variables"); + Set set = controls.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + logger.info(me.getKey().toString() + "=" + + me.getValue().toString()); + } + + } else if (section.equalsIgnoreCase(dataSection)) { + this.parseDataSection(st); + int cardSequence = getCardSequence(); + if (atoms.size() > 0 && cardSequence == UNIQUE) { + applySymmetry(this.SymmetrySymbol, this.AxisOrder, atoms); + } + } else { + System.err.println("Warning: skipping section " + section); + st.pushBack(); + skipSection(st); + } + + return null; + } + + private Object parseControlSection(StreamTokenizer st, Map referenceVars, Map sectionVars) throws + Exception { + + int status = LOOKING_FOR_SWITCH; + String currentSwitch = ""; + String word = ""; + + int token = st.nextToken(); + while (token != StreamTokenizer.TT_EOF) { + token = st.nextToken(); + switch (token) { + case StreamTokenizer.TT_NUMBER: + + // A number was found; the value is in nval + word = String.valueOf(st.nval); + //double num = st.nval; + //break; + case StreamTokenizer.TT_WORD: + + if (token == StreamTokenizer.TT_WORD) { + word = st.sval.toUpperCase(); + } + if (word.equalsIgnoreCase(endSection)) { + if (status == LOOKING_FOR_SWITCH) { + return null; + } else { + System.err.println("unexpected end of a section"); + //throw new Exception( + // "Error parsing GAMESS input file: unexpected end of a section.."); + return null; + } + } + + if (status == LOOKING_FOR_SWITCH) { + if (!referenceVars.containsKey(word)) { + System.err.println("Unknown switch: " + st.sval); + //throw new Exception( + // "Error parsing GAMESS input file: unknown switch in section: " + + // st.sval); + } + currentSwitch = word; + status = LOOKING_FOR_SWITCH_VALUE; + break; + } + + // --- Looking for value + GamessSwitch refSwitch = (GamessSwitch) referenceVars.get( + currentSwitch); + if (refSwitch == null || (!refSwitch.isValidValue(word))) { + System.err.println("Check value " + word + " for switch " + + currentSwitch); + //throw new Exception( + // "Error parsing GAMESS input file: wrong value " + word + + // " for switch " + + // currentSwitch); + } + sectionVars.put(currentSwitch, word); + status = LOOKING_FOR_SWITCH; + break; + case '"': + + // A double-quoted string was found; sval contains the contents + break; + case '\'': + + // A single-quoted string was found; sval contains the contents + break; + case StreamTokenizer.TT_EOL: + + // End of line character found + break; + case StreamTokenizer.TT_EOF: + + // End of file has been reached + break; + default: + + // A regular character was found; the value is the token itself + break; + } + } + + return null; + } + + private Object parseDataSection(BufferedReader in) throws Exception { + String line; + + try { + + // --- reading comment + if ((line = in.readLine()) == null) { + throw new Exception("Unexpected end-of-file while reading a comment in $DATA section"); + } + + Title = line.trim(); + + // --- -2- GROUP, NAXIS + if ((line = in.readLine()) == null) { + throw new Exception("Unexpected end-of-file while reading -2- GROUP, NAXIS card in $DATA section"); + } else if (line.trim().length() == 0) { + throw new Exception("Expecting symmetry symbol in $DATA section"); + } + + StringTokenizer st = new StringTokenizer(line, " \t="); + + if (st.countTokens() < 1) { + throw new Exception("Expecting symmetry symbol in $DATA section"); + } + + this.SymmetrySymbol = st.nextToken(); + if (!validSymmetrySymbols.contains(SymmetrySymbol.toUpperCase())) { + throw new Exception("Unknown symmetry symbol: " + SymmetrySymbol + + " Valid symbols: C1, Cs, Ci, Cn, S2n, Cnh, Cnv, Dn, Dnh, Dnd, T, Th, Td, O, Oh"); + } + + if (st.hasMoreTokens()) { + String token = st.nextToken(); + try { + AxisOrder = Integer.parseInt(token); + } catch (Exception ex) { + throw new Exception("Wrong number for symmetry axis order: " + token); + } + } + + // --- Skip or not next line + if (!SymmetrySymbol.toUpperCase().equals("C1")) { + if ((line = in.readLine()) == null) { + throw new Exception("Unexpected end-of-file while reading blank card after symmetry options in $DATA section"); + } + } + + // --- Start to read molecular geometry + int cardSequence = getCardSequence(); + switch (cardSequence) { + case UNIQUE: + readUniqueCardSequence(in); + if (atoms.size() > 0 && cardSequence == UNIQUE) { + applySymmetry(this.SymmetrySymbol, this.AxisOrder, atoms); + for (int i = 0; i < atoms.size(); i++) { + GamessAtom atom = atoms.get(i); + logger.info((i + 1) + " " + atom.getName() + " " + + atom.getNuclearCharge() + " " + + atom.getX() + " " + atom.getY() + " " + + atom.getZ()); + } + } + return null; + + case ZMT: + readZMatrixCardSequence(in); + return null; + + case CART: + readUniqueCardSequence(in); + return null; + } + + } catch (Exception ex) { + throw ex; + } + return null; + } + + /** + * Parse molecular geometry + */ + private Object parseDataSection(StreamTokenizer st) throws + Exception { + + boolean readingComment = true; + boolean readingSymmetry = false; + boolean readingMasterframe = false; + boolean readingAtoms = false; + String comment = ""; + int status = LOOKING_FOR_SWITCH; + String word = ""; + + //static final int UNIQUE = 0; + //static final int HINT = 0; + //static final int CART = 1; + //static final int ZMT = 2; + //static final int ZMTMPC = 3; + int cardSequence = getCardSequence(); + + int token = st.nextToken(); + while (token != StreamTokenizer.TT_EOF) { + token = st.nextToken(); + switch (token) { + case StreamTokenizer.TT_NUMBER: + + if (readingComment) { + if (comment.length() > 0) { + comment += " "; + } + comment += st.nval; + break; + } + + // --- Reading GROUP is the Schoenflies symbol of the symmetry group, + // you may choose from + // C1, Cs, Ci, Cn, S2n, Cnh, Cnv, Dn, Dnh, Dnd, + // T, Th, Td, O, Oh. + if (readingSymmetry) { + this.AxisOrder = (int) st.nval; + break; + } + + if (readingMasterframe) { + break; + } + + // A number was found; the value is in nval + word = String.valueOf(st.nval); + //double num = st.nval; + //break; + case StreamTokenizer.TT_WORD: + + if (readingComment) { + if (comment.length() > 0) { + comment += " "; + } + comment += st.sval; + break; + } + + if (readingSymmetry) { + this.SymmetrySymbol = st.sval; + if (!validSymmetrySymbols.contains(SymmetrySymbol.toUpperCase())) { + throw new Exception("Unknown symmetry symbol: " + + SymmetrySymbol + + " Valid symbols: C1, Cs, Ci, Cn, S2n, Cnh, Cnv, Dn, Dnh, Dnd, T, Th, Td, O, Oh"); + } + + if (SymmetrySymbol.toUpperCase().equals("C1")) { + readingSymmetry = false; + readingMasterframe = false; + readingAtoms = true; + break; + } + + break; + } + + if (readingMasterframe) { + break; + } + + if (readingAtoms) { + } + + if (token == StreamTokenizer.TT_WORD) { + word = st.sval.toUpperCase(); + } + if (word.equalsIgnoreCase(endSection)) { + if (status == LOOKING_FOR_SWITCH) { + return null; + } else { + throw new Exception( + "Error parsing GAMESS input file: unexpected end of a $CONTROL section.."); + } + } + + break; + case '"': + + // A double-quoted string was found; sval contains the contents + break; + case '\'': + + // A single-quoted string was found; sval contains the contents + break; + case StreamTokenizer.TT_EOL: + + if (readingComment) { + readingComment = false; + readingSymmetry = true; + Title = comment; + break; + } + + if (readingSymmetry) { + readingSymmetry = false; + readingMasterframe = true; + break; + } + + if (readingMasterframe) { + readingMasterframe = false; + switch (cardSequence) { + case UNIQUE: + readUniqueCardSequence(st); + return null; + case ZMT: + readZMatrixCardSequence(st); + return null; + } + + break; + } + + if (readingAtoms) { + switch (cardSequence) { + case UNIQUE: + readUniqueCardSequence(st); + return null; + case ZMT: + readZMatrixCardSequence(st); + return null; + + } + break; + } + + // End of line character found + break; + case StreamTokenizer.TT_EOF: + + // End of file has been reached + break; + default: + + // A regular character was found; the value is the token itself + break; + } + } + + return null; + } + + private Object readUniqueCardSequence(BufferedReader in) throws Exception { + + GamessAtom atom = null; + + double factor = 1; + int cardSequence = UNIQUE; + if (currentVars.containsKey(controlSection)) { + Map csection = currentVars.get(controlSection); + + if (csection.containsKey("UNITS")) { + String value = (String) csection.get("UNITS"); + value = value.toUpperCase(); + if (value.equals("ANGS")) { + factor = 1; + } else if (value.equals("BOHR")) { + factor = ONE_BOHR; + } + } + + if (csection.containsKey("COORD")) { + String value = (String) csection.get("COORD"); + if (value.toUpperCase().equals("CART")) { + cardSequence = CART; + } + } + } + + String line, token; + StringTokenizer st; + + boolean readBasis = !currentVars.containsKey( basisSection); + if (cardSequence == CART) { + readBasis = false; + } + + boolean readingAtom = true; + + try { + while ((line = in.readLine()) != null) { + + if (line.trim().toUpperCase().startsWith(endSection)) { + return null; + } + + if (readingAtom) { + st = new StringTokenizer(line, " \t"); + + if (!st.hasMoreTokens()) { + throw new Exception("Expecting atom name..."); + } + + atom = new GamessAtom(); + atom.setName(st.nextToken()); + + // --- Reading atomic charge + if (!st.hasMoreTokens()) { + throw new Exception("Expecting atomic charge..."); + } + + token = st.nextToken(); + try { + float charge = Float.parseFloat(token); + atom.setNuclearCharge(charge); + } catch (Exception ex) { + throw new Exception("Wrong value for atomic charge " + token + + " : " + ex.getMessage()); + } + + // --- Reading X + if (!st.hasMoreTokens()) { + atom.setXYZ(0, 0, 0); + atoms.add(atom); + readingAtom = !readBasis; + continue; + } + + token = st.nextToken(); + try { + float coord = Float.parseFloat(token); + atom.setX(coord * factor); + } catch (Exception ex) { + throw new Exception("Wrong value for atom X value " + token + + " : " + ex.getMessage()); + } + + // --- Reading Y + if (!st.hasMoreTokens()) { + atom.setY(0); + atom.setZ(0); + atoms.add(atom); + readingAtom = !readBasis; + continue; + } + + token = st.nextToken(); + try { + float coord = Float.parseFloat(token); + atom.setY(coord * factor); + } catch (Exception ex) { + throw new Exception("Wrong value for atom Y value " + token + + " : " + ex.getMessage()); + } + + // --- Reading Z + if (!st.hasMoreTokens()) { + atom.setZ(0); + atoms.add(atom); + readingAtom = !readBasis; + continue; + } + + token = st.nextToken(); + try { + float coord = Float.parseFloat(token); + atom.setZ(coord * factor); + } catch (Exception ex) { + throw new Exception("Wrong value for atom Y value " + token + + " : " + ex.getMessage()); + } + atoms.add(atom); + readingAtom = !readBasis; + continue; + } else if (line.trim().length() == 0) { // Found blank line after basis + readingAtom = true; + } + } + } catch (Exception ex) { + throw ex; + } + + return null; + } + + private void readFMOXYZSection(BufferedReader in) throws Exception { + + GamessAtom atom = null; + + double factor = 1; + if (currentVars.containsKey(controlSection)) { + Map csection = currentVars.get(controlSection); + + if (csection.containsKey("UNITS")) { + String value = (String) csection.get("UNITS"); + value = value.toUpperCase(); + if (value.equals("ANGS")) { + factor = 1; + } else if (value.equals("BOHR")) { + factor = ONE_BOHR; + } + } + } + + String line, token; + StringTokenizer st; + + boolean readingAtom = true; + + try { + while ((line = in.readLine()) != null) { + + if (line.trim().toUpperCase().startsWith(endSection)) { + return; + } + + if (readingAtom) { + st = new StringTokenizer(line, " \t"); + + if (!st.hasMoreTokens()) { + throw new Exception("Expecting dummy atom name in FMOXYZ section..."); + } + + atom = new GamessAtom(); + st.nextToken(); // Skip it + + // --- Reading atomic charge + if (!st.hasMoreTokens()) { + throw new Exception("Expecting atomic charge in FMOXYZ section..."); + } + + token = st.nextToken(); + try { + float charge = Float.parseFloat(token); + atom.setNuclearCharge(charge); + atom.setName(ChemicalElements.getElementSymbol((int) charge)); + } catch (Exception ex) { + // i.e. we got element symbol + atom.setName(token); + atom.setNuclearCharge(ChemicalElements.getAtomicNumber(token)); + } + + // --- Reading X + if (!st.hasMoreTokens()) { + atom.setXYZ(0, 0, 0); + atoms.add(atom); + continue; + } + + token = st.nextToken(); + try { + float coord = Float.parseFloat(token); + atom.setX(coord * factor); + } catch (Exception ex) { + throw new Exception("Wrong value for atom X value in FMOXYZ Section" + token + " : " + ex.getMessage()); + } + + // --- Reading Y + if (!st.hasMoreTokens()) { + atom.setY(0); + atom.setZ(0); + atoms.add(atom); + continue; + } + + token = st.nextToken(); + try { + float coord = Float.parseFloat(token); + atom.setY(coord * factor); + } catch (Exception ex) { + throw new Exception("Wrong value for atom Y value in FMOXYZ Section " + token + " : " + ex.getMessage()); + } + + // --- Reading Z + if (!st.hasMoreTokens()) { + atom.setZ(0); + atoms.add(atom); + continue; + } + + token = st.nextToken(); + try { + float coord = Float.parseFloat(token); + atom.setZ(coord * factor); + } catch (Exception ex) { + throw new Exception("Wrong value for atom Y value in FMOXYZ Section " + token + " : " + ex.getMessage()); + } + atoms.add(atom); + continue; + } + + } + } catch (Exception ex) { + throw ex; + } + } + + private Object readUniqueCardSequence(StreamTokenizer st) throws + Exception { + boolean readingNAME = true; + boolean readingZNUC = false; + boolean readingX = false, readingY = false, readingZ = false; + boolean waitingForEOL = false; + + boolean skippingBasis = false; + boolean readingBasisData = false; + + boolean readBasis = !currentVars.containsKey( basisSection); + + GamessAtom atom = null; + + double factor = 1; + if (currentVars.containsKey(controlSection)) { + Map csection = currentVars.get(controlSection); + if (csection.containsKey("UNITS")) { + String value = (String) csection.get("UNITS"); + value = value.toUpperCase(); + if (value.equals("ANGS")) { + factor = 1; + } else if (value.equals("BOHR")) { + factor = ONE_BOHR; + } + } + } + + String word = ""; + + int token = StreamTokenizer.TT_EOF + 1; + + while (token != StreamTokenizer.TT_EOF) { + token = st.nextToken(); + switch (token) { + case StreamTokenizer.TT_NUMBER: + case StreamTokenizer.TT_WORD: + + if (waitingForEOL) { + break; + } + + if (st.sval != null && st.sval.equalsIgnoreCase(endSection)) { + return null; + } + + if (readBasis && skippingBasis) { + readingBasisData = true; + break; + } + + // --- Reading atom name + if (readingNAME) { + atom = new GamessAtom(); + if (token == StreamTokenizer.TT_WORD) { + atom.setName(st.sval); + } else if (token == StreamTokenizer.TT_NUMBER) { + atom.setName(String.valueOf(st.nval)); + } + readingNAME = false; + readingZNUC = true; + break; + } + + // --- Reading nuclear charge + if (readingZNUC) { + atom.setNuclearCharge(st.nval); + readingZNUC = false; + readingX = true; + break; + } + + // --- Reading X + if (readingX) { + atom.setX(st.nval * factor); + readingX = false; + readingY = true; + break; + } + + // --- Reading Y + if (readingY) { + atom.setY(st.nval * factor); + readingY = false; + readingZ = true; + break; + } + + // --- Reading Z + if (readingZ) { + atom.setZ(st.nval * factor); + readingZ = false; + waitingForEOL = true; + atoms.add(atom); + break; + } + + // A number was found; the value is in nval + word = String.valueOf(st.nval); + + //double num = st.nval; + //break; + if (token == StreamTokenizer.TT_WORD) { + word = st.sval.toUpperCase(); + } + if (word.equalsIgnoreCase(endSection)) { + return null; + } + + break; + case '"': + + // A double-quoted string was found; sval contains the contents + //String dquoteVal = st.sval; + break; + case '\'': + + // A single-quoted string was found; sval contains the contents + //String squoteVal = st.sval; + break; + case StreamTokenizer.TT_EOL: + + if (readBasis && skippingBasis) { + if (readingBasisData) { + readingBasisData = false; + break; + } else { // Found empty line + skippingBasis = false; + waitingForEOL = false; + readingNAME = true; // Start to read the next atom + } + break; + } + + if (readingX) { + atom.setXYZ(0, 0, 0); + atoms.add(atom); + readingX = false; + if (readBasis) { + skippingBasis = true; + } else { + waitingForEOL = false; + readingNAME = true; // Start to read the next atom + break; + } + } + + if (readingY) { + atom.setY(0); + atom.setZ(0); + atoms.add(atom); + readingY = false; + if (readBasis) { + skippingBasis = true; + } else { + waitingForEOL = false; + readingNAME = true; // Start to read the next atom + break; + } + + } + + if (readingZ) { + atom.setZ(0); + atoms.add(atom); + readingZ = false; + if (readBasis) { + skippingBasis = true; + } else { + waitingForEOL = false; + readingNAME = true; // Start to read the next atom + break; + } + + } + + waitingForEOL = false; + if (readBasis) { + skippingBasis = true; + } else { + readingNAME = true; // Start to read the next atom + } + + // End of line character found + break; + case StreamTokenizer.TT_EOF: + + // End of file has been reached + break; + default: + + // A regular character was found; the value is the token itself + //char ch = (char) st.ttype; + break; + } + } + + return null; + } + + private Object readZMatrixCardSequence(BufferedReader in) throws Exception { + + GamessAtom atom = null; + + double factor = 1; + if (currentVars.containsKey(controlSection)) { + Map csection = currentVars.get(controlSection); + if (csection.containsKey("UNITS")) { + String value = (String) csection.get("UNITS"); + value = value.toUpperCase(); + if (value.equals("ANGS")) { + factor = 1; + } else if (value.equals("BOHR")) { + factor = ONE_BOHR; + } + } + } + + String line, token; + StringTokenizer st; + boolean yesSymbolicStrings = false; + boolean endSectionFound = false; + Map atomNames = new HashMap(100); + Map symbolicStrings = new HashMap(300); + + try { + // --- reading atoms + while ((line = in.readLine()) != null) { + line = line.trim(); //.toUpperCase(); + st = new StringTokenizer(line, " \t"); + + // --- Atom name + if (!st.hasMoreTokens()) { // Blank line - end of input + break; //throw new Exception("Expecting atom name"); + } + + token = st.nextToken(); + + if (token.equalsIgnoreCase(endSection)) { + endSectionFound = true; + break; + } + + atom = new GamessAtom(); + atom.setName(token); + atom.setAtomicNumber(getAtomicNumber(atom.getName())); + + // --- check atom name for uniqueness + if (atomNames.containsKey(atom.getName())) { + // --- it's not unique + atomNames.put(atom.getName(), new Integer(-1)); + } else { + atomNames.put(atom.getName(), new Integer(atoms.size())); + } + + if (atoms.size() == 0) { + atoms.add(atom); + continue; + } + + // Reading i1 + if (!st.hasMoreTokens()) { + throw new Exception("Expecting i1"); + } + token = st.nextToken(); + + // --- if it's atom's name + boolean isNumber = true; + int number = 0; + + try { + number = Integer.parseInt(token); + } catch (Exception ex) { + isNumber = false; + } + + if (isNumber) { // --- If it's a number + if (number < 1 || number > atoms.size()) { + throw new Exception("Wrong i1 value " + number + " for " + (atoms.size() + 1) + " atom : it should be between 1 and " + + atoms.size()); + } + atom.set_i1(number - 1); + } else // --- If it's an atom + if (atomNames.containsKey(token)) { + Integer i = atomNames.get(token); + atom.set_i1(i); + } else { + throw new Exception("Wrong i1 value " + token + + " for " + (atoms.size() + 1) + + " atom : no atom with such name was previously specified"); + } + + // --- Reading Bond Length + if (!st.hasMoreTokens()) { + throw new Exception("Expecting bond length value"); + } + token = st.nextToken(); + + isNumber = true; + float value = 0; + + try { + value = Float.parseFloat(token); + } catch (Exception ex) { + isNumber = false; + } + + // --- if it's a parameter + if (!isNumber) { + String symbolic = token; + if (token.startsWith("-")) { + symbolic = token.substring(1); + } + if (!symbolicStrings.containsKey(symbolic)) { + symbolicStrings.put(symbolic, null); + } + + atom.setBondLength(token); + yesSymbolicStrings = true; + } else { + atom.setBondLength(value); + } + + if (atoms.size() == 1) { + atoms.add(atom); + continue; + } + + // --- Reading i2 + if (!st.hasMoreTokens()) { + throw new Exception("Expecting i2"); + } + token = st.nextToken(); + + // --- if it's atom's name + isNumber = true; + + try { + number = Integer.parseInt(token); + } catch (Exception ex) { + isNumber = false; + } + + if (isNumber) { // --- If it's a number + if (number < 1 || number > atoms.size() + || number == atom.get_i1() + 1) { + throw new Exception("Wrong i2 value " + number + " for " + + (atoms.size() + 1) + + " atom : it should be between 1 and " + + atoms.size() + " and not " + + (atom.get_i1() + 1)); + } + atom.set_i2(number - 1); + } else // --- If it's an atom + if (atomNames.containsKey(token)) { + Integer i = atomNames.get(token); + atom.set_i2(i); + } else { + throw new Exception("Wrong i2 value " + token + + " for " + (atoms.size() + 1) + + " atom : no atom with such name was previously specified"); + } + + // --- Reading ALPHA + if (!st.hasMoreTokens()) { + throw new Exception("Expecting alpha value"); + } + token = st.nextToken(); + + isNumber = true; + + try { + value = Float.parseFloat(token); + } catch (Exception ex) { + isNumber = false; + } + + // --- if it's a parameter + if (!isNumber) { + String symbolic = token; + if (token.startsWith("-")) { + symbolic = token.substring(1); + } + if (!symbolicStrings.containsKey(symbolic)) { + symbolicStrings.put(symbolic, null); + } + + atom.setAlpha(token); + yesSymbolicStrings = true; + } else { + atom.setAlpha(value); + } + + if (atoms.size() == 2) { + atoms.add(atom); + continue; + } + + // --- Reading i3 + if (!st.hasMoreTokens()) { + throw new Exception("Expecting i3"); + } + token = st.nextToken(); + + // --- if it's atom's name + isNumber = true; + + try { + number = Integer.parseInt(token); + } catch (Exception ex) { + isNumber = false; + } + + // --- if it's atom's name + if (!isNumber) { + if (atomNames.containsKey(token)) { + Integer i = atomNames.get(token); + atom.set_i3(i); + } else { + throw new Exception("Wrong i3 value " + token + + " for " + (atoms.size() + 1) + + " atom : no atom with such name was previously specified"); + } + } // --- If it's a number + else { + if (number < 1 || number > atoms.size() + || number == atom.get_i1() + 1 + || number == atom.get_i2() + 1) { + throw new Exception("Wrong i3 value " + number + + " for " + (atoms.size() + 1) + + " atom : it should be between 1 and " + + atoms.size() + " and not " + + (atom.get_i1() + 1) + " or " + + (atom.get_i2() + 1)); + } + atom.set_i3(number - 1); + } + + // --- Reading BETA + if (!st.hasMoreTokens()) { + throw new Exception("Expecting beta value"); + } + token = st.nextToken(); + + isNumber = true; + + try { + value = Float.parseFloat(token); + } catch (Exception ex) { + isNumber = false; + } + + // --- if it's a parameter + if (!isNumber) { + String symbolic = token; + if (token.startsWith("-")) { + symbolic = token.substring(1); + } + if (!symbolicStrings.containsKey(symbolic)) { + symbolicStrings.put(symbolic, null); + } + + atom.setBeta(token); + yesSymbolicStrings = true; + } else { + atom.setBeta(value); + } + + // --- REading i4 (not implemented yet + if (st.hasMoreTokens()) { + token = st.nextToken(); + if (token.startsWith("+")) { + token = token.substring(1); + } + int i4 = 0; + try { + i4 = Integer.parseInt(token); + if (Math.abs(i4) > 1) { + i4 = i4 > 0 ? 1 : -1; + } + } catch (Exception ex) { + throw new Exception("Cannot parse i4 parameter " + token + " : " + ex.getMessage()); + } + + atom.alternateZmatrixFormat = i4; + + //if (i4 != 0) { + // throw new Exception("Rewading i4 is not implemented yet"); + //} + } + + atoms.add(atom); + + } // --- End of while/ reading atoms + + // --- Resolve Z-Matrix + if (symbolicStrings.size() > 0) { + logger.info("Expecting " + symbolicStrings.size() + + " unique symbolic strings"); + if (endSectionFound) { + throw new Exception( + "Unexpected end of $DATA section. Excepting symbolic strings"); + } + } + + // --- Start to read symbolic strings + while ((line = in.readLine()) != null) { + //line = line.trim().toUpperCase(); + + st = new StringTokenizer(line, "= \t"); + + if (st.countTokens() < 1) { + continue; + } + + String currentString = st.nextToken(); + + if (currentString.equalsIgnoreCase(endSection)) { + break; + } + + if (st.countTokens() < 1) { + throw new Exception( + "Expecting at least two values for symbolic strings"); + } + + // --- Read symbol + if (!symbolicStrings.containsKey(currentString)) { + System.err.println( + "Warning: atom string parameters do not have string " + + currentString); + continue; + } + + // --- Read value + token = st.nextToken(); + try { + Float f = new Float(token); + symbolicStrings.put(currentString, f); + } catch (Exception ex) { + throw new Exception("Wrong value for symbolic string " + token); + } + } + } catch (Exception ex) { + throw ex; + } + + if (symbolicStrings.size() > 0) { + try { + resolveSymbolicStrings(symbolicStrings, atoms); + } catch (Exception ex) { + throw ex; + } + } + + // --- Convert to cartesian coordinates + fromZMatrixToCartesians(atoms); + + return null; + } + + private Object readZMatrixCardSequence(StreamTokenizer st) throws + Exception { + int natom = 0; + boolean yesSymbolicStrings = false; + boolean readingNAME = true; + boolean reading_i1 = false, reading_i2 = false, reading_i3 = false, + reading_i4 = false; + boolean readingBLENGTH = false, readingALPHA = false, readingBETA = false; + boolean waitingForEOL = false; + boolean endOfCoordinates = false; + boolean endOfSection = false; + GamessAtom atom = null; + + Map atomNames = new HashMap(100); + Map symbolicStrings = new HashMap(300); + + double factor = 1; + Map controlGroup = currentVars.get(controlSection); + if (controlGroup != null && controlGroup.containsKey("UNITS")) { + String value = (String) controlGroup.get("UNITS"); + value = value.toUpperCase(); + if (value.equals("ANGS")) { + factor = 1; + } else if (value.equals("BOHR")) { + factor = ONE_BOHR; + } + } + + String word = ""; + + int token = StreamTokenizer.TT_EOF + 1; + + while (token != StreamTokenizer.TT_EOF) { + token = st.nextToken(); + switch (token) { + case StreamTokenizer.TT_NUMBER: + case StreamTokenizer.TT_WORD: + + if (token == StreamTokenizer.TT_WORD + && st.sval.equalsIgnoreCase(endSection)) { + endOfCoordinates = true; + endOfSection = true; + break; + } + + if (waitingForEOL) { + break; + } + + if (st.sval != null && st.sval.equalsIgnoreCase(endSection)) { + return null; + } + + // --- Reading atom name + if (readingNAME) { + atom = new GamessAtom(); + if (token == StreamTokenizer.TT_WORD) { + atom.setName(st.sval); + } else if (token == StreamTokenizer.TT_NUMBER) { + atom.setName(String.valueOf(st.nval)); + } + + atom.setAtomicNumber(getAtomicNumber(atom.getName())); + + // --- check atom name for uniqueness + if (atomNames.containsKey(atom.getName())) { + // --- it's not unique + atomNames.put(atom.getName(), new Integer(-1)); + } else { + atomNames.put(atom.getName(), new Integer(natom)); + } + + if (atoms.size() == 0) { + atoms.add(atom); + waitingForEOL = true; + break; + } + + readingNAME = false; + + reading_i1 = true; + break; + } + + // --- Reading i1 + if (reading_i1) { + // --- if it's atom's name + if (token == StreamTokenizer.TT_WORD) { + if (atomNames.containsKey(st.sval)) { + Integer i = atomNames.get(st.sval); + atom.set_i1(i); + } else { + throw new Exception("Wrong i1 value " + st.sval + + " for " + (atoms.size() + 1) + + " atom : no atom with such name was previously specified"); + } + } // --- If it's a number + else { + int nat = (int) st.nval; + if (nat < 1 || nat > atoms.size()) { + throw new Exception("Wrong i1 value " + nat + + " for " + (atoms.size() + 1) + + " atom : it should be between 1 and " + + atoms.size()); + } + atom.set_i1(nat - 1); + } + + reading_i1 = false; + readingBLENGTH = true; + break; + } + + // --- Reading Bond Length + if (readingBLENGTH) { + // --- if it's a parameter + if (token == StreamTokenizer.TT_WORD) { + String symbolic = st.sval; + if (st.sval.startsWith("-")) { + symbolic = st.sval.substring(1); + } + if (!symbolicStrings.containsKey(symbolic)) { + symbolicStrings.put(symbolic, null); + } + + atom.setBondLength(st.sval); + yesSymbolicStrings = true; + } else { + atom.setBondLength((float) st.nval); + } + + readingBLENGTH = false; + + if (atoms.size() == 1) { + atoms.add(atom); + readingNAME = true; + waitingForEOL = true; + break; + } + + reading_i2 = true; + break; + } + + // --- Reading i2 + if (reading_i2) { + // --- if it's atom's name + if (token == StreamTokenizer.TT_WORD) { + if (atomNames.containsKey(st.sval)) { + Integer i = atomNames.get(st.sval); + atom.set_i2(i); + } else { + throw new Exception("Wrong i2 value " + st.sval + + " for " + (atoms.size() + 1) + + " atom : no atom with such name was previously specified"); + } + } // --- If it's a number + else { + int nat = (int) st.nval; + if (nat < 1 || nat > atoms.size() + || nat == atom.get_i1() + 1) { + throw new Exception("Wrong i2 value " + nat + + " for " + (atoms.size() + 1) + + " atom : it should be between 1 and " + + atoms.size() + " and not " + + (atom.get_i1() + 1)); + } + atom.set_i2(nat - 1); + } + + reading_i2 = false; + readingALPHA = true; + break; + } + + // --- Reading ALPHA + if (readingALPHA) { + // --- if it's a parameter + if (token == StreamTokenizer.TT_WORD) { + String symbolic = st.sval; + if (st.sval.startsWith("-")) { + symbolic = st.sval.substring(1); + } + if (!symbolicStrings.containsKey(symbolic)) { + symbolicStrings.put(symbolic, null); + } + + atom.setAlpha(st.sval); + yesSymbolicStrings = true; + } else { + atom.setAlpha((float) st.nval); + } + + readingALPHA = false; + + if (atoms.size() == 2) { + atoms.add(atom); + readingNAME = true; + waitingForEOL = true; + break; + } + + reading_i3 = true; + break; + + } + + // --- Reading i3 + if (reading_i3) { + // --- if it's atom's name + if (token == StreamTokenizer.TT_WORD) { + if (atomNames.containsKey(st.sval)) { + Integer i = atomNames.get(st.sval); + atom.set_i3(i); + } else { + throw new Exception("Wrong i3 value " + st.sval + + " for " + (atoms.size() + 1) + + " atom : no atom with such name was previously specified"); + } + } // --- If it's a number + else { + int nat = (int) st.nval; + if (nat < 1 || nat > atoms.size() + || nat == atom.get_i1() + 1 + || nat == atom.get_i2() + 1) { + throw new Exception("Wrong i3 value " + nat + + " for " + (atoms.size() + 1) + + " atom : it should be between 1 and " + + atoms.size() + " and not " + + (atom.get_i1() + 1) + " or " + + (atom.get_i2() + 1)); + } + atom.set_i3(nat - 1); + } + + reading_i3 = false; + readingBETA = true; + break; + } + + // --- Reading BETA + if (readingBETA) { + // --- if it's a parameter + if (token == StreamTokenizer.TT_WORD) { + String symbolic = st.sval; + if (st.sval.startsWith("-")) { + symbolic = st.sval.substring(1); + } + if (!symbolicStrings.containsKey(symbolic)) { + symbolicStrings.put(symbolic, null); + } + + atom.setBeta(st.sval); + yesSymbolicStrings = true; + } else { + atom.setBeta((float) st.nval); + } + + readingBETA = false; + reading_i4 = true; + break; + + } + + // --- REading i4 (not implemented yet + if (reading_i4) { + throw new Exception("Rewading i4 is not implemented yet"); + } + + // A number was found; the value is in nval + word = String.valueOf(st.nval); + + //double num = st.nval; + //break; + if (token == StreamTokenizer.TT_WORD) { + word = st.sval.toUpperCase(); + } + if (word.equalsIgnoreCase(endSection)) { + return null; + } + + break; + case '"': + + // A double-quoted string was found; sval contains the contents + //String dquoteVal = st.sval; + break; + case '\'': + + // A single-quoted string was found; sval contains the contents + //String squoteVal = st.sval; + break; + case StreamTokenizer.TT_EOL: + + if (reading_i4) { + atoms.add(atom); + reading_i4 = false; + waitingForEOL = false; + readingNAME = true; + break; + } + + if (readingNAME && waitingForEOL) { + waitingForEOL = false; + break; + } else if (readingNAME) { // End of Z-matrix input + endOfCoordinates = true; + break; + } + + waitingForEOL = false; + readingNAME = true; // Start to read the next atom + + // End of line character found + break; + case StreamTokenizer.TT_EOF: + + // End of file has been reached + break; + default: + + // A regular character was found; the value is the token itself + //char ch = (char) st.ttype; + break; + } + + if (endOfCoordinates) { + break; + } + } + + // --- Resolve Z-Matrix + if (symbolicStrings.size() > 0) { + logger.info("Expecting " + symbolicStrings.size() + + " unique symbolic strings"); + + if (endOfSection) { + throw new Exception( + "Unexpected end of $data section. Expecting for string values"); + } + + // --- Start to read symbolic strings + token = StreamTokenizer.TT_EOF + 1; + waitingForEOL = false; + boolean readingSTRING = true, readingVALUE = false; + boolean endOfInput = false; + String currentString = ""; + + while (token != StreamTokenizer.TT_EOF) { + token = st.nextToken(); + + switch (token) { + // --- Reading value + case StreamTokenizer.TT_NUMBER: + + if (waitingForEOL) { + System.err.println("Warning: expecting EOL, got " + + st.nval); + break; + } + + if (!symbolicStrings.containsKey(currentString)) { + System.err.println( + "Warning: atom string parameters do not have string " + + st.sval); + } else if (readingVALUE) { + symbolicStrings.put(currentString, new Float(st.nval)); + } + + readingVALUE = false; + readingSTRING = true; + waitingForEOL = true; + + break; + + // -- reading value + case StreamTokenizer.TT_WORD: + + if (st.sval.equalsIgnoreCase(endSection)) { + endOfInput = true; + endOfSection = true; + break; + } + + if (waitingForEOL) { + System.err.println("Warning: expecting EOL, got " + + st.sval); + break; + } + + if (readingSTRING) { + currentString = st.sval; + if (!symbolicStrings.containsKey(currentString)) { + System.err.println( + "Warning: atom string parameters do not have string " + + st.sval); + } + readingSTRING = false; + readingVALUE = true; + } + + break; + + case StreamTokenizer.TT_EOL: + + if (waitingForEOL) { + readingVALUE = false; + readingSTRING = true; + waitingForEOL = false; + break; + } + + if (readingSTRING) { // Empty line + break; + } + + if (readingVALUE) { + throw new Exception( + "Unexpected end of line while expecting for a value"); + } + + break; + case StreamTokenizer.TT_EOF: + + break; + default: + + // A regular character was found; the value is the token itself + //char ch = (char) st.ttype; + break; + + } + + if (endOfInput) { + break; + } + } + } + + if (symbolicStrings.size() > 0) { + try { + resolveSymbolicStrings(symbolicStrings, atoms); + } catch (Exception ex) { + throw ex; + } + } + + // --- Convert to cartesian coordinates + fromZMatrixToCartesians(atoms); + + return null; + } + + private void resolveSymbolicStrings(Map symbolicStrings, List atoms) throws Exception { + + // --- Error check + boolean error = false; + String Errors = ""; + Set set = symbolicStrings.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String string = me.getKey().toString(); + Object value = me.getValue(); + + if (value == null) { + error = true; + Errors += "No value for string " + string + "\n"; + } else { + logger.info(me.getKey().toString() + "=" + + me.getValue().toString()); + } + } + + if (error) { + throw new Exception(Errors); + } + + // --- resolve strings + for (int i = 0; i < atoms.size(); i++) { + GamessAtom atom = atoms.get(i); + + String string = atom.getBondLengthPar(); + if (string != null) { + boolean negative = string.startsWith("-"); + if (negative) { + string = string.substring(1); + } + Float f = symbolicStrings.get(string); + if (negative) { + f = -f; + } + atom.setBondLength(f); + } + + string = atom.getAlphaPar(); + if (string != null) { + boolean negative = string.startsWith("-"); + if (negative) { + string = string.substring(1); + } + Float f = symbolicStrings.get(string); + if (negative) { + f = -f; + } + atom.setAlpha(f); + } + + string = atom.getBetaPar(); + if (string != null) { + boolean negative = string.startsWith("-"); + if (negative) { + string = string.substring(1); + } + Float f = symbolicStrings.get(string); + if (negative) { + f = -f; + } + atom.setBeta(f); + } + } + + } + + private Object skipSection(StreamTokenizer st) throws + Exception { + String word = ""; + + int token = st.nextToken(); + + while (token != StreamTokenizer.TT_EOF) { + token = st.nextToken(); + switch (token) { + case StreamTokenizer.TT_NUMBER: + + // A number was found; the value is in nval + word = String.valueOf(st.nval); + //double num = st.nval; + //break; + case StreamTokenizer.TT_WORD: + + if (token == StreamTokenizer.TT_WORD) { + word = st.sval.toUpperCase(); + } + if (word.equalsIgnoreCase(endSection)) { + return null; + } + + break; + case '"': + + // A double-quoted string was found; sval contains the contents + //String dquoteVal = st.sval; + break; + case '\'': + + // A single-quoted string was found; sval contains the contents + //String squoteVal = st.sval; + break; + case StreamTokenizer.TT_EOL: + + // End of line character found + break; + case StreamTokenizer.TT_EOF: + + // End of file has been reached + break; + default: + + // A regular character was found; the value is the token itself + //char ch = (char) st.ttype; + break; + } + } + + return null; + } + + public Map getControlSection() { + if (currentVars.containsKey(controlSection)) { + return new HashMap(currentVars.get(controlSection)); + } + return null; //new HashMap(); + } + + public static void main(String[] args) { + Gamess gamess = new Gamess(); + MoleculeInterface mol = new Molecule(); + try { + gamess.parseGamessInput(args[0], 0); + gamess.getMolecularInterface(mol); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + ex.printStackTrace(); + } + + logger.info("Number of atoms " + mol.getNumberOfAtoms()); + for (int i = 0; i < mol.getNumberOfAtoms(); i++) { + AtomInterface atom = mol.getAtomInterface(i); + logger.info((i + 1) + " " + atom.getName() + " " + + atom.getX() + + " " + atom.getY() + " " + atom.getZ()); + } + Map controls = gamess.getControlSection(); + Set set = controls.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + logger.info(me.getKey().toString() + "=" + + me.getValue().toString()); + } + + } + + public void applySymmetry(String symbol, int axisOrder, List points) throws Exception { + + if (symbol.toUpperCase().equals("C1")) { + return; + } + + List generatedAtoms = new ArrayList(); + + for (int i = 0; i < points.size(); i++) { + GamessAtom atom = points.get(i); + Object[] dots = PointGroup.generatePoints(symbol, axisOrder, atom); + if (dots == null) { + continue; + } + for (int j = 0; j < dots.length; j++) { + GamessAtom a = (GamessAtom) dots[j]; + a.setName(atom.getName()); + a.setNuclearCharge(atom.getNuclearCharge()); + generatedAtoms.add(a); + } + } + + // --- Add generated atoms to the pool... + for (int i = 0; i < generatedAtoms.size(); i++) { + points.add(generatedAtoms.get(i)); + } + } + + /** + * Expects bond length in angstroms + * + * @param atoms ArrayList + * @throws Exception + */ + public static void fromZMatrixToCartesians(List atoms) throws + Exception { + int i; + int natoms = atoms.size(); + GamessAtom a, a1, a2, a3; + //Float xyz[] = new Float[3]; + float xyz[] = new float[3], x1[], x2[], x3[]; + + double SIN2, COS2, SIN3, COS3, + VT[] = new double[3], V1[] = new double[3], + V2[] = new double[3]; + double R2, + V3[] = new double[3], VA1, VB1, VC1, R3, V[] = new double[3]; + + if (natoms < 1) { + return; + } + + float factor = 1.0f; + //if (bohrs) { + // factor = (float) ONE_BOHR; + //} + + // --- The first atom. Put it into the origin + GamessAtom atom = atoms.get(0); + atom.setXYZ(0, 0, 0); + + if (natoms < 2) { + return; + } + + // --- ther second atom: put it along the X-axis + atom = atoms.get(1); + atom.setXYZ(atom.getBondLength() * factor, 0, 0); + + if (natoms < 3) { + return; + } + + // --- Third atom (put it into the XOY plane + a = atoms.get(2); + + //x1 = (float[]) cartesians.get(a.ijk[0] - 1); + x1 = new float[3]; + int index = a.get_i1(); + a1 = atoms.get(index); + x1[0] = a1.getX(); + x1[1] = a1.getY(); + x1[2] = a1.getZ(); + + xyz[2] = 0.0f; // Z-coordinate + + //if (a.ijk[0] == 1) { // Connected to the first atom + if (index == 0) { // Connected to the first atom + //logger.info("To the 1st"); + xyz[0] = a.getBondLength() * factor + * (float) Math.cos((double) (a.getAlpha() * DEGREES_TO_RADIANS)); // So, we put it along X-axis + xyz[1] = a.getBondLength() * factor + * (float) Math.sin((double) (a.getAlpha() * DEGREES_TO_RADIANS)); + } else { + //logger.info("To the 2nd"); + xyz[0] = x1[0] + - a.getBondLength() * factor + * (float) Math.cos((double) (a.getAlpha() * DEGREES_TO_RADIANS)); // So, we put it along X-axis + xyz[1] = -a.getBondLength() * factor + * (float) Math.sin((double) (a.getAlpha() * DEGREES_TO_RADIANS)); + } + + //cartesians.add(xyz); + a.setXYZ(xyz[0], xyz[1], xyz[2]); + + // Other atoms + for (i = 3; i < natoms; i++) { + + //xyz = new float[3]; + a = atoms.get(i); + + //x1 = (float[]) cartesians.get(a.ijk[0] - 1); + //x2 = (float[]) cartesians.get(a.ijk[1] - 1); + //x3 = (float[]) cartesians.get(a.ijk[2] - 1); + a1 = atoms.get(a.get_i1()); + a2 = atoms.get(a.get_i2()); + a3 = atoms.get(a.get_i3()); + + x1 = a1.xyz; + x2 = a2.xyz; + x3 = a3.xyz; + + if (a.alternateZmatrixFormat != 0) { + float[] unit = Geometry3d.getForTwoBondAngles( + new float[]{x2[0] - x1[0], x2[1] - x1[1], x2[2] - x1[2]}, + new float[]{x3[0] - x1[0], x3[1] - x1[1], x3[2] - x1[2]}, + a.getAlpha() * DEGREES_TO_RADIANS, a.getBeta() * DEGREES_TO_RADIANS, a.alternateZmatrixFormat); + xyz[0] = x1[0] + a.getBondLength() * unit[0]; + xyz[1] = x1[1] + a.getBondLength() * unit[1]; + xyz[2] = x1[2] + a.getBondLength() * unit[2]; + a.setXYZ(xyz); + continue; + } + + //SIN2 = Math.sin( (double) (a.xyz[1] * DEGREES_TO_RADIANS)); + //COS2 = Math.cos( (double) (a.xyz[1] * DEGREES_TO_RADIANS)); + //SIN3 = Math.sin( (double) (a.xyz[2] * DEGREES_TO_RADIANS)); + //COS3 = Math.cos( (double) (a.xyz[2] * DEGREES_TO_RADIANS)); + SIN2 = Math.sin((double) (a.getAlpha() * DEGREES_TO_RADIANS)); + COS2 = Math.cos((double) (a.getAlpha() * DEGREES_TO_RADIANS)); + SIN3 = Math.sin((double) (a.getBeta() * DEGREES_TO_RADIANS)); + COS3 = Math.cos((double) (a.getBeta() * DEGREES_TO_RADIANS)); + + VT[0] = a.getBondLength() * factor * COS2; + VT[1] = a.getBondLength() * factor * SIN2 * SIN3; + VT[2] = a.getBondLength() * factor * SIN2 * COS3; + + V1[0] = x3[0] - x2[0]; + V1[1] = x3[1] - x2[1]; + V1[2] = x3[2] - x2[2]; + + V2[0] = x2[0] - x1[0]; + V2[1] = x2[1] - x1[1]; + V2[2] = x2[2] - x1[2]; + + R2 = Math.sqrt(V2[0] * V2[0] + V2[1] * V2[1] + V2[2] * V2[2]); + + V3[0] = V1[1] * V2[2] - V1[2] * V2[1]; + V3[1] = V1[2] * V2[0] - V1[0] * V2[2]; + V3[2] = V1[0] * V2[1] - V1[1] * V2[0]; + + R3 = Math.sqrt(V3[0] * V3[0] + V3[1] * V3[1] + V3[2] * V3[2]); + + V2[0] = V2[0] / R2; + V2[1] = V2[1] / R2; + V2[2] = V2[2] / R2; + + V3[0] = V3[0] / R3; + V3[1] = V3[1] / R3; + V3[2] = V3[2] / R3; + + V[0] = V2[1] * V3[2] - V2[2] * V3[1]; + V[1] = V2[2] * V3[0] - V2[0] * V3[2]; + V[2] = V2[0] * V3[1] - V2[1] * V3[0]; + + VA1 = V2[0] * VT[0] + V3[0] * VT[1] + V[0] * VT[2]; + VB1 = V2[1] * VT[0] + V3[1] * VT[1] + V[1] * VT[2]; + VC1 = V2[2] * VT[0] + V3[2] * VT[1] + V[2] * VT[2]; + + xyz[0] = x1[0] + (float) VA1; + xyz[1] = x1[1] + (float) VB1; + xyz[2] = x1[2] + (float) VC1; + + //cartesians.add(xyz); + a.setXYZ(xyz); + } + } + + private int getCardSequence() throws Exception { + int cardSequence = UNIQUE; + + if (!currentVars.containsKey(controlSection)) { + return cardSequence; + } + + Map controlGroup = currentVars.get(controlSection); + + if (controlGroup.containsKey("COORD")) { + String value = (String) controlGroup.get("COORD"); + value = value.toUpperCase(); + if (value.equals("UNIQUE")) { + cardSequence = UNIQUE; + } else if (value.equals("HINT")) { + cardSequence = HINT; + } else if (value.equals("CART")) { + cardSequence = CART; + } else if (value.equals("ZMT")) { + cardSequence = ZMT; + } else if (value.equals("ZMTMPC")) { + cardSequence = ZMTMPC; + } else { + throw new Exception("Unknown card sequence: COORD=" + value); + } + } + return cardSequence; + } + + public static int getAtomicNumber(String symbol) { + byte[] chars = symbol.getBytes(); + String atom = ""; + + if (symbol.length() == 1) { + return ChemicalElements.getAtomicNumber(symbol); + } else if (chars.length > 1 && chars[1] >= '0' && chars[1] <= '9') { + atom = symbol.substring(0, 1); + } else { + atom = symbol.substring(0, 2); + } + + return ChemicalElements.getAtomicNumber(atom); + } + + public int validFormatScore(BufferedReader in) throws Exception { + Gamess g = new Gamess(); + try { + g.parseData(in); + } catch (Exception ex) { + return 0; + } + + if (g.getMolecule() == null || g.getMolecule().getNumberOfAtoms() < 1) { + return 0; + } + return 10; + } + + public void parseData(BufferedReader in) throws Exception { + MoleculeInterface mol = getMoleculeInterface(); + this.addMolecule(mol); + + String line; + ignoreDataSection = false; + + String currentSection = ""; + String currentSwitch = ""; + Map currentOptions = null; + Map references = null; + boolean readingSection = false; + boolean readingSwitch = false; + + // --- Start to parse + try { + //BufferedReader in = new BufferedReader(new FileReader(filename)); + + while ((line = in.readLine()) != null) { + line = line.trim(); + + if (line.length() < 1) { + continue; + } + + if (line.startsWith("!")) { // Comment + continue; + } + + StringTokenizer st = new StringTokenizer(line, " \t="); + + while (st.hasMoreTokens()) { + String token = st.nextToken(); + if (!readingSection && !token.startsWith("$")) { // Looking for a new section + continue; + } else if (!readingSection && token.equalsIgnoreCase(endSection)) { // Found (unexpectedly) end section + System.err.println("Unexpectedly found $END section..."); + readingSection = false; + readingSwitch = false; + //throw new Exception("Unexpectedly found $END section..."); + continue; + } else if (!readingSection && token.startsWith("$")) { // Found a new section + token = token.toUpperCase(); + logger.info("Starting to read section " + token); + if (!validSections.contains(token)) { + logger.warning("Unknown section " + token); + references = null; + } else { + references = sectionVarsReference.get(token); + } + + // -- Special case for some sections... + if (token.equalsIgnoreCase(dataSection) && (!ignoreDataSection)) { + this.parseDataSection(in); + break; + } + + if (token.equalsIgnoreCase(fmoxyzSection)) { + ignoreDataSection = true; + this.readFMOXYZSection(in); + } + + readingSwitch = true; + currentSection = token; + if (currentVars.containsKey(currentSection)) { + currentOptions = currentVars.get(currentSection); + } else { + currentOptions = new HashMap(); + } + readingSection = true; + continue; + } else if (readingSection && token.equalsIgnoreCase(endSection) && !readingSwitch) { // Found end section + logger.warning("Unexpected end of section " + currentSection + " while expecting value for switch " + currentSwitch); + currentOptions.put(currentSection, ""); + currentVars.put(currentSection, currentOptions); + printSection(currentSection, currentOptions); + currentSection = ""; + readingSection = false; + } else if (readingSection && token.equalsIgnoreCase(endSection)) { // Found end section + logger.info("Finished to read section " + currentSection); + currentVars.put(currentSection, currentOptions); + printSection(currentSection, currentOptions); + currentSection = ""; + readingSection = false; + } else if (readingSection && readingSwitch) { // Reading switch + token = token.toUpperCase(); + if (references != null && !references.containsKey(token)) { + logger.warning("Unknown switch: " + token); + } + currentSwitch = token; + readingSwitch = false; + } else if (readingSection && !readingSwitch) { // Reading value + if (references != null) { + GamessSwitch refSwitch = (GamessSwitch) references.get(currentSwitch); + if (refSwitch == null || (!refSwitch.isValidValue(token))) { + logger.warning("Check value " + token + " for switch " + currentSwitch); + } + } + currentOptions.put(currentSwitch, token); + readingSwitch = true; + } + + } + + } + } catch (IOException e) { + logger.severe("Error parsing gamess input: " + e.getMessage()); + throw e; + } + + // --- Build molecule + getMolecularInterface(mol); + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } +} diff --git a/src/main/java/cct/gamess/GamessAtom.java b/src/main/java/cct/gamess/GamessAtom.java new file mode 100644 index 0000000..76c91fa --- /dev/null +++ b/src/main/java/cct/gamess/GamessAtom.java @@ -0,0 +1,264 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gamess; + +import cct.interfaces.Point3fInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class GamessAtom + implements Point3fInterface { + String name; + int element = -1; + float NuclearCharge = 0; + float xyz[] = new float[3]; + float bondLength, alpha, beta; + String bondLengthPar = null, alphaPar = null, betaPar = null; + int i1 = -1, i2 = -1, i3 = -1, i4 = -1; + int alternateZmatrixFormat=0; + + public GamessAtom() { + } + + public GamessAtom(float xx, float yy, float zz) { + xyz[0] = xx; + xyz[1] = yy; + xyz[2] = zz; + } + + public void setBondLength(float bond) { + bondLength = bond; + } + + public float getBondLength() { + return bondLength; + } + + public void setBondLength(String bond) { + bondLengthPar = bond; + } + + public String getBondLengthPar() { + return bondLengthPar; + } + + public void setAlpha(float a) { + alpha = a; + } + + public float getAlpha() { + return alpha; + } + + public void setAlpha(String a) { + alphaPar = a; + } + + public String getAlphaPar() { + return alphaPar; + } + + public void setBeta(float b) { + beta = b; + } + + public float getBeta() { + return beta; + } + + public void setBeta(String b) { + betaPar = b; + } + + public String getBetaPar() { + return betaPar; + } + + public void set_i1(int i1) { + this.i1 = i1; + } + + public int get_i1() { + return this.i1; + } + + public void set_i2(int i2) { + this.i2 = i2; + } + + public int get_i2() { + return this.i2; + } + + public void set_i3(int i3) { + this.i3 = i3; + } + + public int get_i3() { + return this.i3; + } + + public void set_i4(int i4) { + this.i4 = i4; + } + + public void setName(String _name) { + name = _name; + } + + public void setNuclearCharge(float charge) { + NuclearCharge = charge; + } + + public void setNuclearCharge(double charge) { + NuclearCharge = (float) charge; + } + + @Override + public void setX(double x) { + xyz[0] = (float)x; + } + + @Override + public void setY(double y) { + xyz[1] = (float)y; + } + + @Override + public void setZ(double z) { + xyz[2] = (float)z; + } + + + public String getName() { + return name; + } + + public float getNuclearCharge() { + return NuclearCharge; + } + + @Override + public float getX() { + return xyz[0]; + } + + @Override + public float getY() { + return xyz[1]; + } + + @Override + public float getZ() { + return xyz[2]; + } + + public void setAtomicNumber(int number) { + element = number; + } + + public int getAtomicNumber() { + if (element < 0) { + return (int) NuclearCharge; + } + else { + return element; + } + } + + @Override + public double distanceTo(Point3fInterface point) { + return Math.sqrt( (xyz[0] - point.getX()) * (xyz[0] - point.getX()) + + (xyz[1] - point.getY()) * (xyz[1] - point.getY()) + + (xyz[2] - point.getZ()) * (xyz[2] - point.getZ())); + } + + @Override + public void setXYZ(double xx, double yy, double zz) { + xyz[0] = (float)xx; + xyz[1] = (float)yy; + xyz[2] = (float)zz; + } + + public void setXYZ(float xx[]) { + xyz[0] = xx[0]; + xyz[1] = xx[1]; + xyz[2] = xx[2]; + } + + @Override + public void setXYZ(Point3fInterface xyz) { + this.xyz[0] = xyz.getX(); + this.xyz[1] = xyz.getY(); + this.xyz[2] = xyz.getZ(); + } + + @Override + public void subtract(Point3fInterface a1, Point3fInterface a2) { + xyz[0] = a1.getX() - a2.getX(); + xyz[1] = a1.getY() - a2.getY(); + xyz[2] = a1.getZ() - a2.getZ(); + + } + + @Override + public Point3fInterface getInstance() { + return new GamessAtom(); + } + + @Override + public Point3fInterface getInstance(Point3fInterface a) { + return new GamessAtom(a.getX(), a.getY(), a.getZ()); + } + + @Override + public Point3fInterface getInstance(float xx, float yy, float zz) { + return new GamessAtom(xx, yy, zz); + } + +} diff --git a/src/main/java/cct/gamess/GamessOutput.java b/src/main/java/cct/gamess/GamessOutput.java new file mode 100644 index 0000000..8cabddc --- /dev/null +++ b/src/main/java/cct/gamess/GamessOutput.java @@ -0,0 +1,234 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.gamess; + +import cct.Constants; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.CCTAtomTypes; +import cct.modelling.GeneralMolecularDataParser; +import cct.modelling.Molecule; +import java.util.logging.Logger; + +/** + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2007

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class GamessOutput extends GeneralMolecularDataParser { + + static final float ONE_BOHR_FLOAT = Constants.ONE_BOHR_FLOAT; // In Angstrom + static final Logger logger = Logger.getLogger(GamessOutput.class.getCanonicalName()); + Map outputResume = new LinkedHashMap(100); + boolean normalTermination = false; + List Geometries = new ArrayList(); + int natoms = -1; + String runTitle = null; + + public GamessOutput() { + } + + /** + * + * @param filename + * @throws Exception + * @deprecated Use parseData methods instead + */ + @Deprecated + public void parseGamessOutputFile(String filename) throws Exception { + String line; + try { + BufferedReader in = new BufferedReader(new FileReader(filename)); + parseData(in); + } catch (IOException e) { + System.err.println("parseGamessOutputFile: error parsing " + filename + " : " + e.getMessage()); + throw new Exception("Error parsing " + filename + " : " + e.getMessage()); + } + + } + + public static GamessAtom parseAtomData(String data) throws Exception { + GamessAtom atom = new GamessAtom(); + StringTokenizer st = new StringTokenizer(data, " \t"); + + if (st.countTokens() < 5) { + throw new Exception( + "Expecting 5 tokens while reading molecular geometry, got " + data); + } + + atom.setName(st.nextToken()); + + try { + atom.setNuclearCharge(Float.parseFloat(st.nextToken())); + atom.setAtomicNumber((int) atom.getNuclearCharge()); + atom.setX(Float.parseFloat(st.nextToken()) * ONE_BOHR_FLOAT); + atom.setY(Float.parseFloat(st.nextToken()) * ONE_BOHR_FLOAT); + atom.setZ(Float.parseFloat(st.nextToken()) * ONE_BOHR_FLOAT); + } catch (Exception ex) { + throw new Exception("Error while parsing float point atom data: " + data); + } + + return atom; + } + + public void getMolecularInterface(MoleculeInterface molec) throws + Exception { + if (molec == null) { + throw new Exception(this.getClass().getCanonicalName() + " : molec == null"); + } + if (Geometries.size() < 1) { + throw new Exception(this.getClass().getCanonicalName() + " : didn't find atoms in file"); + } + + molec.addMonomer("GAMESS"); + + List atoms = Geometries.get(Geometries.size() - 1); + + for (int i = 0; i < atoms.size(); i++) { + GamessAtom ga = atoms.get(i); + AtomInterface atom = molec.getNewAtomInstance(); + atom.setName(ga.getName()); + atom.setAtomicNumber(ga.getAtomicNumber()); + atom.setXYZ(ga.getX(), ga.getY(), ga.getZ()); + molec.addAtom(atom); + } + } + + public int validFormatScore(BufferedReader in) throws Exception { + GamessOutput g = new GamessOutput(); + try { + g.parseData(in); + } catch (Exception ex) { + return 0; + } + + if (g.getMoleculeInterface() == null || g.getMoleculeInterface().getNumberOfAtoms() < 1) { + return 0; + } + return 10; + } + + public void parseData(BufferedReader in) throws Exception { + + String line; + try { + + while ((line = in.readLine()) != null) { + + if (line.contains("GAMESS VERSION")) { + this.outputResume.put("Gamess Ver", line); + } else if (line.contains("RUNNING WITH")) { + this.outputResume.put("Parallel", line); + } else if (line.contains("THE POINT GROUP")) { + this.outputResume.put("point group", line); + } else if (line.contains("THE ORDER OF")) { + this.outputResume.put("order", line); + } else if (line.contains("ATOM ATOMIC")) { + if (Geometries.size() == 0) { + List atoms = new ArrayList(); + // Skip a line + if ((line = in.readLine()) == null) { + throw new Exception("Unexpected end-of-file while reading molecular geometry"); + } + + while ((line = in.readLine()) != null) { + if (line.trim().length() == 0) { + break; + } + GamessAtom atom = parseAtomData(line); + atoms.add(atom); + } + + Geometries.add(atoms); + } + } else if (line.contains("BASIS OPTIONS")) { + this.outputResume.put("basis0", line); + if ((line = in.readLine()) == null) { + outputResume.put("basis1", line); + break; + } + int count = 1; + while ((line = in.readLine()) != null) { + if (line.trim().length() == 0) { + break; + } + ++count; + outputResume.put("basis" + count, line); + } + } else if (line.contains("RUN TITLE")) { + outputResume.put("title0", line); + if ((line = in.readLine()) == null) { + outputResume.put("basis1", line); + } + if ((line = in.readLine()) == null) { + outputResume.put("basis2", line); + runTitle = line.trim(); + } + } + } + } catch (IOException e) { + logger.severe("Error parsing gamess output: " + e.getMessage()); + throw new Exception("Error parsing gamess output: " + e.getMessage()); + } + + MoleculeInterface mol = getMoleculeInterface(); + this.addMolecule(mol); + getMolecularInterface(mol); + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } +} diff --git a/src/main/java/cct/gamess/GamessSwitch.java b/src/main/java/cct/gamess/GamessSwitch.java new file mode 100644 index 0000000..8f26e67 --- /dev/null +++ b/src/main/java/cct/gamess/GamessSwitch.java @@ -0,0 +1,143 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gamess; + +import java.util.HashMap; +import java.util.Map; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ + +public class GamessSwitch { + boolean anyValue = false; + String name; + String description; + String defaultValue = null; + Map values = new HashMap(); + Object variableType = null; + + public GamessSwitch(String _name, String _description) { + name = _name; + description = _description; + } + + public GamessSwitch(String _name, String _description, boolean _anyValue) { + name = _name; + description = _description; + anyValue = _anyValue; + } + + public void setType(Object type) { + variableType = type; + } + + public void addValue(String value, String _description) { + values.put(value, _description); + } + + public void addValue(String value, String _description, boolean isDefault) { + values.put(value, _description); + if (isDefault) { + defaultValue = value; + } + } + + public boolean isValidValue(String value) { + + // --- first, check value validity + if (variableType != null) { + try { + if (variableType instanceof Boolean) { + Boolean b = (Boolean) variableType; + b = Boolean.parseBoolean(value); + return true; + } + else if (variableType instanceof Integer) { + float num = Float.parseFloat(value); + Integer i = (Integer) variableType; + i = (int) num; + //Integer.parseInt(value); + return true; + } + else if (variableType instanceof Float) { + Float f = (Float) variableType; + f = Float.parseFloat(value); + return true; + } + else if (variableType instanceof Double) { + Double d = (Double) variableType; + d = Double.parseDouble(value); + return true; + } + else if (variableType instanceof Long) { + Long l = (Long) variableType; + l = Long.parseLong(value); + return true; + } + + } + catch (Exception ex) { + return false; + } + } + + // --- Check "any value" + + if (anyValue) { + return true; + } + + // Is it in the list + + return values.containsKey( value ); + } + + public String getName() { + return name; + } +} diff --git a/src/main/java/cct/gaussian/.DS_Store b/src/main/java/cct/gaussian/.DS_Store new file mode 100644 index 0000000..25b31b9 Binary files /dev/null and b/src/main/java/cct/gaussian/.DS_Store differ diff --git a/src/main/java/cct/gaussian/._.DS_Store b/src/main/java/cct/gaussian/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/cct/gaussian/._.DS_Store differ diff --git a/src/main/java/cct/gaussian/G03FormCheckpoint.java b/src/main/java/cct/gaussian/G03FormCheckpoint.java new file mode 100644 index 0000000..ea6b907 --- /dev/null +++ b/src/main/java/cct/gaussian/G03FormCheckpoint.java @@ -0,0 +1,298 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.util.HashMap; +import java.util.Map; + +import cct.Constants; +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.ChemicalElements; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ + +enum TYPE { + REAL, INTEGER, UNKNOWN +} + +enum G03_CHECKPOINT_KEY_WORDS { + FOpt, Number_of_electrons, Number_of_alpha_electrons, SCF_Energy, MP2_Energy, Total_Energy, Atomic_numbers, Number_of_atoms, + Current_cartesian_coordinates +} + +public class G03FormCheckpoint { + + static final Map keyWords = new HashMap (); + + static { + keyWords.put("FOpt", G03_CHECKPOINT_KEY_WORDS.FOpt); + keyWords.put("Number of electrons", G03_CHECKPOINT_KEY_WORDS.Number_of_electrons); + keyWords.put("Number of alpha electrons", G03_CHECKPOINT_KEY_WORDS.Number_of_alpha_electrons); + keyWords.put("SCF Energy", G03_CHECKPOINT_KEY_WORDS.SCF_Energy); + keyWords.put("MP2 Energy", G03_CHECKPOINT_KEY_WORDS.MP2_Energy); + keyWords.put("Total Energy", G03_CHECKPOINT_KEY_WORDS.Total_Energy); + keyWords.put("Atomic numbers", G03_CHECKPOINT_KEY_WORDS.Atomic_numbers); + keyWords.put("Number of atoms", G03_CHECKPOINT_KEY_WORDS.Number_of_atoms); + keyWords.put("Current cartesian coordinates", G03_CHECKPOINT_KEY_WORDS.Current_cartesian_coordinates); + } + + int nAtoms = 0; + GaussianAtom[] atoms = null; + + public G03FormCheckpoint() { + } + + public static void main(String[] args) { + G03FormCheckpoint g03formcheckpoint = new G03FormCheckpoint(); + } + + public void parseFile(String fileName) throws Exception { + String line, keyword, token; + + try { + BufferedReader in = new BufferedReader(new FileReader(fileName)); + + while ( (line = in.readLine()) != null) { + if (line.length() < 44) { + continue; + } + keyword = line.substring(0, 43).trim(); + if (!keyWords.containsKey(keyword)) { + continue; + } + + G03_CHECKPOINT_KEY_WORDS keyWord = keyWords.get(keyword); + + DataBunch data = new DataBunch(); + switch (keyWord) { + case Number_of_atoms: + data.extractNumericalData(line, in); + nAtoms = data.int_vector[0]; + atoms = new GaussianAtom[nAtoms]; + for (int i = 0; i < nAtoms; i++) { + atoms[i] = new GaussianAtom(); + } + break; + case Number_of_electrons: + break; + case Number_of_alpha_electrons: + break; + case SCF_Energy: + break; + case Total_Energy: + break; + case Atomic_numbers: + data.extractNumericalData(line, in); + for (int i = 0; i < nAtoms; i++) { + atoms[i].element = data.int_vector[i]; + } + break; + case Current_cartesian_coordinates: + data.extractNumericalData(line, in); + for (int i = 0; i < nAtoms; i++) { + atoms[i].xyz[0] = (float) data.real_vector[i * 3] * Constants.ONE_BOHR_FLOAT; + atoms[i].xyz[1] = (float) data.real_vector[i * 3 + 1] * Constants.ONE_BOHR_FLOAT; + atoms[i].xyz[2] = (float) data.real_vector[i * 3 + 2] * Constants.ONE_BOHR_FLOAT; + } + break; + } + + } + } + catch (Exception ex) { + throw new Exception("Cannot open file " + fileName + " : " + ex.getMessage()); + } + } + + public void getMolecule(MoleculeInterface molec) throws + Exception { + if (molec == null) { + throw new Exception(this.getClass().getCanonicalName() + " : molec == null"); + } + if (nAtoms < 1) { + throw new Exception(this.getClass().getCanonicalName() + " : no atoms"); + } + + molec.addMonomer("G03"); + + for (int i = 0; i < nAtoms; i++) { + AtomInterface atom = molec.getNewAtomInstance(); + atom.setName(ChemicalElements.getElementSymbol(atoms[i].getElement())); + atom.setAtomicNumber(atoms[i].getElement()); + atom.setXYZ(atoms[i].getX(), atoms[i].getY(), atoms[i].getZ()); + molec.addAtom(atom); + } + + } + + private class DataBunch { + int[] int_vector = null; + double[] real_vector = null; + + public DataBunch() {} + + public void extractNumericalData(String line, BufferedReader in) throws Exception { + boolean vector; + String token; + TYPE valueType; + int intValue, vecLength = 1; + double realValue; + + vector = line.substring(47, 49).equals("N="); + if (vector) { + /* + Info1-9 I N= 9 + */ + vecLength = Integer.parseInt(line.substring(49, 61).trim()); + + } + else { + vecLength = 1; + } + + token = line.substring(43, 44); + + if (token.equals("R")) { + valueType = TYPE.REAL; + + real_vector = new double[vecLength]; + + if (vector) { + readRealVector(in, real_vector); + } + else { // Single real number + token = line.substring(49, 71).trim(); + try { + real_vector[0] = Double.parseDouble(token); + } + catch (Exception ex) { + throw new Exception("Cannot parse real value type: " + line + " " + ex.getMessage()); + } + } + } + else if (token.equals("I")) { + /* + Nuclear charges R N= 14 + */ + valueType = TYPE.INTEGER; + + int_vector = new int[vecLength]; + + if (vector) { + readIntVector(in, int_vector); + } + else { + token = line.substring(49, 61).trim(); + try { + int_vector[0] = Integer.parseInt(token); + } + catch (Exception ex) { + throw new Exception("Cannot parse integer value type: " + line + "" + ex.getMessage()); + } + } + } + + else { + valueType = TYPE.UNKNOWN; + throw new Exception("Unknown value type: " + line); + } + } + + public void readRealVector(BufferedReader in, double[] r_vector) throws Exception { + String line; + int k, n = r_vector.length; + int n_lines = n / 5; + if (n_lines == 0) { + n_lines = 1; + } + else if (n % 5 != 0) { + ++n_lines; + } + /* + 2.99050349E+00 -1.06469478E+00 -2.46420243E-01 2.14195397E+00 -2.86706022E+00 + + */ + k = 0; + for (int i = 0; i < n_lines; i++) { + line = in.readLine(); + int nnum = n - i * 5 > 5 ? 5 : n - i * 5; + for (int j = 0; j < nnum; j++) { + r_vector[k] = Double.parseDouble(line.substring(j * 16, j * 16 + 16).trim()); + ++k; + } + } + } + + public void readIntVector(BufferedReader in, int[] i_vector) throws Exception { + String line; + int k, n = i_vector.length; + int n_lines = n / 6; + if (n_lines == 0) { + n_lines = 1; + } + else if (n % 6 != 0) { + ++n_lines; + } + k = 0; + for (int i = 0; i < n_lines; i++) { + line = in.readLine(); + int nnum = n - i * 6 > 6 ? 6 : n - i * 6; + for (int j = 0; j < nnum; j++) { + i_vector[k] = Integer.parseInt(line.substring(j * 12, j * 12 + 12).trim()); + ++k; + } + } + } + + } + +} diff --git a/src/main/java/cct/gaussian/G03MDTrajectory.java b/src/main/java/cct/gaussian/G03MDTrajectory.java new file mode 100644 index 0000000..4f77736 --- /dev/null +++ b/src/main/java/cct/gaussian/G03MDTrajectory.java @@ -0,0 +1,1043 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.gaussian; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.RandomAccessFile; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import cct.Constants; +import cct.interfaces.AtomInterface; +import cct.interfaces.ChartDataProvider; +import cct.interfaces.MoleculeInterface; +import cct.modelling.ChemicalElements; +import cct.modelling.MolecularGeometry; +import cct.modelling.SingleTrajectoryNew; +import cct.modelling.StructureManagerInterface; +import cct.modelling.TrajectorySnapshot; +import cct.tools.ui.JobProgressInterface; +import cct.vecmath.Point3f; +import java.util.logging.Level; +import javax.swing.JOptionPane; + +/** + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2015 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class G03MDTrajectory extends SingleTrajectoryNew + implements StructureManagerInterface, ChartDataProvider { + + public static final String TOTAL_ENERGY_KEY = "Total energy (au)"; + private static final String STANDARD_GEOMETRY_KEY = "MD"; + public static final String TRJ_BLOCK_MARK = " TRJ-TRJ-TRJ-TRJ-TRJ-TRJ-TRJ-TRJ"; + public static final String TIME_STEP_KEY = " Time Step"; + public static final String ADMP_STEP_INFO_KEY = " Summary information for step"; + public static final String MD_STEP_KEY = "MD Step"; + public static final String TOTAL_TIME_FS_KEY = " Time (fs)"; + public static final String EKinC_KEY = "EKinC", EKinPA_KEY = "EKinPA", EKinPB_KEY = "EKinPB"; + public static final String EKinNucler_KEY = "Nuclear Kinetic Energy"; + public static final String EKinElectronic_KEY = "Electronic Kinetic Energy"; + public static final String EKin_KEY = "EKin ", EKin_PATTERN = "EKin ="; + public static final String EPot_KEY = "EPot", EPot_PATTERN = "EPot ="; + public static final String ETot_KEY = "ETot", ETot_PATTERN = "ETot ="; + public static final String EKinTotal_KEY = "Total Kinetic Energy"; + public static final String EPotential_KEY = "Potential Energy"; + public static final String ETotal_KEY = "Total Energy"; + public static final String Temperature_KEY = "Temperature"; + public static final String ETot_minus_EKinP_KEY = "ETot-EKinP"; + public static final String CARTESIAN_COORD_KEY = " Cartesian coordinates:"; + + private String originalFileName; + private boolean debug = true; + private List gAtoms = null; + //private List snapshots = new ArrayList(); + //private Set propertiesToChart = new HashSet(); + private double timeStep = 0.1; // in fs + private double factor = Constants.ONE_BOHR; + static final Logger logger = Logger.getLogger(G03MDTrajectory.class.getCanonicalName()); + + public G03MDTrajectory() { + } + + public G03MDTrajectory(MoleculeInterface mol) { + super(mol); + } + + public void readCoordsFromTrajFile(float coords[][], RandomAccessFile raf, long offset) throws Exception { + String buffer = null; + raf.seek(offset); + + if (originalFileName.toUpperCase().matches(".*[.](LOG|OUT)$")) { + String numStr; + for (int i = 0; i < coords.length; i++) { + if ((buffer = raf.readLine()) == null) { + System.err.println("Eof while reading in cartesian coordinates from a trajectory"); + break; + } + numStr = getNumberString(buffer, "X"); + coords[i][0] = (float) (factor * Double.parseDouble(numStr)); + numStr = getNumberString(buffer, "Y"); + coords[i][1] = (float) (factor * Double.parseDouble(numStr)); + numStr = getNumberString(buffer, "Z"); + coords[i][2] = (float) (factor * Double.parseDouble(numStr)); + } + } else { + + for (int i = 0; i < coords.length; i++) { + buffer = raf.readLine(); + buffer = fixAllNumbers(buffer); + coords[i][0] = (float) (Constants.ONE_BOHR * Double.parseDouble(buffer.substring(11, 32).trim())); + coords[i][1] = (float) (Constants.ONE_BOHR * Double.parseDouble(buffer.substring(35, 56).trim())); + coords[i][2] = (float) (Constants.ONE_BOHR * Double.parseDouble(buffer.substring(59, 80).trim())); + } + } + } + + public void parseTrajectoryFile(String fileName, JobProgressInterface progress) throws Exception { + if (fileName == null || fileName.length() < 1) { + logger.severe("Trajectory file name is not set"); + throw new Exception("Trajectory file name is not set"); + } + originalFileName = fileName; + if (fileName.toUpperCase().matches(".*[.](LOG|OUT)$")) { + extractG09TrajectoryFromLog(fileName, progress); + + } else { + parseG03Trajectory(fileName, progress); + } + System.out.println("Found " + super.getTrajectorySnapshots().size() + " MD snapshots in trajectory file"); + } + + /** + * Contrary to any similar subroutines it returns the FIRST snapshot + * + * @param molec MoleculeInterface - molecule + * @throws Exception + */ + public void getMolecularInterface(MoleculeInterface molec) throws + Exception { + if (molec == null) { + throw new Exception(this.getClass().getCanonicalName() + " : molec == null"); + } + if (gAtoms.size() < 1) { + throw new Exception(this.getClass().getCanonicalName() + " : no Gaussian atoms"); + } + + molec.addMonomer("GAUSS"); + + for (int i = 0; i < gAtoms.size(); i++) { + GaussianAtom ga = gAtoms.get(i); + AtomInterface atom = molec.getNewAtomInstance(); + if (ga.name == null || ga.name.length() < 1) { + atom.setName(ChemicalElements.getElementSymbol(ga.getElement())); + } else { + atom.setName(ga.name); + } + atom.setAtomicNumber(ga.getElement()); + atom.setXYZ(ga.xyz[0], ga.xyz[1], ga.xyz[2]); + + molec.addAtom(atom); + } + + } + + public String[] getAvailPropToChart() { + if (this.getDescriptors().size() < 1) { + return null; + } + String[] sa = new String[getDescriptors().size()]; + getDescriptors().toArray(sa); + return sa; + } + + public MoleculeInterface parseMolecularGeometryOnly(MoleculeInterface mol, String filename) throws Exception { + try { + BufferedReader in = new BufferedReader(new FileReader(filename)); + return parseMolecularGeometryOnly(in, mol); + } catch (Exception ex) { + throw new Exception("parseMolecularGeometryOnly: ERROR opening file " + filename); + } + } + + public MoleculeInterface parseMolecularGeometryOnly(BufferedReader in, MoleculeInterface mol) throws Exception { + /* + Trajectory Starting Point: + --------------------------------------------------------------------- + Center Atomic Atomic Coordinates (Angstroms) + Number Number Type X Y Z + --------------------------------------------------------------------- + 1 6 20001001 -0.241185 -0.271881 -0.382124 + 2 1 20001035 -1.177106 -0.664240 -0.014125 + 3 1 20001035 -0.315056 0.809277 -0.444002 + 4 1 20001035 -0.048133 -0.668818 -1.370969 + 5 8 20001022 0.768355 -0.655283 0.526139 + 6 1 20001031 1.633769 -0.371391 0.194276 + 7 8 20001021 -4.053620 -1.712267 -3.472290 + 8 1 20001030 -4.735666 -1.205766 -3.951382 + 9 1 20001030 -4.373260 -2.632389 -3.570404 + 10 8 20001021 -1.639883 -2.524523 -2.527601 + 11 1 20001030 -0.987622 -1.996276 -3.026744 + 12 1 20001030 -2.490365 -2.190708 -2.882675 + .... + 424 8 20001021 4.214621 4.206208 5.313912 + 425 1 20001030 3.628498 4.920676 5.625427 + 426 1 20001030 4.840445 4.696562 4.738038 + --------------------------------------------------------------------- + + */ + String line; + try { + + // --- Finding "Trajectory Starting Point" + while ((line = in.readLine()) != null) { + if (line.contains("Trajectory Starting Point:")) { + break; + } + } + + if (line == null) { + throw new Exception("parseMolecularGeometryOnly: ERROR: Unxpected End of file while looking for the start of data"); + } + + // --- Skip 4 lines + for (int i = 0; i < 4; i++) { + line = in.readLine(); + if (line == null) { + throw new Exception( + "parseMolecularGeometryOnly: ERROR: Unxpected End of file while looking for the start of coordinates"); + } + } + + // --- Reading atoms + // 1 6 20001001 -0.241185 -0.271881 -0.382124 + while ((line = in.readLine()) != null) { + if (line.contains("-------------------------")) { + break; + } + + StringTokenizer st = new StringTokenizer(line, " "); + if (st.countTokens() != 6) { + throw new Exception( + "parseMolecularGeometryOnly: ERROR: coordinate input has 6 tokens\n Got: " + line); + } + + AtomInterface atom = mol.getNewAtomInstance(); + + // --- Getting element + // --- Skip 1 token + st.nextToken(); + + int element; + try { + element = Integer.parseInt(st.nextToken()); + if (element < 1) { + element = 0; + } + atom.setAtomicNumber(element); + atom.setName(ChemicalElements.getElementSymbol(element)); + } catch (Exception ex) { + throw new Exception( + "parseMolecularGeometryOnly: ERROR: Error while parsing atom: " + + (mol.getNumberOfAtoms() + 1) + " Cannot parse atom number: " + line); + } + + // --- Getting atomic type + // --- Skip it for now + st.nextToken(); + + // --- Getting x,y,z + float xyz; + try { + xyz = Float.parseFloat(st.nextToken()); + atom.setX(xyz); + xyz = Float.parseFloat(st.nextToken()); + atom.setY(xyz); + xyz = Float.parseFloat(st.nextToken()); + atom.setZ(xyz); + } catch (Exception ex) { + throw new Exception( + "parseMolecularGeometryOnly: ERROR: Error while parsing atom: " + + (mol.getNumberOfAtoms() + 1) + " Cannot parse atom's coordinate(s): " + line); + } + + mol.addAtom(atom); + + } + + in.close(); + } catch (Exception ex) { + throw new Exception("parseMolecularGeometryOnly: ERROR: " + ex.getMessage()); + } + + return mol; + } + + static public List parseMolecularGeometryOnly(RandomAccessFile raf) throws Exception { + List atoms = new ArrayList(); + /* + Trajectory Starting Point: + --------------------------------------------------------------------- + Center Atomic Atomic Coordinates (Angstroms) + Number Number Type X Y Z + --------------------------------------------------------------------- + 1 6 20001001 -0.241185 -0.271881 -0.382124 + 2 1 20001035 -1.177106 -0.664240 -0.014125 + 3 1 20001035 -0.315056 0.809277 -0.444002 + 4 1 20001035 -0.048133 -0.668818 -1.370969 + 5 8 20001022 0.768355 -0.655283 0.526139 + 6 1 20001031 1.633769 -0.371391 0.194276 + 7 8 20001021 -4.053620 -1.712267 -3.472290 + 8 1 20001030 -4.735666 -1.205766 -3.951382 + 9 1 20001030 -4.373260 -2.632389 -3.570404 + 10 8 20001021 -1.639883 -2.524523 -2.527601 + 11 1 20001030 -0.987622 -1.996276 -3.026744 + 12 1 20001030 -2.490365 -2.190708 -2.882675 + .... + 424 8 20001021 4.214621 4.206208 5.313912 + 425 1 20001030 3.628498 4.920676 5.625427 + 426 1 20001030 4.840445 4.696562 4.738038 + --------------------------------------------------------------------- + + */ + String line; + try { + + // --- Finding "Trajectory Starting Point" + while ((line = raf.readLine()) != null) { + if (line.contains("Trajectory Starting Point:")) { + break; + } + } + + if (line == null) { + throw new Exception("parseMolecularGeometryOnly: ERROR: Unxpected End of file while looking for the start of data"); + } + + // --- Skip 4 lines + for (int i = 0; i < 4; i++) { + line = raf.readLine(); + if (line == null) { + throw new Exception( + "parseMolecularGeometryOnly: ERROR: Unxpected End of file while looking for the start of coordinates"); + } + } + + // --- Reading atoms + // 1 6 20001001 -0.241185 -0.271881 -0.382124 + while ((line = raf.readLine()) != null) { + if (line.contains("-------------------------")) { + break; + } + + StringTokenizer st = new StringTokenizer(line, " "); + if (st.countTokens() != 6) { + throw new Exception( + "parseMolecularGeometryOnly: ERROR: coordinate input has 6 tokens\n Got: " + line); + } + + GaussianAtom atom = new GaussianAtom(); + + // --- Getting element + // --- Skip 1 token + st.nextToken(); + + int element; + try { + element = Integer.parseInt(st.nextToken()); + if (element < 1) { + element = 0; + } + atom.element = element; + atom.name = ChemicalElements.getElementSymbol(element); + } catch (Exception ex) { + throw new Exception( + "parseMolecularGeometryOnly: ERROR: Error while parsing atom: " + + (atoms.size() + 1) + " Cannot parse atom number: " + line); + } + + // --- Getting atomic type + // --- Skip it for now + st.nextToken(); + + // --- Getting x,y,z + float xyz; + try { + xyz = Float.parseFloat(st.nextToken()); + atom.xyz[0] = xyz; + xyz = Float.parseFloat(st.nextToken()); + atom.xyz[1] = xyz; + xyz = Float.parseFloat(st.nextToken()); + atom.xyz[2] = xyz; + } catch (Exception ex) { + throw new Exception( + "parseMolecularGeometryOnly: ERROR: Error while parsing atom: " + + (atoms.size() + 1) + " Cannot parse atom's coordinate(s): " + line); + } + + atoms.add(atom); + } + } catch (Exception ex) { + throw new Exception("parseMolecularGeometryOnly: ERROR: " + ex.getMessage()); + } + + return atoms; + } + + public void extractG09TrajectoryFromLog(String fileName) throws Exception { + extractG09TrajectoryFromLog(fileName, null); + } + + public void extractG09TrajectoryFromLog(String fileName, JobProgressInterface progress) throws Exception { + //BufferedReader in = null; + RandomAccessFile in = null; + double numberOfAtoms = (double) super.getNumberOfAtoms(); + try { + //in = new BufferedReader(new FileReader(fileName)); + in = new RandomAccessFile(fileName, "r"); + } catch (Exception ex) { + throw new Exception("Cannot open file " + fileName + " : " + ex.getMessage()); + } + // --- + double fileLength = 0, pointer; + long lineNumber = 0; + long timeCurrent = 0; + long timeInterval = 5000l; + if (progress != null) { + progress.setProgress(0); + progress.setTaskDescription("Parsing G09 Trajectory Data..."); + fileLength = in.length(); + timeCurrent = System.currentTimeMillis(); + } + + // --- + String line=null; + boolean trajBlockFound = false; + try { + while ((line = in.readLine()) != null) { + ++lineNumber; + // --- Progress + if (progress != null) { + if (System.currentTimeMillis() - timeCurrent >= timeInterval) { + pointer = in.getFilePointer(); + progress.setProgress(pointer / fileLength * 100.0); + timeCurrent = System.currentTimeMillis(); + } + } + // --- + if (line.startsWith(TRJ_BLOCK_MARK)) { + trajBlockFound = !trajBlockFound; + continue; + } + if (!trajBlockFound) { + continue; + } + // --- Read in TRJ blocks + if (line.startsWith(" ---------------")) { // Read MD run paramaters + System.out.println("\nReading in MD parameters block\n"); + while ((line = in.readLine()) != null) { + ++lineNumber; + try { + if (line.startsWith(TRJ_BLOCK_MARK)) { + trajBlockFound = false; + break; + } + System.out.println(line); + // --- Parse MD parameters + //if (line.startsWith(TIME_STEP_KEY)) { + // int index = line.indexOf("="); + // String numberStr = line.substring(index + 1).trim(); + // numberStr = numberStr.substring(0, numberStr.indexOf(" ")).trim(); + // timeStep = Double.parseDouble(numberStr); + // this.addData(TIME_STEP_KEY.trim(), timeStep); + //} + } catch (Exception ex) { + System.err.println("Something wrong with a line: " + line); + } + } + // --------------- + } else if (line.trim().length() < 1) { // Blank line - probably admp step + TrajectorySnapshot snapshot = new TrajectorySnapshot(); + snapshot.setReferenceTrajectory(this); + int step = 0; + double time = 0; + double EKinC = 0, EKinPA = 0, EKinPB = 0, EKin = 0, EPot = 0, ETot = 0; + String numStr; + int index; + while ((line = in.readLine()) != null) { // Skip until "Summary information for step" + ++lineNumber; + if (line.startsWith(ADMP_STEP_INFO_KEY)) { + index = line.indexOf(ADMP_STEP_INFO_KEY) + ADMP_STEP_INFO_KEY.length(); + step = Integer.parseInt(line.substring(index).trim()); + snapshot.addProperty(ADMP_STEP_INFO_KEY, step); + this.addData(MD_STEP_KEY, step); + break; + } + } + // -- go through MD step info + + while ((line = in.readLine()) != null) { + ++lineNumber; + if (line.startsWith(CARTESIAN_COORD_KEY)) { + break; + } + try { + if (line.startsWith(TOTAL_TIME_FS_KEY)) { + index = line.indexOf(TOTAL_TIME_FS_KEY) + TOTAL_TIME_FS_KEY.length(); + time = Double.parseDouble(line.substring(index).trim()); + snapshot.addProperty(TOTAL_TIME_FS_KEY, time); + this.addData(TOTAL_TIME_FS_KEY.trim(), time); + continue; + } + // --- + if (line.contains(EKinC_KEY)) { + numStr = getNumberString(line, EKinC_KEY); + EKinC = Double.parseDouble(numStr); + snapshot.addProperty(EKinNucler_KEY, EKinC); + this.addData(EKinNucler_KEY, EKinC); + } + if (line.contains(EKinPA_KEY)) { + numStr = getNumberString(line, EKinPA_KEY); + EKinPA = Double.parseDouble(numStr); + snapshot.addProperty(EKinPA_KEY, EKinPA); + this.addData(EKinPA_KEY, EKinPA); + } + if (line.contains(EKinPB_KEY)) { + numStr = getNumberString(line, EKinPB_KEY); + EKinPB = Double.parseDouble(numStr); + snapshot.addProperty(EKinPB_KEY, EKinPB); + this.addData(EKinPB_KEY, EKinPB); + // --- Sum up A and B electronic kinetic energies + snapshot.addProperty(EKinElectronic_KEY, EKinPA + EKinPB); + this.addData(EKinElectronic_KEY, EKinPA + EKinPB); + } + if (line.contains(EKin_PATTERN)) { + numStr = getNumberString(line, EKin_KEY); + EKin = Double.parseDouble(numStr); + snapshot.addProperty(EKinTotal_KEY, EKin); + this.addData(EKinTotal_KEY, EKin); + // --- Derive temperature from Ekin + double Temp = 210535.14511 * EKin / numberOfAtoms; + snapshot.addProperty(Temperature_KEY, Temp); + this.addData(Temperature_KEY, Temp); + } + if (line.contains(EPot_PATTERN)) { + numStr = getNumberString(line, EPot_KEY); + EPot = Double.parseDouble(numStr); + snapshot.addProperty(EPotential_KEY, EPot); + this.addData(EPotential_KEY, EPot); + } + if (line.contains(ETot_PATTERN)) { + numStr = getNumberString(line, ETot_KEY); + ETot = Double.parseDouble(numStr); + snapshot.addProperty(ETotal_KEY, ETot); + this.addData(ETotal_KEY, ETot); + } + } catch (Exception ex) { + System.err.println("Something was wrong with parsing MD step info in line: " + line + " :" + ex.getMessage()); + } + } + // -- Start to read cartesin coordinates + if (!line.startsWith(CARTESIAN_COORD_KEY)) { + System.err.println("Was expecting cartesian coordinates, got: " + line); + break; + } + snapshot.setOffset(in.getFilePointer()); + float coords[][] = null; + if (this.getNumberOfAtoms() == 0) { // Probably reference structure was not set... + // I= 21 X= 8.508244543715D-02 Y= 8.112008191149D-02 Z= 3.006460701532D-02 + // MW Cartesian velocity: + ArrayList coordList = new ArrayList(); + while ((line = in.readLine()) != null) { + ++lineNumber; + if (!line.startsWith(" I=")) { + this.setNumberOfAtoms(coordList.size()); + coords = new float[getNumberOfAtoms()][3]; + for (int i = 0; i < getNumberOfAtoms(); i++) { + coords[i][0] = coordList.get(i)[0]; + coords[i][1] = coordList.get(i)[1]; + coords[i][2] = coordList.get(i)[2]; + } + break; + } + float[] coord = new float[3]; + numStr = getNumberString(line, "X"); + coord[0] = (float) (factor * Double.parseDouble(numStr)); + numStr = getNumberString(line, "Y"); + coord[1] = (float) (factor * Double.parseDouble(numStr)); + numStr = getNumberString(line, "Z"); + coord[2] = (float) (factor * Double.parseDouble(numStr)); + coordList.add(coord); + } + } else { + coords = new float[getNumberOfAtoms()][3]; + for (int i = 0; i < getNumberOfAtoms(); i++) { + if ((line = in.readLine()) == null) { + ++lineNumber; + System.err.println("Eof while reading in cartesian coordinates from a trajectory"); + break; + } + numStr = getNumberString(line, "X"); + coords[i][0] = (float) (factor * Double.parseDouble(numStr)); + numStr = getNumberString(line, "Y"); + coords[i][1] = (float) (factor * Double.parseDouble(numStr)); + numStr = getNumberString(line, "Z"); + coords[i][2] = (float) (factor * Double.parseDouble(numStr)); + } + } + + snapshot.setCoordinates(coords); + this.addSnapshot(snapshot); + + // --- Now just read in until the end of TRJ block + while ((line = in.readLine()) != null) { + ++lineNumber; + if (line.startsWith(TRJ_BLOCK_MARK)) { + trajBlockFound = false; + break; + } + } + // --- + if (progress != null && progress.isCanceled() ) { + logger.warning("MD Trajectory loading was cancelled by user"); + break; + } + } + } + } catch (Exception ex) { + throw new Exception("Error in line "+lineNumber+"\nLine: "+line+"\nError: "+ex.getMessage()); + } + + logger.info("Found " + this.getSnapshotsCount() + " snapshots"); + //if (logger.isLoggable(Level.INFO)) { + // this.printDataSets(); + //} + } + + /** + * + * @param line - input string + * @param keyWord - keyword for numerical value, for example, XXX + * @return number as a string, i.e. it expects input .... XXX = number ... and will return a "number" + * @throws Exception + */ + public static String getNumberString(String line, String keyWord) throws Exception { + String temp = line.substring(line.indexOf(keyWord) + keyWord.length()); + temp = temp.substring(temp.indexOf("=") + 1).trim(); + if (temp.indexOf(" ") != -1) { + temp = fixNumberString(temp.substring(0, temp.indexOf(" "))); + } else { + temp = fixNumberString(temp); + } + if (temp.contains(";")) { + temp = temp.replaceAll(";", ""); + } + return temp; + } + + public static String fixNumberString(String numStr) { + if (numStr == null) { + logger.warning("numStr is null. Ignored..."); + return numStr; + } + return numStr.replaceFirst("(D|d)", "E"); + } + + public static String fixAllNumbers(String numStr) { + return numStr.replaceAll("(D|d)", "E"); + } + + public void parseG03Trajectory(String fileName) throws Exception { + parseG03Trajectory(fileName, null); + } + + public void parseG03Trajectory(String fileName, JobProgressInterface progress) throws Exception { + if (fileName == null || fileName.length() < 1) { + throw new Exception("Trajectory file name is not set"); + } + if (fileName.toUpperCase().matches("*.[.](LOG|OUT)$")) { + extractG09TrajectoryFromLog(fileName, progress); + return; + } + /* + Time in trajectory (femtosec) 2.000000D-01 + Total energy (au) -1.175171068D+02 + Total angular momentum (h-bar) 2.904529344D-14 + Coordinates (Bohr) + I= 1 X= -4.555420059248D-01 Y= -5.134698398949D-01 Z= -7.216904569806D-01 + I= 2 X= -2.221805396142D+00 Y= -1.254178689967D+00 Z= -2.596959873079D-02 + I= 3 X= -5.952104662883D-01 Y= 1.532677098577D+00 Z= -8.366401222195D-01 + */ + + String line; + long offset; + RandomAccessFile raf = null; + + try { + File f = new File(fileName); + raf = new RandomAccessFile(f, "r"); + + gAtoms = parseMolecularGeometryOnly(raf); + if (gAtoms.size() < 0) { + throw new Exception("Didn't find atoms in file"); + } + + /* + Time in trajectory (femtosec) 2.000000D-01 + Total energy (au) -1.175171068D+02 + Total angular momentum (h-bar) 2.904529344D-14 + Coordinates (Bohr) + I= 1 X= -4.555420059248D-01 Y= -5.134698398949D-01 Z= -7.216904569806D-01 + I= 2 X= -2.221805396142D+00 Y= -1.254178689967D+00 Z= -2.596959873079D-02 + */ + while ((line = raf.readLine()) != null) { + if (line.contains("Time in trajectory ")) { + + //GaussianSnapshot snapshot = new GaussianSnapshot(); + TrajectorySnapshot snapshot = new TrajectorySnapshot(); + + // Add absolute time + double value; + String token = ""; + /* + try { + value = Double.parseDouble(line.substring(30, line.length() - 1).trim()); + snapshot.addProperty("Time in trajectory (femtosec)", value); + } + catch (Exception ex) { + } + */ + + // parsing Total energy (au) -1.175171068D+02 + if ((line = raf.readLine()) == null) { + break; + } + + try { + token = line.substring(18).trim().replaceAll("[D]", "E").replaceAll("[d]", "E"); + value = Double.parseDouble(token); + snapshot.addProperty(TOTAL_ENERGY_KEY, value); + addDescriptor(TOTAL_ENERGY_KEY); + } catch (Exception ex) { + System.err.println("Cannot parse total energy: " + ex.getMessage() + " got: " + token); + } + + // Total angular momentum (h-bar) 1.155222129D-13 + if ((line = raf.readLine()) == null) { + break; + } + try { + token = line.substring(31).trim().replaceAll("[D]", "E").replaceAll("[d]", "E"); + value = Double.parseDouble(token); + snapshot.addProperty("Total angular momentum (h-bar)", value); + addDescriptor("Total angular momentum (h-bar)"); + } catch (Exception ex) { + System.err.println("Cannot parse angular momentum: " + ex.getMessage() + " got: " + token); + } + + // --- Coordinates (Bohr) + if ((line = raf.readLine()) == null) { + break; + } + + if (!line.contains("Bohr")) { + factor = 1.0; + } + + offset = raf.getFilePointer(); + snapshot.setOffset(offset); + + MolecularGeometry geom = new MolecularGeometry(); + geom.setName(STANDARD_GEOMETRY_KEY); + + // ---Read atomic coordinates + for (int i = 0; i < gAtoms.size(); i++) { + if ((line = raf.readLine()) == null) { + break; + } + Point3f point = new Point3f(); + String buffer = line.replaceAll("[D]", "E").replaceAll("[d]", "E"); + point.setX((float) (factor * Double.parseDouble(buffer.substring(11, 32).trim()))); + point.setY((float) (factor * Double.parseDouble(buffer.substring(35, 56).trim()))); + point.setZ((float) (factor * Double.parseDouble(buffer.substring(59, 80).trim()))); + geom.addCoordinates(point); + } + + if (line != null) { + //snapshot.addGeometry(STANDARD_GEOMETRY_KEY, geom); + snapshot.setCoordinates(geom); + this.addSnapshot(snapshot); + } + } + + if (line == null) { + break; + } + + } + + } catch (Exception e) { + } + + try { + raf.seek(0); + raf.close(); + } catch (Exception e) { + } + + logger.info("Found " + this.getSnapshotsCount() + " snapshots"); + } + + public float isThisFormat(String filename) throws Exception { + + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(filename)); + } catch (Exception e) { + throw new Exception("Error opening file " + filename + " : " + e.getMessage()); + } + + float score = isThisFormat(in); + + try { + in.close(); + } catch (Exception ex) { + } + + return score; + } + + public float isThisFormat(BufferedReader in) throws Exception { + float score = 0; + String line; + + while ((line = in.readLine()) != null) { + + if (score >= 1.0) { + score = 1.0f; + return score; + } + + // --- MD info + if (line.contains("TRJ-TRJ-TRJ-TRJ-TRJ-TRJ-TRJ ")) { + score += 0.25; + continue; + } + + if (line.contains("Summary information for step")) { + score += 0.25; + continue; + } + + if (line.contains("EKinC =")) { + score += 0.25; + continue; + } + + if (line.contains("I= 1 X=")) { + score += 0.25; + continue; + } + // --- + if (score >= 1.0) { + score = 1.0f; + return score; + } + } + + return score; + } + + public double[] getAllTerms(String term) { + if (!this.hasDescriptor(term) || this.getSnapshotsCount() < 1) { + return null; + } + + List references = new ArrayList(getSnapshotsCount()); + List values = new ArrayList(getSnapshotsCount()); + for (int i = 0; i < getSnapshotsCount(); i++) { + //GaussianSnapshot snapshot = snapshots.get(i); + TrajectorySnapshot snapshot = this.getSnapshot(i); + try { + //Double value = snapshot.getProperty(term); + Double value = snapshot.getPropertyAsDouble(term); + values.add(value); + references.add(new Integer(i)); + } catch (Exception ex) { + } + } + if (values.size() < 1) { + return null; + } + double[] energies = new double[values.size()]; + for (int i = 0; i < values.size(); i++) { + energies[i] = values.get(i); + } + return energies; + } + + public String getOriginalFileName() { + return originalFileName; + } + + @Override + public float[][] getStructure(int n) { + return getStructure(n, G03MDTrajectory.TOTAL_ENERGY_KEY); + } + + @Override + public float[][] getStructure(int n, String term) { + if (!this.hasDescriptor(term) || this.getSnapshotsCount() < 1) { + return null; + } + + if (getSnapshotsCount() < 1) { + return null; + } + + if (debug) { + logger.info("getStructure: # " + n); + } + + //GaussianSnapshot snapshot = snapshots.get(n); + //MolecularGeometry geom = snapshot.getGeometry(STANDARD_GEOMETRY_KEY); + TrajectorySnapshot snapshot = this.getSnapshot(n); + float[][] coords = snapshot.getCoordinates(); + + //if (geom == null || geom.size() < 1) { + // System.err.println(this.getClass().getCanonicalName() + " : no atoms in selected snapshot"); + // return null; + //} + //float[][] coords = new float[geom.size()][3]; + //for (int i = 0; i < geom.size(); i++) { + // Point3f c = geom.getCoordinates(i); + // coords[i][0] = c.getX(); + // coords[i][1] = c.getY(); + // coords[i][2] = c.getZ(); + // if (debug && i == geom.size() - 1) { + // logger.info(i + " : x=" + coords[i][0] + " y=" + coords[i][1] + " z=" + coords[i][2]); + // } + //} + return coords; + } + + /** + * Not implemented yet... + * + * @param number int + * @throws Exception + */ + @Override + public void selectStructure(int number) throws Exception { + throw new Exception(this.getClass().getCanonicalName() + ": selectStructure(int number) is not implemented yet"); + } + + /** + * Not implemented yet... + * + * @param number int + * @param term String + * @throws Exception + */ + @Override + public void selectStructure(int number, String term) throws Exception { + throw new Exception(this.getClass().getCanonicalName() + ": selectStructure(int number, String term) is not implemented yet"); + } + + // ------------------------------------------------- + // --- Implementation of ChartDataProvider interface + public double[] cdpGetDataAsDouble(String descriptor) { + return this.getDataAsDouble(descriptor); + } + + public float[] cdpGetDataAsFloat(String descriptor) { + return this.getDataAsFloat(descriptor); + } + + public int[] cdpGetDataAsInteger(String descriptor) { + return this.getDataAsInteger(descriptor); + } + + public String[] cdpGetDataAsString(String descriptor) { + return this.getDataAsString(descriptor); + } + + public Object[] cdpGetDataAsObject(String descriptor) { + return this.getDataAsObject(descriptor); + } + + public String cdpGetDescription() { + return "Gaussian 09 MD file"; + } + + public Set cdpGetDescriptors() { + return this.getDescriptors(); + } + + public void cdpParseData(String filename) throws Exception { + this.parseTrajectoryFile(filename); + } + + /** + * Checks format and returns score (0 to 1 range) + * + * @param filename + * @return 0 - wrong format, 1 - for sure it's this format + * @throws Exception + */ + public float cdpIsThisFormat(String filename) throws Exception { + return isThisFormat(filename); + } +} diff --git a/src/main/java/cct/gaussian/GJFParserInterface.java b/src/main/java/cct/gaussian/GJFParserInterface.java new file mode 100644 index 0000000..39f1fc8 --- /dev/null +++ b/src/main/java/cct/gaussian/GJFParserInterface.java @@ -0,0 +1,74 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian; + +import java.util.List; + +/** + *

Title: Gaussian Utility Classes

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface GJFParserInterface { + int parseGJF(String filename, int fileType); + + List getLinkZeroCommands(int step); + + String getRouteSection(int step); + + String getTitleSection(int step); + + String getChargeSection(int step); + + String getMoleculeSpecsSection(int step); + + void removeAllEntries(); + + void validateLink0Section(String link0Specs) throws Exception; + + List validateMolecularGeometry(String molSpecs) throws Exception; + + int getNumberOfSteps(); +} diff --git a/src/main/java/cct/gaussian/Gaussian.java b/src/main/java/cct/gaussian/Gaussian.java new file mode 100644 index 0000000..ca44c19 --- /dev/null +++ b/src/main/java/cct/gaussian/Gaussian.java @@ -0,0 +1,1252 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.gaussian; + +import cct.GlobalSettings; +import cct.cprocessor.CommandInterface; +import cct.cprocessor.Variable; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.OutputStream; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.GraphicsRendererInterface; +import cct.interfaces.MoleculeEventObject; +import cct.interfaces.MoleculeInterface; +import cct.modelling.CCTAtomTypes; +import cct.modelling.ChemicalElements; +import cct.modelling.GeneralMolecularDataParser; +import cct.modelling.Molecule; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.Writer; +import java.util.logging.Level; +import javax.swing.JOptionPane; + +/** + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2004

+ * + *

+ * Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class Gaussian extends GeneralMolecularDataParser implements GJFParserInterface, CommandInterface { + + static boolean Debug = true; + public static final String MEMORY_TEMPLATE = "@@MEMORY@@"; + public static final String NCPUS_TEMPLATE = "@@NCPUS@@"; + public static final String OPT_TEMPLATE = "@@OPT@@"; + public static final String FREQ_TEMPLATE = "@@FREQ@@"; + public static final String METHOD_TEMPLATE = "@@METHOD@@"; + public static final String BASIS_TEMPLATE = "@@BASIS@@"; + public static final String COORDINATES_TEMPLATE = "@@COORDINATES@@"; + public static final String CHARGE_TEMPLATE = "@@CHARGE@@"; + public static final String MULTIPLICITY_TEMPLATE = "@@MULTIPLICITY@@"; + public static final String TITLE_TEMPLATE = "@@TITLE@@"; + // + public static final String ATOM_FIXED_PROPERTY = "GAUSSIAN_ATOM_FIXED"; + public static final String FRAGMENT_PROPERTY = "GAUSSIAN_FRAGMENT"; + // + public final float DEGREES_TO_RADIANS = (float) (Math.PI / 180.0); + protected List percentSection = new ArrayList(); + protected List Molecules = new ArrayList(); + private String Tokens[] = new String[10]; + String Message = null; + GraphicsRendererInterface renderer = null; + static final Logger logger = Logger.getLogger(Gaussian.class.getCanonicalName()); + public final static String LINK_ZERO_COMMANDS_KEY = "GaussianLinkZeroCommand"; + public final static String ROUTE_COMMANDS_KEY = "GaussianRouteCommand"; + public final static String MOLEC_SPECS_KEY = "GaussianMoleculeSpec"; + public final static String NUMBER_OF_ATOMS_KEY = "GaussianNumberOfAtoms"; + final static String link0_MEM = "%MEM"; + final static String link0_CHK = "%CHK"; + final static String link0_RWF = "%RWF"; + final static String link0_INT = "%INT"; + final static String link0_D2E = "%D2E"; + final static String link0_NPROC = "%NPROC"; + final static String link0_KJOB = "%KJOB"; // %KJob LN [M] + final static String link0_NPROCSHARED = "%NPROCSHARED"; + final static String link0_SAVE = "%SAVE"; + final static String link0_NOSAVE = "%NOSAVE"; + final static String link0_SUBST = "%SUBST"; + final static String link0_NPROCLINDA = "%NPROCLINDA"; + final static String link0_LINDAWORKERS = "%LINDAWORKERS"; + // Integer - number of arguments + static final Map link0Commands = new HashMap(); + + static { + link0Commands.put(link0_MEM, new Integer(1)); + link0Commands.put(link0_CHK, new Integer(1)); + link0Commands.put(link0_RWF, new Integer(1)); + link0Commands.put(link0_INT, new Integer(1)); + link0Commands.put(link0_D2E, new Integer(1)); + link0Commands.put(link0_KJOB, new Integer(-2)); // Up to 2 parameters + link0Commands.put(link0_NPROCSHARED, new Integer(1)); + link0Commands.put(link0_NPROC, new Integer(1)); + link0Commands.put(link0_SAVE, new Integer(0)); + link0Commands.put(link0_NOSAVE, new Integer(0)); + link0Commands.put(link0_SUBST, new Integer(2)); + link0Commands.put(link0_NPROCLINDA, new Integer(1)); + link0Commands.put(link0_LINDAWORKERS, new Integer(1)); + } + + public Gaussian() { + } + + static public void setLoggerLevel(Level level) { + logger.setLevel(level); + GaussianMolecule.setLoggerLevel(level); + } + + private void addGaussianMolecule(GaussianMolecule gmol) { + Molecules.add(gmol); + + MoleculeInterface mol = getMoleculeInterface(); + gmol.getMolecule(mol); + if (mol.getNumberOfAtoms() < 1) { + return; + } + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol); + this.addMolecule(mol); + } + + public int getNumberOfMolecules() { + return Molecules.size(); + } + + @Override + public int getNumberOfSteps() { + return getNumberOfMolecules(); + } + + public void setGraphicsRenderer(GraphicsRendererInterface r) { + renderer = r; + } + + void resetTokens() { + for (int i = 0; i < Tokens.length; i++) { + Tokens[i] = null; + } + } + + int numberOfTokens() { + int i; + for (i = 0; i < Tokens.length && Tokens[i] != null; i++) { + } + return i; + } + + public String getErrorMessage() { + return Message; + } + + public int validFormatScore(BufferedReader in) throws Exception { + Gaussian g = new Gaussian(); + try { + g.parseData(in); + } catch (Exception ex) { + return 0; + } + if (g.getMolecule() == null || g.getMolecule().getNumberOfAtoms() < 1) { + return 0; + } + return 10; + } + + public void parseData(BufferedReader in) throws Exception { + String line; + GaussianMolecule Atoms = new GaussianMolecule(); + boolean z_matrix = false; + + try { + + while ((line = in.readLine()) != null) { + logger.info("Parsing: " + line + "\n"); + line = line.trim(); + + if (line.startsWith("#") || line.startsWith("%") || line.startsWith("--Link1--")) { + Atoms = new GaussianMolecule(); + + // --- Skip line if it's a Link 1 section + if (line.startsWith("--Link1--")) { + if ((line = in.readLine()) == null) { + String msg = "Unexpected end-of-file after reading Link 1 section"; + logger.severe(msg); + //throw new Exception(msg); + break; + } + line = line.trim(); + } + + // --- Read Link 0 Commands (% lines) + if (line.startsWith("%")) { + try { + Atoms.addLinkZeroCommands(line); + } catch (Exception ex) { + Message += ex.getMessage() + "\n"; + } + while ((line = in.readLine()) != null) { + logger.info("Parsing %%% section: " + line); + line = line.trim(); + if (line.startsWith("#")) { + break; + } + try { + Atoms.addLinkZeroCommands(line); + } catch (Exception ex) { + Message += ex.getMessage() + "\n"; + } + + } + } + + // --- Read Route section (# lines) + if (line.startsWith("#")) { + logger.info("Parsing route: " + line); + Atoms.addRouteOptions(line); + while ((line = in.readLine()) != null) { + logger.info("Parsing route: " + line); + line = line.trim(); + if (line.length() == 0) { + break; + } + Atoms.addRouteOptions(line); + } + Atoms.parseRouteOptions(); + } + + // --- Read in title section + if (Atoms.routeSection.isSkipTitleSection()) { + continue; + } + + boolean not_first_comment_line = false; + while ((line = in.readLine()) != null) { + logger.info("Parsing title: " + line + "\n"); + line = line.trim(); + if (line.length() == 0 && not_first_comment_line) { + break; + } + not_first_comment_line = true; + Atoms.titleSection.add(line); + } + + // --- Read in charge and spin multiplicity section + if (Atoms.routeSection.isSkipChargeSection()) { + continue; + } + + if ((line = in.readLine()) != null) { + logger.info("Parsing: " + line + "\n"); + int[] ch = null; + try { + ch = Atoms.parseChargeSection(line); + Atoms.setChargeAndMultiplicity(ch); + } catch (Exception ex) { + String msg = "Error parsing line: " + line + " : " + ex.getMessage(); + logger.severe(msg); + //throw new Exception(msg); + return; + } + Atoms.chargeSection.add(line); + } else { + String msg = "Unexpected end of file while reading charge section"; + logger.severe(msg); + //return Molecules.size(); !!! + return; + } + + if (Atoms.routeSection.isSkipMoleculeSpecification()) { + continue; + } + + // Read molecule + z_matrix = false; + //Atoms = new AtomParamArray(); + + while ((line = in.readLine()) != null) { + logger.info("Reading line: " + line); + if (line.equalsIgnoreCase("--Link1--")) { + break; + } + Atoms.addMoleculeSpecsItem(line); + } // End of while + + try { + Atoms.parseMoleculeGeometry(); + } catch (Exception ex) { + logger.warning("Error Parsing Molecular Specifications: " + ex.getMessage()); + } + + logger.info("Number of Atoms: " + Atoms.size() + "\n"); + + } + + if (Atoms.size() > 0) { + //if (z_matrix) { + // Atoms.cartesians = fromInternalToCartesians(Atoms); + //} + + //Molecules.add(Atoms); + addGaussianMolecule(Atoms); + } + + } // --- End of while + + //in.close(); + } catch (Exception e) { + logger.warning("Error: " + e.getMessage()); + //return Molecules.size(); + return; + } + + logger.info("parseGJF: Number of molecules: " + Molecules.size() + "\n"); + //return Molecules.size(); + return; + } + + /** + * Parses Gaussian Job File (gjf). + * + * @param filename String File name or String bufer (see fileType argument) + * @param fileType int File type, 0 - read from the file filename, 1 - filename is a String bufer + * @return int Returns number of molecules. -1 otherwise (use getErrorMessage() to get error description) + */ + @Override + public int parseGJF(String filename, int fileType) { + String line; + GaussianMolecule Atoms = new GaussianMolecule(); + boolean z_matrix = false; + + BufferedReader in = null; + + if (fileType == 0) { // Read from file + try { + in = new BufferedReader(new FileReader(filename)); + } catch (java.io.FileNotFoundException e) { + Message = e.getMessage(); + return -1; + } catch (IOException ex) { + Logger.getLogger(Gaussian.class.getName()).log(Level.SEVERE, null, ex); + } + } else if (fileType == 1) { // Read from String + in = new BufferedReader(new StringReader(filename)); + } else { + Message = "Unknown file type"; + return -1; // Error + } + + try { + //BufferedReader in = new BufferedReader(new FileReader(filename)); + + while ((line = in.readLine()) != null) { + if (Debug) { + logger.info("Parsing: " + line + "\n"); + } + line = line.trim(); + + if (line.startsWith("#") || line.startsWith("%") + || line.startsWith("--Link1--")) { + Atoms = new GaussianMolecule(); + + // --- Skip line if it's a Link 1 section + if (line.startsWith("--Link1--")) { + if ((line = in.readLine()) == null) { + System.err.println( + "Unexpected end-of-file after reading Link 1 section"); + break; + } + line = line.trim(); + } + + // --- Read Link 0 Commands (% lines) + if (line.startsWith("%")) { + try { + Atoms.addLinkZeroCommands(line); + } catch (Exception ex) { + Message += ex.getMessage() + "\n"; + } + while ((line = in.readLine()) != null) { + if (Debug) { + logger.info("Parsing %%% section: " + line); + } + line = line.trim(); + if (line.startsWith("#")) { + break; + } + try { + Atoms.addLinkZeroCommands(line); + } catch (Exception ex) { + Message += ex.getMessage() + "\n"; + } + + } + } + + // --- Read Route section (# lines) + if (line.startsWith("#")) { + if (Debug) { + logger.info("Parsing route: " + line); + } + Atoms.addRouteOptions(line); + while ((line = in.readLine()) != null) { + if (Debug) { + logger.info("Parsing route: " + line); + } + line = line.trim(); + if (line.length() == 0) { + break; + } + Atoms.addRouteOptions(line); + } + Atoms.parseRouteOptions(); + } + + // --- Read in title section + if (Atoms.routeSection.isSkipTitleSection()) { + continue; + } + + boolean not_first_comment_line = false; + while ((line = in.readLine()) != null) { + if (Debug) { + logger.info("Parsing title: " + line + "\n"); + } + line = line.trim(); + if (line.length() == 0 && not_first_comment_line) { + break; + } + not_first_comment_line = true; + Atoms.titleSection.add(line); + } + + // --- Read in charge and spin multiplicity section + if (Atoms.routeSection.isSkipChargeSection()) { + continue; + } + + if ((line = in.readLine()) != null) { + if (Debug) { + logger.info("Parsing: " + line + "\n"); + } + int[] ch = null; + try { + ch = Atoms.parseChargeSection(line); + Atoms.setChargeAndMultiplicity(ch); + } catch (Exception ex) { + System.err.println("ERROR: parseGJF " + ex.getMessage()); + return -1; + } + Atoms.chargeSection.add(line); + } else { + System.err.println( + "parseGJF: Unexpected end of file while reading charge section\n"); + return Molecules.size(); + } + + if (Atoms.routeSection.isSkipMoleculeSpecification()) { + continue; + } + + // Read molecule + z_matrix = false; + //Atoms = new AtomParamArray(); + + while ((line = in.readLine()) != null) { + if (Debug) { + logger.info("Reading line: " + line); + } + if (line.equalsIgnoreCase("--Link1--")) { + break; + } + //line = line.trim(); //.toUpperCase(); + Atoms.addMoleculeSpecsItem(line); + } // End of while + + try { + Atoms.parseMoleculeGeometry(); + } catch (Exception ex) { + System.err.println( + "Error Parsing Molecular Specifications: " + ex.getMessage()); + } + + if (Debug) { + logger.info("Number of Atoms: " + Atoms.size() + "\n"); + } + + } + + if (Atoms.size() > 0) { + //if (z_matrix) { + // Atoms.cartesians = fromInternalToCartesians(Atoms); + //} + + //Molecules.add(Atoms); + addGaussianMolecule(Atoms); + } + + } // --- End of while + + in.close(); + + } catch (IOException e) { + System.err.println("parseGJF: " + e.getMessage() + "\n"); + return Molecules.size(); + } + + if (Debug) { + logger.info("parseGJF: Number of molecules: " + Molecules.size() + "\n"); + } + return Molecules.size(); + } + + public MoleculeInterface getMolecule(MoleculeInterface mol, int n) { + + if (n < 0 || n >= Molecules.size()) { + return null; + } + + //Molecule mol = new Molecule(); + GaussianMolecule molecule = Molecules.get(n); + molecule.getMolecule(mol); + return mol; + } + + public GaussianMolecule getGaussianMolecule(int n) { + + if (n < 0 || n >= Molecules.size()) { + return null; + } + + return Molecules.get(n); + } + + public boolean setMolecule(MoleculeInterface mol, int index) { + if (index < 0 || index > Molecules.size()) { + System.err.println("setMolecule: index < 0 || index > Molecules.size()"); + return false; // unable to add molecule + } else if (mol == null || mol.getNumberOfAtoms() == 0) { + System.err.println("mol == null || mol.getNumberOfAtoms() == 0"); + return false; // unable to add molecule + } + + GaussianMolecule Atoms; + if (index == Molecules.size()) { // Add new molecule at the end + Atoms = new GaussianMolecule(); + //Molecules.add(Atoms); + addGaussianMolecule(Atoms); + percentSection.add(null); + } else { + Atoms = Molecules.get(index); + Atoms.clear(); + } + Atoms.ensureCapacity(mol.getNumberOfAtoms()); + + for (int i = 0; i < mol.getNumberOfAtoms(); i++) { + AtomInterface at = mol.getAtomInterface(i); + GaussianAtom gat = new GaussianAtom(at); + Atoms.add(gat); + } + return true; + } + + @Override + public List getLinkZeroCommands(int step) { + if (step < 0 || step >= Molecules.size()) { + return null; + } + GaussianMolecule molecule = Molecules.get(step); + return molecule.getLinkZeroCommands(); + } + + public String getRouteSection(int step) { + if (step < 0 || step >= Molecules.size()) { + return ""; + } + GaussianMolecule molecule = Molecules.get(step); + GaussianKeywords gk = molecule.getRouteSection(); + return gk.getOptions(); + } + + public String getTitleSection(int step) { + if (step < 0 || step >= Molecules.size()) { + return ""; + } + GaussianMolecule molecule = Molecules.get(step); + List buff = molecule.getTitleSection(); + String title = ""; + for (int i = 0; i < buff.size(); i++) { + title += (String) buff.get(i); + if (!title.endsWith("\n")) { + title += "\n"; + } + } + return title; + } + + public String getChargeSection(int step) { + if (step < 0 || step >= Molecules.size()) { + return ""; + } + GaussianMolecule molecule = Molecules.get(step); + List buff = molecule.getChargeSection(); + String title = ""; + for (int i = 0; i < buff.size(); i++) { + title += (String) buff.get(i); + //if ( !title.endsWith("\n") ) title += "\n"; + } + return title; + } + + public String getMoleculeSpecsSection(int step) { + if (step < 0 || step >= Molecules.size()) { + return ""; + } + GaussianMolecule molecule = Molecules.get(step); + /* + ArrayList buff = molecule.getMoleculeSpecsSection(); + String title = ""; + for (int i = 0; i < buff.size(); i++) { + title += (String) buff.get(i); + if (!title.endsWith("\n")) { + title += "\n"; + } + } + */ + //return title; + return molecule.getMoleculeSpecsSectionAsString(); + } + + public List getMoleculeSpecs(int step) { + if (step < 0 || step >= Molecules.size()) { + return null; + } + GaussianMolecule molecule = Molecules.get(step); + /* + ArrayList buff = molecule.getMoleculeSpecsSection(); + String title = ""; + for (int i = 0; i < buff.size(); i++) { + title += (String) buff.get(i); + if (!title.endsWith("\n")) { + title += "\n"; + } + } + */ + //return title; + return molecule.getMoleculeSpecsSection(); + } + + public void removeAllEntries() { + Molecules.clear(); + } + + public List validateMolecularGeometry(String molSpecs) throws + Exception { + List atoms = null; + try { + GaussianMolecule gmol = new GaussianMolecule(); + atoms = gmol.parseMoleculeGeometry(molSpecs); + } catch (Exception ex) { + throw new Exception("Validating Molecular Geometry: " + ex.getMessage()); + } + + if (atoms.size() > 0 && renderer != null) { + MoleculeInterface m = new Molecule(); + for (int i = 0; i < atoms.size(); i++) { + AtomInterface atom = m.getNewAtomInstance(); + GaussianAtom a = (GaussianAtom) atoms.get(i); + atom.setAtomicNumber(a.element); + atom.setName(a.name); + atom.setX(a.xyz[0]); + atom.setY(a.xyz[1]); + atom.setZ(a.xyz[2]); + atom.setSubstructureNumber(0); + m.addAtom(atom); + + } + Molecule.guessCovalentBonds(m); + renderer.renderMolecule(m); + } + return atoms; + } + + /** + * Returns molecule specifications (coordinates) as a String + * + * @param molecule MoleculeInterface + * @return String + * @throws Exception + */ + public static String getMoleculeSpecsAsString(MoleculeInterface molecule) throws + Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + if (molecule == null || molecule.getNumberOfAtoms() == 0) { + return ""; + } + try { + writeMoleculeSpecs(molecule, out); + } catch (Exception ex) { + throw ex; + } + return out.toString(); + } + + /** + * Writes coordinates of atoms into output stream + * + * @param molecule MoleculeInterface + * @param out OutputStream + * @throws Exception + */ + public static void writeMoleculeSpecs(MoleculeInterface molecule, OutputStream out) throws + Exception { + + try { + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface atom = molecule.getAtomInterface(i); + /* + String name = atom.getName(); + String elSymbol = ChemicalElements.getElementSymbol( atom.getAtomicNumber() ); + String theRest = ""; + if ( name.length() > elSymbol.length() ) { + theRest = name.substring(elSymbol.length()); + } + + if ( !theRest.matches("\\d.") ) { + name = name.substring(0,elSymbol.length()); + } + */ + + String aName = atom.getName(); + int element = atom.getAtomicNumber(); + String symbol = ChemicalElements.getElementSymbol(element); + + String element_label = String.valueOf(element); + + if (symbol.length() == 2) { + if (aName.startsWith(symbol)) { + element_label = aName; + } else { + element_label = symbol; + } + } else if (aName.length() > 1) { + int el = ChemicalElements.getAtomicNumber(aName.substring(0, 2)); + if (el == 0) { + element_label = aName; + } + } else { + int el = ChemicalElements.getAtomicNumber(aName); + if (el == element) { + element_label = aName; + } + } + + // --- Process dummy atom + if (element == 0 && element_label.toUpperCase().startsWith("DU")) { + if (element_label.length() == 2) { + element_label = "X"; + } else { + element_label = "X" + element_label.substring(2); + } + } + + String s = String.format("%6s %10.6f %10.6f %10.6f\n", + element_label, atom.getX(), + atom.getY(), atom.getZ()); + out.write(s.getBytes()); + //out.write( (atom.getAtomicNumber() + " ").getBytes()); + + //out.write( (" " + atom.getX() + " " + atom.getY() + " " + atom.getZ()). + // getBytes()); + //out.write( ("\n").getBytes()); + } + + out.write(("\n").getBytes()); + } catch (IOException e) { + System.err.println("writeCartesianCoordinates: Error: " + e.getMessage()); + throw e; + } + + } + + /** + * Defines element of an atom + * + * @param aname String - Atom label 9name) + * @return int - Element (0 for dummy atom), -1 for "Tv" + * @throws Exception + */ + public static int getAtomNumber(String aname) throws Exception { + + if (aname == null || aname.length() < 1) { + throw new IllegalArgumentException("Atom name is empty"); + } + + if (aname.indexOf("-") != -1) { + aname = aname.substring(0, aname.indexOf("-")); + } + + if (aname.equalsIgnoreCase("Tv")) { + return -1; + } + + // --- remove leading zeros (if any) + while (aname.length() > 0 && aname.startsWith("0")) { + aname = aname.substring(1); + } + + if (aname.length() < 1) { + return 0; + } + + int element = 0; + try { // --- Is it number? + element = Integer.parseInt(aname); + if (element < 0 || element > ChemicalElements.getNumberOfElements()) { + throw new Exception("Wrong element: " + element); + } + return element; + } catch (NumberFormatException e) { + // Do nothing + } + + // --- Parse non-numeric atom label of two letters + if (aname.length() > 1) { + try { + element = ChemicalElements.checkAtomicSymbol(aname.substring(0, 2)); + return element; + } catch (Exception ex) { + //throw ex; --- Do nothing + } + } + + // --- Parse non-numeric atom label of one letter + try { + element = ChemicalElements.checkAtomicSymbol(aname.substring(0, 1)); + return element; + } catch (Exception ex) { + throw ex; + } + } + + public static void main(String[] args) { + Gaussian gamess = new Gaussian(); + + try { + gamess.parseGJF(args[0], 0); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + ex.printStackTrace(); + } + List ms = gamess.getMoleculeSpecs(0); + logger.info(ms.toString()); + /* + Set set = controls.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + logger.info(me.getKey().toString() + "=" + + me.getValue().toString()); + } + */ + } + + public void validateLink0Section(String link0Specs) throws Exception { + boolean waitingOption = true; + boolean waitingNextOption = false; + boolean waitingValue = false; + boolean variableNumber = false; + int nValues = 0; + String Errors = ""; + String option = ""; + + StringTokenizer st = new StringTokenizer(link0Specs, " =\t\n"); + while (st.hasMoreTokens()) { + + String token = st.nextToken(); + + if (waitingNextOption) { + if (token.startsWith("%")) { + waitingOption = true; + waitingNextOption = false; + } else { + continue; + } + } + + if (variableNumber && waitingValue && token.startsWith("%")) { + waitingOption = true; + waitingValue = false; + variableNumber = false; + } + + // --- Parsing option + if (waitingOption) { + option = token.toUpperCase(); + if (!link0Commands.containsKey(option)) { + waitingOption = false; + waitingNextOption = true; + Errors += "Unknown Link0 option: " + option + "\n"; + continue; + } + + Integer n = link0Commands.get(option); + if (n == 0) { + continue; + } + + waitingOption = false; + waitingValue = true; + nValues = n > 0 ? n : -n; + variableNumber = n < 0; + continue; + } + + // --- Parsing value + if (waitingValue) { + if (option.equals(link0_MEM)) { + try { + parseLink0MemValue(token); + } catch (Exception ex) { + Errors += "Wrong %Mem value: " + token + " : " + + ex.getMessage() + "\n"; + } + } else if (option.equals(link0_NPROCSHARED) + || option.equals(link0_NPROC) + || option.equals(link0_NPROCLINDA)) { + int n = 0; + try { + n = Integer.parseInt(token); + if (n < 1) { + Errors += "Wrong value for " + option + " : " + token + + " : should be > 0\n"; + } + } catch (Exception ex) { + Errors += "Wrong value for " + option + " : " + token + " : " + + ex.getMessage() + "\n"; + } + + } + + --nValues; + if (nValues == 0) { + waitingOption = true; + waitingValue = false; + } + } + } + + if (Errors.length() > 0) { + throw new Exception(Errors); + } + } + + /** + * Returns number in bytes + * + * @param value String + * @return long + * @throws Exception + */ + static public long parseLink0MemValue(String value) throws Exception { + // %Mem=N + // Sets the amount of dynamic memory used to N words (8N bytes). + // The default is 6MW. N may be optionally followed by a units designation: KB, MB, GB, KW, MB or GW. + + // long - max 9223372036854775807, inclusive + String Value = value.toUpperCase(); + String number; + long factor = 0; + + if (Value.endsWith("KB")) { + factor = 1024L; + number = value.substring(0, value.length() - 2); + } else if (Value.endsWith("MW")) { + factor = 8L * 1024L * 1024L; + number = value.substring(0, value.length() - 2); + } else if (Value.endsWith("MB")) { + factor = 1024L * 1024L; + number = value.substring(0, value.length() - 2); + } else if (Value.endsWith("GB")) { + factor = 1024L * 1024L * 1024L; + number = value.substring(0, value.length() - 2); + } else if (Value.endsWith("KW")) { + factor = 8L * 1024L; + number = value.substring(0, value.length() - 2); + } else if (Value.endsWith("GW")) { + factor = 8L * 1024L * 1024L * 1024L; + number = value.substring(0, value.length() - 2); + } else { // in MW + factor = 8L * 1024L * 1024L; + number = value; + } + + long valueInBytes = 0; + + try { + valueInBytes = Long.parseLong(number); + } catch (Exception ex) { + throw ex; + } + + if (valueInBytes <= 0) { + throw new Exception("Value should be positive"); + } + + return valueInBytes * factor; + } + + /** + * Returns the maximum number of processors from all molecules + * + * @return int + */ + public int getNumberOfProcessors() { + int nprocs = 1; + for (int i = 0; i < Molecules.size(); i++) { + GaussianMolecule mol = Molecules.get(i); + nprocs = Math.max(nprocs, mol.getNumberOfProcessors()); + } + return nprocs; + } + + /** + * Returns memory in KB + * + * @return int + */ + public int getMemory() { + int memory = 0; + for (int i = 0; i < Molecules.size(); i++) { + GaussianMolecule mol = Molecules.get(i); + if (i == 0) { + memory = mol.getMemory(); + continue; + } + + memory = Math.max(memory, mol.getMemory()); + } + return memory; + } + + public static void saveGJFUsingTemplate(MoleculeInterface mol, String template, String fileName) throws Exception { + if (mol == null || mol.getNumberOfAtoms() < 1) { + throw new Exception("Molecule has no atoms"); + } + if (template == null || template.trim().length() < 1) { + throw new Exception("Template is empty"); + } + BufferedWriter bw; + try { + bw = new BufferedWriter(new FileWriter(fileName)); + } catch (Exception ex) { + throw new Exception("Cannot open file " + fileName + " for writing: " + ex.getLocalizedMessage()); + } + saveGJFUsingTemplate(mol, template, bw); + bw.close(); + } + + public static void saveGJFUsingTemplate(MoleculeInterface mol, String template, Writer writer) throws Exception { + if (mol == null || mol.getNumberOfAtoms() < 1) { + throw new Exception("Molecule has no atoms"); + } + if (template == null || template.trim().length() < 1) { + throw new Exception("Template is empty"); + } + + if (template.contains(TITLE_TEMPLATE)) { + String title = "Some molecule"; + if (mol.getName() != null && mol.getName().trim().length() > 0) { + title = mol.getName().trim(); + } + template = template.replaceAll(TITLE_TEMPLATE, title); + } + + if (template.contains(CHARGE_TEMPLATE)) { + double charge = 0; + Object obj = mol.getProperty(MoleculeInterface.ChargeProperty); + if (obj != null && obj instanceof Number) { + charge = ((Number) obj).doubleValue(); + double ch = (double) ((int) charge); + if (Math.abs(ch - charge) > 0.01) { + logger.warning("Total charge is a bit far from integer number: " + charge); + } + if (charge != ch) { + if (charge - ch > 0.5) { + ch += 1; + } else if (charge - ch < -0.5) { + ch -= 1; + } + //ch = charge > ch ? ch + 1 : ch -1; + } + System.out.println("Sum of partial charges: " + charge + " Attributed xharge: " + ((int) ch)); + template = template.replaceAll(CHARGE_TEMPLATE, String.valueOf((int) ch)); + } else { + logger.warning("Total charge is not defined or is not a number: " + (obj == null ? obj : obj.toString())); + } + } + + if (!template.contains(COORDINATES_TEMPLATE)) { + throw new Exception("GJF Template must contain " + COORDINATES_TEMPLATE); + } + StringBuilder sb = new StringBuilder(mol.getNumberOfAtoms() * 40); + boolean yesFixed = false; + String fragment; + for (int i = 0; i < mol.getNumberOfAtoms(); i++) { + fragment = ""; + AtomInterface atom = mol.getAtomInterface(i); + if ((!yesFixed) && atom.getProperty(ATOM_FIXED_PROPERTY) != null) { + yesFixed = true; + } + Object obj = atom.getProperty(FRAGMENT_PROPERTY); + if (obj != null && obj instanceof Number) { + int frag = ((Number) obj).intValue(); + fragment = "(Fragment=" + String.valueOf(frag) + ")"; + } + sb.append(atom.getAtomicNumber() + fragment + " " + + String.format("%10.4f %10.4f %10.4f", atom.getX(), atom.getY(), atom.getZ()) + "\n"); + } + + if (yesFixed) { + sb.append("\n"); + for (int i = 0; i < mol.getNumberOfAtoms(); i++) { + AtomInterface atom = mol.getAtomInterface(i); + if (atom.getProperty(ATOM_FIXED_PROPERTY) != null) { + sb.append("X " + String.valueOf(i + 1) + " F\n"); + } + } + } + + template = template.replaceAll(COORDINATES_TEMPLATE, sb.toString()); + + writer.write(template); + } + + public CommandInterface ciInstance() { + return new Gaussian(); + } + + public Object ciExecuteCommand(Object[] args) throws Exception { + String fileName = null; + if (args[0] instanceof Variable) { + fileName = ((Variable) args[0]).getValue().toString(); + } else { + fileName = args[0].toString(); + } + int n = parseGJF(fileName, 0); + int sel = 1; + if (args.length > 1) { + sel = ((Integer) args[1]).intValue(); + } + if (sel > n) { + throw new Exception("Load Gaussian input command: input file contains " + n + + " structures. Requested: " + sel); + } + MoleculeInterface m = Molecule.getNewInstance(); + m = getMolecule(m, sel - 1); + if (m == null || m.getNumberOfAtoms() < 1) { + throw new Exception("Load Gaussian input command: Didn't find atoms in file"); + } + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + return m; + } + + /** + * Parses command parameters. + * + * @param tokens - arguments. The first argument is a command name, so it's ignored + * @return parsed and parameters + * @throws Exception + */ + public Object[] ciParseCommand(String[] tokens) throws Exception { + if (tokens.length < 2) { + throw new Exception("Load Gaussian input command requires at least one argument (file name)"); + } + + if (tokens[1] == null) { + throw new Exception("Load Gaussian input command: file name is empty"); + } + if (tokens.length >= 2) { + File file = new File(tokens[1]); + if (!file.exists()) { + throw new Exception("Load Gaussian input command: file " + tokens[1] + " does not exist"); + } + } + + Object[] parsedArgs = new Object[tokens.length > 2 ? 2 : 1]; + parsedArgs[0] = tokens[1]; + + // --- + if (tokens.length > 2) { + Integer n = null; + try { + n = Integer.parseInt(tokens[2]); + } catch (Exception ex) { + throw new Exception("Load Gaussian input command: expected a structure number as the second argument, got: " + + tokens[2]); + } + if (n < 1) { + throw new Exception("Load Gaussian input command: the second argument should be > 0, got: " + + tokens[2]); + } + parsedArgs[1] = n; + } + + return parsedArgs; + } +} diff --git a/src/main/java/cct/gaussian/GaussianAtom.java b/src/main/java/cct/gaussian/GaussianAtom.java new file mode 100644 index 0000000..ce2eded --- /dev/null +++ b/src/main/java/cct/gaussian/GaussianAtom.java @@ -0,0 +1,295 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.gaussian; + +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class GaussianAtom { + + static public String PDB_NAME_KEYWORD = "PDBName".toUpperCase(); + static public String RES_NAME_KEYWORD = "ResName".toUpperCase(); + static public String RES_NUM_KEYWORD = "ResNum".toUpperCase(); + public String name = null; + public String atomType = null; + public String extraParam = null; + private String PDBName, ResName; + private int ResNum = -01; + public String parxyz[] = new String[3]; + public String parijk[] = new String[3]; + public int element = 0; + public float charge = 0.0f; + public float xyz[] = new float[3]; + public int ijk[] = new int[3]; + public int alternateZmatrixFormat = 0; // Regular Z-matrix, +1 or -1 otherwise + boolean frozen = false; + String Layer = null; + ONIOM_LAYER ONIOM_Layer = ONIOM_LAYER.HIGH; + String link_atom = null; + int Bonded_to = -1; + float scale_fac1, scale_fac2, scale_fac3; + private boolean dummy = false; + static final Logger logger = Logger.getLogger(GaussianAtom.class.getCanonicalName()); + + public GaussianAtom() { + parxyz[0] = parxyz[1] = parxyz[2] = null; + parijk[0] = parijk[1] = parijk[2] = null; + element = 0; + xyz[0] = xyz[1] = xyz[2] = 0.0f; + ijk[0] = ijk[1] = ijk[2] = 0; + } + + public GaussianAtom(AtomInterface a) { + super(); + element = a.getAtomicNumber(); + xyz[0] = a.getX(); + xyz[1] = a.getY(); + xyz[2] = a.getZ(); + name = a.getName(); + } + + public int getElement() { + return element; + } + + public boolean isDummy() { + return dummy; + } + + public void setDummy(boolean is_dummy) { + dummy = is_dummy; + } + + public float getX() { + return xyz[0]; + } + + public float getY() { + return xyz[1]; + } + + public float getZ() { + return xyz[2]; + } + + public void parseAtomName(String aname, boolean complex_name) throws Exception { + String token, atomName = aname; + StringTokenizer st = null; + boolean minusCharge = atomName.regionMatches(0, "--", 0, 2); + + if (complex_name) { + // C(PDBName=C3,ResName=NH3,ResNum=1) + name = atomName.substring(0, atomName.indexOf("(")); + name = name.trim(); + + } else { + st = new StringTokenizer(atomName, "-"); + + // --- Parse element + if (st.hasMoreTokens()) { + token = st.nextToken(); + } else { + token = "-"; + } + name = token; + } + + if (name.equalsIgnoreCase("X")) { + setDummy(true); + element = 0; + } else { + try { + element = Gaussian.getAtomNumber(name); + } catch (Exception e) { + element = 0; + //throw new Exception(e.getMessage() + " Set atom to dummy"); + System.err.println(e.getMessage() + " Set atom to dummy"); + } + } + + if (complex_name) { + // C(PDBName=C3,ResName=NH3,ResNum=1) + String temp; + atomName = atomName.toUpperCase(); + if (atomName.contains(PDB_NAME_KEYWORD)) { + try { + int start_index = atomName.indexOf(PDB_NAME_KEYWORD) + PDB_NAME_KEYWORD.length() + 1; + int end_index = start_index + atomName.substring(start_index).indexOf(","); + temp = atomName.substring(start_index, end_index); + name = temp; + this.setPDBName(temp); + } catch (Exception ex) { + logger.severe("Cannot properly parse atom name " + atomName + " : " + ex.getMessage() + " Ignored & continuing..."); + } + } + + if (atomName.contains(RES_NAME_KEYWORD)) { + try { + int start_index = atomName.indexOf(RES_NAME_KEYWORD) + RES_NAME_KEYWORD.length() + 1; + int end_index = start_index + atomName.substring(start_index).indexOf(","); + temp = atomName.substring(start_index, end_index); + this.setResName(temp); + } catch (Exception ex) { + logger.severe("Cannot properly parse residue name " + atomName + " : " + ex.getMessage() + " Ignored & continuing..."); + } + } + + if (atomName.contains(RES_NUM_KEYWORD)) { + try { + int start_index = atomName.indexOf(RES_NUM_KEYWORD) + RES_NUM_KEYWORD.length() + 1; + int end_index = start_index + atomName.substring(start_index).indexOf(")"); + temp = atomName.substring(start_index, end_index); + this.setResNum(temp); + } catch (Exception ex) { + logger.severe("Cannot properly parse residue number " + atomName + " : " + ex.getMessage() + " Ignored & continuing..."); + } + } + + } + + // + if (st == null) { + return; + } + + if (!st.hasMoreTokens()) { + return; + } + + token = st.nextToken(); + + if (token.startsWith("(")) { + extraParam = token; + return; + } + + // --- MM Atom Type + + atomType = token; + + if (!st.hasMoreTokens()) { + return; + } + + token = st.nextToken(); + + if (token.startsWith("(")) { + extraParam = token; + return; + } + + // --- MM charge + + try { + charge = Float.parseFloat(token); + if (minusCharge) { + charge = -charge; + } + } catch (NumberFormatException e) { + logger.info("ERROR: expecting MM charge. Got " + token); + } + + if (!st.hasMoreTokens()) { + return; + } + + extraParam = st.nextToken(); + } + + /** + * @deprecated Use parseAtomName(String aname, boolean complex_name) instead + */ + @Deprecated + public void parseAtomName(String aname) throws Exception { + parseAtomName(aname, false); + } + + public void setONIOMLayer(String layer) throws Exception { + Layer = layer; + if (layer.equalsIgnoreCase("H") || layer.equalsIgnoreCase("High")) { + ONIOM_Layer = ONIOM_LAYER.HIGH; + } else if (layer.equalsIgnoreCase("M") || layer.equalsIgnoreCase("Medium")) { + ONIOM_Layer = ONIOM_LAYER.MEDIUM; + } else if (layer.equalsIgnoreCase("L") || layer.equalsIgnoreCase("Low")) { + ONIOM_Layer = ONIOM_LAYER.LOW; + } else { + throw new Exception("Unknown ONIOM layer: " + layer); + } + } + + public String getPDBName() { + return PDBName; + } + + public void setPDBName(String PDBName) { + this.PDBName = PDBName; + } + + public String getResName() { + return ResName; + } + + public void setResName(String ResName) { + this.ResName = ResName; + } + + public int getResNum() { + return ResNum; + } + + public void setResNum(int ResNum) { + this.ResNum = ResNum; + } + + public void setResNum(String resNum) throws Exception { + this.ResNum = Integer.parseInt(resNum); + } +} diff --git a/src/main/java/cct/gaussian/GaussianCube.java b/src/main/java/cct/gaussian/GaussianCube.java new file mode 100644 index 0000000..f784b50 --- /dev/null +++ b/src/main/java/cct/gaussian/GaussianCube.java @@ -0,0 +1,751 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.util.StringTokenizer; +import java.util.prefs.Preferences; + +import javax.swing.JFileChooser; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.math.VolumeData; +import cct.modelling.ChemicalElements; +import cct.tools.FileFilterImpl; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class GaussianCube extends VolumeData { + + static int BOHR_UNITS = 0; + static int ANGSTROM_UNITS = 1; + + private static String lastPWDKey = "lastPWD"; + private static String MO_COEFF_TAG = "MO coefficients".toUpperCase(); + private static String DENSITY_TAG = "Electron density".toUpperCase(); + private static String ESP_TAG = "Electrostatic potential".toUpperCase(); + private int units = ANGSTROM_UNITS; + private double value_factor = 1.0; + + + private boolean readPreVolumetric = false; + private int numberAtoms; + + private AtomInfo atoms[] = null; + + private Preferences prefs = Preferences.userNodeForPackage(getClass()); + private File currentWorkingDirectory = null; + private JFileChooser chooser = null; + private JFileChooser save_chooser = null; + private FileFilterImpl filter = null; + private float defaultIsovalue = 0; + private boolean positiveValuesOnly = false; + + + public GaussianCube() { + } + + static public void extractGeometry(String filename, MoleculeInterface molecule) throws + Exception { + + int natoms; + float factor = ONE_BOHR_FLOAT; + + String str, commentLine; + StringTokenizer st; + try { + BufferedReader in = new BufferedReader(new FileReader(filename)); + + if ((commentLine = in.readLine()) == null) { + throw new Exception( + "Unexpected end of file while reading the first line"); + } + + if ((str = in.readLine()) == null) { + throw new Exception( + "Unexpected end of file while reading the second line"); + } + commentLine += " " + str; + molecule.setName(commentLine); + + // --- the third line + + if ((str = in.readLine()) == null) { + throw new Exception( + "Unexpected end of file while reading the third line"); + } + + st = new StringTokenizer(str, " \t"); + + try { + natoms = Integer.parseInt(st.nextToken()); + } catch (Exception ex) { + throw new Exception( + "Error parsing number of atoms: " + str); + } + + // --- Skip the forth-sixth lines + + for (int i = 0; i < 3; i++) { + + if ((str = in.readLine()) == null) { + throw new Exception( + "Unexpected end of file while reading the " + + (4 + i) + + "th line"); + } + } + + // --- Reading atoms + + if (natoms < 0) { + natoms = -natoms; + //factor = 1.0f; + } + + for (int i = 0; i < natoms; i++) { + + AtomInterface atom = molecule.getNewAtomInstance(); + + if ((str = in.readLine()) == null) { + throw new Exception( + "Unexpected end of file while reading the " + + (i + 1) + "atom info"); + } + st = new StringTokenizer(str, " \t"); + + try { + atom.setAtomicNumber(Integer.parseInt(st.nextToken())); + atom.setName(ChemicalElements.getElementSymbol(atom. + getAtomicNumber())); + Float.parseFloat(st.nextToken()); // Atomic charge + atom.setX(Float.parseFloat(st.nextToken()) * factor); + atom.setY(Float.parseFloat(st.nextToken()) * factor); + atom.setZ(Float.parseFloat(st.nextToken()) * factor); + } catch (Exception ex) { + throw new Exception( + "Error parsing atom info data for " + (i + 1) + + " atom: " + str); + } + + molecule.addAtom(atom); + } + + in.close(); + } catch (IOException e) { + throw new Exception("Error parsing file " + filename + " : " + + e.getMessage()); + } + } + + /** + * Loads Gaussian cube file + * @param filename String - file name + * @throws Exception + */ + public void parseVolumetricData(String filename) throws Exception { + + float factor = ONE_BOHR_FLOAT; + String str; + StringTokenizer st; + try { + BufferedReader in = new BufferedReader(new FileReader(filename)); + + if ((commentLine_1 = in.readLine()) == null) { + throw new Exception( + "Unexpected end of file while reading the first line"); + } + + if ((commentLine_2 = in.readLine()) == null) { + throw new Exception( + "Unexpected end of file while reading the second line"); + } + + // --- Setup default isovalue + + if (commentLine_2.toUpperCase().contains(MO_COEFF_TAG)) { + defaultIsovalue = 0.02f; + positiveValuesOnly = false; + value_factor = 1.0 / ONE_BOHR; + } else if (commentLine_2.toUpperCase().contains(DENSITY_TAG)) { + defaultIsovalue = 0.0004f; + positiveValuesOnly = true; + value_factor = 1.0 / ONE_BOHR; + } else if (commentLine_2.toUpperCase().contains(ESP_TAG)) { + defaultIsovalue = 0.0004f; + positiveValuesOnly = false; + value_factor = 1.0 / ONE_BOHR; + } else { + defaultIsovalue = 0.0004f; + positiveValuesOnly = false; + } + + // --- the third line + + if ((str = in.readLine()) == null) { + throw new Exception( + "Unexpected end of file while reading the third line"); + } + + st = new StringTokenizer(str, " \t"); + + try { + numberAtoms = Integer.parseInt(st.nextToken()); + } catch (Exception ex) { + throw new Exception("Error parsing number of atoms: " + str); + } + + if (numberAtoms < 0) { + readPreVolumetric = true; + numberAtoms = -numberAtoms; + } + + if (st.countTokens() < 3) { + throw new Exception("Not enough numbers for data origin: " + + str); + } + + try { + dataOrigin[0] = Float.parseFloat(st.nextToken()) * factor; + dataOrigin[1] = Float.parseFloat(st.nextToken()) * factor; + dataOrigin[2] = Float.parseFloat(st.nextToken()) * factor; + } catch (Exception ex) { + throw new Exception("Error parsing origin of volumetric data: " + + str); + } + + // --- The forth-sixth line + + for (int i = 0; i < 3; i++) { + + if ((str = in.readLine()) == null) { + throw new Exception( + "Unexpected end of file while reading the forth line"); + } + + st = new StringTokenizer(str, " \t"); + try { + numberOfVoxels[i] = Integer.parseInt(st.nextToken()); + if (numberOfVoxels[i] < 0) { + units = BOHR_UNITS; + numberOfVoxels[i] = -numberOfVoxels[i]; + } else { + units = ANGSTROM_UNITS; + } + axisVectors[i][0] = Float.parseFloat(st.nextToken()) * + factor; + axisVectors[i][1] = Float.parseFloat(st.nextToken()) * + factor; + axisVectors[i][2] = Float.parseFloat(st.nextToken()) * + factor; + } catch (Exception ex) { + throw new Exception( + "Error parsing voxel data for " + i + "-axis: " + + str); + } + } + + // --- Reading atoms + + if (numberAtoms < 0) { + numberAtoms = -numberAtoms; + } + + atoms = new AtomInfo[numberAtoms]; + for (int i = 0; i < numberAtoms; i++) { + atoms[i] = new AtomInfo(); + if ((str = in.readLine()) == null) { + throw new Exception( + "Unexpected end of file while reading the " + + (i + 1) + "atom info"); + } + st = new StringTokenizer(str, " \t"); + + try { + atoms[i].atomNumber = Integer.parseInt(st.nextToken()); + atoms[i].qNumber = Float.parseFloat(st.nextToken()); + atoms[i].xyz[0] = Float.parseFloat(st.nextToken()) * factor; + atoms[i].xyz[1] = Float.parseFloat(st.nextToken()) * factor; + atoms[i].xyz[2] = Float.parseFloat(st.nextToken()) * factor; + } catch (Exception ex) { + throw new Exception("Error parsing atom info data for " + + (i + 1) + " atom: " + str); + } + + } + + // --- Number of volumetric cubes + + if (readPreVolumetric) { + if ((str = in.readLine()) == null) { + throw new Exception( + "Unexpected end of file while reading the pre-volumetric (???) data: " + + str); + } + + st = new StringTokenizer(str, " \t"); + + try { + nVolumetrics = Integer.parseInt(st.nextToken()); + } catch (Exception ex) { + throw new Exception("Error parsing pre-volumetric data : " + + str); + } + + labels = new int[nVolumetrics]; + + for (int i = 0; i < nVolumetrics; i++) { + if (!st.hasMoreTokens()) { + if ((str = in.readLine()) == null) { + throw new Exception( + "Unexpected end of file while reading the pre-volumetric labels: " + + str); + } + st = new StringTokenizer(str, " \t"); + } + + try { + labels[i] = Integer.parseInt(st.nextToken()); + } catch (Exception ex) { + throw new Exception( + "Error parsing pre-volumetric label: " + str); + } + } + + } + + // --- Reading volumetric data + + data = new double[nVolumetrics][numberOfVoxels[0]][numberOfVoxels[1]][ + numberOfVoxels[2]]; + + if ((str = in.readLine()) == null) { + throw new Exception( + "Unexpected end of file while reading the volumetric data: " + + str); + } + st = new StringTokenizer(str, " \t"); + + boolean firstValue = true; + float value = 0; + + for (int ix = 0; ix < numberOfVoxels[0]; ix++) { + for (int iy = 0; iy < numberOfVoxels[1]; iy++) { + for (int iz = 0; iz < numberOfVoxels[2]; iz++) { + + for (int i = 0; i < nVolumetrics; i++) { + if (!st.hasMoreTokens()) { + if ((str = in.readLine()) == null) { + throw new Exception( + "Unexpected end of file while reading the volumetric data: " + + str); + } + st = new StringTokenizer(str, " \t"); + } + + try { + value = Float.parseFloat(st.nextToken()); + data[i][ix][iy][iz] = value * + (float) value_factor; + + if (firstValue) { + minFValue = value; + maxFValue = value; + firstValue = false; + } + + if (minFValue > value) { + minFValue = value; + } else if (maxFValue < value) { + maxFValue = value; + } + } catch (Exception ex) { + throw new Exception( + "Error parsing volumetric data: " + str); + } + } + } + } + } + + in.close(); + } catch (IOException e) { + throw e; + } + } + + public void getMolecule(MoleculeInterface molecule) { + molecule.setName(commentLine_1 + " " + commentLine_2); + for (int i = 0; i < atoms.length; i++) { + + AtomInterface atom = molecule.getNewAtomInstance(); + + atom.setAtomicNumber(atoms[i].atomNumber); + atom.setName(ChemicalElements.getElementSymbol(atom. + getAtomicNumber())); + atom.setX(atoms[i].xyz[0]); + atom.setY(atoms[i].xyz[1]); + atom.setZ(atoms[i].xyz[2]); + + molecule.addAtom(atom); + } + } + + + public void parseGaussianCube() throws Exception { + if (chooser == null) { + chooser = new JFileChooser(); + filter = new FileFilterImpl(); + + String temp[] = { + "cub", "cube"}; // extensions.split(";"); + for (int i = 0; i < temp.length; i++) { + filter.addExtension(temp[i]); + } + filter.setDescription("Gaussian G03 Cube Files (*.cub,*cube)"); + chooser.setFileFilter(filter); + } + + chooser.setDialogTitle("Open Gaussian Cube File"); + chooser.setDialogType(JFileChooser.OPEN_DIALOG); + + if (currentWorkingDirectory != null) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } else { + String lastPWD = prefs.get(lastPWDKey, ""); + if (lastPWD.length() > 0) { + currentWorkingDirectory = new File(lastPWD); + if (currentWorkingDirectory.isDirectory() && + currentWorkingDirectory.exists()) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } + } + } + + int returnVal = JFileChooser.CANCEL_OPTION; + + returnVal = chooser.showOpenDialog(null); + + if (returnVal == JFileChooser.CANCEL_OPTION) { + return; + } + + if (returnVal == JFileChooser.APPROVE_OPTION) { + String fileName = chooser.getSelectedFile().getPath(); + currentWorkingDirectory = chooser.getCurrentDirectory(); + try { + prefs.put(lastPWDKey, currentWorkingDirectory.getAbsolutePath()); + } catch (Exception ex) { + System.err.println("Cannot save cwd: " + ex.getMessage() + + " Ignored..."); + } + //logger.info("You chose to open this file: " + + // fileName); + + + this.parseVolumetricData(fileName); + } + + } + + /** + * Overwrites + * @param n int + * @throws Exception + */ + public void saveVolumeData(int n) throws Exception { + + if (save_chooser == null) { + javax.swing.filechooser.FileFilter[] filters = getDefaultSaveFileFilters(); + save_chooser = new JFileChooser(); + for (int i = 0; i < filters.length; i++) { + save_chooser.addChoosableFileFilter(filters[i]); + } + filter = new FileFilterImpl(); + + String temp[] = { + "cub", "cube"}; // extensions.split(";"); + for (int i = 0; i < temp.length; i++) { + filter.addExtension(temp[i]); + } + filter.setDescription("Gaussian G03 Cube Files (*.cub,*cube)"); + save_chooser.addChoosableFileFilter(filter); + } + + save_chooser.setDialogTitle("Save Volume Data in File"); + save_chooser.setDialogType(JFileChooser.SAVE_DIALOG); + + if (currentWorkingDirectory != null) { + save_chooser.setCurrentDirectory(currentWorkingDirectory); + } else { + String lastPWD = prefs.get(lastPWDKey, ""); + if (lastPWD.length() > 0) { + currentWorkingDirectory = new File(lastPWD); + if (currentWorkingDirectory.isDirectory() && + currentWorkingDirectory.exists()) { + save_chooser.setCurrentDirectory(currentWorkingDirectory); + } + } + } + + int returnVal = JFileChooser.CANCEL_OPTION; + + returnVal = save_chooser.showSaveDialog(null); + + if (returnVal == JFileChooser.CANCEL_OPTION) { + return; + } + + if (returnVal == JFileChooser.APPROVE_OPTION) { + + javax.swing.filechooser.FileFilter selectedFilter = save_chooser.getFileFilter(); + String fileName = save_chooser.getSelectedFile().getPath(); + + if (selectedFilter == filter) { // --- Save in gaussian cube format + + if (fileName.endsWith(".")) { + fileName += "cube"; + } else if (!fileName.endsWith(".cub") && !fileName.endsWith(".CUB") && + !fileName.endsWith(".cube") && + !fileName.endsWith(".CUBE")) { + fileName += ".cube"; + } + saveGaussianCube(n, fileName); + } else { + super.saveVolumeData(n, fileName, selectedFilter.getDescription()); + } + + currentWorkingDirectory = chooser.getCurrentDirectory(); + try { + prefs.put(lastPWDKey, currentWorkingDirectory.getAbsolutePath()); + } catch (Exception ex) { + System.err.println("Cannot save cwd: " + ex.getMessage() + " Ignored..."); + } + } + } + + public void saveGaussianCube(int n) throws Exception { + + if (nVolumetrics < 1) { + System.err.println("saveGaussianCube: nVolumetrics < 1"); + throw new Exception("saveGaussianCube: nVolumetrics < 1"); + } + + if (n < 0 || n >= nVolumetrics) { + System.err.println("saveGaussianCube: n < 0 || n>=nVolumetrics"); + throw new Exception("saveGaussianCube: n < 0 || n>=nVolumetrics"); + } + + if (save_chooser == null) { + save_chooser = new JFileChooser(); + filter = new FileFilterImpl(); + + String temp[] = { + "cub", "cube"}; // extensions.split(";"); + for (int i = 0; i < temp.length; i++) { + filter.addExtension(temp[i]); + } + filter.setDescription("Gaussian G03 Cube Files (*.cub,*cube)"); + save_chooser.setFileFilter(filter); + } + + save_chooser.setDialogTitle("Save Gaussian Cube File"); + save_chooser.setDialogType(JFileChooser.SAVE_DIALOG); + + if (currentWorkingDirectory != null) { + save_chooser.setCurrentDirectory(currentWorkingDirectory); + } else { + String lastPWD = prefs.get(lastPWDKey, ""); + if (lastPWD.length() > 0) { + currentWorkingDirectory = new File(lastPWD); + if (currentWorkingDirectory.isDirectory() && + currentWorkingDirectory.exists()) { + save_chooser.setCurrentDirectory(currentWorkingDirectory); + } + } + } + + int returnVal = JFileChooser.CANCEL_OPTION; + + returnVal = save_chooser.showSaveDialog(null); + + if (returnVal == JFileChooser.CANCEL_OPTION) { + return; + } + + if (returnVal == JFileChooser.APPROVE_OPTION) { + String fileName = save_chooser.getSelectedFile().getPath(); + if (fileName.endsWith(".")) { + fileName += "cube"; + } else if (!fileName.endsWith(".cub") && !fileName.endsWith(".CUB") && + !fileName.endsWith(".cube") && !fileName.endsWith(".CUBE")) { + fileName += ".cube"; + } + currentWorkingDirectory = chooser.getCurrentDirectory(); + try { + prefs.put(lastPWDKey, currentWorkingDirectory.getAbsolutePath()); + } catch (Exception ex) { + System.err.println("Cannot save cwd: " + ex.getMessage() + " Ignored..."); + } + + saveGaussianCube(n, fileName); + } + } + + public void saveGaussianCube(int n, String filename) throws Exception { + + float factor = ONE_BOHR_FLOAT; + + FileOutputStream out; + try { + out = new FileOutputStream(filename); + + out.write((commentLine_1 + "\n").getBytes()); + + out.write((commentLine_2 + "\n").getBytes()); + + // --- the third line + + int sign = 1; + if (readPreVolumetric) { + sign = -1; + } + + out.write((String.format("%5d %11.6f %11.6f %11.6f", + (sign * numberAtoms), + dataOrigin[0] / factor, + dataOrigin[1] / factor, + dataOrigin[2] / factor) + "\n").getBytes()); + + // --- The forth-sixth line + + for (int i = 0; i < 3; i++) { + + out.write((String.format("%5d", numberOfVoxels[i])).getBytes()); + + out.write((String.format(" %11.6f", axisVectors[i][0] / factor)). + getBytes()); + out.write((String.format(" %11.6f", axisVectors[i][1] / factor)). + getBytes()); + out.write((String.format(" %11.6f", axisVectors[i][2] / factor)). + getBytes()); + + out.write(("\n").getBytes()); + } + + // --- Writing atoms + + for (int i = 0; i < numberAtoms; i++) { + + out.write((String.format("%5d", atoms[i].atomNumber)).getBytes()); + + out.write((String.format(" %11.6f", atoms[i].qNumber)).getBytes()); + + out.write((String.format(" %11.6f", atoms[i].xyz[0] / factor)). + getBytes()); + out.write((String.format(" %11.6f", atoms[i].xyz[1] / factor)). + getBytes()); + out.write((String.format(" %11.6f", atoms[i].xyz[2] / factor)). + getBytes()); + + out.write(("\n").getBytes()); + } + + // --- Number of volumetric cubes + + if (readPreVolumetric) { + out.write((String.format("%5d %4d", 1, labels[n]) + "\n").getBytes()); + } + + // --- Reading volumetric data + + int items = 0; + for (int ix = 0; ix < numberOfVoxels[0]; ix++) { + for (int iy = 0; iy < numberOfVoxels[1]; iy++) { + for (int iz = 0; iz < numberOfVoxels[2]; iz++) { + + out.write((String.format(" %12.5g", data[n][ix][iy][iz])).getBytes()); + ++items; + if (items == 6) { + items = 0; + out.write(("\n").getBytes()); + } + } + if (items != 0) { + items = 0; + out.write(("\n").getBytes()); + } + } + } + + out.close(); + } catch (IOException e) { + throw e; + } + } + + public float getDefaultIsovalue() { + return defaultIsovalue; + } + + public boolean isPositiveValuesOnly() { + return this.positiveValuesOnly; + } + + private class AtomInfo { + public int atomNumber; + public float qNumber; + public float xyz[] = new float[3]; + } + +} diff --git a/src/main/java/cct/gaussian/GaussianFragment.java b/src/main/java/cct/gaussian/GaussianFragment.java new file mode 100644 index 0000000..0574e1f --- /dev/null +++ b/src/main/java/cct/gaussian/GaussianFragment.java @@ -0,0 +1,216 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.util.StringTokenizer; + +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; +import cct.interfaces.MoleculeInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class GaussianFragment { + public GaussianFragment() { + } + + public static void main(String[] args) { + GaussianFragment parsegaussianfragment = new GaussianFragment(); + } + + public static MoleculeInterface parseGaussianFragmentFile(MoleculeInterface + mol, + String filename) throws Exception { + String line; + try { + BufferedReader in = new BufferedReader(new FileReader(filename)); + + // --- Reading fragment name + if ( (line = in.readLine()) == null) { + throw new Exception("parseGaussianOutputFile: ERROR: Unxpected End of file while reading fragment name"); + } + mol.setName(line); + + // --- Reading number of atoms + if ( (line = in.readLine()) == null) { + throw new Exception("parseGaussianOutputFile: ERROR: Unxpected End of file while reading number of atoms"); + } + + int natoms = 0; + try { + natoms = Integer.parseInt(line.trim()); + } + catch (Exception e) { + throw new Exception( + "parseGaussianOutputFile: ERROR: Error while parsing number of atoms: " + + e.getMessage()); + } + + // --- Reading atoms + + for (int i = 0; i < natoms; i++) { + + AtomInterface atom = mol.getNewAtomInstance(); + + if ( (line = in.readLine()) == null) { + throw new Exception( + "parseGaussianOutputFile: ERROR: Unxpected End of file while atom " + + (i + 1)); + } + StringTokenizer st = new StringTokenizer(line, " "); + if (st.countTokens() < 4) { + throw new Exception( + "parseGaussianOutputFile: ERROR: Error while parsing atom: " + + (i + 1) + + " Number of tokens < 4: " + line); + } + + // --- Getting element + + int element; + try { + element = Integer.parseInt(st.nextToken()); + if (element < 1) { + element = 0; + } + atom.setAtomicNumber(element); + } + catch (Exception ex) { + throw new Exception( + "parseGaussianOutputFile: ERROR: Error while parsing atom: " + + (i + 1) + + " Cannot parse atom number: " + line); + } + + // --- Getting x,y,z + + float xyz; + try { + xyz = Float.parseFloat(st.nextToken()); + atom.setX(xyz); + xyz = Float.parseFloat(st.nextToken()); + atom.setY(xyz); + xyz = Float.parseFloat(st.nextToken()); + atom.setZ(xyz); + } + catch (Exception ex) { + throw new Exception( + "parseGaussianOutputFile: ERROR: Error while parsing atom: " + + (i + 1) + + " Cannot parse atom's coordinate(s): " + line); + } + + mol.addAtom(atom); + } + + // --- Reading number of bonds (if any) + if ( (line = in.readLine()) == null) { + System.err.println( + "parseGaussianOutputFile: Warning: No covalent bonds in fragment"); + return mol; + } + + int bonds = 0; + try { + bonds = Integer.parseInt(line.trim()); + } + catch (Exception e) { + throw new Exception( + "parseGaussianOutputFile: ERROR: Error while parsing number of bonds: " + + e.getMessage()); + } + + // --- Reading bonds + + for (int i = 0; i < bonds; i++) { + if ( (line = in.readLine()) == null) { + throw new Exception( + "parseGaussianOutputFile: ERROR: Unxpected End of file while reading bond " + + (i + 1)); + } + StringTokenizer st = new StringTokenizer(line, " "); + if (st.countTokens() < 2) { + throw new Exception( + "parseGaussianOutputFile: ERROR: Error while parsing bond: " + + (i + 1) + + " Number of tokens < 2: " + line); + } + + // --- Getting i & j + + int i_atom, j_atom; + try { + i_atom = Integer.parseInt(st.nextToken()) - 1; + j_atom = Integer.parseInt(st.nextToken()) - 1; + + AtomInterface a_i = mol.getAtomInterface(i_atom); + AtomInterface a_j = mol.getAtomInterface(j_atom); + + BondInterface bond = mol.getNewBondInstance(a_i, a_j); + + mol.addBond(bond); + } + catch (Exception ex) { + throw new Exception( + "parseGaussianOutputFile: ERROR: Error while parsing bond: " + + (i + 1) + + " Cannot parse atom numbers: " + line); + } + + } + + } + catch (Exception ex) { + throw new Exception("parseGaussianOutputFile: ERROR: " + ex.getMessage()); + } + + return mol; + } +} diff --git a/src/main/java/cct/gaussian/GaussianFrequency.java b/src/main/java/cct/gaussian/GaussianFrequency.java new file mode 100644 index 0000000..d1d80c8 --- /dev/null +++ b/src/main/java/cct/gaussian/GaussianFrequency.java @@ -0,0 +1,302 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; + +import cct.modelling.VIBRATIONAL_SPECTRUM; +import cct.vecmath.Point3f; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class GaussianFrequency { + private static final String aliasInfraredSpectrum = "Infrared Spectrum"; + private static final String aliasVCDRot = "VCD Rotational Stregth Spectrum"; + private static final String aliasRamanSpectrum = "Raman Spectrum"; + private static final String aliasPDepSpectrum = "P-Depolarization Spectrum"; + private static final String aliasUDepSpectrum = "U-Depolarization Spectrum"; + + private static final Map aliases = new HashMap (); + private static final Map valueTitles = new HashMap (); + private static final Map refTable = new HashMap (); + + static { + aliases.put(aliasInfraredSpectrum, "IR Inten"); + aliases.put(aliasVCDRot, "Rot. str."); + aliases.put(aliasRamanSpectrum, "Raman Activ"); + aliases.put(aliasPDepSpectrum, "Depolar (P)"); + aliases.put(aliasUDepSpectrum, "Depolar (U)"); + + valueTitles.put("IR Inten", "Intensity"); + valueTitles.put("Rot. str.", "Strength"); + valueTitles.put("Raman Activ", "Activity"); + valueTitles.put("Depolar (P)", "Depolarization"); + valueTitles.put("Depolar (U)", "Depolarization"); + + refTable.put(VIBRATIONAL_SPECTRUM.INFRARED_SPECTRUM, "IR Inten"); + refTable.put(VIBRATIONAL_SPECTRUM.VCD_ROTATIONAL_STRENGTH_SPECTRUM, "Rot. str."); + refTable.put(VIBRATIONAL_SPECTRUM.RAMAN_SPECTRUM, "Raman Activ"); + refTable.put(VIBRATIONAL_SPECTRUM.P_DEPOLARIZATION_SPECTRUM, "Depolar (P)"); + refTable.put(VIBRATIONAL_SPECTRUM.U_DEPOLARIZATION_SPECTRUM, "Depolar (U)"); + } + + private Map properties = new HashMap (); + private int nVectors; + private String symbol; + private double frequencyValue; + private float reducedMass, frcConst, IR_Intencity, Raman_Activ, Depolar_P, Depolar_U; + Point3f vectors[]; + + public GaussianFrequency(int n_vectors) { + nVectors = n_vectors; + vectors = new Point3f[nVectors]; + for (int i = 0; i < nVectors; i++) { + vectors[i] = new Point3f(); + } + } + + public boolean hasDisplacementVectors() { + return !(vectors == null || vectors.length < 1); + } + + public float[][] getDisplacementVectors() { + if (vectors == null || vectors.length < 1) { + return null; + } + float[][] vect = new float[vectors.length][3]; + for (int i = 0; i < vectors.length; i++) { + vect[i][0] = vectors[i].getX(); + vect[i][1] = vectors[i].getY(); + vect[i][2] = vectors[i].getZ(); + } + return vect; + } + + public void setSymbol(String sym) { + symbol = sym; + } + + public boolean hasSpectrum(VIBRATIONAL_SPECTRUM spectrum) { + if (properties == null || properties.size() < 1) { + return false; + } + if (!properties.containsKey("Frequencies")) { + return false; + } + + String spectrum_name = refTable.get(spectrum); + if (spectrum_name == null) { + return false; + } + + return properties.containsKey( spectrum_name ); + + } + + public boolean hasSpectrum(String spectrum) { + if (properties == null || properties.size() < 1) { + return false; + } + if (!properties.containsKey("Frequencies")) { + return false; + } + + String spectrum_name = spectrum; + if (aliases.containsKey(spectrum)) { + spectrum_name = aliases.get(spectrum); + } + + return properties.containsKey( spectrum_name ); + + } + + public int vibrationalSpectraCount() { + if (properties == null || properties.size() < 1) { + return 0; + } + if (!properties.containsKey("Frequencies")) { + return 0; + } + int count = 0; + if (properties.containsKey("IR Inten")) { + ++count; + } + if (properties.containsKey("Rot. str.")) { + ++count; + } + + return count; + } + + public VIBRATIONAL_SPECTRUM[] availableVibrationalSpectra() { + if (properties == null || properties.size() < 1) { + return null; + } + if (!properties.containsKey("Frequencies")) { + return null; + } + + List spectra = new ArrayList (); + if (properties.containsKey("IR Inten")) { + spectra.add(VIBRATIONAL_SPECTRUM.INFRARED_SPECTRUM); + } + if (properties.containsKey("Rot. str.")) { + spectra.add(VIBRATIONAL_SPECTRUM.VCD_ROTATIONAL_STRENGTH_SPECTRUM); + } + if (properties.containsKey("Raman Activ")) { + spectra.add(VIBRATIONAL_SPECTRUM.RAMAN_SPECTRUM); + } + if (properties.containsKey("Depolar (P)")) { + spectra.add(VIBRATIONAL_SPECTRUM.P_DEPOLARIZATION_SPECTRUM); + } + if (properties.containsKey("Depolar (U)")) { + spectra.add(VIBRATIONAL_SPECTRUM.U_DEPOLARIZATION_SPECTRUM); + } + + if (spectra.size() < 1) { + return null; + } + + VIBRATIONAL_SPECTRUM[] sp = new VIBRATIONAL_SPECTRUM[spectra.size()]; + spectra.toArray(sp); + + return sp; + } + + public void setProperty(String name, double value) { + properties.put(name, new Double(value)); + } + + public double getProperty(VIBRATIONAL_SPECTRUM spectrum) throws Exception { + String name = refTable.get(spectrum); + if (name == null) { + throw new Exception("Unknown spectrum " + spectrum.toString()); + } + return getProperty(name); + } + + public double getProperty(String name) throws Exception { + + if (aliases.containsKey(name)) { + name = aliases.get(name); + } + + if (!properties.containsKey(name)) { + throw new Exception("No such frequencies property " + name); + } + return properties.get(name); + } + + public String getXTitle(String name) throws Exception { + + if (aliases.containsKey(name)) { + name = aliases.get(name); + } + + if (!properties.containsKey(name)) { + throw new Exception("No such frequencies property " + name); + } + return "Frequency"; + } + + public String getYTitle(String name) throws Exception { + + if (aliases.containsKey(name)) { + name = aliases.get(name); + } + + if (!properties.containsKey(name)) { + throw new Exception("No such frequencies property " + name); + } + return valueTitles.get(name); + } + + /** + * Parses lines of type + * Frequencies -- 1739.7799 1739.7799 3186.7640 + * @param line String - line to be parsed + * @param values double[3] + * @return String - property name + * @throws Exception + */ + static public String parsePropLine(String line, double[] values) throws Exception { + int n = line.indexOf("--"); + if (n == -1 || n == 0) { + throw new Exception("Cannot find frequency property"); + } + else if (n + 2 >= line.length()) { + throw new Exception("No values for frequency property"); + } + String name = line.substring(0, n - 1).trim(); + String val = line.substring(n + 2).trim(); + StringTokenizer st = new StringTokenizer(val, " \t"); + + if (st.countTokens() < 1 || st.countTokens() > 3) { + throw new Exception("Expecting 1 to 3 values, got " + st.countTokens()); + } + + //values = new double[st.countTokens()]; + + int num = st.countTokens(); + for (int i = 0; i < num; i++) { + String token = st.nextToken(); + try { + values[i] = Double.parseDouble(token); + } + catch (Exception ex) { + throw new Exception("Cannot parse value (" + token + ") for property " + name + " : " + ex.getMessage()); + } + } + + return name; + } +} diff --git a/src/main/java/cct/gaussian/GaussianJob.java b/src/main/java/cct/gaussian/GaussianJob.java new file mode 100644 index 0000000..a99c697 --- /dev/null +++ b/src/main/java/cct/gaussian/GaussianJob.java @@ -0,0 +1,117 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian; + +import java.util.ArrayList; +import java.util.List; + +import cct.interfaces.MoleculeInterface; +import cct.interfaces.MoleculeSelectorInterface; +import cct.modelling.MolecularGeometry; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2009 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class GaussianJob + extends ArrayList + implements MoleculeSelectorInterface { + + public GaussianJob() { + } + + public int countSteps() { + return this.size(); + } + + public GaussianStep getStep(int n) { + if (countSteps() < 1) { + return null; + } + if (n < 0) { + System.err.println("Warning: GaussianStep: n < 0: 0 index was used..."); + return this.get(0); + } + else if (n >= countSteps()) { + System.err.println("Warning: GaussianStep: n >= countSteps(): the last index was used..."); + return this.get(countSteps() - 1); + } + return this.get(n); + } + + public void addStep(GaussianStep step) { + this.add(step); + } + + @Override + public MoleculeInterface getMolecule(int n) { + GaussianStep step = getStep(n); + if (step == null) { + return null; + } + return step.getMolecule(); + } + + public List getGeometries(int n) { + GaussianStep step = getStep(n); + if (step == null) { + return null; + } + return step.getGeometries(); + } + + @Override + public int countMolecules() { + return this.size(); + } + + @Override + public String getMoleculeDescription(int n) throws Exception { + GaussianStep step = getStep(n); + return step.getDescription(); + } + +} diff --git a/src/main/java/cct/gaussian/GaussianKeywords.java b/src/main/java/cct/gaussian/GaussianKeywords.java new file mode 100644 index 0000000..951bee4 --- /dev/null +++ b/src/main/java/cct/gaussian/GaussianKeywords.java @@ -0,0 +1,608 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian; + +import cct.Constants; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class GaussianKeywords { + + public static final int JOB_UNKNOWN = 0; + + static final int KEYWORD_UNKNOWN = 0; + static final int KEYWORD_JOB_TYPE = 1; + static final int KEYWORD_METHOD = 2; + static final int KEYWORD_BASIS_SET = 3; + static final int KEYWORD_GEOM = 4; + + static final int WAVEFUNCTION_R = 0; + static final int WAVEFUNCTION_U = 1; + static final int WAVEFUNCTION_RO = 2; + + static final Map jobTypes = new HashMap(); + static final Map allKeywords = new HashMap(); + static final Set freqOptions = new HashSet(); + static final Set geomOptions = new HashSet(); + + protected int Wavefunction_type = WAVEFUNCTION_R; + protected String Method = "HF"; + protected String jobType = "SP"; + protected String basisSet = "STO-3G"; + protected String Options = null; + protected double distanceUnits = 1.0; + + protected boolean skipTitleSection = false; + protected boolean skipChargeSection = false; + protected boolean skipMoleculeSpecification = false; + protected boolean isONIOM = false; + static final Logger logger = Logger.getLogger(GaussianKeywords.class.getCanonicalName()); + + static { + final int JOB_SINGLE_POINT_ENERGY = 1; + final int JOB_GEOM_OPTIMIZATION = 2; + final int JOB_FREQUENCY_ANALYSIS = 3; + final int JOB_REACTION_PATH = 4; + final int JOB_MAXIMUM_ENERGY = 5; + final int JOB_SURFACE_SCAN = 6; + final int JOB_POLARIZABILITIES = 7; + final int JOB_DYNAMICS_ADMP = 8; + final int JOB_DYNAMICS_BOMD = 9; + final int JOB_COMPUTE_FORCES = 10; + final int JOB_TEST_WAVEFUNCTION = 11; + final int JOB_COMPUTE_VOLUME = 12; + final int JOB_RECOMPUTE_POP_ANALYSIS = 13; + final int JOB_INITIAL_GUESS = 14; + final int JOB_EXTRACT_ARCHIVE = 15; + + // 1) Not all MM options are here + // 2) no Frozen Core Options + + // --- Method keywords + allKeywords.put("AM1", new Integer(KEYWORD_METHOD)); + allKeywords.put("BD", new Integer(KEYWORD_METHOD)); + allKeywords.put("CASSCF", new Integer(KEYWORD_METHOD)); + allKeywords.put("CAS", new Integer(KEYWORD_METHOD)); + allKeywords.put("CBS-4M", new Integer(KEYWORD_METHOD)); + allKeywords.put("CBS-LQ", new Integer(KEYWORD_METHOD)); + allKeywords.put("CBS-Q", new Integer(KEYWORD_METHOD)); + allKeywords.put("CBS-QB3", new Integer(KEYWORD_METHOD)); + allKeywords.put("CBS-APNO", new Integer(KEYWORD_METHOD)); + allKeywords.put("CC", new Integer(KEYWORD_METHOD)); + allKeywords.put("CCD", new Integer(KEYWORD_METHOD)); + allKeywords.put("CCSD", new Integer(KEYWORD_METHOD)); + allKeywords.put("CIS", new Integer(KEYWORD_METHOD)); + allKeywords.put("CNDO", new Integer(KEYWORD_METHOD)); + allKeywords.put("DFT", new Integer(KEYWORD_METHOD)); + allKeywords.put("G1", new Integer(KEYWORD_METHOD)); + allKeywords.put("G2", new Integer(KEYWORD_METHOD)); + allKeywords.put("G2MP2", new Integer(KEYWORD_METHOD)); + allKeywords.put("G3", new Integer(KEYWORD_METHOD)); + allKeywords.put("G3MP2", new Integer(KEYWORD_METHOD)); + allKeywords.put("G3B3", new Integer(KEYWORD_METHOD)); + allKeywords.put("G3MP2B3", new Integer(KEYWORD_METHOD)); + allKeywords.put("GVB", new Integer(KEYWORD_METHOD)); + allKeywords.put("HF", new Integer(KEYWORD_METHOD)); + allKeywords.put("INDO", new Integer(KEYWORD_METHOD)); + allKeywords.put("MINDO3", new Integer(KEYWORD_METHOD)); + allKeywords.put("MNDO", new Integer(KEYWORD_METHOD)); + allKeywords.put("MP2", new Integer(KEYWORD_METHOD)); + allKeywords.put("MP3", new Integer(KEYWORD_METHOD)); + allKeywords.put("MP4", new Integer(KEYWORD_METHOD)); + allKeywords.put("MP5", new Integer(KEYWORD_METHOD)); + allKeywords.put("ONIOM", new Integer(KEYWORD_METHOD)); + allKeywords.put("OVGF", new Integer(KEYWORD_METHOD)); + allKeywords.put("PM3", new Integer(KEYWORD_METHOD)); + allKeywords.put("QCID", new Integer(KEYWORD_METHOD)); + allKeywords.put("QCISD", new Integer(KEYWORD_METHOD)); + allKeywords.put("TD", new Integer(KEYWORD_METHOD)); + allKeywords.put("W1U", new Integer(KEYWORD_METHOD)); + allKeywords.put("W1BD", new Integer(KEYWORD_METHOD)); + allKeywords.put("ZINDO", new Integer(KEYWORD_METHOD)); + + // --- Basis set (AUG -?) + allKeywords.put("STO-3G", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("3-21G", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("6-21G", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("4-31G", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("6-31G", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("6-311G", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("6-311+G", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("MC-311G", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("D95V", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("D95", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("SHC", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("SEC", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("CEP-4G", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("CEP-31G", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("CEP-121G", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("LANL2MB", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("LANL2DZ", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("SDD", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("SDDALL", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("CC-PVDZ", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("CC-PVTZ", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("CC-PVQZ", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("CC-PV5Z", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("CC-PV6Z", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("SV", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("SVP", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("TZV", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("TZVP", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("MIDIX", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("EPR-II", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("EPR-III", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("UGBS", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("UGBS1P", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("UGBS2P", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("UGBS3P", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("MTSMALL", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("DGDZVP", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("DGDZVP2", new Integer(KEYWORD_BASIS_SET)); + allKeywords.put("DGTZVP", new Integer(KEYWORD_BASIS_SET)); + + // --- Job types + allKeywords.put("SP", new Integer(KEYWORD_JOB_TYPE)); + allKeywords.put("OPT", new Integer(KEYWORD_JOB_TYPE)); + allKeywords.put("FREQ", new Integer(KEYWORD_JOB_TYPE)); + allKeywords.put("IRC", new Integer(KEYWORD_JOB_TYPE)); + allKeywords.put("IRCMAX", new Integer(KEYWORD_JOB_TYPE)); + allKeywords.put("SCAN", new Integer(KEYWORD_JOB_TYPE)); + allKeywords.put("POLAR", new Integer(KEYWORD_JOB_TYPE)); + allKeywords.put("ADMP", new Integer(KEYWORD_JOB_TYPE)); + allKeywords.put("BOMD", new Integer(KEYWORD_JOB_TYPE)); + allKeywords.put("FORCE", new Integer(KEYWORD_JOB_TYPE)); + allKeywords.put("STABLE", new Integer(KEYWORD_JOB_TYPE)); + allKeywords.put("VOLUME", new Integer(KEYWORD_JOB_TYPE)); + allKeywords.put("DENSITY", new Integer(KEYWORD_JOB_TYPE)); + allKeywords.put("GUESS", new Integer(KEYWORD_JOB_TYPE)); + allKeywords.put("REARCHIVE", new Integer(KEYWORD_JOB_TYPE)); + + allKeywords.put("#", new Integer(KEYWORD_UNKNOWN)); + allKeywords.put("ARCHIVE", new Integer(KEYWORD_UNKNOWN)); + + allKeywords.put("CHARGE", new Integer(KEYWORD_UNKNOWN)); + allKeywords.put("CPHF", new Integer(KEYWORD_UNKNOWN)); + // --- MM Options + allKeywords.put("AMBER", new Integer(KEYWORD_UNKNOWN)); + allKeywords.put("DREIDING", new Integer(KEYWORD_UNKNOWN)); + allKeywords.put("GEOM", new Integer(KEYWORD_GEOM)); + allKeywords.put("UFF", new Integer(KEYWORD_UNKNOWN)); + allKeywords.put("QEQ", new Integer(KEYWORD_UNKNOWN)); + allKeywords.put("UNTYPED", new Integer(KEYWORD_UNKNOWN)); + allKeywords.put("UNCHARGED", new Integer(KEYWORD_UNKNOWN)); + allKeywords.put("HARDFIRST", new Integer(KEYWORD_UNKNOWN)); + allKeywords.put("SOFTFIRST", new Integer(KEYWORD_UNKNOWN)); + allKeywords.put("SOFTONLY", new Integer(KEYWORD_UNKNOWN)); + allKeywords.put("CHKPARAMETERS", new Integer(KEYWORD_UNKNOWN)); + allKeywords.put("NEWPARAMETERS", new Integer(KEYWORD_UNKNOWN)); + allKeywords.put("MODIFY", new Integer(KEYWORD_UNKNOWN)); + allKeywords.put("FIRSTEQUIV", new Integer(KEYWORD_UNKNOWN)); + allKeywords.put("LASTEQUIV", new Integer(KEYWORD_UNKNOWN)); + + allKeywords.put("FREQ", new Integer(KEYWORD_UNKNOWN)); + + allKeywords.put("ARCHIVE", new Integer(KEYWORD_UNKNOWN)); + allKeywords.put("ARCHIVE", new Integer(KEYWORD_UNKNOWN)); + allKeywords.put("ARCHIVE", new Integer(KEYWORD_UNKNOWN)); + + // --- Job Types + jobTypes.put("SP", new Integer(JOB_SINGLE_POINT_ENERGY)); + jobTypes.put("OPT", new Integer(JOB_GEOM_OPTIMIZATION)); + jobTypes.put("FREQ", new Integer(JOB_FREQUENCY_ANALYSIS)); + jobTypes.put("IRC", new Integer(JOB_REACTION_PATH)); + jobTypes.put("IRCMAX", new Integer(JOB_MAXIMUM_ENERGY)); + jobTypes.put("SCAN", new Integer(JOB_SURFACE_SCAN)); + jobTypes.put("POLAR", new Integer(JOB_POLARIZABILITIES)); + jobTypes.put("ADMP", new Integer(JOB_DYNAMICS_ADMP)); + jobTypes.put("BOMD", new Integer(JOB_DYNAMICS_BOMD)); + jobTypes.put("FORCE", new Integer(JOB_COMPUTE_FORCES)); + jobTypes.put("STABLE", new Integer(JOB_TEST_WAVEFUNCTION)); + jobTypes.put("VOLUME", new Integer(JOB_COMPUTE_VOLUME)); + jobTypes.put("DENSITY", new Integer(JOB_RECOMPUTE_POP_ANALYSIS)); + jobTypes.put("GUESS", new Integer(JOB_INITIAL_GUESS)); + jobTypes.put("REARCHIVE", new Integer(JOB_EXTRACT_ARCHIVE)); + + // --- frequency options + freqOptions.add("VCD"); + freqOptions.add("RAMAN"); + freqOptions.add("NRAMAN"); + freqOptions.add("NNRAMAN"); + freqOptions.add("NORAMAN"); + freqOptions.add("VIBROT"); + freqOptions.add("ANHARMONIC"); + freqOptions.add("READANHARM"); + freqOptions.add("READFC"); + freqOptions.add("HPMODES"); + freqOptions.add("INTERNALMODES"); + freqOptions.add("ANALYTIC"); + freqOptions.add("NUMERICAL"); + freqOptions.add("ENONLY"); + freqOptions.add("CUBIC"); + freqOptions.add("STEP"); + freqOptions.add("RESTART"); + freqOptions.add("PROJECTED"); + freqOptions.add("HINDEREDROTOR"); + freqOptions.add("MODREDUNDANT"); + freqOptions.add("READISOTOPES"); + + // GEOM options + geomOptions.add("CHECKPOINT"); + geomOptions.add("ALLCHECK"); + geomOptions.add("STEP"); + geomOptions.add("MODREDUNDANT"); + geomOptions.add("MODIFY"); + geomOptions.add("CONNECT"); + geomOptions.add("MODCONNECT"); + geomOptions.add("ZMCONNECT"); + geomOptions.add("IHARMONIC"); + geomOptions.add("CHKHARMONIC"); + geomOptions.add("READHARMONIC"); + geomOptions.add("OLDREDUNDANT"); + geomOptions.add("DISTANCE"); + geomOptions.add("NODISTANCE"); + } + + //*********************************************************** + public void addOptions(String opt) { + if (opt == null) { + return; + } + if (Options != null) { + Options += " "; + Options += opt; + } + else { + Options = opt; + } + } + + //public Wavefunction_type = WAVEFUNCTION_R; + public String getMethod() { + return Method; + } + + public String getJobType() { + return jobType; + } + + public String getBasisSet() { + return basisSet; + } + + public String getOptions() { + return Options; + } + + //*********************************************************** + public void parseOptions() { + String opts = Options.toUpperCase(); + StringTokenizer subtok, tokens = new StringTokenizer(opts, " ,/"); + String token, option, RO, subtoken; + Integer keyword_type; + boolean suboptions = false, one_option = false, many_options = false; + + if (opts.matches(".*?UNITS\\s*?[=]\\s*?AU.*?")) { + distanceUnits = Constants.ONE_BOHR; + } + + logger.info("Starting Parsing keywords..."); + while (tokens.hasMoreTokens()) { + token = tokens.nextToken(); + if (token == null) { + return; + } + logger.info("Parsing token: " + token); + + /* + if ( one_option ) { + logger.info("Parsing token: " + token + " - assuming it's the only option"); + one_option = false; + continue; + } + */ + if (many_options) { + if (token.indexOf(')') != -1) { + logger.info(" - last in many options"); + many_options = false; + } + else { + logger.info(" - continue to skip options"); + } + continue; + } + + // --- Try to determine wheather we have option(s) with a keyword + suboptions = false; + subtok = new StringTokenizer(token, "=("); + subtoken = subtok.nextToken(); + + // Try to determine number of options + if (subtoken.length() != token.length()) { + // keyword=(option) or keyword(option) + if (token.indexOf('(') != -1 && token.indexOf(')') != -1) { + one_option = true; + } + // keyword=(option, + else if (token.indexOf('(') != -1) { + many_options = true; + } + // keyword=option + else if (token.indexOf('=') != -1) { + one_option = true; + } + + } + + if (token.startsWith("ONIOM")) { + isONIOM = true; + continue; + } + + // --- Go through all keywords + Set set = allKeywords.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + option = me.getKey().toString(); + keyword_type = (Integer) me.getValue(); + + if (token.startsWith(option) && + subtoken.compareTo(option) == 0) { // We got a keyword + logger.info("Find keyword: " + subtoken); + if (keyword_type.intValue() == KEYWORD_METHOD) { + Method = subtoken; + } + else if (keyword_type.intValue() == KEYWORD_BASIS_SET) { + basisSet = subtoken; + } + else if (keyword_type.intValue() == KEYWORD_JOB_TYPE) { + jobType = subtoken; + } + else if (keyword_type.intValue() == KEYWORD_GEOM) { + parseGEOMKeyword(token, tokens); + } + + } + else if (keyword_type.intValue() == KEYWORD_METHOD) { + if (subtoken.startsWith("R")) { + RO = "R" + option; + if (subtoken.compareTo(RO) == 0) { + logger.info("Find keyword: " + subtoken); + Method = subtoken; + Wavefunction_type = WAVEFUNCTION_R; + } + } + else if (subtoken.startsWith("U")) { + RO = "U" + option; + if (subtoken.compareTo(RO) == 0) { + logger.info("Find keyword: " + subtoken); + Method = subtoken; + Wavefunction_type = WAVEFUNCTION_U; + } + } + else if (subtoken.startsWith("RO")) { + RO = "RO" + option; + if (subtoken.compareTo(RO) == 0) { + logger.info("Find keyword: " + subtoken); + Method = subtoken; + Wavefunction_type = WAVEFUNCTION_RO; + } + } + } + } // --- End of while ( iter.hasNext() ) + + } + + } + + /** + * Returns true in the case of success, false otherwise + * @param token String + * @param tokens StringTokenizer + * @return boolean + */ + public boolean parseGEOMKeyword(String token, StringTokenizer tokens) { + if ( (token = stripKeyword(token, "GEOM")) == null) { + return false; + } + + boolean manyOptions = false; + String option = getOption(token); + logger.info("parseGEOMKeyword: Parsing token: " + token); + + if (option.startsWith("CHECKPOINT") || option.startsWith("CHECK")) { + skipMoleculeSpecification = true; + logger.info("parseGEOMKeyword: Found option: " + option); + } + else if (option.startsWith("ALLCHECK")) { + skipMoleculeSpecification = true; + skipTitleSection = true; + skipChargeSection = true; + logger.info("parseGEOMKeyword: Found option: " + option); + } + else if (option.startsWith("MODIFY")) { + skipMoleculeSpecification = true; + logger.info("parseGEOMKeyword: Found option: " + option); + } + + if (lastOption(token, manyOptions)) { + return true; + } + else { + manyOptions = true; + } + + // If we are here we have many options... + + while (tokens.hasMoreTokens()) { + token = tokens.nextToken(); + if (token == null) { + return false; + } + logger.info("parseGEOMKeyword: Parsing token: " + token); + + option = getOption(token); + logger.info("parseGEOMKeyword: Parsing token: " + token); + + if (option.startsWith("CHECKPOINT") || option.startsWith("CHECK")) { + skipMoleculeSpecification = true; + logger.info("parseGEOMKeyword: Found option: " + option); + } + else if (option.startsWith("ALLCHECK")) { + skipMoleculeSpecification = true; + skipTitleSection = true; + skipChargeSection = true; + logger.info("parseGEOMKeyword: Found option: " + option); + } + else if (option.startsWith("MODIFY")) { + skipMoleculeSpecification = true; + logger.info("parseGEOMKeyword: Found option: " + option); + } + + if (lastOption(token, manyOptions)) { + return true; + } + + } + + return true; + } + + /** + * Strips a keyword and returns the rest of the string + * + * @param keyword String + * @return String + */ + String stripKeyword(String str, String keyword) { + if (str.length() <= keyword.length()) { + logger.info("stripKeyword: ERROR: cannot strip keyword " + + keyword + "from string " + str); + return null; + } + else if (str.startsWith(keyword)) { + return str.substring(keyword.length()); + } + logger.info("stripKeyword: ERROR: string " + str + + " does not start from keyword " + keyword); + return null; + } + + String getOption(String str) { + if (str == null) { + return null; + } + String option = str; + if (str.startsWith("=")) { + option = option.substring(1); + } + if (str.startsWith("(")) { + option = option.substring(1); + } + return option; + } + + boolean lastOption(String option, boolean manyOptions) { + if (option == null) { + logger.info("lastOption: ERROR: trying to test zero string"); + return true; + } + + // keyword=(option) or keyword(option) + if (option.indexOf('(') != -1 && option.indexOf(')') != -1) { + return true; + } + // keyword=(option, or keyword(option, + else if (option.indexOf('(') != -1) { + return false; + } + // ,option) + else if (option.indexOf(')') != -1) { + return true; + } + + // keyword=option + else if (option.startsWith("=") && (!manyOptions)) { + return true; + } + + return false; + } + + public boolean isSkipTitleSection() { + return skipTitleSection; + } + + public boolean isSkipChargeSection() { + return skipChargeSection; + } + + public boolean isSkipMoleculeSpecification() { + return skipMoleculeSpecification; + } + + public boolean isONIOMCalculation() { + return isONIOM; + } + + public double getDistanceUnits() { + return distanceUnits; + } + + public void setDistanceUnits(double distanceUnits) { + this.distanceUnits = distanceUnits; + } +} diff --git a/src/main/java/cct/gaussian/GaussianMolecule.java b/src/main/java/cct/gaussian/GaussianMolecule.java new file mode 100644 index 0000000..4776d0d --- /dev/null +++ b/src/main/java/cct/gaussian/GaussianMolecule.java @@ -0,0 +1,1352 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.gaussian; + +import static cct.gaussian.Gaussian.logger; +import java.io.BufferedReader; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import javax.swing.JOptionPane; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.vecmath.Geometry3d; +import java.util.logging.Level; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +enum Link0_Commands { + + MEM, CHK, RWF, INT, D2E, NPROC, KJOB, NPROCSHARED, SAVE, NOSAVE, SUBST, NPROCLINDA, LINDAWORKERS +} + +public class GaussianMolecule + extends ArrayList { + + static boolean Debug = true; + public static final float DEGREES_TO_RADIANS = (float) (Math.PI / 180.0); + int jobType = GaussianKeywords.JOB_UNKNOWN; + int Charge = 0, Multiplicity = 1; + int[] chargeAndMultiplicity = null; + List LinkZeroCommands = new ArrayList(); + Map LinkZeroObjects = new HashMap(); + //ArrayList routeSection = new ArrayList(); + GaussianKeywords routeSection = new GaussianKeywords(); + List titleSection = new ArrayList(); + List chargeSection = new ArrayList(); + List moleculeSpecsSection = new ArrayList(); + //String moleculeSpecsSection = ""; + List cartesians = null; + private double distanceUnits = 1.0; + public Map Parameters = new HashMap(); + static final Logger logger = Logger.getLogger(GaussianMolecule.class.getCanonicalName()); + private static String ATOM_TYPE_REGEX = "^[a-zA-Z0-9]{1,2}[(].*[)].*"; + private static Pattern ATOM_TYPE_MATCHER; + + static { + try { + ATOM_TYPE_MATCHER = Pattern.compile(ATOM_TYPE_REGEX); + } catch (Exception ex) { + logger.severe("Wrong " + ATOM_TYPE_REGEX + " " + ex.getMessage() + " Ignoring & continuing..."); + } + } + + public GaussianMolecule() { + //if (ATOM_TYPE_MATCHER == null) { + // try { + // ATOM_TYPE_MATCHER = Pattern.compile(ATOM_TYPE_REGEX); + // } catch (Exception ex) { + // logger.severe("Wrong " + ATOM_TYPE_REGEX + " " + ex.getMessage() + " Ignoring & continuing..."); + // } + //} + } + + static public void setLoggerLevel(Level level) { + logger.setLevel(level); + GaussianKeywords.logger.setLevel(level); + } + + public void addRouteOptions(String opt) { + routeSection.addOptions(opt); + } + + public void parseRouteOptions() { + routeSection.parseOptions(); + distanceUnits = routeSection.getDistanceUnits(); + } + + public void addLinkZeroCommands(String command) throws Exception { + parseLink0Command(command); + LinkZeroCommands.add(command); + } + + public void parseLink0Command(String command) throws Exception { + command = command.trim(); + if (!command.startsWith("%")) { + throw new Exception("Link0 command should start with %, got " + command); + } + + StringTokenizer st = new StringTokenizer(command, "= ,", false); + + String token = st.nextToken(); + + if (token.length() < 2) { + throw new Exception("Too short Link0 command: " + command); + } + + Link0_Commands link0 = getLinkZeroCommandbject(token.substring(1)); + + //MEM, CHK, RWF, INT, D2E, NPROC, KJOB, NPROCSHARED, SAVE, NOSAVE, SUBST, NPROCLINDA, LINDAWORKERS; + switch (link0) { + case MEM: + if (!st.hasMoreTokens()) { + throw new Exception("Expecting memory value for %" + link0.toString() + " command"); + } + token = st.nextToken(); + MemoryObject memory = null; + try { + memory = new MemoryObject(token); + } catch (Exception ex) { + throw new Exception("Cannot parse memory value: " + ex.getMessage()); + } + + LinkZeroObjects.put(link0, memory); + break; + + case CHK: + if (!st.hasMoreTokens()) { + throw new Exception("Expecting checkfile file name"); + } + token = st.nextToken(); + + LinkZeroObjects.put(link0, token); + break; + + case RWF: + if (!st.hasMoreTokens()) { + throw new Exception("Expecting a single, unified Read-Write file name"); + } + token = st.nextToken(); + + LinkZeroObjects.put(link0, token); + break; + + case INT: + if (!st.hasMoreTokens()) { + throw new Exception("Expecting the two-electron integral file name(s) in %" + link0.toString() + + " command"); + } + token = st.nextToken(); + + LinkZeroObjects.put(link0, token); + break; + + case D2E: + if (!st.hasMoreTokens()) { + throw new Exception("Expecting the two-electron integral derivative file name(s) in %" + link0.toString() + + " command"); + } + token = st.nextToken(); + + LinkZeroObjects.put(link0, token); + break; + + case NPROC: + case NPROCSHARED: + case NPROCLINDA: + if (!st.hasMoreTokens()) { + throw new Exception("Expecting number of processors in %" + link0.toString() + + " command"); + } + + Integer nproc = 0; + try { + nproc = Integer.parseInt(st.nextToken()); + } catch (Exception ex) { + throw new Exception("Cannot parse number of processors in %" + link0.toString() + + " command, got " + command); + } + + LinkZeroObjects.put(link0, nproc); + break; + + case KJOB: + if (!st.hasMoreTokens()) { + throw new Exception("Expecting link number in %" + link0.toString() + + " command"); + } + token = st.nextToken(); + + LinkZeroObjects.put(link0, token); + break; + + case SAVE: + case NOSAVE: + LinkZeroObjects.put(link0, null); + break; + + case SUBST: + if (!st.hasMoreTokens()) { + throw new Exception("Expecting a link from an alternate directory in %" + link0.toString() + + " command"); + } + token = st.nextToken(); + + LinkZeroObjects.put(link0, token); + break; + + case LINDAWORKERS: + if (!st.hasMoreTokens()) { + throw new Exception("Expecting the list of the TCP node nams in %" + link0.toString() + + " command"); + } + token = st.nextToken(); + + LinkZeroObjects.put(link0, token); + break; + } + } + + /** + * Returns memory in KB. The default is 6MW + * + * @return int + */ + public int getMemory() { + if (!LinkZeroObjects.containsKey(Link0_Commands.MEM)) { + return 6 * 8 * 1024; + } + + MemoryObject memory = (MemoryObject) LinkZeroObjects.get(Link0_Commands.MEM); + return memory.memoryInKB; + } + + public int getNumberOfProcessors() { + if (!LinkZeroObjects.containsKey(Link0_Commands.NPROC) + && !LinkZeroObjects.containsKey(Link0_Commands.NPROCSHARED) + && !LinkZeroObjects.containsKey(Link0_Commands.NPROCLINDA)) { + return 1; + } + + Integer nproc = (Integer) LinkZeroObjects.get(Link0_Commands.NPROC); + if (nproc == null) { + nproc = 1; + } + Integer nproc_shared = (Integer) LinkZeroObjects.get(Link0_Commands.NPROCSHARED); + if (nproc_shared == null) { + nproc_shared = 1; + } + Integer nproc_linda = (Integer) LinkZeroObjects.get(Link0_Commands.NPROCLINDA); + if (nproc_linda == null) { + nproc_linda = 1; + } + + int nprocs = 1; + nprocs = Math.max(nproc, nproc_shared); + nprocs = Math.max(nprocs, nproc_linda); + + return nprocs; + } + + /** + * Command should be without initial "%" + * + * @param command String + * @return Link0_Commands + * @throws Exception + */ + Link0_Commands getLinkZeroCommandbject(String command) throws Exception { + for (Link0_Commands c : Link0_Commands.values()) { + if (command.equalsIgnoreCase(c.toString())) { + return c; + } + } + throw new Exception("No such Link0 command: " + command); + } + + public List getLinkZeroCommands() { + return LinkZeroCommands; + } + + public List getTitleSection() { + return titleSection; + } + + public List getChargeSection() { + return chargeSection; + } + + public void setTotalCharge(int charge) { + Charge = charge; + } + + public int[] getChargeAndMultiplicity() { + return this.chargeAndMultiplicity; + } + + public void setTotalMultiplicity(int mult) throws Exception { + if (mult < 1) { + throw new Exception("Wrong multiplicity : " + mult + + " Should be positive"); + } + Multiplicity = mult; + } + + public void setChargeAndMultiplicity(int[] ch) throws Exception { + if (ch.length < 1 || (ch.length % 2) != 0) { + throw new Exception( + "Charge section does not consists of CHARGE MULTIPLICITY pair(s): " + + ch.length); + } + + chargeAndMultiplicity = ch; + Charge = ch[0]; + Multiplicity = ch[1]; + } + +// public ArrayList getMoleculeSpecsSection() { +// return moleculeSpecsSection; +// } + public List getMoleculeSpecsSection() { + return moleculeSpecsSection; + } + + public MoleculeInterface getMolecule(MoleculeInterface mol) { + int natoms = size(); + if (natoms < 1) { + return mol; + } + mol.addMonomer("Gaussian"); + + if (cartesians != null) { + for (int i = 0; i < size(); i++) { + float xyz[]; + AtomInterface atom = mol.getNewAtomInstance(); + GaussianAtom a = getAtom(i); + atom.setAtomicNumber(a.element); + atom.setName(a.name); + xyz = (float[]) cartesians.get(i); + atom.setX(xyz[0]); + atom.setY(xyz[1]); + atom.setZ(xyz[2]); + mol.addAtom(atom); + } + } else { + for (int i = 0; i < size(); i++) { + AtomInterface atom = mol.getNewAtomInstance(); + GaussianAtom a = getAtom(i); + atom.setAtomicNumber(a.element); + atom.setName(a.name); + atom.setX(a.xyz[0]); + atom.setY(a.xyz[1]); + atom.setZ(a.xyz[2]); + mol.addAtom(atom); + } + } + + List props = null; + + // --- Add (if any) link zero commands + + props = getLinkZeroCommands(); + if (props != null) { + for (int i = 0; i < props.size(); i++) { + mol.addProperty(Gaussian.LINK_ZERO_COMMANDS_KEY, props.get(i).toString()); + } + } + + // --- Add route section + + GaussianKeywords gk = getRouteSection(); + if (gk != null && gk.getOptions() != null) { + mol.addProperty(Gaussian.ROUTE_COMMANDS_KEY, gk.getOptions()); + } + + // --- Get title + + props = getTitleSection(); + if (props != null) { + String title = ""; + for (int i = 0; i < props.size(); i++) { + title += props.get(i).toString() + " "; + } + mol.setName(title); + } + + // --- Get charge and multiplicity + + int[] ch = getChargeAndMultiplicity(); + if (ch != null) { + mol.addProperty(MoleculeInterface.ChargeProperty, new Integer(ch[0])); + mol.addProperty(MoleculeInterface.MultiplicityProperty, new Integer(ch[1])); + } + + // --- Molecular specifications + + mol.addProperty(Gaussian.NUMBER_OF_ATOMS_KEY, new Integer(natoms)); + props = getMoleculeSpecsSection(); + for (int i = 0; i < props.size(); i++) { + String line = props.get(i).toString(); + mol.addProperty(Gaussian.MOLEC_SPECS_KEY, line); + } + + return mol; + } + + public String getMoleculeSpecsSectionAsString() { + if (moleculeSpecsSection == null || moleculeSpecsSection.size() < 1) { + return null; + } + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < moleculeSpecsSection.size(); i++) { + buffer.append(moleculeSpecsSection.get(i).toString() + "\n"); + } + return buffer.toString(); + } + + public List getCartesians() { + return cartesians; + } + + public GaussianKeywords getRouteSection() { + return routeSection; + } + + void addMoleculeSpecsItem(String item) { + //if (item.length() == 0 || !item.endsWith("\n")) { + // item = item.concat("\n"); + // } + //moleculeSpecsSection += item; + moleculeSpecsSection.add(item); + } + + public void addAtom(GaussianAtom a) { + add(a); + } + + public GaussianAtom getAtom(int n) { + if (n < 0 || n >= size()) { + return null; + } + return (GaussianAtom) get(n); + } + + public boolean writeLinkZeroCommands(FileOutputStream out) { + for (int i = 0; i < LinkZeroCommands.size(); i++) { + String line = (String) LinkZeroCommands.get(i); + try { + out.write((line + "\n").getBytes()); + } catch (IOException e) { + System.err.println("saveGJF: Error writing Link Zero Commands"); + return false; + } + } + + // --- Final empty line + + if (LinkZeroCommands.size() > 0) { + try { + out.write("\n".getBytes()); + } catch (IOException e) { + System.err.println("saveGJF: Error writing Link Zero Commands"); + return false; + } + + } + return true; + } + + public boolean writeRouteSection(FileOutputStream out) { + String line; + try { + // --- First line + /* + * out.write(("#p ").getBytes()); line = routeSection.getMethod(); if (line != null) { out.write((line + " ").getBytes()); } + * line = routeSection.getJobType(); if (line != null) { out.write((line + " ").getBytes()); } line = + * routeSection.getBasisSet(); if (line != null) { out.write((line + " ").getBytes()); } line = routeSection.getOptions(); if + * (line != null) { out.write((line + " ").getBytes()); } out.write(("\n").getBytes()); + */ + // --- Second line (if any) + line = routeSection.getOptions(); + if (line != null) { + out.write((line + "\n").getBytes()); + } + // --- Empty line + out.write(("\n").getBytes()); + } catch (IOException e) { + System.err.println("saveGJF: Error writing Route Section"); + return false; + } + + return true; + } + + public boolean writeTitleSection(FileOutputStream out) { + for (int i = 0; i < titleSection.size(); i++) { + String line = (String) titleSection.get(i); + try { + out.write((line + "\n").getBytes()); + } catch (IOException e) { + System.err.println("saveGJF: Error writing Title Section"); + return false; + } + } + + // --- Final empty line + + if (titleSection.size() > 0) { + try { + out.write("\n".getBytes()); + } catch (IOException e) { + System.err.println("saveGJF: Error writing Title Section"); + return false; + } + + } + return true; + } + + public boolean writeChargeSection(FileOutputStream out) { + for (int i = 0; i < chargeSection.size(); i++) { + String line = (String) chargeSection.get(i); + try { + out.write((line + " ").getBytes()); + } catch (IOException e) { + System.err.println("saveGJF: Error writing Charge Section"); + return false; + } + } + + try { + out.write("\n".getBytes()); + } catch (IOException e) { + System.err.println("saveGJF: Error writing Charge Section"); + return false; + } + + return true; + } + + public boolean writeAtoms(FileOutputStream out) { + for (int i = 0; i < this.size(); i++) { + GaussianAtom atom = this.getAtom(i); + try { + out.write((atom.getElement() + " ").getBytes()); + out.write((" " + atom.getX() + " " + atom.getY() + " " + atom.getZ()).getBytes()); + out.write(("\n").getBytes()); + } catch (IOException e) { + System.err.println("saveGJF: Error writing Atoms Section"); + return false; + } + } + + try { + out.write(("\n").getBytes()); + } catch (IOException e) { + System.err.println("saveGJF: Error writing Atoms Section"); + return false; + } + + return true; + } + + public int[] parseChargeSection(String line) throws Exception { + int[] ch_and_mult = null; + + if (line == null) { + throw new Exception( + "Charge section has zero length"); + } + + StringTokenizer st = new StringTokenizer(line, " ,", false); + int nTokens = st.countTokens(); + if (nTokens < 1 || (nTokens % 2) != 0) { + throw new Exception( + "Charge section does not consists of CHARGE MULTIPLICITY pair(s)"); + } + + ch_and_mult = new int[nTokens]; + + // --- parse the first pair + + String ch = ""; + /* + * try { ch = st.nextToken(); Charge = Integer.parseInt(ch); ch_and_mult[0] = Charge; } catch (Exception ex) { throw new + * Exception("Error while parsing the total system charge: " + ch + " : " + ex.getMessage()); } + * + * try { ch = st.nextToken(); Multiplicity = Integer.parseInt(ch); ch_and_mult[1] = Multiplicity; } catch (Exception ex) { throw + * new Exception( "Error while parsing the total system multiplicity: " + ch + " : " + ex.getMessage()); } + */ + + // --- parse the rest + + for (int i = 0; i < nTokens; i++) { + try { + ch = st.nextToken(); + ch_and_mult[i] = Integer.parseInt(ch); + } catch (Exception ex) { + throw new Exception( + "Error while parsing the charge or multiplicity: " + + ch + " : " + ex.getMessage()); + } + } + + return ch_and_mult; + } + + /** + * + * @return ArrayList + * @throws IOException + */ + public List parseMoleculeGeometry() throws Exception { + + String specs = this.getMoleculeSpecsSectionAsString(); + + BufferedReader in = new BufferedReader(new StringReader(specs)); + //moleculeSpecsSection)); + List atoms = null; + try { + atoms = parseMoleculeGeometry(in); + if (Debug) { + logger.info("Atoms: " + atoms.size()); + } + this.clear(); + this.addAll(atoms); + } catch (IOException ex) { + throw ex; + } + return atoms; + } + + /** + * + * @param stringBuffer String + * @return ArrayList + * @throws IOException + */ + public List parseMoleculeGeometry(String stringBuffer) throws Exception { + BufferedReader in = new BufferedReader(new StringReader(stringBuffer)); + List atoms = null; + try { + atoms = parseMoleculeGeometry(in); + } catch (IOException ex) { + throw ex; + } + return atoms; + } + + /** + * + * @param in BufferedReader + * @return ArrayList + */ + public List parseMoleculeGeometry(BufferedReader in) throws Exception { + List atoms = new ArrayList(); + String line; + String message = ""; + boolean z_matrix = false; + String atomName = null; + + try { + + // Read molecule + int natoms = 0; + z_matrix = false; + String token = null; + StringTokenizer st = null; + String tokens[] = new String[10]; + GaussianAtom a; + Map parameters = new HashMap(); + Map atref = new HashMap(); + boolean connectivityParam = false; + Matcher m = null; + //Atoms = new AtomParamArray(); + + while ((line = in.readLine()) != null) { + if (Debug) { + logger.info("Parsing: " + line); + } + //Atoms.addMoleculeSpecsItem(line); + line = line.trim().toUpperCase(); + //if (Debug) { + // logger.info("Trimmed line: " + line); + //} + if (line.length() == 0 || line.startsWith("VARIABLES:")) { + break; + } + resetTokens(tokens); + //Tokens = line.split(" ,", Tokens.length); + //Tokens = line.split(","); + boolean complex_atom_type = false; + if (ATOM_TYPE_MATCHER != null) { + try { + m = ATOM_TYPE_MATCHER.matcher(line); + complex_atom_type = m.matches(); + } catch (Exception ex) { + logger.severe("Error while matching a string: " + line + " : " + ex.getMessage() + " Ignoring & continuing..."); + } + } + + if (complex_atom_type) { + int index = line.indexOf(")") + 1; + atomName = line.substring(0, index); + line = line.substring(index); + st = new StringTokenizer(line, " ,"); + } else { + st = new StringTokenizer(line, " ,"); + atomName = st.nextToken(); + } + + + ++natoms; + + a = new GaussianAtom(); + + // ---- Parse Atom Number + + try { + a.parseAtomName(atomName, complex_atom_type); + } catch (Exception ex) { + message += ex.getMessage() + "\n"; + } + atref.put(a.name, natoms); + /* + * a.name = st.nextToken(); a.element = ChemicalElements.getAtomicNumber(a.name); + */ + if (Debug) { + logger.info(" Atom: " + natoms + " " + a.name + " " + a.element + "\n"); + } + + // --- Start to parse atom parameters + + //int number_of_tokens = numberOfTokens(); + int number_of_tokens = st.countTokens(); + if (Debug) { + logger.info(" Number of tokens: " + (number_of_tokens + 1) + "\n"); + } + + // --- Parse 1st Atom + + if (natoms == 1 && number_of_tokens >= 3) { // It looks like it's Cartesian + try { + parseCartesianCoord(a, st); + } catch (Exception ex) { + throw new Exception("Cannot parse line " + line); + } + } else if (natoms == 1 && number_of_tokens == 0) { // It looks like it's Z-matrix + z_matrix = true; + + } // --- Parse 2nd Atom + else if (natoms == 2 && number_of_tokens >= 3 && (!z_matrix)) { // Cartesian + try { + parseCartesianCoord(a, st); + } catch (Exception ex) { + throw new Exception("Cannot parse line " + line); + } + } else if (natoms == 2 && number_of_tokens == 2) { // It looks like it's Z-matrix + // Get i + token = st.nextToken(); + try { + a.ijk[0] = Integer.parseInt(token); + } catch (NumberFormatException e) { + // It's a parameter + a.parijk[0] = token; + connectivityParam = true; + } + + // Get bond length + token = st.nextToken(); + try { + a.xyz[0] = Float.parseFloat(token) * (float) distanceUnits; + } catch (NumberFormatException e) { + a.parxyz[0] = token; + } + + z_matrix = true; + + } // --- Parse 3d Atom + else if (natoms == 3 && number_of_tokens >= 3 && (!z_matrix)) { // Cartesian + try { + parseCartesianCoord(a, st); + } catch (Exception ex) { + throw new Exception("Cannot parse line " + line); + } + } else if (natoms == 3 && number_of_tokens >= 4 && z_matrix) { // It looks like it's Z-matrix + + for (int i = 0; i < 2; i++) { + // --- Parse i & j + token = st.nextToken(); + try { + a.ijk[i] = Integer.parseInt(token); + } catch (NumberFormatException e) { + a.parijk[i] = token; + connectivityParam = true; + } + + // Get bond length and angle + token = st.nextToken(); + try { + a.xyz[i] = Float.parseFloat(token); + if (i == 0) { + a.xyz[i] *= (float) distanceUnits; + } + } catch (NumberFormatException e) { + a.parxyz[i] = token; + } + } + + z_matrix = true; + } // --- Parse atoms > 3 + else if (natoms > 3 && number_of_tokens >= 3 && (!z_matrix)) { // Cartesian + try { + parseCartesianCoord(a, st); + } catch (Exception ex) { + throw new Exception("Cannot parse line " + line); + } + } else if (natoms > 3 && number_of_tokens >= 6 && z_matrix) { // It looks like it's Z-matrix + + for (int i = 0; i < 3; i++) { + // --- Parse i, j, & k + token = st.nextToken(); + try { + a.ijk[i] = Integer.parseInt(token); + } catch (NumberFormatException e) { + a.parijk[i] = token; + connectivityParam = true; + } + + // Get bond length, angle, and dihedral + token = st.nextToken(); + try { + a.xyz[i] = Float.parseFloat(token); + if (i == 0) { + a.xyz[i] *= (float) distanceUnits; + } + } catch (NumberFormatException e) { + a.parxyz[i] = token; + } + } + + if (st.hasMoreTokens()) { // Check for the Alternate Z-matrix Format + token = st.nextToken(); + try { + a.alternateZmatrixFormat = Integer.parseInt(token); + } catch (NumberFormatException e) { + throw new Exception("Expected an additional (integer) field for the Alternate Z-matrix Format. got " + token); + } + } + + z_matrix = true; + } else { + System.err.println("Unable to parse line: " + line + "\n"); + } + + atoms.add(a); + + } // End of while + + logger.info("Number of Atoms: " + atoms.size() + "\n"); + + // -- Now we check whether geometry contain parameters to resolve to... + + int numParams = 0; + for (int i = 0; i < atoms.size(); i++) { + a = (GaussianAtom) atoms.get(i); + if (a.parxyz[0] != null || a.parxyz[1] != null || a.parxyz[2] != null) { + ++numParams; + } + } + + logger.info("Number of parameters to be resolved: " + numParams); + + // --- Parse parameters (if any) + + if (numParams > 0) { + // read parameters + while ((line = in.readLine()) != null) { + logger.info("Parsing: " + line); + //Atoms.addMoleculeSpecsItem(line); + line = line.trim().toUpperCase(); + if (line.length() == 0) { + continue; // Instead of break... + //break; + } + resetTokens(tokens); + //Tokens = line.split(" ,=", Tokens.length); + st = new StringTokenizer(line, " ,="); + //Atoms.Parameters.put(Tokens[0], Tokens[1]); + if (st.countTokens() < 2) { + } else { + token = st.nextToken(); + parameters.put(token, st.nextToken()); + } + } + logger.info("Number of parameters: " + parameters.size() + "\n"); + // Assign parameters + + String param, key; + boolean change_sign = false; + for (int j = 0; j < parameters.size(); j++) { + for (int i = 0; i < atoms.size(); i++) { + a = (GaussianAtom) atoms.get(i); + for (int k = 0; k < 3; k++) { + change_sign = false; + + if (a.parxyz[k] != null) { + key = a.parxyz[k]; + if (a.parxyz[k].startsWith("-")) { + key = a.parxyz[k].substring(1); + change_sign = true; + } + + param = (String) parameters.get(key); + + try { + a.xyz[k] = Float.parseFloat(param); + if (k == 0) { + a.xyz[k] *= (float) distanceUnits; + } + if (change_sign) { + a.xyz[k] = -a.xyz[k]; + } + } catch (NumberFormatException e) { + System.err.println("Cannot convert to float value: " + param + "\n"); + } + } + } + } + } + + // Resolve connectivity paramaters, if any + boolean errors = false; + if (connectivityParam) { + for (int i = 0; i < atoms.size(); i++) { + a = (GaussianAtom) atoms.get(i); + for (int k = 0; k < 3; k++) { + + if (a.parijk[k] != null) { + if (!atref.containsKey(a.parijk[k])) { + throw new Exception("Atom " + (i + 1) + ": connectivity parameter refers to atom " + a.parijk[k] + " but no atom with such name"); + } + a.ijk[k] = atref.get(a.parijk[k]); + } + } + } + } + + // print out atoms with resolved parameters + + if (Debug) { + logger.info("\nAtoms with resolved parameters\n"); + for (int i = 0; i < atoms.size(); i++) { + a = (GaussianAtom) atoms.get(i); + System.out.print((i + 1) + " " + a.name + " " + a.element + " "); + if (z_matrix) { + System.out.print(a.ijk[0] + " "); + } + System.out.print(a.xyz[0] + " "); + if (z_matrix) { + System.out.print(a.ijk[1] + " "); + } + System.out.print(a.xyz[1] + " "); + if (z_matrix) { + System.out.print(a.ijk[2] + " "); + } + System.out.println(String.valueOf(a.xyz[2])); + } + } + } + + if (atoms.size() > 0) { + if (z_matrix) { + List cartesians = fromInternalToCartesians(atoms); + for (int i = 0; i < atoms.size(); i++) { + a = (GaussianAtom) atoms.get(i); + float xyz[] = (float[]) cartesians.get(i); + a.xyz[0] = xyz[0]; + a.xyz[1] = xyz[1]; + a.xyz[2] = xyz[2]; + } + } + } + } catch (IOException e) { + System.err.println("parseMoleculeGeometry: " + e.getMessage()); + throw e; + } + + if (message.length() > 0) { + JOptionPane.showMessageDialog(null, + "Error(s) while parsing molecule specifications\n\n" + + message, "Error", + JOptionPane.ERROR_MESSAGE); + } + + return atoms; + } + + void parseCartesianCoord(GaussianAtom atom, StringTokenizer st) throws Exception { + if (st.countTokens() < 3) { + throw new Exception("Expecting x,y,z coordinates. Got only " + st.countTokens() + " tokens"); + } + String token = null; + + // --- Simple case + + if (st.countTokens() == 3) { + for (int i = 0; i < 3; i++) { + // Get X, Y, and Z + token = st.nextToken(); + try { + atom.xyz[i] = Float.parseFloat(token) * (float) distanceUnits; + } catch (NumberFormatException e) { + atom.parxyz[i] = token; + } + } + return; + } + + // --- Check for optimization/frozen flag + + token = st.nextToken(); + int i_start = 0; + try { + int flag = Integer.parseInt(token); + if (flag != 0 && flag != -1) { + atom.xyz[0] = flag; + i_start = 1; + } else { + atom.frozen = flag == -1; + } + } catch (NumberFormatException e) { + i_start = 1; + try { + atom.xyz[0] = Float.parseFloat(token) * (float) distanceUnits; + } catch (NumberFormatException ex) { + atom.parxyz[0] = token; + } + } + + for (int i = i_start; i < 3; i++) { + // Get X, Y, and Z + token = st.nextToken(); + try { + atom.xyz[i] = Float.parseFloat(token) * (float) distanceUnits; + } catch (NumberFormatException e) { + atom.parxyz[i] = token; + } + } + + // --- Check for ONIOM options (if any) + + // atom coordinate-spec layer [link-atom [bonded-to [scale-fac1 [scale-fac2 [scale-fac3]]]]] + if (routeSection.isONIOMCalculation()) { + // --- Get Layer + if (!st.hasMoreTokens()) { + return; + } + token = st.nextToken(); + try { + atom.setONIOMLayer(token); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + } + + // --- Get link atom + if (!st.hasMoreTokens()) { + return; + } + token = st.nextToken(); + atom.link_atom = token; + + // --- Get bonded-to + if (!st.hasMoreTokens()) { + return; + } + token = st.nextToken(); + try { + atom.Bonded_to = Integer.parseInt(token); + } catch (Exception ex) { + System.err.println("Cannot parse bonded-to atom number: " + token + " : " + ex.getMessage()); + } + + // --- Get scale-fac1 + if (!st.hasMoreTokens()) { + return; + } + token = st.nextToken(); + try { + atom.scale_fac1 = Float.parseFloat(token); + } catch (Exception ex) { + System.err.println("Cannot parse scale-fac1: " + token + " : " + ex.getMessage()); + } + + // --- Get scale-fac2 + if (!st.hasMoreTokens()) { + return; + } + token = st.nextToken(); + try { + atom.scale_fac2 = Float.parseFloat(token); + } catch (Exception ex) { + System.err.println("Cannot parse scale-fac2: " + token + " : " + ex.getMessage()); + } + + // --- Get scale-fac3 + if (!st.hasMoreTokens()) { + return; + } + token = st.nextToken(); + try { + atom.scale_fac3 = Float.parseFloat(token); + } catch (Exception ex) { + System.err.println("Cannot parse scale-fac3: " + token + " : " + ex.getMessage()); + } + + } + + } + + /** + * + * @param params ArrayList + * @return ArrayList + */ + public static List fromInternalToCartesians(List params) throws Exception { + int i, ii, jj, kk, ll; + int natoms = params.size(); + GaussianAtom a, a1, a2, a3; + //Float xyz[] = new Float[3]; + float xyz[], x1[], x2[], x3[]; + + double SIN2, COS2, SIN3, COS3, + VT[] = new double[3], V1[] = new double[3], + V2[] = new double[3]; + double R2, + V3[] = new double[3], VA1, VB1, VC1, R3, V[] = new double[3]; + + if (natoms < 1) { + return null; + } + + List cartesians = new ArrayList(natoms); + + // --- The first atom. Put it into the origin + + xyz = new float[3]; + xyz[0] = 0.0f; + xyz[1] = 0.0f; + xyz[2] = 0.0f; + cartesians.add(xyz); + + if (natoms < 2) { + return cartesians; + } + + // --- ther second atom: put it along the X-axis + + a = (GaussianAtom) params.get(1); + + xyz = new float[3]; + xyz[0] = a.xyz[0]; // So, we put it along X-axis + xyz[1] = 0.0f; + xyz[2] = 0.0f; + cartesians.add(xyz); + + if (natoms < 3) { + return cartesians; + } + + // --- Third atom (put it into the XOY plane + + a = (GaussianAtom) params.get(2); + + x1 = (float[]) cartesians.get(a.ijk[0] - 1); + + xyz = new float[3]; + xyz[2] = 0.0f; // Z-coordinate + + if (a.ijk[0] == 1) { // Connected to the first atom + //logger.info("To the 1st"); + xyz[0] = a.xyz[0] + * (float) Math.cos((double) (a.xyz[1] * DEGREES_TO_RADIANS)); // So, we put it along X-axis + xyz[1] = a.xyz[0] + * (float) Math.sin((double) (a.xyz[1] * DEGREES_TO_RADIANS)); + } else { + //logger.info("To the 2nd"); + xyz[0] = x1[0] + - a.xyz[0] + * (float) Math.cos((double) (a.xyz[1] * DEGREES_TO_RADIANS)); // So, we put it along X-axis + xyz[1] = -a.xyz[0] * (float) Math.sin((double) (a.xyz[1] * DEGREES_TO_RADIANS)); + } + /* + * a = (GaussianAtom) params.get(2); + * + * xyz = new float[3]; xyz[0] = xyz[0] + a.xyz[0] * (float) Math.cos( (double) (a.xyz[1] * 1.74532925199e-2f)); // So, we put it + * along X-axis xyz[1] = xyz[1] + a.xyz[0] * (float) Math.sin( (double) (a.xyz[1] * 1.74532925199e-2f)); xyz[2] = 0.0f; + */ + + cartesians.add(xyz); + + for (i = 3; i < natoms; i++) { + + a = (GaussianAtom) params.get(i); + + x1 = (float[]) cartesians.get(a.ijk[0] - 1); + x2 = (float[]) cartesians.get(a.ijk[1] - 1); + x3 = (float[]) cartesians.get(a.ijk[2] - 1); + + xyz = new float[3]; + + if (a.alternateZmatrixFormat != 0) { + float[] unit = Geometry3d.getForTwoBondAngles( + new float[]{x2[0] - x1[0], x2[1] - x1[1], x2[2] - x1[2]}, + new float[]{x3[0] - x1[0], x3[1] - x1[1], x3[2] - x1[2]}, + a.xyz[1] * DEGREES_TO_RADIANS, a.xyz[2] * DEGREES_TO_RADIANS, a.alternateZmatrixFormat); + xyz[0] = x1[0] + a.xyz[0] * unit[0]; + xyz[1] = x1[1] + a.xyz[0] * unit[1]; + xyz[2] = x1[2] + a.xyz[0] * unit[2]; + cartesians.add(xyz); + continue; + } + + SIN2 = Math.sin((double) (a.xyz[1] * DEGREES_TO_RADIANS)); + COS2 = Math.cos((double) (a.xyz[1] * DEGREES_TO_RADIANS)); + SIN3 = Math.sin((double) (a.xyz[2] * DEGREES_TO_RADIANS)); + COS3 = Math.cos((double) (a.xyz[2] * DEGREES_TO_RADIANS)); + + VT[0] = a.xyz[0] * COS2; + VT[1] = a.xyz[0] * SIN2 * SIN3; + VT[2] = a.xyz[0] * SIN2 * COS3; + + V1[0] = x3[0] - x2[0]; + V1[1] = x3[1] - x2[1]; + V1[2] = x3[2] - x2[2]; + + V2[0] = x2[0] - x1[0]; + V2[1] = x2[1] - x1[1]; + V2[2] = x2[2] - x1[2]; + + R2 = Math.sqrt(V2[0] * V2[0] + V2[1] * V2[1] + V2[2] * V2[2]); + + V3[0] = V1[1] * V2[2] - V1[2] * V2[1]; + V3[1] = V1[2] * V2[0] - V1[0] * V2[2]; + V3[2] = V1[0] * V2[1] - V1[1] * V2[0]; + + R3 = Math.sqrt(V3[0] * V3[0] + V3[1] * V3[1] + V3[2] * V3[2]); + + V2[0] = V2[0] / R2; + V2[1] = V2[1] / R2; + V2[2] = V2[2] / R2; + + V3[0] = V3[0] / R3; + V3[1] = V3[1] / R3; + V3[2] = V3[2] / R3; + + V[0] = V2[1] * V3[2] - V2[2] * V3[1]; + V[1] = V2[2] * V3[0] - V2[0] * V3[2]; + V[2] = V2[0] * V3[1] - V2[1] * V3[0]; + + VA1 = V2[0] * VT[0] + V3[0] * VT[1] + V[0] * VT[2]; + VB1 = V2[1] * VT[0] + V3[1] * VT[1] + V[1] * VT[2]; + VC1 = V2[2] * VT[0] + V3[2] * VT[1] + V[2] * VT[2]; + + xyz[0] = x1[0] + (float) VA1; + xyz[1] = x1[1] + (float) VB1; + xyz[2] = x1[2] + (float) VC1; + + cartesians.add(xyz); + } + return cartesians; + } + + static void resetTokens(String tokens[]) { + for (int i = 0; i < tokens.length; i++) { + tokens[i] = null; + } + } + + private class MemoryObject { + + int memoryInKB = 0; + String Memory; + + public MemoryObject(String memory) throws Exception { + // Sets the amount of dynamic memory used to N words (8N bytes). + // The default is 6MW. N may be optionally followed by a units designation: KB, MB, GB, KW, MB or GW. + Memory = memory; + memory = memory.toUpperCase(); + if (memory.matches(".+KB")) { + memoryInKB = Integer.parseInt(memory.substring(0, memory.length() - 2)); + } else if (memory.matches(".+MB")) { + memoryInKB = Integer.parseInt(memory.substring(0, memory.length() - 2)) * 1024; + } else if (memory.matches(".+GB")) { + memoryInKB = Integer.parseInt(memory.substring(0, memory.length() - 2)) * 1024 * 1024; + } else if (memory.matches(".+KW")) { + memoryInKB = Integer.parseInt(memory.substring(0, memory.length() - 2)) * 8; + } else if (memory.matches(".+MW")) { + memoryInKB = Integer.parseInt(memory.substring(0, memory.length() - 2)) * 8 * 1024; + } else if (memory.matches(".+GW")) { + memoryInKB = Integer.parseInt(memory.substring(0, memory.length() - 2)) * 8 * 1024 * 1024; + } else { + memoryInKB = Integer.parseInt(memory) * 8; + memoryInKB = (int) ((float) memoryInKB / 1024.0f); + } + } + } +} diff --git a/src/main/java/cct/gaussian/GaussianOutput.java b/src/main/java/cct/gaussian/GaussianOutput.java new file mode 100644 index 0000000..08fd862 --- /dev/null +++ b/src/main/java/cct/gaussian/GaussianOutput.java @@ -0,0 +1,1850 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.gaussian; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.ChemicalElements; +import cct.modelling.GeneralMolecularDataParser; +import cct.modelling.MolecularGeometry; +import cct.modelling.MolecularProperties; +import cct.vecmath.Point3f; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.io.StringWriter; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Pattern; + +/** + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2004

+ * + *

+ * Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class GaussianOutput extends GeneralMolecularDataParser + implements MolecularProperties { + + static final int VERSION_UNKNOWN = 0; + static final int VERSION_G94 = 1; + static final int VERSION_G98 = 2; + private static final int VERSION_G03 = 3; + + public static final String INPUT_ORIENTATION_KEY = "Input orientation"; + public static final String STANDARD_ORIENTATION_KEY = "Standard orientation"; + public static final String Z_MATRIX_ORIENTATION_KEY = "Z-Matrix orientation"; + + static Pattern freqVecPattern = Pattern.compile("\\s*Atom\\s+AN\\s+X\\s+Y.*"); + + static boolean Debug = true; + + private GaussianStep step = null; + private String scfEnergy = null; + private Set availableStructures = new HashSet(); + private Set availableProperties = new HashSet(); + private Set propertiesToChart = new HashSet(); + private Map outputResume = new LinkedHashMap(); + private List frequencies = new ArrayList(); + private boolean normalTermination = false; + private Map diffGeometries = new HashMap(); + private List snapshots = new ArrayList(); + private GaussianMolecule gaussMol; + private Level logLevel = Level.WARNING; + static final Logger logger = Logger.getLogger(GaussianOutput.class.getCanonicalName()); + + public GaussianOutput() { + } + + public void setLoggerLevel(Level level) { + logLevel = level; + logger.setLevel(level); + GaussianMolecule.setLoggerLevel(level); + } + + public String[] getAvailPropToChart() { + if (propertiesToChart.size() < 1) { + return null; + } + String[] sa = new String[propertiesToChart.size()]; + propertiesToChart.toArray(sa); + return sa; + } + + public int getSnapshotsCount() { + return snapshots.size(); + } + + public List getFrequencies() { + return frequencies; + } + + public boolean isNormalTermination() { + return normalTermination; + } + + public GaussianJob parseFile(MoleculeInterface mol, String filename, boolean update) throws Exception { + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(filename)); + } catch (Exception ex) { + throw new Exception("Cannot open file " + filename + ": " + ex.getMessage()); + } + GaussianJob gaussianJob = new GaussianJob(); + step = null; + int count = 1; + do { + MoleculeInterface molecule = mol.getInstance(); + step = parseFile(molecule, in, update); + + if (step == null) { + break; + } + + step.setNormalTermination(this.isNormalTermination()); + + if (this.countFrequencies() > 0) { + step.setFrequencies(this.getFrequencies()); + } + frequencies.clear(); + + GaussianKeywords gk = gaussMol.getRouteSection(); + step.setDescription(String.valueOf(count) + ": " + gk.getOptions()); + + gaussMol = null; + + step.setChartProperties(propertiesToChart); + propertiesToChart.clear(); + + step.setOutputResume(outputResume); + outputResume.clear(); + + step.setSnapshots(snapshots); + snapshots.clear(); + + if (step.getMolecule().getNumberOfAtoms() < 1 && step.countFrequencies() < 1) { + break; + } + + gaussianJob.addStep(step); + ++count; + } while (!step.isFinalStep()); + + try { + in.close(); + } catch (Exception ex) { + System.err.println("Warning: Cannot close file " + filename + ": " + ex.getMessage()); + } + + return gaussianJob; + } + + public GaussianStep parseFile(MoleculeInterface mol, BufferedReader in, boolean update) { + String line, token; + String Info = new String(); + String mulliken = new String(); + String espCharges = new String(); + StringTokenizer st; + int g_version = VERSION_UNKNOWN; + MolecularGeometry geom = null; + Map outputResults = new HashMap(); + step = null; + gaussMol = new GaussianMolecule(); + + List Geometries = new ArrayList(); + boolean gotCharge = false, gotMulliken = false, gotESP = false; + Double SCF_Energy = null, S_Squared = null, ZeroPointCorr = null; + int errorMessage = 0; + int nBasisFuncs = 0; + GaussianSnapshot snapshot = new GaussianSnapshot(); + + Float EnergyThermCorr = null, EnthalpyThermCorr = null, GibbsThermCorr = null; + + frequencies.clear(); + propertiesToChart.clear(); + outputResume.clear(); + snapshots.clear(); + + try { + + if (!update) { + //mol = new Molecule(); + } + while ((line = in.readLine()) != null) { + //line.trim(); + //logger.info("Parsing line: " + line); + + if (line.contains("Gaussian") && line.contains("Revision")) { + Info.concat(line + "\n"); + this.outputResume.put("Gaussian Rev", line); + } else if (line.indexOf("Normal termination ") != -1) { + normalTermination = true; + Info.concat(line + "\n"); + if (Debug) { + logger.info("Reached Normal termination line"); + } + this.outputResume.put("Normal termination", line); + /* + if (mol.getNumberOfAtoms() == 0) { + if (Debug) { + logger.info("Since number of atoms = 0, continuing..."); + } + continue; + } + */ + break; + } // --- Trying to get the route section + else if (line.startsWith(" #")) { + gaussMol.addRouteOptions(line); + while ((line = in.readLine()) != null && !line.startsWith(" ----------")) { + gaussMol.addRouteOptions(line); + } + gaussMol.parseRouteOptions(); + } // --- Trying to get the %% section + else if (line.startsWith(" %")) { + try { + gaussMol.addLinkZeroCommands(line.trim()); + } catch (Exception ex) { + System.err.println("Getting link0 command: " + line + " : " + ex.getMessage()); + } + } else if (line.contains("basis functions") && line.contains("primitive gaussians")) { + this.outputResume.put("basis functions", line); + st = new StringTokenizer(line, " "); + if (st.countTokens() < 3) { + continue; + } + token = st.nextToken(); + try { + nBasisFuncs = Integer.parseInt(token); + if (Debug) { + logger.info("Number of basis functions " + nBasisFuncs); + } + } catch (Exception ex) { + System.err.println("Warning: cannot parse number of basis functions " + token + ": " + ex.getMessage()); + continue; + } + } else if (line.contains("Step number") && line.contains("out of a maximum of")) { + this.outputResume.put("Step number", line); + } else if (line.contains("Error termination")) { + outputResume.put("Error termination" + String.valueOf(errorMessage), line); + ++errorMessage; + } else if (line.contains("Optimization completed")) { + this.outputResume.put("Optimization completed", line); + } else if (line.contains("Job cpu time")) { + this.outputResume.put("Job cpu time", "\n" + line); + } else if (line.contains("Gaussian 09")) { + g_version = VERSION_G03; + if (Debug) { + logger.info("Gaussian 09"); + } + } else if (line.contains("Gaussian 98")) { + g_version = VERSION_G98; + } else if (line.contains("Gaussian 94")) { + g_version = VERSION_G94; + } else if (line.contains("Job cpu time")) { + Info.concat(line + "\n"); + if (logger.isLoggable(Level.INFO)) { + logger.info("Job cpu time"); + } + } // Reading in Vibration related data + else if (line.contains("Molecular mass:")) { + appendOutputResume(outputResume, "Vibrations-related", "\n" + line); + while ((line = in.readLine()) != null) { + if (line.trim().length() < 1) { + break; + } + appendOutputResume(outputResume, "Vibrations-related", line); + } + } // Thermo-chemistry + else if (line.contains("Zero-point correction=")) { + String label, svalue; + Double value; + double Enthalpies = 0.0, FreeEnergies = 0.0; + appendOutputResume(outputResume, "Thermochemistry", "\n" + line); + try { + label = line.substring(0, line.indexOf("=")).trim(); + svalue = line.substring(line.indexOf("=") + 1, line.indexOf("(")).trim(); + value = new Double(svalue); + availableProperties.add(label); + addToLastSnapshot(label, value); + } catch (Exception ex) { + logger.severe("Cannot parse " + line); + } + // --- + while ((line = in.readLine()) != null) { + if (line.trim().length() < 1) { + break; + } + appendOutputResume(outputResume, "Thermochemistry", line); + try { + label = line.substring(0, line.indexOf("=")).trim(); + svalue = line.substring(line.indexOf("=") + 1).trim(); + value = new Double(svalue); + availableProperties.add(label); + addToLastSnapshot(label, value); + if (line.contains("electronic and thermal Enthalpies")) { + Enthalpies = value; + } else if (line.contains("electronic and thermal Free Energies")) { + FreeEnergies = value; + } + } catch (Exception ex) { + logger.severe("Cannot parse " + line); + } + } + // --- + String[] tokens = null; + line = in.readLine(); + appendOutputResume(outputResume, "Thermochemistry", line); + line = in.readLine(); + appendOutputResume(outputResume, "Thermochemistry", line); + // --- Parse TOTAL contributions + line = in.readLine(); + appendOutputResume(outputResume, "Thermochemistry", line); + try { + label = line.substring(0, 16).trim(); + tokens = line.substring(label.length() + 1).trim().split("\\s+"); + value = new Double(tokens[0]); + availableProperties.add(label + " E(Thermal) KCal/Mol"); + addToLastSnapshot(label + " E(Thermal) KCal/Mol", value); + value = new Double(tokens[1]); + availableProperties.add(label + " CV (Cal/Mol-Kelvin)"); + addToLastSnapshot(label + " CV (Cal/Mol-Kelvin)", value); + value = new Double(tokens[2]); + availableProperties.add(label + " S (Cal/Mol-Kelvin)"); + addToLastSnapshot(label + " S (Cal/Mol-Kelvin)", value); + } catch (Exception ex) { + logger.severe("Cannot parse " + line + " Tokens: " + Arrays.toString(tokens)); + } + // --- Parse Electronic contributions + line = in.readLine(); + appendOutputResume(outputResume, "Thermochemistry", line); + try { + label = line.substring(0, 16).trim(); + tokens = line.substring(16).trim().split("\\s+"); + value = new Double(tokens[0]); + availableProperties.add(label + " E(Thermal) KCal/Mol"); + addToLastSnapshot(label + " E(Thermal) KCal/Mol", value); + value = new Double(tokens[1]); + availableProperties.add(label + " CV (Cal/Mol-Kelvin)"); + addToLastSnapshot(label + " CV (Cal/Mol-Kelvin)", value); + value = new Double(tokens[2]); + availableProperties.add(label + " S (Cal/Mol-Kelvin)"); + addToLastSnapshot(label + " S (Cal/Mol-Kelvin)", value); + } catch (Exception ex) { + logger.severe("Cannot parse " + line + " Tokens: " + Arrays.toString(tokens)); + } + // --- Parse Translational contributions + line = in.readLine(); + appendOutputResume(outputResume, "Thermochemistry", line); + try { + label = line.substring(0, 16).trim(); + tokens = line.substring(16).trim().split("\\s+"); + value = new Double(tokens[0]); + availableProperties.add(label + " E(Thermal) KCal/Mol"); + addToLastSnapshot(label + " E(Thermal) KCal/Mol", value); + value = new Double(tokens[1]); + availableProperties.add(label + " CV (Cal/Mol-Kelvin)"); + addToLastSnapshot(label + " CV (Cal/Mol-Kelvin)", value); + value = new Double(tokens[2]); + availableProperties.add(label + " S (Cal/Mol-Kelvin)"); + addToLastSnapshot(label + " S (Cal/Mol-Kelvin)", value); + } catch (Exception ex) { + logger.severe("Cannot parse " + line + " Tokens: " + Arrays.toString(tokens)); + } + // --- Parse Rotational contributions + line = in.readLine(); + appendOutputResume(outputResume, "Thermochemistry", line); + try { + label = line.substring(0, 16).trim(); + tokens = line.substring(16).trim().split("\\s+"); + value = new Double(tokens[0]); + availableProperties.add(label + " E(Thermal) KCal/Mol"); + addToLastSnapshot(label + " E(Thermal) KCal/Mol", value); + value = new Double(tokens[1]); + availableProperties.add(label + " CV (Cal/Mol-Kelvin)"); + addToLastSnapshot(label + " CV (Cal/Mol-Kelvin)", value); + value = new Double(tokens[2]); + availableProperties.add(label + " S (Cal/Mol-Kelvin)"); + addToLastSnapshot(label + " S (Cal/Mol-Kelvin)", value); + } catch (Exception ex) { + logger.severe("Cannot parse " + line + " Tokens: " + Arrays.toString(tokens)); + } + // --- Parse Vibrational contributions + line = in.readLine(); + appendOutputResume(outputResume, "Thermochemistry", line); + try { + label = line.substring(0, 16).trim(); + tokens = line.substring(16).trim().split("\\s+"); + value = new Double(tokens[0]); + availableProperties.add(label + " E(Thermal) KCal/Mol"); + addToLastSnapshot(label + " E(Thermal) KCal/Mol", value); + value = new Double(tokens[1]); + availableProperties.add(label + " CV (Cal/Mol-Kelvin)"); + addToLastSnapshot(label + " CV (Cal/Mol-Kelvin)", value); + value = new Double(tokens[2]); + availableProperties.add(label + " S (Cal/Mol-Kelvin)"); + addToLastSnapshot(label + " S (Cal/Mol-Kelvin)", value); + } catch (Exception ex) { + logger.severe("Cannot parse " + line + " Tokens: " + Arrays.toString(tokens)); + } + // --- + double EThermal = 0, CV = 0, S = 0; + while ((line = in.readLine()) != null) { + if (line.contains("Q Log10(Q)")) { + break; + } + appendOutputResume(outputResume, "Thermochemistry", line); + // Vibration 10 0.689 1.684 1.448 + tokens = line.substring(16).trim().split("\\s+"); + try { + value = new Double(tokens[0]); + EThermal += value; + value = new Double(tokens[1]); + CV += value; + value = new Double(tokens[2]); + S += value; + } catch (Exception ex) { + logger.severe("Cannot parse " + line + " Tokens: " + Arrays.toString(tokens)); + } + } + // --- Correction for internal rotation + appendOutputResume(outputResume, "Thermochemistry", "Thermal Energy correction for internal rotations: " + + String.valueOf(EThermal) + " kcal/mol"); + EThermal /= 627.51; + // Temperature 298.150 Kelvin. Pressure 1.00000 Atm. + double TdS = S * 298.150 / 1000.0; + appendOutputResume(outputResume, "Thermochemistry", "TdS correction for internal rotations: " + + String.valueOf(TdS) + " kcal/mol"); + TdS /= 627.51; + double corrEnthalpies = Enthalpies - EThermal; + double corrFreeEnergies = FreeEnergies - EThermal + TdS; + appendOutputResume(outputResume, "Thermochemistry", "Internal rotations correction: Enthalpies: " + + String.format("%15.6f", corrEnthalpies) + " Free Energies: " + + String.format("%15.6f", corrFreeEnergies) + " Hartrees"); + } // --- Getting archive data + else if (line.contains("\\GINC-") || line.contains("|UNPC-UNK")) { // Different on PC !!! + if (logger.isLoggable(Level.INFO)) { + logger.info("Reading archive data..."); + } + try { + + String delim = "\\"; + if (line.contains("|UNPC-UNK")) { + delim = "|"; + } + String archive = line; + // Accumulate archive + while ((line = in.readLine()) != null) { + //logger.info("Parsing line: " + line); + if (line.trim().length() == 0) { + break; + } + archive += line.substring(1); + } + + mol.addProperty(MoleculeInterface.ProgramProperty, "Gaussian"); + + // First, extract information from archive variable + if (archive.length() == 0) { + continue; + } + //mol.addProperty(NotesProperty,archive); // Can be too long + + Double value = null; + st = new StringTokenizer(archive, delim); + //logger.info("Archive string: " + archive); + //String tokens[] = archive.split(backsl); + // Go through tokens + //for (int i = 0; i < tokens.length; i++) { + while (st.hasMoreTokens()) { + token = st.nextToken(); + try { + if (token.startsWith("HF=")) { + String temp[] = token.split("="); + SCF_Energy = new Double(temp[1]); + availableProperties.add("HF"); + this.addToLastSnapshot("HF", SCF_Energy); + } else if (token.startsWith("MP2=")) { + String temp[] = token.split("="); + value = new Double(temp[1]); + mol.addProperty(MoleculeInterface.MP2EnergyProperty, value); + availableProperties.add("MP2"); + addToLastSnapshot("MP2", value); + } else if (token.startsWith("MP3=")) { + String temp[] = token.split("="); + value = new Double(temp[1]); + mol.addProperty(MoleculeInterface.MP3EnergyProperty, value); + availableProperties.add("MP3"); + addToLastSnapshot("MP3", value); + } else if (token.startsWith("MP4D=")) { + String temp[] = token.split("="); + value = new Double(temp[1]); + mol.addProperty(MoleculeInterface.MP4DEnergyProperty, value); + availableProperties.add("MP4D"); + addToLastSnapshot("MP4D", value); + } else if (token.startsWith("MP4DQ=")) { + String temp[] = token.split("="); + value = new Double(temp[1]); + mol.addProperty(MoleculeInterface.MP4DQEnergyProperty, value); + availableProperties.add("MP4DQ"); + addToLastSnapshot("MP4DQ", value); + } else if (token.startsWith("MP4SDQ=")) { + String temp[] = token.split("="); + value = new Double(temp[1]); + mol.addProperty(MoleculeInterface.MP4SDQEnergyProperty, value); + availableProperties.add("MP4SDQ"); + addToLastSnapshot("MP4SDQ", value); + } else if (token.startsWith("CCSD=")) { + String temp[] = token.split("="); + value = new Double(temp[1]); + mol.addProperty(MoleculeInterface.CCSDEnergyProperty, value); + availableProperties.add("CCSD"); + addToLastSnapshot("CCSD", value); + } else if (token.startsWith("RMSD=")) { + String temp[] = token.split("="); + value = new Double(temp[1]); + mol.addProperty("RMSD", value); + availableProperties.add("RMSD"); + addToLastSnapshot("CCSD", value); + } else if (token.startsWith("CCSD(T)=")) { + String temp[] = token.split("="); + value = new Double(temp[1]); + mol.addProperty(MoleculeInterface.CCSDTEnergyProperty, value); + availableProperties.add("CCSD(T)"); + addToLastSnapshot("CCSD(T)", value); + } else if (token.startsWith("Version=")) { + String temp[] = token.split("="); + mol.addProperty(MoleculeInterface.VersionProperty, temp[1]); + } else if (token.startsWith("Dipole=")) { + String temp[] = token.split("="); + Float dp = parseDipoleMoment(temp[1]); + if (dp != null) { + mol.addProperty(MoleculeInterface.DipoleMomentProperty, dp); + } + } + + } catch (Exception ex) { + System.err.println("Cannot parse token " + token + " : " + ex.getMessage() + " Ignored..."); + } + + } + } catch (Exception ex) { + logger.severe("Error readin archive data: " + ex.getMessage()); + } + } // --- Getting framework group + else if (line.contains("Framework Group")) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Parsing Framework Group: line: " + line); + } + try { + st = new StringTokenizer(line, " "); + if (st.countTokens() != 3) { + continue; + } + st.nextToken(); // Skip a token + st.nextToken(); // Skip a token + mol.addProperty(MoleculeInterface.FrameGroupProperty, st.nextToken()); + outputResume.put(MoleculeInterface.FrameGroupProperty, line); + } catch (Exception ex) { + logger.severe("Error reading Framework group: " + ex.getMessage()); + } + } else if (line.contains("Gross orbital populations:") && nBasisFuncs > 0) { + appendOutputResume(outputResume, "Gross orbital populations", "\n" + line); + try { + // Total Alpha Beta Spin + line = in.readLine(); + appendOutputResume(outputResume, "Gross orbital populations", line); + + for (int i = 0; i < nBasisFuncs && (line = in.readLine()) != null; i++) { + appendOutputResume(outputResume, "Gross orbital populations", line); + } + } catch (Exception ex) { + logger.severe("Error reading Gross orbital populations: " + ex.getMessage()); + } + } else if (line.contains("Scan the potential surface")) { + appendOutputResume(outputResume, "Scan the potential surface", "\n" + line); + } else if (line.contains("Variable Value No.")) { + appendOutputResume(outputResume, "Variable Value No.", line); + for (int i = 0; i < 3; i++) { + line = in.readLine(); + appendOutputResume(outputResume, "Variable Value No.", line); + } + } else if (line.contains("Variable Step Value")) { + appendOutputResume(outputResume, "Variable Step Value", "\n" + line); + line = in.readLine(); + appendOutputResume(outputResume, "Variable Step Value", line); + while ((line = in.readLine()) != null) { + if (line.trim().length() < 1 || line.contains("-----")) { + break; + } + appendOutputResume(outputResume, "Variable Step Value", line); + } + } else if (line.contains("Summary of the potential surface scan")) { + appendOutputResume(outputResume, "Summary of the potential surface scan", "\n" + line); + line = in.readLine(); + appendOutputResume(outputResume, "Summary of the potential surface scan", line); + line = in.readLine(); + appendOutputResume(outputResume, "Summary of the potential surface scan", line); + while ((line = in.readLine()) != null) { + if (line.trim().length() < 1 || line.contains("----")) { + break; + } + appendOutputResume(outputResume, "Summary of the potential surface scan", line); + } + } else if (line.contains("EUMP2=") || line.contains("EUMP3=")) { + try { + // E2 = -0.3718352303D+00 EUMP2 = -0.15680202189090D+03 + st = new StringTokenizer(line, " ="); + if (st.countTokens() < 4) { + continue; + } + token = st.nextToken(); + String token2 = st.nextToken(); + token2 = token2.replaceAll("[D]", "E"); + token2 = token2.replaceAll("[d]", "E"); + try { + addToLastSnapshot(token, new Double(token2)); + propertiesToChart.add(token); + } catch (Exception ex) { + } + token = st.nextToken(); + token2 = st.nextToken(); + token2 = token2.replaceAll("[D]", "E"); + token2 = token2.replaceAll("[d]", "E"); + try { + propertiesToChart.add(token); + addToLastSnapshot(token, new Double(token2)); + } catch (Exception ex) { + } + + if (line.contains("EUMP3=")) { + appendOutputResume(outputResume, "EUMP3=", line); + } else { + appendOutputResume(outputResume, "EUMP2 =", line); + } + } catch (Exception ex) { + logger.severe("Error reading EUMP2= or EUMP3= " + ex.getMessage()); + } + } else if (line.contains("MP4(R+Q)")) { + //MP4(R+Q)= 0.45510290D-03 + try { + st = new StringTokenizer(line, " ="); + if (st.countTokens() < 2) { + continue; + } + token = st.nextToken(); + String token2 = st.nextToken(); + token2 = token2.replaceAll("[D]", "E"); + token2 = token2.replaceAll("[d]", "E"); + try { + propertiesToChart.add(token); + addToLastSnapshot(token, new Double(token2)); + } catch (Exception ex) { + } + appendOutputResume(outputResume, "MP4(R+Q)", line); + } catch (Exception ex) { + logger.severe("Error reading MP4(R+Q) " + ex.getMessage()); + } + } else if (line.contains("E4(DQ)") || line.contains("E4(SDQ)") || line.contains("DE(Corr)") || line.contains("DE(Z)")) { + try { + st = new StringTokenizer(line, " ="); + if (st.countTokens() < 4) { + continue; + } + token = st.nextToken(); + String token2 = st.nextToken(); + token2 = token2.replaceAll("[D]", "E"); + token2 = token2.replaceAll("[d]", "E"); + try { + propertiesToChart.add(token); + addToLastSnapshot(token, new Double(token2)); + } catch (Exception ex) { + } + token = st.nextToken(); + token2 = st.nextToken(); + token2 = token2.replaceAll("[D]", "E"); + token2 = token2.replaceAll("[d]", "E"); + try { + propertiesToChart.add(token); + addToLastSnapshot(token, new Double(token2)); + } catch (Exception ex) { + } + appendOutputResume(outputResume, "E4(DQ)", line); + } catch (Exception ex) { + logger.severe("Error reading E4(DQ) " + ex.getMessage()); + } + } else if (line.contains("UMP4(DQ)=")) { + appendOutputResume(outputResume, "UMP4(DQ)=", line); + } else if (line.contains("UMP4(SDQ)=")) { + appendOutputResume(outputResume, "UMP4(SDQ)=", line); + } else if (line.contains("UMP4(SDTQ)=")) { + appendOutputResume(outputResume, "UMP4(SDTQ)=", line); + } else if (line.contains("MP5 =")) { + appendOutputResume(outputResume, "MP5 =", line); + } else if (line.contains("Counterpoise: ")) { + appendOutputResume(outputResume, "Counterpoise: ", "\n" + line); + } // Thermal correction to Gibbs Free Energy= 0.307428 + else if (line.contains("Thermal correction to Gibbs Free Energy=")) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Parsing Thermal correction to Gibbs Free Energy=: line: " + line); + } + try { + String bufer = line.substring(line.indexOf("Energy=") + "Energy=".length()); + st = new StringTokenizer(bufer, " "); + if (st.countTokens() != 1) { + continue; + } + GibbsThermCorr = new Float(st.nextToken()); // Stupid stuff + outputResume.put("Thermal correction to Gibbs Free Energy=", line); + } catch (Exception ex) { + logger.severe("Error reading Thermal correction to Gibbs Free Energy: " + ex.getMessage()); + } + } // Thermal correction to Enthalpy= 0.386909 + else if (line.contains("Thermal correction to Enthalpy=")) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Parsing Thermal correction to Enthalpy=: line: " + line); + } + st = new StringTokenizer(line, " "); + if (st.countTokens() != 5) { + continue; + } + st.nextToken(); // Skip a token + st.nextToken(); // Skip a token + st.nextToken(); // Skip a token + st.nextToken(); // Skip a token + EnthalpyThermCorr = new Float(st.nextToken()); // Stupid stuff + outputResume.put("Thermal correction to Enthalpy=", line); + } // Thermal correction to Energy= 0.385965 + else if (line.contains("Thermal correction to Energy=")) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Parsing Thermal correction to Energy=: line: " + line); + } + st = new StringTokenizer(line, " "); + if (st.countTokens() != 5) { + continue; + } + st.nextToken(); // Skip a token + st.nextToken(); // Skip a token + st.nextToken(); // Skip a token + st.nextToken(); // Skip a token + EnergyThermCorr = new Float(st.nextToken()); // Stupid stuff + outputResume.put("Thermal correction to Energy=", line); + } // --- Getting Zero-point correction + // Zero-point correction= 0.361162 (Hartree/Particle) + else if (line.contains("Zero-point correction")) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Parsing Zero-point correction: line: " + line); + } + st = new StringTokenizer(line, " "); + if (st.countTokens() != 4) { + continue; + } + st.nextToken(); // Skip a token + st.nextToken(); // Skip a token + ZeroPointCorr = new Double(st.nextToken()); // Stupid stuff + outputResume.put("Zero-point correction", line); + } // In semiempirical calc we have + // Energy= -0.094390560183 NIter= 17. + else if (line.matches(" Energy=(.*?) NIter=(.*?)")) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Parsing Energy=(.*?) NIter=(.*?): line: " + line); + } + snapshots.add(snapshot); + snapshot = new GaussianSnapshot(); + st = new StringTokenizer(line, " ="); + if (st.countTokens() < 2) { + System.err.println("Warning: parsing Energy=(.*?) NIter=(.*?): got less than 2 tokens..."); + continue; + } + token = st.nextToken(); // Energy + String token2 = st.nextToken(); // number + SCF_Energy = new Double(token2); // Stupid stuff + addToLastSnapshot(token, SCF_Energy); + propertiesToChart.add(token); + if (scfEnergy == null) { + scfEnergy = token; + } + appendOutputResume(outputResume, "Semiempirical Energy:", "\n" + line); + } // --- Getting SCF Energy and S**2 + else if (line.contains("SCF Done:")) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Parsing SCF Done: line: " + line); + } + + token = null; + String token2 = null; + snapshots.add(snapshot); + snapshot = new GaussianSnapshot(); + + // --- process the first line + line = line.trim(); + st = new StringTokenizer(line, " ="); + if (st.countTokens() < 5) { + System.err.println("Warning: parsing SCF Done: got less than 5 tokens..."); + continue; + } + st.nextToken(); // Skip a token: SCF + st.nextToken(); // Skip a token: Done: + token = st.nextToken(); // E(bla-bla-bla) + token2 = st.nextToken(); // number + SCF_Energy = new Double(token2); // Stupid stuff + addToLastSnapshot(token, SCF_Energy); + propertiesToChart.add(token); + if (scfEnergy == null) { + scfEnergy = token; + } + appendOutputResume(outputResume, "SCF Done:", "\n" + line); + + // --- process the second line + line = in.readLine(); + st = new StringTokenizer(line, " ="); + if (st.countTokens() < 4) { + System.err.println("Warning: parsing SCF Done: Convg = : got less than 4 tokens..."); + continue; + } else { + token = st.nextToken(); + token2 = st.nextToken(); + try { + token2 = token2.replaceAll("[D]", "E"); + token2 = token2.replaceAll("[d]", "E"); + addToLastSnapshot(token, new Double(token2)); + propertiesToChart.add(token); + } catch (Exception ex) { + // --- Do nothing + } + + token = st.nextToken(); + token2 = st.nextToken(); + try { + token2 = token2.replaceAll("[D]", "E"); + token2 = token2.replaceAll("[d]", "E"); + addToLastSnapshot(token, new Double(token2)); + propertiesToChart.add(token); + } catch (Exception ex) { + // --- Do nothing + } + } + + // --- The third line + line = in.readLine(); + if (line.contains("S**2")) { + st = new StringTokenizer(line, " ="); + if (st.countTokens() < 2) { + continue; + } + token = st.nextToken(); // S**2 + S_Squared = new Double(st.nextToken()); // Stupid stuff + appendOutputResume(outputResume, "S**2", line); + addToLastSnapshot(token, S_Squared); + propertiesToChart.add(token); + } + } // --- Getting Dipole Moment (for final structure only) + else if (line.contains("Dipole moment")) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Dipole moment"); + } + appendOutputResume(outputResume, "Dipole moment", "\n" + line); + line = in.readLine(); + appendOutputResume(outputResume, "Dipole moment2", line); + st = new StringTokenizer(line, " "); + if (st.countTokens() != 8) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Parsing Dipole moment: temp.length != 8: " + st.countTokens()); + } + continue; + } + // We rearrange dipole moment values (total value first) + st.nextToken(); // Skip a token + String dipole = st.nextToken(); // X-compomnent + st.nextToken(); // Skip a token + dipole += " " + st.nextToken(); // Y-compomnent + st.nextToken(); // Skip a token + dipole += " " + st.nextToken(); // Z-compomnent + st.nextToken(); // Skip a token + String total_dipole = st.nextToken(); + dipole = total_dipole + " " + dipole; // Total compomnent in front + //mol.addProperty(DipoleMomentProperty, dipole); !!! + // --- Now save only a total dipole moment (scalar) + try { + Double dp = new Double(total_dipole); + availableProperties.add("Dipole Moment"); + mol.addProperty(MoleculeInterface.DipoleMomentProperty, dp); + this.addToLastSnapshot("Dipole Moment", dp); + } catch (NumberFormatException e) { + if (Debug) { + System.err.println("Cannot parse total dipole moment: " + e.getMessage()); + } + continue; + } + + } else if (line.startsWith(" Item Value Threshold Converged?")) { + appendOutputResume(outputResume, "Opt", "\n" + line); + line = in.readLine(); + appendOutputResume(outputResume, "Opt", line); + line = in.readLine(); + appendOutputResume(outputResume, "Opt", line); + line = in.readLine(); + appendOutputResume(outputResume, "Opt", line); + } else if (line.contains("Quadrupole moment (field-independent basis, Debye-Ang)")) { + if (logger.isLoggable(Level.INFO)) { + logger.info(line); + } + appendOutputResume(outputResume, "Quadrupole moment", "\n" + line); + line = in.readLine(); + appendOutputResume(outputResume, "Quadrupole moment", line); + line = in.readLine(); + appendOutputResume(outputResume, "Quadrupole moment", line); + } else if (line.contains("Traceless Quadrupole moment (field-independent basis, Debye-Ang)")) { + if (logger.isLoggable(Level.INFO)) { + logger.info(line); + } + appendOutputResume(outputResume, "Traceless Quadrupole moment", "\n" + line); + line = in.readLine(); + appendOutputResume(outputResume, "Traceless Quadrupole moment", line); + line = in.readLine(); + appendOutputResume(outputResume, "Traceless Quadrupole moment", line); + } else if (line.contains("Octapole moment (field-independent basis, Debye-Ang**2)")) { + if (logger.isLoggable(Level.INFO)) { + logger.info(line); + } + appendOutputResume(outputResume, "Octapole moment", "\n" + line); + line = in.readLine(); + appendOutputResume(outputResume, "Octapole moment", line); + line = in.readLine(); + appendOutputResume(outputResume, "Octapole moment", line); + line = in.readLine(); + appendOutputResume(outputResume, "Octapole moment", line); + } else if (line.contains("Hexadecapole moment (field-independent basis, Debye-Ang**3)")) { + if (logger.isLoggable(Level.INFO)) { + logger.info(line); + } + appendOutputResume(outputResume, "Hexadecapole moment", "\n" + line); + line = in.readLine(); + appendOutputResume(outputResume, "Hexadecapole moment", line); + line = in.readLine(); + appendOutputResume(outputResume, "Hexadecapole moment", line); + line = in.readLine(); + appendOutputResume(outputResume, "Hexadecapole moment", line); + line = in.readLine(); + appendOutputResume(outputResume, "Hexadecapole moment", line); + } // --- Mulliken atomic charges + else if (line.contains("Mulliken atomic charges:")) { + Info.concat(line + "\n"); + appendOutputResume(outputResume, "Mulliken atomic charges", "\n" + line); + gotMulliken = false; + if (logger.isLoggable(Level.INFO)) { + logger.info("Parsing Mulliken atomic charges:"); + } + line = in.readLine(); // Skiping a line + mulliken = ""; + int count = 0; + while ((line = in.readLine()) != null) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Parsing line: " + line); + } + if (line.length() == 0 || line.contains("Sum of Mulliken charges=")) { + break; + } + st = new StringTokenizer(line, " "); + if (st.countTokens() != 3) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Error Parsing Mulliken atomic charges: " + line); + } + break; + } + st.nextToken(); + st.nextToken(); + mulliken += st.nextToken() + " "; + + ++count; + appendOutputResume(outputResume, "Mulliken atomic charges" + + String.valueOf(count), line); + } + gotMulliken = true; + } // --- ESP fitted atomic charges + else if (line.contains("Charges from ESP fit")) { + Info.concat(line + "\n"); + gotESP = false; + if (logger.isLoggable(Level.INFO)) { + logger.info("Parsing Charges from ESP fit"); + } + line = in.readLine(); // Skiping a line + line = in.readLine(); // Skiping a line + espCharges = ""; + while ((line = in.readLine()) != null) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Parsing line: " + line); + } + if (line.length() == 0 || line.contains("--------------------")) { + break; + } + st = new StringTokenizer(line, " "); + if (st.countTokens() != 3) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Error Parsing ESP atomic charges: " + line); + } + break; + } + st.nextToken(); + st.nextToken(); + espCharges += st.nextToken() + " "; + } + gotESP = true; + } // Extracting + /* + else if (line.contains("imaginary frequencies (negative Signs)")) { + if (Debug) { + logger.info("Parsing imaginary frequencies (negative Signs), line:" + line); + } + appendOutputResume(outputResume, "imaginary frequencies", line); + line = line.substring(line.indexOf("******") + "******".length()); + st = new StringTokenizer(line, " "); + int n_freqs = 0; + try { + n_freqs = Integer.parseInt(st.nextToken()); + } + catch (NumberFormatException e) { + if (Debug) { + logger.info("Cannot parse number of imaginary frequences:" + e.getMessage()); + } + continue; + } + + String freqs = String.valueOf(n_freqs); + + for (int i = 0; i < 8; i++) { + line = in.readLine(); // Skiping 8 lines + } + line = in.readLine(); + line = line.substring(line.indexOf("Frequencies --") + "Frequencies --".length()); + st = new StringTokenizer(line, " "); + + for (int i = 0; i < n_freqs; i++) { + freqs += " " + st.nextToken(); ; + } + appendOutputResume(outputResume, "imaginary frequencies2", line); + mol.addProperty(MoleculeInterface.ImaginaryFreqsProperty, freqs); + } + */ // --- // --- Extracting charge and multiplicity (to be sure) + else if (line.contains("Multiplicity")) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Parsing Charge, line:" + line); + } + st = new StringTokenizer(line, " "); + if (st.countTokens() >= 3 && (!gotCharge)) { + try { + st.nextToken(); + st.nextToken(); + Integer charge = new Integer(st.nextToken()); + mol.addProperty(MoleculeInterface.ChargeProperty, charge); + gotCharge = true; + } catch (NumberFormatException e) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Cannot parse integer:" + e.getMessage()); + } + } + } + + if (st.countTokens() >= 3) { + try { + st.nextToken(); + st.nextToken(); + Integer mult = new Integer(st.nextToken()); + mol.addProperty(MoleculeInterface.MultiplicityProperty, mult); + } catch (NumberFormatException e) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Mult: Cannot parse integer:" + e.getMessage()); + } + } + } + } // --- Reading in BSSE info... + else if (line.contains("Counterpoise corrected energy =")) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Parsing Counterpoise corrected energy info, line:" + line); + } + appendOutputResume(outputResume, "Counterpoise corrected energy", "\n" + line); + for (int i = 0; i < 4; i++) { + line = in.readLine(); + if (line == null) { + if (logger.isLoggable(Level.WARNING)) { + logger.warning("Parsing Counterpoise corrected energy info: unexpected eof"); + } + break; + } + appendOutputResume(outputResume, "Counterpoise corrected energy", line); + } + } // Redundant internal coordinates taken from checkpoint file + else if (line.contains("Redundant internal coordinates taken from checkpoint file")) { // Not always present + // Redundant internal coordinates taken from checkpoint file: + // path/file-name.chk + // Charge = 0 Multiplicity = 1 + // C,0,0.0000000027,1.3986013041,0. + // ... + // H,0,2.1526510788,1.2428336743,0. + // Recover connectivity data from disk. + + line = in.readLine(); // skipping 1st line + line = in.readLine(); // Charge and Mult + if (line.contains("Charge =") && (!gotCharge)) { + int[] cam = parseChargeAndMultiplicityLine(line); + //Info.concat(line + "\n"); + Integer charge = new Integer(cam[0]); + mol.addProperty(MoleculeInterface.ChargeProperty, charge); + gotCharge = true; + Integer mult = new Integer(cam[1]); + mol.addProperty(MoleculeInterface.MultiplicityProperty, mult); + } + + while ((line = in.readLine()) != null) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Parsing line: " + line); + } + line = line.trim(); + if (line.contains("Charge =")) { + continue; + } else if (line.contains("Recover")) { + break; + } + + st = new StringTokenizer(line, ","); + if (st.countTokens() < 5) { + System.err.println("Warning: Expected at least 5 tokens, got: " + line); + break; + } + + if (!update) { + token = st.nextToken(); + GaussianAtom a = new GaussianAtom(); + try { + a.parseAtomName(token); + } catch (Exception ex) { + } + AtomInterface atom = mol.getNewAtomInstance(); + atom.setName(token); + atom.setAtomicNumber(a.getElement()); + + st.nextToken(); // Skip + + try { + atom.setX(Float.parseFloat(st.nextToken())); + atom.setY(Float.parseFloat(st.nextToken())); + atom.setZ(Float.parseFloat(st.nextToken())); + } catch (Exception ex) { + System.err.println("Cannot parse atom coordinate(s) for: " + line); + break; + } + + mol.addAtom(atom); + } + + } + + } // Z-Matrix No Z-matrix found on checkpoint file + else if (line.contains("Symbolic Z-matrix") || line.contains("No Z-matrix found on checkpoint file")) { // Not always present + if (mol.getNumberOfAtoms() > 0) { + continue; + } + if (line.contains("No Z-matrix found on checkpoint file")) { + // No Z-matrix found on checkpoint file. + // Cartesian coordinates read from the checkpoint file: + // /tmp/transp/k300a-12.chk + // Charge = 1 Multiplicity = 1 + + line = in.readLine(); // skipping 1st line + line = in.readLine(); // skipping 2nd line + } + + line = in.readLine(); // Charge and Mult + + // --- Extracting charge and multiplicity + if (line.contains("Charge =") && (!gotCharge)) { + int[] cam = parseChargeAndMultiplicityLine(line); + //Info.concat(line + "\n"); + Integer charge = new Integer(cam[0]); + mol.addProperty(MoleculeInterface.ChargeProperty, charge); + gotCharge = true; + Integer mult = new Integer(cam[1]); + mol.addProperty(MoleculeInterface.MultiplicityProperty, mult); + } + + if (!update) { + Info.concat(line + "\n"); + } + if (logger.isLoggable(Level.INFO)) { + logger.info("Parsing Symbolic Z-matrix records"); + } + + while ((line = in.readLine()) != null) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Parsing line: " + line); + } + String bufer = line.trim(); + if (bufer.contains("Charge =")) { + continue; + } + if (bufer.length() == 0 || bufer.startsWith("Recover connectivity data")) { + break; + } + + if (bufer.compareToIgnoreCase("Variables:") == 0) { + + } + + gaussMol.addMoleculeSpecsItem(line); + + if (false) { + st = new StringTokenizer(line, " "); + token = st.nextToken(); + if (token.compareToIgnoreCase("X") == 0) { + continue; + } + int element; + try { // --- Is it number? + element = Integer.parseInt(token); + } catch (NumberFormatException e) { + StringTokenizer st2 = new StringTokenizer(token, "0123456789"); + String truncatedName = st2.nextToken(); + + if (truncatedName.length() == 1) { + element = ChemicalElements.getAtomicNumber(truncatedName); + } else { + int initialGuess = ChemicalElements.getAtomicNumber(truncatedName.substring(0, 2)); + element = ChemicalElements.getAtomicNumber(truncatedName.substring(0, 1)); + element = initialGuess != 0 ? initialGuess : element; + } + + } + if (!update) { + AtomInterface atom = mol.getNewAtomInstance(); + atom.setName(token); + atom.setAtomicNumber(element); + mol.addAtom(atom); + } + } + } + + try { + gaussMol.parseMoleculeGeometry(); + mol = gaussMol.getMolecule(mol); + } catch (Exception ex) { + System.err.println("Error Parsing Molecular Specifications..."); + } + + if (logger.isLoggable(Level.INFO)) { + logger.info("Setup " + mol.getNumberOfAtoms() + " atoms from Symbolic Z-matrix information"); + } + } else if (line.contains("Standard orientation****")) { + /* --- For G03 + Input orientation: + --------------------------------------------------------------------- + Center Atomic Atomic Coordinates (Angstroms) + Number Number Type X Y Z + --------------------------------------------------------------------- + 1 8 0 0.000000 0.000000 0.000000 + 2 1 0 0.000000 0.000000 0.960000 + 3 1 0 0.905097 0.000000 -0.320000 + --------------------------------------------------------------------- + */ + + } else if (line.contains(INPUT_ORIENTATION_KEY) + || line.contains(Z_MATRIX_ORIENTATION_KEY) + || line.contains(STANDARD_ORIENTATION_KEY)) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Found " + line); + } + /* For G03 + Standard orientation: + --------------------------------------------------------------------- + Center Atomic Atomic Coordinates (Angstroms) + Number Number Type X Y Z + --------------------------------------------------------------------- + 1 8 0 0.000000 0.000000 0.110851 + 2 1 0 0.000000 0.783837 -0.443405 + 3 1 0 0.000000 -0.783837 -0.443405 + --------------------------------------------------------------------- + */ + boolean setupAtoms = false; + if (!update && Geometries.size() == 0 && mol.getNumberOfAtoms() == 0) { + setupAtoms = true; + } + + geom = new MolecularGeometry(); + + // --- Input orientation + if (line.contains(INPUT_ORIENTATION_KEY)) { + if (!availableStructures.contains(INPUT_ORIENTATION_KEY)) { + availableStructures.add(INPUT_ORIENTATION_KEY); + } + // Java 1.5 + //geom.setName(String.format("Input orientation %1$d", + // Geometries.size())); + geom.setName(INPUT_ORIENTATION_KEY + " " + Geometries.size()); + + List g = diffGeometries.get(INPUT_ORIENTATION_KEY); + if (g == null) { + g = new ArrayList(); + } + g.add(geom); + diffGeometries.put(INPUT_ORIENTATION_KEY, g); + snapshot.addGeometry(INPUT_ORIENTATION_KEY, geom); + } // --- Z-matrix orientation + else if (line.contains(Z_MATRIX_ORIENTATION_KEY)) { + if (!availableStructures.contains(Z_MATRIX_ORIENTATION_KEY)) { + availableStructures.add(Z_MATRIX_ORIENTATION_KEY); + } + + // Java 1.5 + //geom.setName(String.format("Z-Matrix orientation %1$d", + // Geometries.size())); + geom.setName(Z_MATRIX_ORIENTATION_KEY + " " + Geometries.size()); + + List g = diffGeometries.get(Z_MATRIX_ORIENTATION_KEY); + if (g == null) { + g = new ArrayList(); + } + g.add(geom); + diffGeometries.put(Z_MATRIX_ORIENTATION_KEY, g); + snapshot.addGeometry(Z_MATRIX_ORIENTATION_KEY, geom); + } else if (line.contains(STANDARD_ORIENTATION_KEY)) { + if (!availableStructures.contains(STANDARD_ORIENTATION_KEY)) { + availableStructures.add(STANDARD_ORIENTATION_KEY); + } + + // Java 1.5 + //geom.setName(String.format("Standard orientation %1$d", + // Geometries.size())); + geom.setName(STANDARD_ORIENTATION_KEY + " " + Geometries.size()); + + List g = diffGeometries.get(STANDARD_ORIENTATION_KEY); + if (g == null) { + g = new ArrayList(); + } + g.add(geom); + diffGeometries.put(STANDARD_ORIENTATION_KEY, g); + snapshot.addGeometry(STANDARD_ORIENTATION_KEY, geom); + } + + // Skip 4 lines + in.readLine(); + in.readLine(); + in.readLine(); + in.readLine(); + + // --- Start to read geometry + while ((line = in.readLine()) != null && !line.contains("-----------")) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Parsing line" + line); + } + st = new StringTokenizer(line, " "); + token = st.nextToken(); // Skip Center number + + if (setupAtoms) { + int element; + token = st.nextToken(); + try { // --- Is it number? have to!... + element = Integer.parseInt(token); + } catch (NumberFormatException e) { + StringTokenizer st2 = new StringTokenizer(token, "0123456789"); + element = ChemicalElements.getAtomicNumber(st2.nextToken()); + } + AtomInterface atom = mol.getNewAtomInstance(); + atom.setName(token); + atom.setAtomicNumber(element); + mol.addAtom(atom); + } else { + st.nextToken(); // Skip Atomic Number + } + + st.nextToken(); // Skip Atomic Type + //token = st.nextToken(); + Point3f point = new Point3f(); + try { + point.setX(Float.parseFloat(st.nextToken())); + point.setY(Float.parseFloat(st.nextToken())); + point.setZ(Float.parseFloat(st.nextToken())); + + } catch (NumberFormatException e) { + if (logger.isLoggable(Level.INFO)) { + logger.info("parseGaussianOutputFile: Error converting cartesian coordinates\n"); + } + break; + } + geom.add(point); + } + Geometries.add(geom); + } // --- Read frequencies + else if (line.contains("and normal coordinates:")) { + if (logger.isLoggable(Level.INFO)) { + logger.info("Starting to read frequences..."); + } + try { + frequencies = new ArrayList(); + if (frequencies instanceof ArrayList) { + ((ArrayList) frequencies).ensureCapacity(mol.getNumberOfAtoms()); + } + boolean freq_error = false; + + while ((line = in.readLine()) != null && line.trim().length() > 0) { + + st = new StringTokenizer(line, " \t"); + int num_freq = st.countTokens(); + GaussianFrequency freqs[] = new GaussianFrequency[num_freq]; + + for (int i = 0; i < num_freq; i++) { + freqs[i] = new GaussianFrequency(mol.getNumberOfAtoms()); + } + + // --- Reading symbols + if ((line = in.readLine()) == null) { + logger.severe("Error: expecting symbols for frequencies, got eof. Ignored..."); + frequencies.clear(); + frequencies = null; + break; + } + st = new StringTokenizer(line, " \t"); + if (st.countTokens() != num_freq) { + logger.severe("Error: expecting " + num_freq + " symbols for frequencies, got " + st.countTokens() + + " Ignored..."); + frequencies.clear(); + frequencies = null; + break; + } + + for (int i = 0; i < num_freq; i++) { + freqs[i].setSymbol(st.nextToken()); + } + + while (true) { + if ((line = in.readLine()) == null && line.trim().length() == 0) { + freq_error = true; + break; + } + + if (freqVecPattern.matcher(line).matches()) { + break; + } + + double[] values = new double[3]; + String prop_name = null; + try { + prop_name = GaussianFrequency.parsePropLine(line, values); + } catch (Exception ex) { + logger.severe("Error parsing frequency properties " + line + " : " + ex.getMessage()); + freq_error = true; + break; + } + + for (int i = 0; i < num_freq; i++) { + freqs[i].setProperty(prop_name, values[i]); + } + } + + if (freq_error) { + frequencies.clear(); + frequencies = null; + break; + } + + // --- Read vectors + for (int j = 0; j < mol.getNumberOfAtoms(); j++) { // Read vectors + if ((line = in.readLine()) == null) { + logger.severe("End of file while reading frequencies' vectors. Ignored..."); + break; + } + st = new StringTokenizer(line, " \t"); + if (st.countTokens() != 3 * num_freq + 2) { + logger.severe("Error: expecting " + (3 * num_freq + 2) + " values for vectors, got " + st.countTokens() + + " Ignored..."); + break; + } + // --- Skip two tokens... + st.nextToken(); + st.nextToken(); + for (int i = 0; i < num_freq; i++) { + try { + freqs[i].vectors[j].setX(Float.parseFloat(st.nextToken())); + freqs[i].vectors[j].setY(Float.parseFloat(st.nextToken())); + freqs[i].vectors[j].setZ(Float.parseFloat(st.nextToken())); + } catch (Exception ex) { + logger.severe("Error parsing vector value: " + ex.getMessage() + " Ignored..."); + freq_error = true; + break; + } + } + } + + if (freq_error) { + frequencies.clear(); + frequencies = null; + break; + } + + for (int i = 0; i < num_freq; i++) { + frequencies.add(freqs[i]); + } + } + } catch (Exception ex) { + logger.severe("Error reading frequences: " + ex.getMessage()); + } + } + + } // --- End of while + + // in.close(); + } catch (IOException e) { + logger.severe("parseGaussianOutFile: " + e.getMessage()); + //outputResults.put("molecule", mol); + //outputResults.put("geometries", Geometries); + //return outputResults; + step = new GaussianStep(); + step.setMolecule(mol); + step.setGeometries(Geometries); + step.setFinalStep(true); + return step; + } + + // --- One needs to decide what to return... + if (update) { + //outputResults.put("molecule", mol); + //outputResults.put("geometries", Geometries); + //return outputResults; + step = new GaussianStep(); + step.setMolecule(mol); + step.setGeometries(Geometries); + return step; + } + + if (logger.isLoggable(Level.INFO)) { + for (int i = 0; i < Geometries.size(); i++) { + + logger.info("Geometry: " + i); + + MolecularGeometry g = (MolecularGeometry) Geometries.get(i); + for (int j = 0; j < g.size(); j++) { + Point3f point = g.get(j); + logger.info(j + " " + point.x + " " + point.y + " " + point.z); + } + } + } + if (SCF_Energy != null) { + mol.addProperty(MoleculeInterface.SCFEnergyProperty, SCF_Energy); + } + if (S_Squared != null) { + mol.addProperty(MoleculeInterface.S_SquaredProperty, S_Squared); + } + + if (ZeroPointCorr != null) { + mol.addProperty(MoleculeInterface.ZeroPointCorrProperty, ZeroPointCorr); + } + if (EnergyThermCorr != null) { + mol.addProperty(MoleculeInterface.EnergyThermCorrProperty, EnergyThermCorr); + } + if (EnthalpyThermCorr != null) { + mol.addProperty(MoleculeInterface.EnthalpyThermCorrProperty, EnthalpyThermCorr); + } + if (GibbsThermCorr != null) { + mol.addProperty(MoleculeInterface.GibbsThermCorrProperty, GibbsThermCorr); + } + if (gotMulliken) { + String temp[] = mulliken.split(" "); + if (temp.length == mol.getNumberOfAtoms()) { + mol.addProperty(MoleculeInterface.MullikenChargesProperty, mulliken); + } else if (logger.isLoggable(Level.INFO)) { + logger.info("Number of atoms and mulliken charges do not match"); + } + } + if (gotESP) { + String temp[] = espCharges.split(" "); + if (temp.length == mol.getNumberOfAtoms()) { + mol.addProperty(MoleculeInterface.ESPChargesProperty, espCharges); + } else if (logger.isLoggable(Level.INFO)) { + logger.info("Number of atoms and ESP charges do not match"); + } + } + + //mol.setGeometries(Geometries); + if (logger.isLoggable(Level.INFO)) { + logger.info("Molecular Properties"); + } + Map prop = mol.getProperties(); + Set set = prop.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String name = me.getKey().toString(); + String values = me.getValue() == null ? "No value" : me.getValue().toString(); + if (logger.isLoggable(Level.INFO)) { + logger.info(name + " : " + values); + } + } + //outputResults.put("molecule", mol); + //outputResults.put("geometries", Geometries); + step = new GaussianStep(); + + if (snapshots.size() != 0) { + snapshot = snapshots.get(snapshots.size() - 1); + geom = snapshot.getGeometry(STANDARD_ORIENTATION_KEY); + if (geom == null) { + geom = snapshot.getGeometry( INPUT_ORIENTATION_KEY); + } + if (geom == null) { + geom = snapshot.getGeometry( Z_MATRIX_ORIENTATION_KEY); + } + if (geom != null) { + int j = 0; // --- Cound only "real" atom skipping dummy ones + for (int i = 0; i < mol.getNumberOfAtoms(); i++) { + AtomInterface atom = mol.getAtomInterface(i); + if (atom.getName().toUpperCase().startsWith("X")) { + continue; + } + Point3f at = geom.getCoordinates(j); + atom.setXYZ(at); + ++j; + } + } + } + step.setMolecule(mol); + step.setGeometries(Geometries); + + //return outputResults; + return step; + } + + /** + * Parses line "Charge = 0 Multiplicity = 1" + * + * @return int[] - int[0] - charge, int[1] - multiplicity + */ + public static int[] parseChargeAndMultiplicityLine(String line) { + int[] cam = new int[]{ + 0, 1}; + if (Debug) { + logger.info("Parsing Charge and Mult line:" + line); + } + + if (!line.contains("Charge =")) { + System.err.println("parseChargeAndMultiplicityLine: cannot parse line: " + line); + return cam; + } + + StringTokenizer st = new StringTokenizer(line, " "); + if (st.countTokens() < 3) { + System.err.println("parseChargeAndMultiplicityLine: Expected at least 3 tokens, got: " + line); + return cam; + } + + try { + st.nextToken(); + st.nextToken(); + Integer charge = new Integer(st.nextToken()); + cam[0] = charge; + } catch (NumberFormatException e) { + System.err.println("parseChargeAndMultiplicityLine: Cannot parse integer for charge: " + e.getMessage()); + return cam; + } + + if (st.countTokens() < 3) { + System.err.println("parseChargeAndMultiplicityLine: Expected \"Multiplicity =\" record, got: " + line); + return cam; + } + + try { + st.nextToken(); + st.nextToken(); + Integer mult = new Integer(st.nextToken()); + cam[1] = mult; + } catch (NumberFormatException e) { + System.err.println("parseChargeAndMultiplicityLine: Cannot parse integer for multiplicity: " + e.getMessage()); + return cam; + } + + return cam; + } + + static Float parseDipoleMoment(String values) { + String dxyz[] = values.split(","); + try { + float dx = Float.parseFloat(dxyz[0]); + float dy = Float.parseFloat(dxyz[1]); + float dz = Float.parseFloat(dxyz[2]); + Float dp = new Float(Math.sqrt((double) (dx * dx + dy * dy + dz * dz))); + return dp; + } catch (NumberFormatException e) { + if (Debug) { + logger.info("parseDipoleMoment: Cannot parse dipole moment: " + e.getMessage()); + } + } + return null; + } + + public String getOutputResume() { + StringWriter sWriter = new StringWriter(); + Set set = outputResume.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String line = me.getValue().toString(); + sWriter.write(line + "\n"); + } + + if (!normalTermination) { + sWriter.write( + "\n***** !!!!! IT IS NOT A NORMAL TERMINATION of GAUSSIAN !!!!! *****"); + } + return sWriter.toString(); + } + + public void appendOutputResume(Map resume, String key, String value) { + if (!resume.containsKey(key)) { + resume.put(key, value); + return; + } + + for (int i = 0; i < 1000; i++) { + String new_key = key + String.valueOf(i); + if (!resume.containsKey(new_key)) { + resume.put(new_key, value); + return; + } + } + String new_key = key + String.valueOf(1001); + if (!resume.containsKey(new_key)) { + resume.put(new_key, value); + + } + } + + /** + * Adds property to the last snapshot + * + * @param property String + * @param value double + */ + private void addToLastSnapshot(String property, double value) { + if (snapshots.size() < 1) { + System.err.println("addToLastSnapshot: snapshots.size() < 1"); + return; + } + snapshots.get(snapshots.size() - 1).addProperty(property, new Double(value)); + } + + public int vibrationalSpectraCount() { + if (frequencies == null || frequencies.size() < 1) { + return 0; + } + GaussianFrequency freq = frequencies.get(0); + return freq.vibrationalSpectraCount(); + } + + public String getYTitle(String name) { + if (frequencies == null || frequencies.size() < 1) { + System.err.println("No frequencies info in gaussian output file. Ignored..."); + return "Values"; + } + GaussianFrequency freq = frequencies.get(0); + if (!freq.hasSpectrum(name)) { + System.err.println("Does not have spectrum " + name + " Ignored..."); + return "Values"; + } + try { + return freq.getYTitle(name); + } catch (Exception ex) { + System.err.println(ex.getMessage() + " Ignored..."); + } + return "Values"; + } + + public String getXTitle(String name) { + if (frequencies == null || frequencies.size() < 1) { + System.err.println("No frequencies info in gaussian output file. Ignored..."); + return "Frequencies"; + } + GaussianFrequency freq = frequencies.get(0); + if (!freq.hasSpectrum(name)) { + System.err.println("Does not have spectrum " + name + " Ignored..."); + return "Frequencies"; + } + try { + return freq.getXTitle(name); + } catch (Exception ex) { + System.err.println(ex.getMessage() + " Ignored..."); + } + return "Frequencies"; + } + + public int countFrequencies() { + if (frequencies == null) { + return 0; + } + return frequencies.size(); + } + + public GaussianStep getStep() { + return step; + } + + public int validFormatScore(BufferedReader in) throws Exception { + String line = null; + int score = 0; + for (int i = 0; i < 20; i++) { + line = in.readLine(); + if (line == null) { + break; + } else if (line.contains("Gaussian, Inc. All Rights Reserved.")) return 10; // For g09 + else if (line.contains("This is the Gaussian(R) 03 program. It is based on the")) return 10; // For g03 + else if (line.contains("This is part of the Gaussian(R) 98 program. It is based on")) return 10; // For g98 + else if (line.contains("This is part of the Gaussian 94(TM) system of programs. It is")) return 10; // For g94 + } + return score; + } + + public void parseData(BufferedReader in) throws Exception { + step = parseFile(this.getMoleculeInterface(), in, false); + } +} diff --git a/src/main/java/cct/gaussian/GaussianSnapshot.java b/src/main/java/cct/gaussian/GaussianSnapshot.java new file mode 100644 index 0000000..cc93796 --- /dev/null +++ b/src/main/java/cct/gaussian/GaussianSnapshot.java @@ -0,0 +1,105 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian; + +import java.util.HashMap; +import java.util.Map; + +import cct.modelling.MolecularGeometry; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class GaussianSnapshot { + + private double latticeVectors[][] = null; + private Map energyDecomp = new HashMap (10); + private Map geometries = new HashMap (); + private long offset = -1L; + + public GaussianSnapshot() { + } + + public void setOffset(long offset) { + this.offset = offset; + } + + public long getOffset() { + return this.offset; + } + + public void addProperty(String type, double value) { + energyDecomp.put(type, new Double(value)); + } + + public void addGeometry(String type, MolecularGeometry geom) { + geometries.put(type, geom); + } + + public double getProperty(String type) throws Exception { + if (!energyDecomp.containsKey(type)) { + throw new Exception("Snapshot does not have energy term " + type); + } + return energyDecomp.get(type); + } + + public MolecularGeometry getGeometry(String type) { + return geometries.get(type); + } + + public boolean hasEnergyTerm(String type) { + return energyDecomp.containsKey(type); + } + + public double[][] getLatticeVectors() { + return latticeVectors; + } + + public static void main(String[] args) { + GaussianSnapshot gaussiansnapshot = new GaussianSnapshot(); + } +} diff --git a/src/main/java/cct/gaussian/GaussianStep.java b/src/main/java/cct/gaussian/GaussianStep.java new file mode 100644 index 0000000..3661106 --- /dev/null +++ b/src/main/java/cct/gaussian/GaussianStep.java @@ -0,0 +1,560 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.gaussian; + +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.interfaces.OutputResultsInterface; +import cct.modelling.CCTAtomTypes; +import cct.modelling.Frequencies; +import cct.modelling.MolecularGeometry; +import cct.modelling.Molecule; +import cct.modelling.StructureManagerInterface; +import cct.modelling.VIBRATIONAL_SPECTRUM; +import cct.modelling.VIBRATIONAL_SPECTRUM_CURVE; +import cct.vecmath.Point3f; +import javax.swing.JOptionPane; + +/** + *

+ * Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

+ * Description: Collection of Computational Chemistry related code

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

+ * Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class GaussianStep + implements OutputResultsInterface, StructureManagerInterface { + + private boolean Debug = true; + private MoleculeInterface molecule; + private List geometries = new ArrayList(); + private List frequencies = null; + private Map outputResume; + private Set propertiesToChart = new HashSet(); + private List snapshots = new ArrayList(); + private boolean finalStep = false; + private boolean guessBonds = true, guessAtomTypes = true, normalTermination = true; + private String description = "Gaussian Step"; + private String scfEnergy = null; + private Map termVsStrReference = new HashMap(); + static final Logger logger = Logger.getLogger(GaussianStep.class.getCanonicalName()); + + public GaussianStep() { + } + + public void setMolecule(MoleculeInterface mol) { + molecule = mol; + if (molecule == null || molecule.getNumberOfAtoms() < 1) { + return; + } + if (guessBonds) { + Molecule.guessCovalentBonds(molecule); + } + if (guessAtomTypes) { + Molecule.guessAtomTypes(molecule, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } + } + + public void setGuessCovalentBonds(boolean guess) { + guessBonds = guess; + } + + @Override + public void setNormalTermination(boolean yes) { + normalTermination = yes; + } + + @Override + public boolean isNormalTermination() { + return normalTermination; + } + + public void setSnapshots(List snaps) { + snapshots.addAll(snaps); + } + + public void setChartProperties(Set properties) { + propertiesToChart.addAll(properties); + } + + public void setGuessAtomTypes(boolean guess) { + guessAtomTypes = guess; + } + + public void setOutputResume(Map outputRes) { + outputResume = new LinkedHashMap(outputRes); + } + + public void setGeometries(List geoms) { + if (geoms != null) { + geometries = new ArrayList(geoms); + } + } + + public void setFrequencies(List freq) { + frequencies = new ArrayList(freq); + } + + public boolean isFinalStep() { + return finalStep; + } + + public void setFinalStep(boolean yes) { + finalStep = yes; + } + + public MoleculeInterface getMolecule() { + return molecule; + } + + public List getGeometries() { + return geometries; + } + + @Override + public void getSpectrum(double[] x, double[] y, int dim, VIBRATIONAL_SPECTRUM type) throws Exception { + getSpectrum(x, y, dim, spectrumType2String(type)); + } + + private String spectrumType2String(VIBRATIONAL_SPECTRUM type) throws Exception { + String name; + + switch (type) { + case INFRARED_SPECTRUM: + name = "IR Inten"; + break; + case RAMAN_SPECTRUM: + name = "Raman Activ"; + break; + case VCD_ROTATIONAL_STRENGTH_SPECTRUM: + name = "Rot. str."; + break; + case P_DEPOLARIZATION_SPECTRUM: + name = "Depolar (P)"; + break; + case U_DEPOLARIZATION_SPECTRUM: + name = "Depolar (U)"; + break; + default: + throw new Exception("Unknown vibrational spectrum " + type.toString()); + } + return name; + } + + public void getSpectrum(double[] x, double[] y, int dim, String name) throws Exception { + if (frequencies == null || frequencies.size() < 1) { + throw new Exception("No frequencies info in gaussian output file"); + } + GaussianFrequency freq = frequencies.get(0); + if (!freq.hasSpectrum(name)) { + throw new Exception("Does not have spectrum " + name); + } + + double[] freqs = new double[frequencies.size()]; + double[] values = new double[frequencies.size()]; + + for (int i = 0; i < frequencies.size(); i++) { + freq = frequencies.get(i); + freqs[i] = freq.getProperty("Frequencies"); + values[i] = freq.getProperty(name); + } + + Frequencies.makeCurve(freqs, values, x, y, dim, VIBRATIONAL_SPECTRUM_CURVE.GAUSSIAN); + //Frequencies.makeCurve(freqs, values, x, y, dim, VIBRATIONAL_SPECTRUM_CURVE.LORENTZ); + } + + public double[] getFrequencies(VIBRATIONAL_SPECTRUM type) throws Exception { + return getFrequencies(spectrumType2String(type)); + } + + public double[] getFrequencies(String name) throws Exception { + if (frequencies == null || frequencies.size() < 1) { + throw new Exception("No frequencies info in gaussian output file"); + } + GaussianFrequency freq = frequencies.get(0); + if (!freq.hasSpectrum(name)) { + throw new Exception("Does not have spectrum " + name); + } + + double[] freqs = new double[frequencies.size()]; + //values = new double[frequencies.size()]; + + for (int i = 0; i < frequencies.size(); i++) { + freq = frequencies.get(i); + freqs[i] = freq.getProperty("Frequencies"); + //values[i] = freq.getProperty(name); + } + + return freqs; + } + + public double[] getIntensities(VIBRATIONAL_SPECTRUM type) throws Exception { + return getIntensities(spectrumType2String(type)); + } + + public double[] getIntensities(String name) throws Exception { + if (frequencies == null || frequencies.size() < 1) { + throw new Exception("No frequencies info in gaussian output file"); + } + GaussianFrequency freq = frequencies.get(0); + if (!freq.hasSpectrum(name)) { + throw new Exception("Does not have spectrum " + name); + } + + //double [] freqs = new double[frequencies.size()]; + double[] values = new double[frequencies.size()]; + + for (int i = 0; i < frequencies.size(); i++) { + freq = frequencies.get(i); + //freqs[i] = freq.getProperty("Frequencies"); + values[i] = freq.getProperty(name); + } + + return values; + } + + @Override + public double getSpectrumValue(int n, VIBRATIONAL_SPECTRUM spectrum) { + if (frequencies == null) { + System.err.println("frequencies == null"); + return 0; + } + + if (n < 0 || n >= frequencies.size()) { + System.err.println("n < 0 || n >= frequencies.size()"); + return 0; + } + + GaussianFrequency freq = frequencies.get(n); + + if (!freq.hasSpectrum(spectrum)) { + System.err.println("Does not have spectrum " + spectrum); + return 0; + } + + try { + Double value = freq.getProperty(spectrum); + return value; + } catch (Exception ex) { + System.err.println("value == null"); + return 0; + } + } + + @Override + public double getFrequency(int n) { + if (frequencies == null) { + System.err.println("frequencies == null"); + return 0; + } + + if (n < 0 || n >= frequencies.size()) { + System.err.println("frequencies == null"); + return 0; + } + + GaussianFrequency freq = frequencies.get(n); + try { + Double value = freq.getProperty("Frequencies"); + return value; + } catch (Exception ex) { + System.err.println("value == null"); + return 0; + } + } + + @Override + public float[][] getDisplacementVectors(int n) { + if (frequencies == null) { + System.err.println("getDisplacementVectors: frequencies == null"); + return null; + } + + if (n < 0 || n >= frequencies.size()) { + System.err.println("getDisplacementVectors: n < 0 || n >= frequencies.size()"); + return null; + } + + GaussianFrequency freq = frequencies.get(n); + return freq.getDisplacementVectors(); + } + + @Override + public boolean hasInfraredSpectrum() { + return hasSpectrum("IR Inten"); + } + + @Override + public boolean hasVCDSpectrum() { + return hasSpectrum("Rot. str."); + } + + @Override + public boolean hasUDepolSpectrum() { + return hasSpectrum("Depolar (U)"); + } + + @Override + public boolean hasPDepolSpectrum() { + return hasSpectrum("Depolar (P)"); + } + + @Override + public boolean hasRamanSpectrum() { + return hasSpectrum("Raman Activ"); + } + + @Override + public boolean hasJobSummary() { + if (outputResume == null) { + return false; + } + return outputResume.size() > 0; + } + + @Override + public boolean hasInteractiveChart() { + return !(propertiesToChart.size() < 1 || snapshots.size() < 2); + } + + @Override + public boolean hasDisplacementVectors() { + if (frequencies == null || frequencies.size() < 1) { + return false; + } + + GaussianFrequency freq = frequencies.get(0); + return freq.hasDisplacementVectors(); + } + + @Override + public int countSpectra() { + if (frequencies == null || frequencies.size() < 1) { + return 0; + } + GaussianFrequency freq = frequencies.get(0); + return freq.vibrationalSpectraCount(); + } + + @Override + public int countFrequencies() { + if (frequencies == null) { + return 0; + } + return frequencies.size(); + } + + /** + * Returns names of available vibrational spectra (if any) + * + * @return String[] + */ + @Override + public VIBRATIONAL_SPECTRUM[] availableVibrationalSpectra() { + if (frequencies == null || frequencies.size() < 1) { + return null; + } + GaussianFrequency freq = frequencies.get(0); + return freq.availableVibrationalSpectra(); + } + + public boolean hasSpectrum(String type) { + if (frequencies == null || frequencies.size() < 1) { + return false; + } + GaussianFrequency freq = frequencies.get(0); + return freq.hasSpectrum( type ); + } + + public String getDescription() { + return description; + } + + public void setDescription(String descr) { + description = descr; + } + + @Override + public String[] getAvailPropToChart() { + if (propertiesToChart.size() < 1) { + return null; + } + String[] sa = new String[propertiesToChart.size()]; + propertiesToChart.toArray(sa); + return sa; + } + + @Override + public String getOutputResume() { + StringWriter sWriter = new StringWriter(); + Set set = outputResume.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String line = me.getValue().toString(); + sWriter.write(line + "\n"); + } + + if (!isNormalTermination()) { + sWriter.write( + "\n***** !!!!! IT IS NOT A NORMAL TERMINATION of GAUSSIAN !!!!! *****"); + } + return sWriter.toString(); + } + + @Override + public float[][] getStructure(int n) { + return getStructure(n, scfEnergy); + } + + @Override + public float[][] getStructure(int n, String term) { + if (!propertiesToChart.contains(term) || snapshots.size() < 1) { + return null; + } + + if (snapshots == null || snapshots.size() < 1) { + return null; + } + + List references = termVsStrReference.get(term); + if (references == null) { + System.err.println("references == null"); + return null; + } else if (n >= references.size()) { + System.err.println("n >= references.size()"); + return null; + } + + if (Debug) { + logger.info("getStructure: # " + n); + } + + GaussianSnapshot snapshot = snapshots.get(references.get(n)); + MolecularGeometry geom = snapshot.getGeometry(GaussianOutput.STANDARD_ORIENTATION_KEY); // GaussView uses standard orientation + if (geom == null) { + geom = snapshot.getGeometry(GaussianOutput.INPUT_ORIENTATION_KEY); + } + if (geom == null) { + geom = snapshot.getGeometry(GaussianOutput.Z_MATRIX_ORIENTATION_KEY); + } + + if (geom == null || geom.size() < 1) { + System.err.println(this.getClass().getCanonicalName() + " : no atoms in selected snapshot"); + return null; + } + + float[][] coords = new float[geom.size()][3]; + for (int i = 0; i < geom.size(); i++) { + Point3f c = geom.getCoordinates(i); + + coords[i][0] = c.getX(); + coords[i][1] = c.getY(); + coords[i][2] = c.getZ(); + if (Debug && i == geom.size() - 1) { + logger.info(i + " : x=" + coords[i][0] + " y=" + coords[i][1] + " z=" + coords[i][2]); + } + } + return coords; + } + + @Override + public void selectStructure(int number) throws Exception { + throw new Exception(this.getClass().getCanonicalName() + ": selectStructure(int number) is not implemented yet"); + } + + /** + * Not implemented yet... + * + * @param number int + * @param term String + * @throws Exception + */ + @Override + public void selectStructure(int number, String term) throws Exception { + throw new Exception(this.getClass().getCanonicalName() + ": selectStructure(int number, String term) is not implemented yet"); + } + + @Override + public double[] getAllTerms(String term) { + if (!propertiesToChart.contains(term) || snapshots.size() < 1) { + return null; + } + + List references = new ArrayList(snapshots.size()); + List values = new ArrayList(snapshots.size()); + for (int i = 0; i < snapshots.size(); i++) { + GaussianSnapshot snapshot = snapshots.get(i); + try { + Double value = snapshot.getProperty(term); + values.add(value); + references.add(new Integer(i)); + } catch (Exception ex) { + } + } + if (values.size() < 1) { + return null; + } + termVsStrReference.put(term, references); + double[] energies = new double[values.size()]; + for (int i = 0; i < values.size(); i++) { + energies[i] = values.get(i); + } + return energies; + } + +} diff --git a/src/main/java/cct/gaussian/GaussianSymbolicCartesianCoordinates.java b/src/main/java/cct/gaussian/GaussianSymbolicCartesianCoordinates.java new file mode 100644 index 0000000..104b47e --- /dev/null +++ b/src/main/java/cct/gaussian/GaussianSymbolicCartesianCoordinates.java @@ -0,0 +1,66 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.gaussian; + +import cct.Constants; +import cct.interfaces.AtomInterface; +import cct.interfaces.CoordinateBuilderInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.ChemicalElements; +import java.io.StringWriter; +import java.io.Writer; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Map.Entry; + +/** + * + * @author Vlad + */ +public class GaussianSymbolicCartesianCoordinates implements CoordinateBuilderInterface { + + public void getCoordinates(MoleculeInterface mol, boolean inAngstroms, Writer writer) throws Exception { + if (mol == null || mol.getNumberOfAtoms() < 1) { + throw new Exception("Molecule has no atoms"); + } + float factor = 1.0f; + if (!inAngstroms) { + factor /= Constants.ONE_BOHR_FLOAT; + } + + String x, y, z; + Map variables = new LinkedHashMap(); + for (int i = 0, j = 1; i < mol.getNumberOfAtoms(); i++, j++) { + AtomInterface atom = mol.getAtomInterface(i); + int element = atom.getAtomicNumber(); + String symbol = ChemicalElements.getElementSymbol(element); + if (symbol == null) { + symbol = " X"; + } + x = String.format("x%03d", j); + y = String.format("y%03d", j); + z = String.format("z%03d", j); + variables.put(x, atom.getX() * factor); + variables.put(y, atom.getY() * factor); + variables.put(z, atom.getZ() * factor); + + writer.write(String.format("%-2s 0 %s %s %s\n", symbol, x, y, z)); + } + // --- + writer.write(" Variables:\n"); + for (Entry c : variables.entrySet()) { + writer.write(String.format("%s %8.4f\n", c.getKey(), c.getValue())); + } + writer.write("\n"); + } + + public String getCoordinatesAsString(MoleculeInterface molec, boolean inAngstroms) throws Exception { + StringWriter sw = new StringWriter(); + getCoordinates(molec, inAngstroms, sw); + return sw.toString(); + } +} diff --git a/src/main/java/cct/gaussian/InputOrientationParser.java b/src/main/java/cct/gaussian/InputOrientationParser.java new file mode 100644 index 0000000..9c3c7e8 --- /dev/null +++ b/src/main/java/cct/gaussian/InputOrientationParser.java @@ -0,0 +1,209 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian; + +import java.io.BufferedReader; +import java.util.StringTokenizer; + +import cct.interfaces.AtomInterface; +import cct.interfaces.CoordinateParserInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.ChemicalElements; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class InputOrientationParser + implements CoordinateParserInterface { + public InputOrientationParser() { + } + + public static void main(String[] args) { + InputOrientationParser simpleparser = new InputOrientationParser(); + } + + @Override + public void parseCoordinates(BufferedReader in, MoleculeInterface molecule) throws Exception { + try { + molecule.addMonomer("GAUSS"); + // --- Reading atoms + String line; + while ( (line = in.readLine()) != null) { + + line = line.trim(); + if (line.length() < 1) { + continue; // Empty line + } + + AtomInterface atom = molecule.getNewAtomInstance(); + + // 1 7 0 0.250464 0.322510 -1.260153 + + StringTokenizer st = new StringTokenizer(line, " \t", false); + if (st.countTokens() < 6) { + throw new Exception("InputOrientationParser: Expected at least 6 tokens, got: " + line); + } + + // --- Skip first token + + st.nextToken(); + + // --- Getting element + + String token = st.nextToken(); + try { + int element = Integer.parseInt(token); + atom.setAtomicNumber(element); + atom.setName(ChemicalElements.getElementSymbol(element)); + + } + catch (Exception ex) { + throw new Exception("Cannot parse element number: " + ex.getMessage()); + } + + // --- Skip token + + st.nextToken(); + + // --- Getting x,y,z + + float xyz; + try { + xyz = Float.parseFloat(st.nextToken()); + atom.setX(xyz); + xyz = Float.parseFloat(st.nextToken()); + atom.setY(xyz); + xyz = Float.parseFloat(st.nextToken()); + atom.setZ(xyz); + } + catch (Exception ex) { + throw new Exception("InputOrientationParser: Error while parsing atom's coordinate: " + line); + } + + molecule.addAtom(atom); + } + + } + catch (Exception ex) { + throw ex; + } + } + + @Override + public double evaluateCompliance(BufferedReader in) throws Exception { + double score = 0; + try { + // --- Reading atoms + String line; + while ( (line = in.readLine()) != null) { + + line = line.trim(); + if (line.length() < 1) { + continue; // Empty line + } + + score = 1.0; + // 1 7 0 0.250464 0.322510 -1.260153 + + StringTokenizer st = new StringTokenizer(line, " \t", false); + if (st.countTokens() < 6) { + return 0; + } + else if (st.countTokens() > 6) { + score -= 0.25; + } + + // --- The first token should be integer number + + try { + Integer.parseInt(st.nextToken()); + } + catch (Exception ex) { + score -= 0.25; + } + + // --- Getting element + + String token = st.nextToken(); + try { + Integer.parseInt(token); + + } + catch (Exception ex) { + return 0; + } + + // --- token should be a number + + try { + Integer.parseInt(st.nextToken()); + } + catch (Exception ex) { + score -= 0.25; + } + + // --- Getting x,y,z + + try { + Float.parseFloat(st.nextToken()); + Float.parseFloat(st.nextToken()); + Float.parseFloat(st.nextToken()); + } + catch (Exception ex) { + return 0; + } + + return score; // i.e. we check only the first line + } + + } + catch (Exception ex) { + throw ex; + } + return score; + } +} diff --git a/src/main/java/cct/gaussian/ONIOM_LAYER.java b/src/main/java/cct/gaussian/ONIOM_LAYER.java new file mode 100644 index 0000000..3bfdd40 --- /dev/null +++ b/src/main/java/cct/gaussian/ONIOM_LAYER.java @@ -0,0 +1,56 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public enum ONIOM_LAYER { + HIGH, MEDIUM, LOW; + ONIOM_LAYER() { + } +} diff --git a/src/main/java/cct/gaussian/SelectPropShowDialog.java b/src/main/java/cct/gaussian/SelectPropShowDialog.java new file mode 100644 index 0000000..176df15 --- /dev/null +++ b/src/main/java/cct/gaussian/SelectPropShowDialog.java @@ -0,0 +1,83 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian; + +import java.awt.BorderLayout; +import java.awt.Frame; + +import javax.swing.JDialog; +import javax.swing.JPanel; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class SelectPropShowDialog + extends JDialog { + private JPanel panel1 = new JPanel(); + private BorderLayout borderLayout1 = new BorderLayout(); + + public SelectPropShowDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public SelectPropShowDialog() { + this(new Frame(), "SelectPropShowDialog", false); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + getContentPane().add(panel1); + } +} diff --git a/src/main/java/cct/gaussian/java3d/GaussianJava3dFactory.java b/src/main/java/cct/gaussian/java3d/GaussianJava3dFactory.java new file mode 100644 index 0000000..87326e1 --- /dev/null +++ b/src/main/java/cct/gaussian/java3d/GaussianJava3dFactory.java @@ -0,0 +1,770 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian.java3d; + +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; + +import org.scijava.java3d.Appearance; +import org.scijava.java3d.BranchGroup; +import org.scijava.java3d.GeometryArray; +import org.scijava.java3d.LineArray; +import org.scijava.java3d.Node; +import org.scijava.java3d.PointArray; +import org.scijava.java3d.Shape3D; +import org.scijava.java3d.TransformGroup; +import org.scijava.java3d.TriangleArray; +import org.scijava.vecmath.Color3f; +import org.scijava.vecmath.Color4f; +import org.scijava.vecmath.Point3f; +import org.scijava.vecmath.Vector3f; + +import cct.gaussian.GaussianCube; +import cct.interfaces.GraphicsObjectInterface; +import cct.interfaces.ImplicitFunctionInterface; +import cct.j3d.ColorRangeScheme; +import cct.j3d.USER_DATA_FLAG; +import cct.j3d.UserData; +import cct.j3d.VerticesObject; +import cct.j3d.VerticesObjectProperties; +import cct.math.polyg.java3d.j3dPolygonizer; +import cct.poly.NORMAL; +import cct.poly.Polygonizer; +import cct.poly.TRIANGLE; +import cct.poly.VERTEX; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class GaussianJava3dFactory { + + static Color3f blackColor = new Color3f(0.0f, 0.0f, 0.0f); + static Color3f whiteColor = new Color3f(1.0f, 1.0f, 1.0f); + static Color3f redColor = new Color3f(1.0f, 0.0f, 0.0f); + static Color3f greenColor = new Color3f(0.0f, 1.0f, 0.0f); + static Color3f blueColor = new Color3f(0.0f, 0.0f, 1.0f); + + private static int isosurfaceSet = 0; + static final Logger logger = Logger.getLogger(GaussianJava3dFactory.class.getCanonicalName()); + + private GaussianJava3dFactory() { + } + + public static void main(String[] args) { + GaussianJava3dFactory gaussianjava3dfactory = new GaussianJava3dFactory(); + } + + public static GraphicsObjectInterface getGraphicsObject(GaussianCube gCube, int n, float delta, boolean useReverse) { + + GraphicsObjectInterface graph2; + + GraphicsObjectInterface graphics = new VerticesObject(); + graphics.setName(gCube.getCubeDescription()); + + VerticesObject vObject = new VerticesObject(); + vObject.setName("Isovalue: " + String.valueOf(delta)); + Shape3D shape3d = new Shape3D(); + ++isosurfaceSet; + + String value = ""; + try { + value = (gCube.getCubeDescription() + "_" + String.valueOf(delta)).replaceAll("[ ]", "_").replaceAll("[.]", "_"); + } + catch (Exception ex) { + } + + UserData.setUserData(shape3d, UserData.NODE_NAME, "ISOSURFACE_" + String.format("%03d_", isosurfaceSet) + value); + //shape3d.setName("Isovalue: " + String.valueOf(delta)); // --- >1.4 java3d feature + shape3d.setCapability(Node.ALLOW_PARENT_READ); + shape3d.setCapability(Shape3D.ALLOW_GEOMETRY_READ); + shape3d.setCapability(Shape3D.ALLOW_GEOMETRY_WRITE); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_READ); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_READ); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_WRITE); + + TriangleArray surface = null; + if (true) { + surface = getSurface2(gCube, n, delta); + } + else { + surface = getSurface(gCube, n, delta); + } + shape3d.setGeometry(surface); + + VerticesObjectProperties voP = new VerticesObjectProperties(); + + Color3f red = new Color3f(1.0f, 0.0f, 0.0f); + Appearance app = voP.getAppearence(red); + + shape3d.setAppearance(app); + + vObject.addGraphics(graphics.getNGraphicsElements() + " Red Isosurface", shape3d); + + graph2 = vObject; + graphics.addGraphics(graph2); + + // --- Negative isovalue + + if (useReverse && Math.abs(delta) > 0.000001) { + graph2 = new VerticesObject(); + graph2.setName("Isovalue: " + ( -delta)); + shape3d = new Shape3D(); + + value = ""; + try { + value = (gCube.getCubeDescription() + "_" + String.valueOf( -delta)).replaceAll("[ ]", "_").replaceAll("[.]", "_"); + } + catch (Exception ex) { + } + + UserData.setUserData(shape3d, UserData.NODE_NAME, "ISOSURFACE_" + String.format("%03d_", isosurfaceSet) + value); + + //shape3d.setName("Isovalue: " + ( -delta)); // --- >1.4 java3d feature + shape3d.setCapability(Node.ALLOW_PARENT_READ); // java3d >= 1.4 + shape3d.setCapability(Shape3D.ALLOW_GEOMETRY_READ); + shape3d.setCapability(Shape3D.ALLOW_GEOMETRY_WRITE); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_READ); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_READ); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_WRITE); + + if (true) { + surface = getSurface2(gCube, n, -delta); + } + else { + surface = getSurface(gCube, n, -delta); + } + shape3d.setGeometry(surface); + + voP = new VerticesObjectProperties(); + + Color3f blue = new Color3f(0.0f, 0.0f, 1.0f); + app = voP.getAppearence(blue); + + shape3d.setAppearance(app); + graph2.addGraphics(graphics.getNGraphicsElements() + " Blue Isosurface", shape3d); + + graphics.addGraphics(graph2); + } + + /* + graph2 = new VerticesObject(); + graph2.setName("Grid Box"); + shape3d = new Shape3D(); + shape3d.setCapability(Shape3D.ALLOW_PARENT_READ); // java3d >= 1.4 + shape3d.setCapability(Shape3D.ALLOW_GEOMETRY_READ); + shape3d.setCapability(Shape3D.ALLOW_GEOMETRY_WRITE); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_READ); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_READ); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_WRITE); + + app = new Appearance(); + PointAttributes pa = new PointAttributes(3,true); + app.setPointAttributes(pa); + + shape3d.setGeometry(getGridAsPoints(gCube)); + shape3d.setAppearance(app); + graph2.addGraphics("Grid Box", shape3d); + + graphics.addGraphics(graph2); + */ + + return graphics; + } + + /** + * Creates two surfaces for values delta and -delta and returns them as a Shape3D + * @param gCube GaussianCube + * @param n int + * @param delta float + * @return Shape3D + */ + public static Shape3D getSymmetricSurfaces(GaussianCube gCube, int n, + float delta) { + Shape3D shape3d = new Shape3D(); + TriangleArray surface; + surface = getSurface(gCube, n, delta); + shape3d.setGeometry(surface); + surface = getSurface(gCube, n, -delta); + shape3d.addGeometry(surface); + return shape3d; + } + + public static PointArray getGridAsPoints(GaussianCube gCube) { + float[] origin = gCube.getDataOrigin(); + int[] voxels = gCube.getNumberOfVoxels(); + float axisVectors[][] = gCube.getAxisVectors(); + int nPoints = voxels[0] * voxels[1] * voxels[2]; + + PointArray points = new PointArray(nPoints, + GeometryArray.COORDINATES | + GeometryArray.COLOR_3); + + points.setCapability(GeometryArray.ALLOW_COLOR_READ); + points.setCapability(GeometryArray.ALLOW_COLOR_WRITE); + points.setCapability(GeometryArray.ALLOW_COORDINATE_READ); + points.setCapability(GeometryArray.ALLOW_COORDINATE_WRITE); + + int count = 0; + + for (int i = 0; i < voxels[0]; i++) { + float x = origin[0] + axisVectors[0][0] * i; + for (int j = 0; j < voxels[1]; j++) { + float y = origin[1] + axisVectors[1][1] * j; + for (int k = 0; k < voxels[2]; k++, count++) { + float z = origin[2] + axisVectors[2][2] * k; + points.setCoordinate(count, new Point3f(x, y, z)); + points.setColor(count, whiteColor); + + } + } + } + return points; + } + + public static LineArray getGridAsLines(GaussianCube gCube) { + float[] origin = gCube.getDataOrigin(); + int[] voxels = gCube.getNumberOfVoxels(); + float axisVectors[][] = gCube.getAxisVectors(); + int nPoints = 2 * (voxels[1] * voxels[2] + voxels[0] * voxels[2] + + voxels[0] * voxels[1]); + + LineArray box = new LineArray(nPoints, + GeometryArray.COORDINATES | GeometryArray.COLOR_3); + Point3f[] coordinates = new Point3f[nPoints]; + + int count = 0; + + // -- Creates lines parallel to X Axis + + float x_end = origin[0] + axisVectors[0][0] * (voxels[0] - 1); + for (int i = 0; i < voxels[1]; i++) { + float y = origin[1] + axisVectors[1][1] * i; + for (int j = 0; j < voxels[2]; j++) { + float z = origin[2] + axisVectors[2][2] * j; + coordinates[count] = new Point3f(origin[0], y, z); + box.setColor(count, redColor); + ++count; + coordinates[count] = new Point3f(x_end, y, z); + box.setColor(count, redColor); + ++count; + } + } + + // -- Creates lines parallel to Y Axis + + float y_end = origin[1] + axisVectors[1][1] * (voxels[1] - 1); + for (int i = 0; i < voxels[0]; i++) { + float x = origin[0] + axisVectors[0][0] * i; + for (int j = 0; j < voxels[2]; j++) { + float z = origin[2] + axisVectors[2][2] * j; + coordinates[count] = new Point3f(x, origin[1], z); + box.setColor(count, greenColor); + ++count; + coordinates[count] = new Point3f(x, y_end, z); + box.setColor(count, greenColor); + ++count; + } + } + + // -- Creates lines parallel to Z Axis + + float z_end = origin[2] + axisVectors[2][2] * (voxels[2] - 1); + for (int i = 0; i < voxels[0]; i++) { + float x = origin[0] + axisVectors[0][0] * i; + for (int j = 0; j < voxels[1]; j++) { + float y = origin[1] + axisVectors[1][1] * j; + coordinates[count] = new Point3f(x, y, origin[2]); + box.setColor(count, blueColor); + ++count; + coordinates[count] = new Point3f(x, y, z_end); + box.setColor(count, blueColor); + ++count; + } + } + + box.setCoordinates(0, coordinates); + + return box; + } + + /** + * Creates surface as a TriangleArray + * @param gCube GaussianCube + * @param n int + * @param delta float + * @return TriangleArray + */ + public static TriangleArray getSurface(GaussianCube gCube, int n, + float delta) { + + java.awt.Color color; + if (delta >= 0) { + color = java.awt.Color.RED; + } + else { + color = java.awt.Color.BLUE; + } + + float size[] = { + gCube.getAxisVectors()[0][0], gCube.getAxisVectors()[1][1], + gCube.getAxisVectors()[2][2]}; + int bounds[] = { + gCube.getNumberOfVoxels()[0] / 2 - 3, + gCube.getNumberOfVoxels()[1] / 2 - 3, + gCube.getNumberOfVoxels()[2] / 2 - 3}; + + float xOrigin = gCube.getDataOrigin()[0] + (gCube.getAxisVectors()[0][0] * gCube.getNumberOfVoxels()[0]) / 2; + float yOrigin = gCube.getDataOrigin()[1] + (gCube.getAxisVectors()[1][1] * gCube.getNumberOfVoxels()[1]) / 2; + float zOrigin = gCube.getDataOrigin()[2] + (gCube.getAxisVectors()[2][2] * gCube.getNumberOfVoxels()[2]) / 2; + + boolean dotet = true; + + ImplicitFunctionInterface function = new VolumetricData(gCube.getVolumetricData(n), gCube.getDataOrigin(), + gCube.getNumberOfVoxels(), gCube.getAxisVectors(), delta); + + Polygonizer polygonizer = new Polygonizer(function, size, bounds); + + //polygonizer.march(dotet, xOrigin, yOrigin, zOrigin); + float xyz_step[] = { + gCube.getAxisVectors()[0][0], gCube.getAxisVectors()[1][1], + gCube.getAxisVectors()[2][2]}; + polygonizer.march2(dotet, gCube.getDataOrigin(), gCube.getNumberOfVoxels(), xyz_step); + + logger.info("# triangles: " + polygonizer.no_triangles()); + if (polygonizer.no_triangles() < 1) { + return null; + } + + TriangleArray tetra2 = new TriangleArray(polygonizer.no_triangles() * 3, + GeometryArray.COORDINATES | + GeometryArray.NORMALS | + GeometryArray.COLOR_3); + Point3f[] coordinates = new Point3f[polygonizer.no_triangles() * 3]; + Vector3f[] normals = new Vector3f[polygonizer.no_triangles() * 3]; + Color3f[] colors = new Color3f[polygonizer.no_triangles() * 3]; + + int count = 0; + for (int i = 0; i < polygonizer.no_triangles(); ++i) { + TRIANGLE t = polygonizer.get_triangle(i); + NORMAL n0 = polygonizer.get_normal(t.v0); + VERTEX v0 = polygonizer.get_vertex(t.v0); + + NORMAL n1 = polygonizer.get_normal(t.v1); + VERTEX v1 = polygonizer.get_vertex(t.v1); + + NORMAL n2 = polygonizer.get_normal(t.v2); + VERTEX v2 = polygonizer.get_vertex(t.v2); + + coordinates[3 * i] = new Point3f(v0.x, v0.y, v0.z); + coordinates[3 * i + 1] = new Point3f(v1.x, v1.y, v1.z); + coordinates[3 * i + 2] = new Point3f(v2.x, v2.y, v2.z); + + float factor = 1.0f; + if (delta > 0) { + factor = -factor; + } + + normals[3 * + i] = new Vector3f(factor * n0.x, factor * n0.y, factor * n0.z); + normals[3 * i + + 1] = new Vector3f(factor * n1.x, factor * n1.y, factor * n1.z); + normals[3 * i + + 2] = new Vector3f(factor * n2.x, factor * n2.y, factor * n2.z); + + if (v0.rgb[1] != 0) { + colors[3 * i] = new Color3f(v0.rgb); + colors[3 * i + 1] = new Color3f(v0.rgb); + colors[3 * i + 2] = new Color3f(v0.rgb); + } + else { + colors[3 * i] = new Color3f(color); + colors[3 * i + 1] = new Color3f(color); + colors[3 * i + 2] = new Color3f(color); + } + + count += 3; + //logger.info("Triangle: "+i+" v1, v2, v3 "+t.v0+" "+t.v1+" "+t.v2); + } + + tetra2.setCoordinates(0, coordinates); + tetra2.setNormals(0, normals); + tetra2.setColors(0, colors); + + return tetra2; + } + + public static float[] calcPropertyOnSurface(Object obj, GaussianCube gCube, int n) { + + if (! (obj instanceof BranchGroup)) { + System.err.println("Warning: calcPropertyOnSurface: Uknown object " + obj.getClass().getCanonicalName() + " Ignored..."); + return new float[] { + 0, 0}; + } + BranchGroup bg = (BranchGroup) obj; + + ImplicitFunctionInterface fun = new VolumetricData(gCube.getVolumetricData(n), gCube.getDataOrigin(), + gCube.getNumberOfVoxels(), gCube.getAxisVectors(), 0); + return calcPropertyOnSurface(bg, fun); + } + + /** + * + * @param bg BranchGroup + * @param fun ImplicitFunctionInterface + * @return float[] - two-dimensional array, 0 - min, 1 - max + */ + public static float[] calcPropertyOnSurface(BranchGroup bg, ImplicitFunctionInterface fun) { + boolean minMaxSet = false; + float fMin = 0; + float fMax = 0; + + Enumeration enumer = bg.getAllChildren(); + while (enumer.hasMoreElements()) { + Object bgChild = enumer.nextElement(); + if (bgChild instanceof Shape3D) { + Shape3D shape3D = (Shape3D) bgChild; + boolean shMinMaxSet = false; + float shMin = 0, shMax = 0; + Enumeration geoms = shape3D.getAllGeometries(); + while (geoms.hasMoreElements()) { + Object geometry = geoms.nextElement(); + + // --- TriangleArray + if (geometry instanceof TriangleArray) { + TriangleArray ta = (TriangleArray) geometry; + int nVertices = ta.getValidVertexCount(); + Point3f[] coords = new Point3f[nVertices]; + for (int j = 0; j < nVertices; j++) { + coords[j] = new Point3f(); + } + + float[] values = new float[nVertices]; + ta.getCoordinates(0, coords); + float min = 0, max = 0; + for (int j = 0; j < nVertices; j++) { + values[j] = (float) fun.eval(coords[j].x, coords[j].y, coords[j].z); + + if (j == 0) { + min = values[j]; + max = values[j]; + } + else if (min > values[j]) { + min = values[j]; + } + else if (max < values[j]) { + max = values[j]; + } + + } + + // -- Storing user data in TriangleArray + Map userData = new HashMap (); + userData.put(USER_DATA_FLAG.FUN_VALUES_AT_VERTICES, values); + userData.put(USER_DATA_FLAG.MIN_FUN_VALUE_AT_VERTICES, new Float(min)); + userData.put(USER_DATA_FLAG.MAX_FUN_VALUE_AT_VERTICES, new Float(max)); + ta.setUserData(userData); + + // --- Setting min & max for shape3d + if (!shMinMaxSet) { + shMin = min; + shMax = max; + shMinMaxSet = true; + } + else { + if (shMin > min) { + shMin = min; + } + if (shMax < max) { + fMax = max; + } + } + + // -- Setting "global" min & max + + if (!minMaxSet) { + fMin = min; + fMax = max; + minMaxSet = true; + } + else { + if (fMin > min) { + fMin = min; + } + if (fMax < max) { + fMax = max; + } + } + + } + else { // --- end of TriangleArray + System.err.println( + "Warning: calcPropertyOnSurface(BranchGroup, ImplicitFunctionInterface): ignoring geometry type " + + geometry.getClass().getCanonicalName()); + } + } // --- End of while + + Map userData = new HashMap (); + userData.put(USER_DATA_FLAG.MIN_FUN_VALUE_AT_VERTICES, new Float(shMin)); + userData.put(USER_DATA_FLAG.MAX_FUN_VALUE_AT_VERTICES, new Float(shMax)); + shape3D.setUserData(userData); + + } + } + + return new float[] { + fMin, fMax}; + + } + + /** + * + * @param graphics GraphicsObjectInterface + * @param gCube GaussianCube + * @param n int - Cube number + * @return float[] - two dimensional array, index 0 - min value, 1 - max value + */ + public static float[] calcPropertyOnSurface(GraphicsObjectInterface graphics, GaussianCube gCube, int n) { + + ImplicitFunctionInterface fun = new VolumetricData(gCube.getVolumetricData(n), gCube.getDataOrigin(), + gCube.getNumberOfVoxels(), gCube.getAxisVectors(), 0); + + boolean minMaxSet = false; + float fMin = 0; + float fMax = 0; + + List ges = graphics.getShape3DElements(); + for (int i = 0; i < ges.size(); i++) { + Object obj = ges.get(i); + if (obj instanceof BranchGroup) { + BranchGroup bg = (BranchGroup) obj; + float[] minMax = calcPropertyOnSurface(bg, fun); + if (!minMaxSet) { + fMin = minMax[0]; + fMax = minMax[1]; + minMaxSet = true; + } + else { + if (fMin > minMax[0]) { + fMin = minMax[0]; + } + if (fMax < minMax[1]) { + fMax = minMax[1]; + } + } + + } + else { + System.err.println("Warning: calcPropertyOnSurface: ignoring graphics object " + obj.getClass().getCanonicalName()); + } + } + + return new float[] { + fMin, fMax}; + } + + public static void mapSurface(GraphicsObjectInterface graphics, ColorRangeScheme crange) { + + List ges = graphics.getShape3DElements(); + for (int i = 0; i < ges.size(); i++) { + Object obj = ges.get(i); + if (obj instanceof BranchGroup) { + BranchGroup bg = (BranchGroup) obj; + Enumeration enumer = bg.getAllChildren(); + + Node parent = bg.getParent(); + if (parent != null && enumer.hasMoreElements()) { + bg.detach(); + } + + while (enumer.hasMoreElements()) { + Object bgChild = enumer.nextElement(); + if (bgChild instanceof Shape3D) { + Shape3D shape3D = (Shape3D) bgChild; + mapSurface(shape3D, crange); + } + } + + if (parent != null) { + if (parent instanceof TransformGroup) { + ( (TransformGroup) parent).addChild(bg); + } + else if (parent instanceof BranchGroup) { + ( (BranchGroup) parent).addChild(bg); + } + } + + } + else { + System.err.println("Warning: mapSurface: ignoring graphics object " + obj.getClass().getCanonicalName()); + } + } + + } + + public static void mapSurface(Shape3D shape3D, ColorRangeScheme crange) { + + Map shape3dUserData = null; + if (shape3D.getUserData() == null) { + shape3dUserData = new HashMap (); + } + else { + shape3dUserData = (Map) shape3D.getUserData(); + } + shape3dUserData.put(USER_DATA_FLAG.COLOR_RANGE_SCHEME_OBJECT, crange); + + Enumeration geoms = shape3D.getAllGeometries(); + while (geoms.hasMoreElements()) { + Object geometry = geoms.nextElement(); + if (geometry instanceof TriangleArray) { + TriangleArray ta = (TriangleArray) geometry; + + Object uObj = ta.getUserData(); + + if (uObj == null) { + System.err.println("Warning: mapSurface: No user data (values on surface). Ignoring..."); + continue; + } + + float[] values = null; + try { + Map userData = (Map) uObj; + values = (float[]) userData.get(USER_DATA_FLAG.FUN_VALUES_AT_VERTICES); + List palette = crange.getColor3fPalette(); + userData.put(USER_DATA_FLAG.COLOR_PALETTE_ARRAY, palette); + + userData.put(USER_DATA_FLAG.MIN_CLIP_FUN_VALUE_AT_VERTICES, new Float(crange.getClipMin())); + userData.put(USER_DATA_FLAG.MAX_CLIP_FUN_VALUE_AT_VERTICES, new Float(crange.getClipMax())); + userData.put(USER_DATA_FLAG.COLOR_RANGE_SCHEME_OBJECT, crange); + } + catch (Exception ex) { + System.err.println("Warning: mapSurface: Cannot get user data (values on surface): " + ex.getMessage() + + " Ignoring..."); + continue; + } + + int nVertices = ta.getValidVertexCount(); + + if (nVertices != values.length) { + System.err.println("Warning: mapSurface: nVertices != values.length : " + nVertices + " != " + + values.length + " Ignoring..."); + continue; + } + + int vertexFormat = ta.getVertexFormat(); + boolean useColor4f = (vertexFormat & GeometryArray.COLOR_4) == GeometryArray.COLOR_4; + + Color3f[] colors = null; + Color4f[] colors4f = null; + + if (useColor4f) { + colors4f = new Color4f[nVertices]; + Color4f color4f = new Color4f(); + for (int j = 0; j < nVertices; j++) { + ta.getColor(j, color4f); + colors4f[j] = new Color4f(color4f); + crange.getColor4f(values[j], colors4f[j]); + } + } + else { + colors = new Color3f[nVertices]; + for (int j = 0; j < nVertices; j++) { + colors[j] = new Color3f(); + crange.getColor3f(values[j], colors[j]); + } + } + + if (useColor4f) { + ta.setColors(0, colors4f); + } + else { + ta.setColors(0, colors); + } + + } + else { + System.err.println("Warning: mapSurface: ignoring geometry type " + geometry.getClass().getCanonicalName()); + } + } + + } + + public static TriangleArray getSurface2(GaussianCube gCube, int n, float delta) { + + int bounds[] = { + gCube.getNumberOfVoxels()[0] - 1, + gCube.getNumberOfVoxels()[1] - 1, + gCube.getNumberOfVoxels()[2] - 1}; + + boolean dotet = false; + + ImplicitFunctionInterface fun = new VolumetricData(gCube.getVolumetricData(n), gCube.getDataOrigin(), + gCube.getNumberOfVoxels(), gCube.getAxisVectors(), delta); + + j3dPolygonizer polygonizer = new j3dPolygonizer(gCube.getDataOrigin(), bounds, gCube.getAxisVectors()[0][0], delta, fun); + polygonizer.setMarchingTatrahedrons(dotet); + + polygonizer.marchCubes(); + TriangleArray tetra2 = polygonizer.getTriangleArray(); + + logger.info("# triangles: " + polygonizer.noTriangles()); + if (polygonizer.noTriangles() < 1) { + return null; + } + + // --- Release memory + polygonizer.dispose(); + + return tetra2; + } + +} diff --git a/src/main/java/cct/gaussian/java3d/VolumetricData.java b/src/main/java/cct/gaussian/java3d/VolumetricData.java new file mode 100644 index 0000000..81e8236 --- /dev/null +++ b/src/main/java/cct/gaussian/java3d/VolumetricData.java @@ -0,0 +1,744 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian.java3d; + +import java.util.logging.Logger; + +import cct.interfaces.ImplicitFunctionInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class VolumetricData implements ImplicitFunctionInterface { + + double data[][][] = null; + float dataOrigin[] = null; + int numberOfVoxels[]; + float axisVectors[][]; + double delta = 0.0005f; + double max = 0, min = 0; + + float[] xvalues = new float[4]; + float[] yvalues = new float[4]; + float[] fun = new float[4]; + + float[] xv = new float[8]; + float[] yv = new float[8]; + float[] zv = new float[8]; + float[] fv = new float[8]; + + int maxErrorsOutput = 5; + int errorsCount = 0; + static final Logger logger = Logger.getLogger(VolumetricData.class.getCanonicalName()); + + public VolumetricData(double _data[][][], float _dataOrigin[], int _numberOfVoxels[], float _axisVectors[][], float _delta) { + data = _data; + dataOrigin = _dataOrigin; + numberOfVoxels = _numberOfVoxels; + axisVectors = _axisVectors; + delta = _delta; + + min = data[0][0][0]; + max = data[0][0][0]; + for (int i = 0; i < numberOfVoxels[0]; i++) { + for (int j = 0; j < numberOfVoxels[1]; j++) { + for (int k = 0; k < numberOfVoxels[2]; k++) { + if (data[i][j][k] > max) { + max = data[i][j][k]; + } else if (data[i][j][k] < min) { + min = data[i][j][k]; + } + } + } + } + logger.info("Min=" + min + " Max=" + max); + } + + @Override + public double eval(float x, float y, float z) { + + if (x < dataOrigin[0]) { + if (errorsCount <= maxErrorsOutput) { + System.err.println("eval: x out of lower bound " + dataOrigin[0] + " : " + x); + } + if (errorsCount == maxErrorsOutput) { + System.err.println("Further errors output will be supressed"); + } + ++errorsCount; + return 0; + } + + if (y < dataOrigin[1]) { + if (errorsCount <= maxErrorsOutput) { + System.err.println("eval: y out of lower bound " + dataOrigin[1] + " : " + y); + } + if (errorsCount == maxErrorsOutput) { + System.err.println("Further errors output will be supressed"); + } + ++errorsCount; + return 0; + } + + if (z < dataOrigin[2]) { + if (errorsCount <= maxErrorsOutput) { + System.err.println("eval: z out of lower bound " + dataOrigin[2] + " : " + z); + } + if (errorsCount == maxErrorsOutput) { + System.err.println("Further errors output will be supressed"); + } + ++errorsCount; + return 0; + } + + float local_x = (x - dataOrigin[0]) / axisVectors[0][0]; + float local_y = (y - dataOrigin[1]) / axisVectors[1][1]; + float local_z = (z - dataOrigin[2]) / axisVectors[2][2]; + + int start_x = (int) local_x; + if ((start_x + 1) - local_x < 0.001) { + start_x += 1; + } + int end_x = start_x; + float x_start = dataOrigin[0] + (start_x) * axisVectors[0][0]; + //if (Math.abs(x_start - x) > 0.0001) { + if ((x - x_start) > 0.001) { + end_x = start_x + 1; + } + + int start_y = (int) local_y; + if ((start_y + 1) - local_y < 0.001) { + start_y += 1; + } + int end_y = start_y; + float y_start = dataOrigin[1] + start_y * axisVectors[1][1]; + if (Math.abs(y_start - y) > 0.0001) { + end_y = start_y + 1; + } + + int start_z = (int) local_z; + if ((start_z + 1) - local_z < 0.001) { + start_z += 1; + } + int end_z = start_z; + float z_start = dataOrigin[2] + start_z * axisVectors[2][2]; + if (Math.abs(z_start - z) > 0.0001) { + end_z = start_z + 1; + } + + if (end_x == start_x && end_y == start_y && end_z == start_z) { + //logger.info("Exact"); + return data[start_x][start_y][start_z] - delta; + } + + // --- Error check + + if (start_x < 0 || start_x >= data.length) { + if (errorsCount <= maxErrorsOutput) { + System.err.println("start_x(" + start_x + ") < 0 || start_x >= data.length(" + data.length + ")"); + } + if (errorsCount == maxErrorsOutput) { + System.err.println("Further errors output will be supressed"); + } + ++errorsCount; + return 0; + } + + if (end_x >= data.length) { + if (errorsCount <= maxErrorsOutput) { + System.err.println("end_x(" + end_x + ") >= data.length(" + data.length + ")"); + } + if (errorsCount == maxErrorsOutput) { + System.err.println("Further errors output will be supressed"); + } + ++errorsCount; + return 0; + } + + if (start_y < 0 || start_y >= data[0].length) { + if (errorsCount <= maxErrorsOutput) { + System.err.println("start_y(" + start_y + ") < 0 || start_y >= data.length(" + data[0].length + ")"); + } + if (errorsCount == maxErrorsOutput) { + System.err.println("Further errors output will be supressed"); + } + ++errorsCount; + return 0; + } + + if (end_y >= data[0].length) { + if (errorsCount <= maxErrorsOutput) { + System.err.println("end_y(" + end_y + ") >= data.length(" + data[0].length + ")"); + } + if (errorsCount == maxErrorsOutput) { + System.err.println("Further errors output will be supressed"); + } + ++errorsCount; + return 0; + } + + if (start_z < 0 || start_z >= data[0][0].length) { + if (errorsCount <= maxErrorsOutput) { + System.err.println("start_z(" + start_z + ") < 0 || start_z >= data.length(" + data[0][0].length + ")"); + } + if (errorsCount == maxErrorsOutput) { + System.err.println("Further errors output will be supressed"); + } + ++errorsCount; + return 0; + } + + if (end_z >= data[0][0].length) { + if (errorsCount <= maxErrorsOutput) { + System.err.println("end_z(" + end_z + ") >= data.length(" + data[0][0].length + ")"); + } + if (errorsCount == maxErrorsOutput) { + System.err.println("Further errors output will be supressed"); + } + ++errorsCount; + return 0; + } + + /* + // --- Along X + if (end_y == start_y && end_z == start_z) { + float a = (data[end_x][start_y][start_z] - + data[start_x][start_y][start_z]) / axisVectors[0][0]; + float c = data[start_x][start_y][start_z] - a * x_start; + float fun = a * x + c; + logger.info("Exact Along X: f(" + x + ")=" + fun + " Y0(" + x_start + ")=" + + data[start_x][start_y][start_z] + " Y1(" + (x_start + axisVectors[0][0]) + ")=" + + data[end_x][start_y][start_z]); + return fun - delta; + } + + // --- Along Y + if (end_x == start_x && end_z == start_z) { + float a = (data[start_x][end_y][start_z] - + data[start_x][start_y][start_z]) / axisVectors[1][1]; + float c = data[start_x][start_y][start_z] - a * y_start; + float fun = a * y + c; + //logger.info("Exact Along Y: " + fun+ " Y0=" + + // data[start_x][start_y][start_z] + " Y1=" + + // data[start_x][end_y][start_z]); + return fun - delta; + } + + // --- Along Z + if (end_x == start_x && end_y == start_y) { + float a = (data[start_x][start_y][end_z] - + data[start_x][start_y][start_z]) / axisVectors[2][2]; + float c = data[start_x][start_y][start_z] - a * z_start; + float fun = a * z + c; + //logger.info("Exact Along Z: " + fun+ " Y0=" + + // data[start_x][start_y][start_z] + " Y1=" + + // data[start_x][start_y][end_z]); + return fun - delta; + } + + // --- In Z-plane + if (end_z == start_z) { + xvalues[0] = x_start; + yvalues[0] = y_start; + fun[0] = data[start_x][start_y][start_z]; + + xvalues[1] = x_start + axisVectors[0][0]; + yvalues[1] = y_start; + fun[1] = data[start_x + 1][start_y][start_z]; + + xvalues[2] = x_start + axisVectors[0][0]; + yvalues[2] = y_start + axisVectors[1][1]; + fun[2] = data[start_x + 1][start_y + 1][start_z]; + + xvalues[3] = x_start; + yvalues[3] = y_start + axisVectors[1][1]; + fun[3] = data[start_x][start_y + 1][start_z]; + + try { + float func = interpolate(xvalues, yvalues, fun, x, y); + logger.info("In Z-plane : " + func + "\n Y0=" + fun[0] + " Y1=" + fun[1] + " Y2=" + fun[2] + " Y3=" + fun[3]); + return func - delta; + } + catch (Exception ex) { + System.err.println("In Z-plane: Error: " + ex.getMessage()); + return 0; + } + } + + // --- In Y-plane + else if (end_y == start_y) { + xvalues[0] = x_start; + yvalues[0] = z_start; + fun[0] = data[start_x][start_y][start_z]; + + xvalues[1] = x_start + axisVectors[0][0]; + yvalues[1] = z_start; + fun[1] = data[start_x + 1][start_y][start_z]; + + xvalues[2] = x_start + axisVectors[0][0]; + yvalues[2] = z_start + axisVectors[2][2]; + fun[2] = data[start_x + 1][start_y][start_z + 1]; + + xvalues[3] = x_start; + yvalues[3] = z_start + axisVectors[2][2]; + fun[3] = data[start_x][start_y][start_z + 1]; + + try { + float func = interpolate(xvalues, yvalues, fun, x, z); + logger.info("In Y-plane : " + func + "\n Y0=" + fun[0] + " Y1=" + fun[1] + " Y2=" + fun[2] + " Y3=" + fun[3]); + return func - delta; + } + catch (Exception ex) { + System.err.println("In Y-plane: Error: " + ex.getMessage()); + return 0; + } + } + + // --- In X-plane + else if (end_x == start_x) { + xvalues[0] = y_start; + yvalues[0] = z_start; + fun[0] = data[start_x][start_y][start_z]; + + xvalues[1] = y_start + axisVectors[1][1]; + yvalues[1] = z_start; + fun[1] = data[start_x][start_y + 1][start_z]; + + xvalues[2] = y_start + axisVectors[1][1]; + yvalues[2] = z_start + axisVectors[2][2]; + fun[2] = data[start_x][start_y + 1][start_z + 1]; + + xvalues[3] = y_start; + yvalues[3] = z_start + axisVectors[2][2]; + fun[3] = data[start_x][start_y][start_z + 1]; + + try { + float func = interpolate(xvalues, yvalues, fun, y, z); + logger.info("In X-plane : " + func + "\n Y0=" + fun[0] + " Y1=" + fun[1] + " Y2=" + fun[2] + " Y3=" + fun[3]); + return func - delta; + } + catch (Exception ex) { + System.err.println("In X-plane: Error: " + ex.getMessage()); + return 0; + } + } + + // --- General case... + + xv[0] = x_start; + yv[0] = y_start; + zv[0] = z_start; + fv[0] = data[start_x][start_y][start_z]; + + xv[1] = x_start + axisVectors[0][0]; + yv[1] = y_start; + zv[1] = z_start; + fv[1] = data[start_x + 1][start_y][start_z]; + + xv[2] = x_start + axisVectors[0][0]; + yv[2] = y_start + axisVectors[1][1]; + zv[2] = z_start; + fv[2] = data[start_x + 1][start_y + 1][start_z]; + + xv[3] = x_start; + yv[3] = y_start + axisVectors[1][1]; + zv[3] = z_start; + fv[3] = data[start_x][start_y + 1][start_z]; + + xv[4] = x_start; + yv[4] = y_start; + zv[4] = z_start + axisVectors[2][2]; + fv[4] = data[start_x][start_y][start_z + 1]; + + xv[5] = x_start + axisVectors[0][0]; + yv[5] = y_start; + zv[5] = z_start + axisVectors[2][2]; + fv[5] = data[start_x + 1][start_y][start_z + 1]; + + xv[6] = x_start + axisVectors[0][0]; + yv[6] = y_start + axisVectors[1][1]; + zv[6] = z_start + axisVectors[2][2]; + fv[6] = data[start_x + 1][start_y + 1][start_z + 1]; + + xv[7] = x_start; + yv[7] = y_start + axisVectors[1][1]; + zv[7] = z_start + axisVectors[2][2]; + fv[7] = data[start_x][start_y + 1][start_z + 1]; + + try { + float func = interpolate(xv, yv, zv, fv, x, y, z); + return func - delta; + } + catch (Exception ex) { + System.err.println("General case exception: " + ex.getMessage()); + } + */ + // --- Old stuff + + double fun_y[] = { + 0, 0}; + double fun_x[] = { + 0, 0}; + + for (int ix = start_x, x_count = 0; ix <= end_x; ix++, x_count++) { + + for (int iy = start_y, y_count = 0; iy <= end_y; iy++, y_count++) { + if (start_z == end_z) { + fun_y[y_count] = data[ix][iy][start_z]; + } else { + fun_y[y_count] = data[ix][iy][start_z] + + (z - z_start) / axisVectors[2][2] * + (data[ix][iy][end_z] - data[ix][iy][start_z]); + //logger.info("Interpolated Z: "+fun_y[y_count]+" At the corners: "+data[ix][iy][start_z]+" & "+data[ix][iy][end_z]); + } + } + + if (start_y == end_y) { + fun_x[x_count] = fun_y[0]; + } else { + fun_x[x_count] = fun_y[0] + (y - y_start) / axisVectors[1][1] * + (fun_y[1] - fun_y[0]); + //logger.info("Interpolated Y: "+fun_x[x_count]+" At the corners: "+fun_y[1]+" & "+fun_y[0]); + } + + } + + double fun; + if (start_x == end_x) { + fun = fun_x[0]; + } else { + fun = fun_x[0] + (x - x_start) / axisVectors[0][0] * + (fun_x[1] - fun_x[0]); + } + + if (fun < min || fun > max) { + logger.info("Wrong function: " + fun + " at i, j, k " + start_x + + " " + start_y + " " + start_z); + if (fun < min) { + fun = min; + } else if (fun > max) { + fun = max; + } + } + + return fun - delta; + } + + private float interpolate(float[] xvalues, float[] yvalues, float[] fun, float x, float y) throws Exception { + if (xvalues.length != yvalues.length || xvalues.length != fun.length) { + throw new Exception("xvalues.length != yvalues.length || xvalues.length != fun.length"); + } + + float sumXi = 0, sumYi = 0, sumZi = 0, sumXSq_i = 0, sumYSq_i = 0; + float sumXiYi = 0, sumXiZi = 0, sumYiZi = 0; + + for (int i = 0; i < xvalues.length; i++) { + sumXi += xvalues[i]; + sumYi += yvalues[i]; + sumZi += fun[i]; + sumXSq_i += xvalues[i] * xvalues[i]; + sumYSq_i += yvalues[i] * yvalues[i]; + sumXiYi += xvalues[i] * yvalues[i]; + sumXiZi += xvalues[i] * fun[i]; + sumYiZi += yvalues[i] * fun[i]; + } + + float d11 = xvalues.length; + float d12 = sumXi; + float d13 = sumYi; + float D1 = sumZi; + + float d21 = sumXi; + float d22 = sumXSq_i; + float d23 = sumXiYi; + float D2 = sumXiZi; + + float d31 = sumYi; + float d32 = sumXiYi; + float d33 = sumYSq_i; + float D3 = sumYiZi; + + float det = d13 * d22 * d31 - d12 * d23 * d31 - + d13 * d21 * d32 + d11 * d23 * d32 + d12 * d21 * d33 - d11 * d22 * d33; + + float a = -(d13 * d21 * D3 - d11 * d23 * D3 - d13 * D2 * d31 + D1 * d23 * d31 + + d11 * D2 * d33 - D1 * d21 * d33) / det; + + float b = (d12 * d21 * D3 - d11 * d22 * D3 - d12 * D2 * d31 + D1 * d22 * d31 + + d11 * D2 * d32 - D1 * d21 * d32) / det; + + float c = (d13 * d22 * D3 - d12 * d23 * D3 - d13 * D2 * d32 + D1 * d23 * d32 + + d12 * D2 * d33 - D1 * d22 * d33) / det; + + float func = a * x + b * y + c; + + // --- Error check (debug) + + + + float min = fun[0], max = fun[0]; + for (int i = 1; i < fun.length; i++) { + if (min > fun[i]) { + min = fun[i]; + } else if (max < fun[i]) { + max = fun[i]; + } + } + if (func < min || func > max) { + //throw new Exception("func < min || func > max : func="+func+" min="+min+" max="+max); + System.err.println("func < min || func > max : func=" + func + " min=" + min + " max=" + max); + logger.info("a=" + a + " b=" + b + " c=" + c); + float err = 0; + for (int i = 1; i < fun.length; i++) { + float t = a * xvalues[i] + b * yvalues[i] + c - fun[i]; + err += t * t; + } + logger.info("Error: " + err); + logger.info("x0=" + xvalues[0] + " y0=" + yvalues[0] + " fun=" + fun[0]); + logger.info("x1=" + xvalues[1] + " y1=" + yvalues[1] + " fun=" + fun[1]); + logger.info("x2=" + xvalues[2] + " y2=" + yvalues[2] + " fun=" + fun[2]); + logger.info("x3=" + xvalues[3] + " y3=" + yvalues[3] + " fun=" + fun[3]); + logger.info("Interpolated: x=" + x + " y=" + y + " fun=" + func); + //System.exit(0); + + int imin = 0; + double mind = Math.sqrt((x - xvalues[0]) * (x - xvalues[0]) + (y - yvalues[0]) * (y - yvalues[0])); + for (int i = 1; i < fun.length; i++) { + double dist = Math.sqrt((x - xvalues[i]) * (x - xvalues[i]) + (y - yvalues[i]) * (y - yvalues[i])); + if (mind > dist) { + mind = dist; + imin = i; + } + } + func = fun[imin]; + } + + return func; + } + + private float interpolate(float[] xvalues, float[] yvalues, float[] zvalues, float[] fun, float x, float y, float z) throws + Exception { + if (xvalues.length != yvalues.length || xvalues.length != fun.length) { + throw new Exception("xvalues.length != yvalues.length || xvalues.length != fun.length"); + } + + float sumXi = 0, sumYi = 0, sumZi = 0, sumXSq_i = 0, sumYSq_i = 0, sumZSq_i = 0; + float sumXiYi = 0, sumXiZi = 0, sumYiZi = 0, sumFi = 0, sumXiFi = 0, sumYiFi = 0; + float sumZiFi = 0; + + for (int i = 0; i < xvalues.length; i++) { + sumXi += xvalues[i]; + sumYi += yvalues[i]; + sumZi += zvalues[i]; + sumFi += fun[i]; + + sumXSq_i += xvalues[i] * xvalues[i]; + sumYSq_i += yvalues[i] * yvalues[i]; + sumZSq_i += zvalues[i] * zvalues[i]; + + sumXiYi += xvalues[i] * yvalues[i]; + sumXiZi += xvalues[i] * zvalues[i]; + sumYiZi += yvalues[i] * zvalues[i]; + + sumXiFi += xvalues[i] * fun[i]; + sumYiFi += yvalues[i] * fun[i]; + sumZiFi += zvalues[i] * fun[i]; + } + + float d11 = xvalues.length; + float d12 = sumXi; + float d13 = sumYi; + float d14 = sumZi; + float D1 = sumFi; + + float d21 = sumXi; + float d22 = sumXSq_i; + float d23 = sumXiYi; + float d24 = sumXiZi; + float D2 = sumXiFi; + + float d31 = sumYi; + float d32 = sumXiYi; + float d33 = sumYSq_i; + float d34 = sumYiZi; + float D3 = sumYiFi; + + float d41 = sumZi; + float d42 = sumXiZi; + float d43 = sumYiZi; + float d44 = sumZSq_i; + float D4 = sumZiFi; + + float a = (d14 * d23 * d31 * D4 - d13 * d24 * d31 * D4 - d14 * d21 * d33 * D4 + + d11 * d24 * d33 * D4 + d13 * d21 * d34 * D4 - + d11 * d23 * d34 * D4 - d14 * d23 * D3 * d41 + + d13 * d24 * D3 * d41 + d14 * D2 * d33 * d41 - + D1 * d24 * d33 * d41 - d13 * D2 * d34 * d41 + + D1 * d23 * d34 * d41 + d14 * d21 * D3 * d43 - + d11 * d24 * D3 * d43 - d14 * D2 * d31 * d43 + + D1 * d24 * d31 * d43 + d11 * D2 * d34 * d43 - + D1 * d21 * d34 * d43 - d13 * d21 * D3 * d44 + + d11 * d23 * D3 * d44 + d13 * D2 * d31 * d44 - + D1 * d23 * d31 * d44 - d11 * D2 * d33 * d44 + D1 * d21 * d33 * d44) / + ( -(d14 * d23 * d32 * d41) + d13 * d24 * d32 * d41 + + d14 * d22 * d33 * d41 - d12 * d24 * d33 * d41 - + d13 * d22 * d34 * d41 + d12 * d23 * d34 * d41 + + d14 * d23 * d31 * d42 - d13 * d24 * d31 * d42 - + d14 * d21 * d33 * d42 + d11 * d24 * d33 * d42 + + d13 * d21 * d34 * d42 - d11 * d23 * d34 * d42 - + d14 * d22 * d31 * d43 + d12 * d24 * d31 * d43 + + d14 * d21 * d32 * d43 - d11 * d24 * d32 * d43 - + d12 * d21 * d34 * d43 + d11 * d22 * d34 * d43 + + d13 * d22 * d31 * d44 - d12 * d23 * d31 * d44 - + d13 * d21 * d32 * d44 + d11 * d23 * d32 * d44 + + d12 * d21 * d33 * d44 - d11 * d22 * d33 * d44); + + float b = ( -(d14 * d22 * d31 * D4) + d12 * d24 * d31 * D4 + d14 * d21 * d32 * D4 - + d11 * d24 * d32 * D4 - d12 * d21 * d34 * D4 + + d11 * d22 * d34 * D4 + d14 * d22 * D3 * d41 - + d12 * d24 * D3 * d41 - d14 * D2 * d32 * d41 + + D1 * d24 * d32 * d41 + d12 * D2 * d34 * d41 - + D1 * d22 * d34 * d41 - d14 * d21 * D3 * d42 + + d11 * d24 * D3 * d42 + d14 * D2 * d31 * d42 - + D1 * d24 * d31 * d42 - d11 * D2 * d34 * d42 + + D1 * d21 * d34 * d42 + d12 * d21 * D3 * d44 - + d11 * d22 * D3 * d44 - d12 * D2 * d31 * d44 + + D1 * d22 * d31 * d44 + d11 * D2 * d32 * d44 - D1 * d21 * d32 * d44) / + ( -(d14 * d23 * d32 * d41) + d13 * d24 * d32 * d41 + + d14 * d22 * d33 * d41 - d12 * d24 * d33 * d41 - + d13 * d22 * d34 * d41 + d12 * d23 * d34 * d41 + + d14 * d23 * d31 * d42 - d13 * d24 * d31 * d42 - + d14 * d21 * d33 * d42 + d11 * d24 * d33 * d42 + + d13 * d21 * d34 * d42 - d11 * d23 * d34 * d42 - + d14 * d22 * d31 * d43 + d12 * d24 * d31 * d43 + + d14 * d21 * d32 * d43 - d11 * d24 * d32 * d43 - + d12 * d21 * d34 * d43 + d11 * d22 * d34 * d43 + + d13 * d22 * d31 * d44 - d12 * d23 * d31 * d44 - + d13 * d21 * d32 * d44 + d11 * d23 * d32 * d44 + + d12 * d21 * d33 * d44 - d11 * d22 * d33 * d44); + + float c = ( -(d13 * d22 * d31 * D4) + d12 * d23 * d31 * D4 + d13 * d21 * d32 * D4 - + d11 * d23 * d32 * D4 - d12 * d21 * d33 * D4 + + d11 * d22 * d33 * D4 + d13 * d22 * D3 * d41 - + d12 * d23 * D3 * d41 - d13 * D2 * d32 * d41 + + D1 * d23 * d32 * d41 + d12 * D2 * d33 * d41 - + D1 * d22 * d33 * d41 - d13 * d21 * D3 * d42 + + d11 * d23 * D3 * d42 + d13 * D2 * d31 * d42 - + D1 * d23 * d31 * d42 - d11 * D2 * d33 * d42 + + D1 * d21 * d33 * d42 + d12 * d21 * D3 * d43 - + d11 * d22 * D3 * d43 - d12 * D2 * d31 * d43 + + D1 * d22 * d31 * d43 + d11 * D2 * d32 * d43 - D1 * d21 * d32 * d43) / + (d14 * d23 * d32 * d41 - d13 * d24 * d32 * d41 - + d14 * d22 * d33 * d41 + d12 * d24 * d33 * d41 + + d13 * d22 * d34 * d41 - d12 * d23 * d34 * d41 - + d14 * d23 * d31 * d42 + d13 * d24 * d31 * d42 + + d14 * d21 * d33 * d42 - d11 * d24 * d33 * d42 - + d13 * d21 * d34 * d42 + d11 * d23 * d34 * d42 + + d14 * d22 * d31 * d43 - d12 * d24 * d31 * d43 - + d14 * d21 * d32 * d43 + d11 * d24 * d32 * d43 + + d12 * d21 * d34 * d43 - d11 * d22 * d34 * d43 - + d13 * d22 * d31 * d44 + d12 * d23 * d31 * d44 + + d13 * d21 * d32 * d44 - d11 * d23 * d32 * d44 - + d12 * d21 * d33 * d44 + d11 * d22 * d33 * d44); + + float d = ( -(d14 * d23 * d32 * D4) + d13 * d24 * d32 * D4 + d14 * d22 * d33 * D4 - + d12 * d24 * d33 * D4 - d13 * d22 * d34 * D4 + + d12 * d23 * d34 * D4 + d14 * d23 * D3 * d42 - + d13 * d24 * D3 * d42 - d14 * D2 * d33 * d42 + + D1 * d24 * d33 * d42 + d13 * D2 * d34 * d42 - + D1 * d23 * d34 * d42 - d14 * d22 * D3 * d43 + + d12 * d24 * D3 * d43 + d14 * D2 * d32 * d43 - + D1 * d24 * d32 * d43 - d12 * D2 * d34 * d43 + + D1 * d22 * d34 * d43 + d13 * d22 * D3 * d44 - + d12 * d23 * D3 * d44 - d13 * D2 * d32 * d44 + + D1 * d23 * d32 * d44 + d12 * D2 * d33 * d44 - D1 * d22 * d33 * d44) / + ( -(d14 * d23 * d32 * d41) + d13 * d24 * d32 * d41 + + d14 * d22 * d33 * d41 - d12 * d24 * d33 * d41 - + d13 * d22 * d34 * d41 + d12 * d23 * d34 * d41 + + d14 * d23 * d31 * d42 - d13 * d24 * d31 * d42 - + d14 * d21 * d33 * d42 + d11 * d24 * d33 * d42 + + d13 * d21 * d34 * d42 - d11 * d23 * d34 * d42 - + d14 * d22 * d31 * d43 + d12 * d24 * d31 * d43 + + d14 * d21 * d32 * d43 - d11 * d24 * d32 * d43 - + d12 * d21 * d34 * d43 + d11 * d22 * d34 * d43 + + d13 * d22 * d31 * d44 - d12 * d23 * d31 * d44 - + d13 * d21 * d32 * d44 + d11 * d23 * d32 * d44 + + d12 * d21 * d33 * d44 - d11 * d22 * d33 * d44); + + float func = a * x + b * y + c * z + d; + + // --- Error check + + float min = fun[0], max = fun[0]; + for (int i = 1; i < fun.length; i++) { + if (min > fun[i]) { + min = fun[i]; + } else if (max < fun[i]) { + max = fun[i]; + } + } + if (func < min || func > max) { + //throw new Exception("func < min || func > max : func="+func+" min="+min+" max="+max); + System.err.println("General case: func < min || func > max : func=" + func + " min=" + min + " max=" + max); + int imin = 0; + double mind = Math.sqrt((x - xvalues[0]) * (x - xvalues[0]) + (y - yvalues[0]) * (y - yvalues[0]) + + (z - zvalues[0]) * (z - zvalues[0])); + for (int i = 1; i < fun.length; i++) { + double dist = Math.sqrt((x - xvalues[i]) * (x - xvalues[i]) + (y - yvalues[i]) * (y - yvalues[i]) + + (z - zvalues[i]) * (z - zvalues[i])); + if (mind > dist) { + mind = dist; + imin = i; + } + } + func = fun[imin]; + + } + + return func; + } + +} diff --git a/src/main/java/cct/gaussian/ui/GaussianInputEditorFrame.java b/src/main/java/cct/gaussian/ui/GaussianInputEditorFrame.java new file mode 100644 index 0000000..1d66b80 --- /dev/null +++ b/src/main/java/cct/gaussian/ui/GaussianInputEditorFrame.java @@ -0,0 +1,1257 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian.ui; + +import cct.gaussian.GJFParserInterface; +import cct.interfaces.MoleculeInterface; +import cct.resources.images.ImageResources; +import cct.tools.IOUtils; +import cct.tools.ui.FontSelectorDialog; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.prefs.Preferences; + +/** + *

Title: Gasussian Utility Classes

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class GaussianInputEditorFrame + extends JFrame implements ActionListener { + + static String FontNameKey = "FontName"; + static String FontSizeKey = "FontSize"; + static String FontStyleKey = "FontStyle"; + static String defaultFontName = "default"; + + Preferences prefs; + FontSelectorDialog fontSelector = null; + GJFParserInterface gjfParser = null; + int numberOfEntries = 1; + int count = 0; + java.util.List additionalEntries = new ArrayList(); + java.util.List entryLabels = new ArrayList(); + String fileName = ""; + String workingDirectory = ""; + //String rootDir = IOUtils.getRootDirectory(this); + String protocol = "file:"; + String images16x16Path = "cct/images/icons16x16/"; + String images32x32Path = "cct/images/icons32x32/"; + //String path = protocol + rootDir + "cct/resources/images/icons32x32/"; + + int size, style; + String fontName; + Font newFont; + + JPanel contentPane; + BorderLayout borderLayout1 = new BorderLayout(); + JMenuBar jMenuBar1 = new JMenuBar(); + JMenu jMenuFile = new JMenu(); + JMenuItem jMenuFileExit = new JMenuItem(); + JMenu jMenuHelp = new JMenu(); + JMenuItem jMenuHelpAbout = new JMenuItem(); + JToolBar jToolBar = new JToolBar(); + JButton openFileButton = new JButton(); + JButton resetButton = new JButton(); + JButton jButton3 = new JButton(); + ImageIcon image1 = new ImageIcon(GaussianInputEditorFrame.class. + getResource("openFile.png")); + ImageIcon image2 = new ImageIcon(GaussianInputEditorFrame.class. + getResource("closeFile.png")); + ImageIcon image3 = new ImageIcon(GaussianInputEditorFrame.class. + getResource("help.png")); + JLabel statusBar = new JLabel(); + SimpleG03EditorPanel simpleG03EditorPanel1 = new SimpleG03EditorPanel(gjfParser); + JPanel mainPanel = new JPanel(); + JPanel goStepsPanel = new JPanel(); + JButton previousStepButton = new JButton(); + JButton nextStepButton = new JButton(); + BorderLayout borderLayout2 = new BorderLayout(); + ImageIcon arrowUp = new ImageIcon(ImageResources.class. + getResource("icons32x32/arrowUp.gif")); + + //ImageIcon arrowUp = new ImageIcon(IOUtils.getURL(protocol, this, + // images32x32Path, "arrowUp.gif")); + + ImageIcon arrowUpFaded = new ImageIcon(ImageResources.class. + getResource( + "icons32x32/arrowUpFaded.gif")); + ImageIcon arrowDown = new ImageIcon(ImageResources.class. + getResource("icons32x32/arrowDown.gif")); + ImageIcon arrowDownFaded = new ImageIcon(ImageResources.class. + getResource( + "icons32x32/arrowDownFaded.gif")); + ImageIcon deleteStep = new ImageIcon(ImageResources.class. + getResource( + "icons32x32/window-exit.png")); + ImageIcon insertNewStep = new ImageIcon(ImageResources.class. + getResource( + "icons32x32/window-new.png")); + ImageIcon openFile = new ImageIcon(ImageResources.class. + getResource("icons16x16/openFile.png")); + ImageIcon saveFile = new ImageIcon(ImageResources.class. + getResource("icons16x16/saveFile.png")); + + ImageIcon saveStepInFile = new ImageIcon(ImageResources.class. + getResource( + "icons32x32/fileSaveAs.png")); + ImageIcon okReturnBack = new ImageIcon(ImageResources.class. + getResource( + "icons32x32/button-ok.png")); + + GridBagLayout gridBagLayout4 = new GridBagLayout(); + JPanel cardPanel = new JPanel(); + JPanel topPanel = new JPanel(); + CardLayout cardLayout1 = new CardLayout(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + JLabel jLabel1 = new JLabel(); + JComboBox stepsComboBox = new JComboBox(); + FlowLayout flowLayout2 = new FlowLayout(); + JButton deleteEntryButton = new JButton(); + JButton insertEntryButton = new JButton(); + JLabel jLabel2 = new JLabel(); + JMenuItem jMenuItem1 = new JMenuItem(); + JLabel jLabel3 = new JLabel(); + JComboBox fileComboBox = new JComboBox(); + JButton openSelectedFileButton = new JButton(); + JButton saveFileButton = new JButton(); + JButton saveStepButton = new JButton(); + public JButton returnBackButton = new JButton(); + JMenu viewMenu = new JMenu(); + JMenuItem increaseMenuItem = new JMenuItem(); + JMenuItem decreaseMenuItem = new JMenuItem(); + JMenuItem jMenuItem4 = new JMenuItem(); + + public GaussianInputEditorFrame(GJFParserInterface parser) { + gjfParser = parser; + simpleG03EditorPanel1.setGeometryValidator(gjfParser); + try { + setDefaultCloseOperation(EXIT_ON_CLOSE); + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + /** + * Component initialization. + * + * @throws Exception + */ + private void jbInit() throws Exception { + /* + logger.info("Root directory : " + rootDir + "\nPath: " + path); + + URL imagesURL = null; + try { + imagesURL = new URL(path + "fileSaveAs.png"); + saveStepInFile = new ImageIcon(imagesURL); + imagesURL = new URL(path + "button-ok.png"); + okReturnBack = new ImageIcon(imagesURL); + } + catch (java.net.MalformedURLException ex) { + System.err.println("Linking resource images: " + ex.getMessage()); + } + */ + + contentPane = (JPanel) getContentPane(); + contentPane.setLayout(borderLayout1); + this.setDefaultCloseOperation(EXIT_ON_CLOSE); + //setSize(new Dimension(400, 300)); + setTitle("Gaussian Input Editor"); + statusBar.setText(" "); + jMenuFile.setText("File"); + jMenuFileExit.setText("Exit"); + jMenuFileExit.addActionListener(new + GaussianInputEditorFrame_jMenuFileExit_ActionAdapter(this)); + jMenuHelp.setText("Help"); + jMenuHelpAbout.setText("About"); + jMenuHelpAbout.addActionListener(new + GaussianInputEditorFrame_jMenuHelpAbout_ActionAdapter(this)); + mainPanel.setLayout(borderLayout2); + previousStepButton.setPreferredSize(new Dimension(41, 41)); + previousStepButton.setToolTipText("Previous Step"); + previousStepButton.setIcon(arrowUp); + previousStepButton.addActionListener(new + GaussianInputEditorFrame_previousStepButton_actionAdapter(this)); + nextStepButton.setPreferredSize(new Dimension(41, 41)); + nextStepButton.setToolTipText("Next Step"); + nextStepButton.setIcon(arrowDown); + nextStepButton.addActionListener(new + GaussianInputEditorFrame_nextStepButton_actionAdapter(this)); + cardPanel.setLayout(cardLayout1); + goStepsPanel.setLayout(gridBagLayout1); + jLabel1.setToolTipText(""); + jLabel1.setHorizontalAlignment(SwingConstants.LEFT); + jLabel1.setText(" Step: "); + deleteEntryButton.setPreferredSize(new Dimension(41, 41)); + deleteEntryButton.setToolTipText("Delete this Step"); + deleteEntryButton.setIcon(new ImageIcon(ImageResources.class. + getResource( + "icons32x32/window-exit.png"))); + deleteEntryButton.addActionListener(new + GaussianInputEditorFrame_jButton6_actionAdapter(this)); + insertEntryButton.setPreferredSize(new Dimension(41, 41)); + insertEntryButton.setToolTipText("Insert New Step"); + insertEntryButton.setIcon(new ImageIcon(ImageResources.class. + getResource( + "icons32x32/window-new.png"))); + insertEntryButton.addActionListener(new + GaussianInputEditorFrame_insertEntryButton_actionAdapter(this)); + jLabel2.setToolTipText(""); + jLabel2.setHorizontalAlignment(SwingConstants.LEFT); + openFileButton.addActionListener(new + GaussianInputEditorFrame_openFileButton_actionAdapter(this)); + stepsComboBox.addItemListener(new + GaussianInputEditorFrame_stepsComboBox_itemAdapter(this)); + stepsComboBox.setMaximumSize(new Dimension(100, 19)); + stepsComboBox.setPreferredSize(new Dimension(60, 19)); + stepsComboBox.setToolTipText("Select Step to Edit"); + jMenuItem1.setText("Open File"); + jMenuItem1.addActionListener(new + GaussianInputEditorFrame_jMenuItem1_actionAdapter(this)); + jLabel3.setToolTipText(""); + jLabel3.setHorizontalAlignment(SwingConstants.LEFT); + jLabel3.setText("File: "); + fileComboBox.setToolTipText("Select Step to Edit"); + openSelectedFileButton.setMaximumSize(new Dimension(25, 25)); + openSelectedFileButton.setMinimumSize(new Dimension(25, 25)); + openSelectedFileButton.setPreferredSize(new Dimension(25, 25)); + openSelectedFileButton.setToolTipText("Click to Open Selected File"); + openSelectedFileButton.setBorderPainted(false); + openSelectedFileButton.setIcon(openFile); + openSelectedFileButton.setMnemonic('0'); + openSelectedFileButton.addActionListener(new + GaussianInputEditorFrame_openSelectedFileButton_actionAdapter(this)); + saveFileButton.setToolTipText("Save Gaussian Job File"); + saveFileButton.setIcon(saveFile); + saveFileButton.addActionListener(new + GaussianInputEditorFrame_saveFileButton_actionAdapter(this)); + saveStepButton.setPreferredSize(new Dimension(41, 41)); + saveStepButton.setToolTipText("Save this Step in Separate File"); + saveStepButton.setIcon(saveStepInFile); + saveStepButton.addActionListener(new + GaussianInputEditorFrame_saveStepButton_actionAdapter(this)); + resetButton.addActionListener(new + GaussianInputEditorFrame_resetButton_actionAdapter(this)); + returnBackButton.setPreferredSize(new Dimension(41, 41)); + returnBackButton.setToolTipText( + "Select current Step and return back to the Parent Window"); + returnBackButton.setVisible(false); + returnBackButton.setIcon(okReturnBack); + viewMenu.setToolTipText("Adjust Text Appearance"); + viewMenu.setText("View"); + increaseMenuItem.setToolTipText(""); + increaseMenuItem.setText("Increase Font Size"); + increaseMenuItem.addActionListener(this); + decreaseMenuItem.setToolTipText(""); + decreaseMenuItem.setText("Decrease Font Size"); + decreaseMenuItem.addActionListener(this); + jMenuItem4.setToolTipText(""); + jMenuItem4.setText("Select Font"); + jMenuItem4.addActionListener(this); + jMenuBar1.add(jMenuFile); + jMenuFile.add(jMenuItem1); + jMenuFile.addSeparator(); + jMenuFile.add(jMenuFileExit); + jMenuBar1.add(viewMenu); + jMenuBar1.add(jMenuHelp); + jMenuHelp.add(jMenuHelpAbout); + setJMenuBar(jMenuBar1); + openFileButton.setIcon(image1); + openFileButton.setToolTipText("Open Gaussian Job File"); + resetButton.setIcon(image2); + resetButton.setToolTipText("Close File"); + jButton3.setIcon(image3); + jButton3.setToolTipText("Help"); + jToolBar.add(openFileButton); + jToolBar.add(resetButton); + jToolBar.add(saveFileButton); + jToolBar.add(jButton3); + mainPanel.add(topPanel, BorderLayout.NORTH); + topPanel.add(jLabel3); + topPanel.add(fileComboBox); + topPanel.add(openSelectedFileButton); + topPanel.add(jLabel1); + topPanel.add(stepsComboBox); + flowLayout2.setAlignment(FlowLayout.LEFT); + topPanel.setLayout(flowLayout2); + contentPane.add(statusBar, BorderLayout.SOUTH); + mainPanel.add(cardPanel, BorderLayout.CENTER); + cardPanel.add(simpleG03EditorPanel1, "step0"); + contentPane.add(mainPanel, BorderLayout.CENTER); + mainPanel.add(goStepsPanel, BorderLayout.EAST); + contentPane.add(jToolBar, BorderLayout.NORTH); + goStepsPanel.add(jLabel2, new GridBagConstraints(0, 6, 3, 1, 0.0, 1.0 + , GridBagConstraints.CENTER, GridBagConstraints.VERTICAL, + new Insets(0, 0, 0, 0), 0, 0)); + goStepsPanel.add(saveStepButton, + new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + goStepsPanel.add(deleteEntryButton, + new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + goStepsPanel.add(insertEntryButton, + new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + goStepsPanel.add(nextStepButton, + new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + goStepsPanel.add(previousStepButton, + new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(0, 2, 2, 2), 0, 0)); + goStepsPanel.add(returnBackButton + , new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + viewMenu.add(increaseMenuItem); + viewMenu.add(decreaseMenuItem); + viewMenu.addSeparator(); + viewMenu.add(jMenuItem4); + stepsComboBox.addItem(" " + String.valueOf(numberOfEntries)); + + // --- Retrieving font properties + + Font currentFont = simpleG03EditorPanel1.getFontForText(); + size = currentFont.getSize(); + style = currentFont.getStyle(); + fontName = currentFont.getFontName(); + + try { + prefs = Preferences.userNodeForPackage(this.getClass()); + fontName = prefs.get(FontNameKey, currentFont.getFontName()); + size = prefs.getInt(FontSizeKey, 12); + style = prefs.getInt(FontStyleKey, 0); + } + catch (Exception ex) { + System.err.println("Error retrieving Font Preferences: " + + ex.getMessage()); + return; + } + + newFont = new Font(fontName, style, size); + simpleG03EditorPanel1.setFontForText(newFont); + + this.pack(); + } + + public JMenu getFileMenu() { + return jMenuFile; + } + + public JToolBar getToolBar() { + return jToolBar; + } + + /** + * File | Exit action performed. + * + * @param actionEvent ActionEvent + */ + void jMenuFileExit_actionPerformed(ActionEvent actionEvent) { + System.exit(0); + } + + public String addMenuItem(String menuName, JMenuItem menuItem) { + for (int i = 0; i < jMenuBar1.getMenuCount(); i++) { + JMenu menu = jMenuBar1.getMenu(i); + //logger.info("Name: "+menu.getName()+" ActionCommand: "+menu.getActionCommand()); + if (menuName.equalsIgnoreCase(menu.getActionCommand())) { + menu.add(menuItem); + return null; + } + } + return "No menu with name " + menuName; + } + + public void removeMenuItem(String menuName, String menuItemName) throws + Exception { + for (int i = 0; i < jMenuBar1.getMenuCount(); i++) { + JMenu menu = jMenuBar1.getMenu(i); + if (menu == null) { + continue; + } + //logger.info("Name: "+menu.getName()+" ActionCommand: "+menu.getActionCommand()); + if (menuName.equalsIgnoreCase(menu.getActionCommand())) { + for (int j = 0; j < menu.getItemCount(); j++) { + JMenuItem item = null; + try { + item = menu.getItem(j); + } + catch (Exception ex) { + continue; + } + if (item == null) { + continue; + } + if (item.getText().equalsIgnoreCase(menuItemName)) { + menu.remove(item); + return; + } + } + } + } + throw new Exception("No menu item " + menuItemName + " in the menu " + + menuName); + } + + /** + * Help | About action performed. + * + * @param actionEvent ActionEvent + */ + void jMenuHelpAbout_actionPerformed(ActionEvent actionEvent) { + GaussianInputEditorFrame_AboutBox dlg = new + GaussianInputEditorFrame_AboutBox(this); + Dimension dlgSize = dlg.getPreferredSize(); + Dimension frmSize = getSize(); + Point loc = getLocation(); + dlg.setLocation( (frmSize.width - dlgSize.width) / 2 + loc.x, + (frmSize.height - dlgSize.height) / 2 + loc.y); + dlg.setModal(true); + dlg.pack(); + dlg.setVisible(true); + } + + public void openFileButton_actionPerformed(ActionEvent e) { + FileDialog fd = new FileDialog(new Frame(), "Open Gaussian Job File File", + FileDialog.LOAD); + fd.setFile("*.gjf;*.com;*.g03"); + fd.setVisible(true); + if (fd.getFile() == null) { + return; + } + + fileName = new String(fd.getFile()); + workingDirectory = new String(fd.getDirectory()); + + parseNewFile(workingDirectory + fileName); + + } + + public void setupMolecule(MoleculeInterface mol) { + if (gjfParser != null) { + gjfParser.removeAllEntries(); + } + simpleG03EditorPanel1.setupMolecule(mol); + } + + /** + * + * @param gjfFile String + */ + void parseNewFile(String gjfFile) { + gjfParser.removeAllEntries(); + int n = gjfParser.parseGJF(gjfFile, 0); + + if (n < 1) { + JOptionPane.showMessageDialog(null, + "No entries found in the input file", + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + fileComboBox.setEnabled(false); + fileComboBox.addItem(gjfFile); + fileComboBox.setSelectedIndex(fileComboBox.getItemCount() - 1); + fileComboBox.setEnabled(true); + + setupEditor(gjfParser); + + } + + public void setupEditor(GJFParserInterface parser) { + + if (parser == null || parser.getNumberOfSteps() < 1) { + JOptionPane.showMessageDialog(null, + "No entries found in the input file", + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + int n = parser.getNumberOfSteps(); + +// --- Clean up old stuff + + if (stepsComboBox.getItemCount() > 1) { + CardLayout cl = (CardLayout) cardPanel.getLayout(); + cl.show(cardPanel, "step0"); + for (int i = stepsComboBox.getItemCount() - 1; i > 0; i--) { + cardPanel.remove(i); + } + additionalEntries.clear(); + entryLabels.clear(); + } + +// --- Fill in a new contents + + java.util.List buffer = parser.getLinkZeroCommands(0); + simpleG03EditorPanel1.setLinkZeroCommands(buffer); + simpleG03EditorPanel1.setRouteSection(parser.getRouteSection(0)); + simpleG03EditorPanel1.setTitleSection(parser.getTitleSection(0)); + simpleG03EditorPanel1.setChargeSection(parser.getChargeSection(0)); + simpleG03EditorPanel1.setMoleculeSpecsSection(parser. + getMoleculeSpecsSection(0)); + + deleteEntryButton.setEnabled(true); + + stepsComboBox.setEnabled(false); + stepsComboBox.removeAllItems(); + setStep(stepsComboBox, 0 ); +//stepsComboBox.addItem(" 1"); + previousStepButton.setIcon(arrowUpFaded); + previousStepButton.setEnabled(false); + stepsComboBox.setEnabled(true); + + if (n == 1) { + nextStepButton.setIcon(arrowDownFaded); + nextStepButton.setEnabled(false); + return; + } + + nextStepButton.setEnabled(true); + nextStepButton.setIcon(arrowDown); + + stepsComboBox.setEnabled(false); + for (int i = 1; i < n; i++) { + SimpleG03EditorPanel sG03 = new SimpleG03EditorPanel(parser); + sG03.setFontForText(newFont); + buffer = parser.getLinkZeroCommands(i); + sG03.setLinkZeroCommands(buffer); + sG03.setRouteSection(parser.getRouteSection(i)); + sG03.setTitleSection(parser.getTitleSection(i)); + sG03.setChargeSection(parser.getChargeSection(i)); + sG03.setMoleculeSpecsSection(parser.getMoleculeSpecsSection(i)); + + cardPanel.add(sG03, "step" + String.valueOf(i)); + + setStep(stepsComboBox, i); + } + + setActiveStep(0); + + stepsComboBox.setEnabled(true); + numberOfEntries = n; + + } + + void setStep(JComboBox cb, int i) { + boolean store = cb.isEnabled(); + cb.setEnabled(false); + + String zeros = ""; + if (i + 1 < 10) { + zeros = " "; + } + else if (i + 1 < 100) { + zeros = " "; + } + else if (i + 1 < 1000) { + zeros = " "; + } + + if (i == 0) { + cb.addItem(zeros + String.valueOf( (i + 1))); + } + else { + cb.insertItemAt(zeros + String.valueOf( (i + 1)), i); + } + // + + cb.setEnabled(store); + } + + public void stepsComboBox_itemStateChanged(ItemEvent e) { + if (!stepsComboBox.isEnabled()) { + return; + } + + stepsComboBox.setEnabled(false); + setActiveStep(stepsComboBox.getSelectedIndex()); + stepsComboBox.setEnabled(true); + /* + String card = "step" + String.valueOf(stepsComboBox.getSelectedIndex()); + CardLayout cl = (CardLayout) cardPanel.getLayout(); + cl.show(cardPanel, card); + int items = stepsComboBox.getItemCount(); + int n = stepsComboBox.getSelectedIndex(); + + if (items == 1) { + previousStepButton.setIcon(arrowUpFaded); + previousStepButton.setEnabled(false); + nextStepButton.setIcon(arrowDownFaded); + nextStepButton.setEnabled(false); + } + // At the beginning + else if (n == 0) { + previousStepButton.setIcon(arrowUpFaded); + previousStepButton.setEnabled(false); + nextStepButton.setIcon(arrowDown); + nextStepButton.setEnabled(true); + } + + // At the end + else if (n == items - 1) { + previousStepButton.setIcon(arrowUp); + previousStepButton.setEnabled(true); + nextStepButton.setIcon(arrowDownFaded); + nextStepButton.setEnabled(false); + } + // In the middle + + else if (items > 1) { + previousStepButton.setIcon(arrowUp); + previousStepButton.setEnabled(true); + nextStepButton.setIcon(arrowDown); + nextStepButton.setEnabled(true); + } + */ + } + + public void previousStepButton_actionPerformed(ActionEvent e) { + if (!previousStepButton.isEnabled()) { + return; + } + + int n = stepsComboBox.getSelectedIndex(); + stepsComboBox.setSelectedIndex(n - 1); + } + + public void setActiveStep(int nstep) { + if (nstep < 0 || nstep >= stepsComboBox.getItemCount()) { + return; + } + + String card = "step" + String.valueOf(stepsComboBox.getSelectedIndex()); + CardLayout cl = (CardLayout) cardPanel.getLayout(); + cl.show(cardPanel, card); + int items = stepsComboBox.getItemCount(); + int n = stepsComboBox.getSelectedIndex(); + + if (items == 1) { + previousStepButton.setIcon(arrowUpFaded); + previousStepButton.setEnabled(false); + nextStepButton.setIcon(arrowDownFaded); + nextStepButton.setEnabled(false); + } + // At the beginning + else if (n == 0) { + previousStepButton.setIcon(arrowUpFaded); + previousStepButton.setEnabled(false); + nextStepButton.setIcon(arrowDown); + nextStepButton.setEnabled(true); + } + + // At the end + else if (n == items - 1) { + previousStepButton.setIcon(arrowUp); + previousStepButton.setEnabled(true); + nextStepButton.setIcon(arrowDownFaded); + nextStepButton.setEnabled(false); + } + // In the middle + + else if (items > 1) { + previousStepButton.setIcon(arrowUp); + previousStepButton.setEnabled(true); + nextStepButton.setIcon(arrowDown); + nextStepButton.setEnabled(true); + } + + stepsComboBox.setSelectedIndex(nstep); + } + + public void nextStepButton_actionPerformed(ActionEvent e) { + if (!nextStepButton.isEnabled()) { + return; + } + + int n = stepsComboBox.getSelectedIndex(); + stepsComboBox.setSelectedIndex(n + 1); + + } + + public void jMenuItem1_actionPerformed(ActionEvent e) { + openFileButton_actionPerformed(e); + } + + public void jButton6_actionPerformed(ActionEvent e) { + + int index = stepsComboBox.getSelectedIndex(); + SimpleG03EditorPanel ref = getSimpleEditor(index); + if (!ref.isEdited()) { + return; + } + + JOptionPane optionPane = new JOptionPane( + "Confirm deletion", + JOptionPane.QUESTION_MESSAGE, + JOptionPane.YES_NO_OPTION); + optionPane.setVisible(true); + int n = + JOptionPane.showConfirmDialog(null, + "Are you sure to delete this step?", + "Confirm Removal", + JOptionPane.YES_NO_OPTION); + if (n == JOptionPane.NO_OPTION || n == JOptionPane.CLOSED_OPTION) { + return; + } + + n = stepsComboBox.getItemCount(); + + if (n == 1 || index == 0) { + simpleG03EditorPanel1.resetPanel(); + return; + } + + removeEntry(index); + } + + void resetEntry(SimpleG03EditorPanel sG03) { + sG03.resetPanel(); + } + + void removeEntry(int step) { + stepsComboBox.setEnabled(false); + cardPanel.remove(step); + stepsComboBox.removeItemAt(step); + + for (int i = stepsComboBox.getItemCount() - 1; i >= step; i--) { + Component comp = cardPanel.getComponent(i); + cardPanel.remove(i); + stepsComboBox.removeItemAt(i); + cardPanel.add(comp, "step" + String.valueOf(i), i); + setStep(stepsComboBox, i); + } + + stepsComboBox.setEnabled(true); + + if (step >= stepsComboBox.getItemCount()) { + setActiveStep(step - 1); + } + else { + setActiveStep(step); + } + } + + public void insertEntryButton_actionPerformed(ActionEvent e) { + JOptionPane optionPane = new JOptionPane( + "Confirm copy of the previous step", + JOptionPane.QUESTION_MESSAGE, + JOptionPane.YES_NO_OPTION); + optionPane.setVisible(true); + int n = + JOptionPane.showConfirmDialog(null, + "Copy fields from the previous step?", + "Confirm Copy", + JOptionPane.YES_NO_OPTION); + if (n == JOptionPane.CLOSED_OPTION) { + return; + } + + SimpleG03EditorPanel sG03 = new SimpleG03EditorPanel(gjfParser); + sG03.setFontForText(newFont); + + int index = stepsComboBox.getSelectedIndex(); + + if (n == JOptionPane.YES_OPTION) { + SimpleG03EditorPanel ref = getSimpleEditor(index); + sG03.setLinkZeroCommands(ref.getLinkZeroCommands()); + sG03.setRouteSection(ref.getRouteSection()); + sG03.setTitleSection(ref.getTitleSection()); + sG03.setChargeSection(ref.getChargeSection()); + sG03.setMoleculeSpecsSection(ref.getMoleculeSpecsSection()); + } + + insertEntry(sG03, index); + } + + void insertEntry(SimpleG03EditorPanel sG03, int n) { + stepsComboBox.setEnabled(false); + + int nitems = stepsComboBox.getItemCount(); + + if (nitems == 1 || nitems - 1 == n) { + cardPanel.add(sG03, "step" + String.valueOf( (n + 1))); + } + else { + cardPanel.add(sG03, "step" + String.valueOf( (n + 1)), n + 1); + } + setStep(stepsComboBox, nitems); + + for (int i = n + 1; i < stepsComboBox.getItemCount(); i++) { + Component comp = cardPanel.getComponent(i); + cardPanel.remove(i); + stepsComboBox.removeItemAt(i); + cardPanel.add(comp, "step" + String.valueOf(i), i); + setStep(stepsComboBox, i); + } + + stepsComboBox.setEnabled(true); + + setActiveStep(n + 1); + + } + + SimpleG03EditorPanel getSimpleEditor(int n) { + SimpleG03EditorPanel reference = (SimpleG03EditorPanel) cardPanel. + getComponent(n); + return reference; + } + + public void saveFileButton_actionPerformed(ActionEvent e) { + int warning = 0; + //for (int i = 0; i < stepsComboBox.getItemCount(); i++) { + // SimpleG03EditorPanel ref = getSimpleEditor(i); + // if (ref.isEdited()) { + // warning++; + // } + //} + + if (warning > 0) { + JOptionPane optionPane = new JOptionPane( + "Confirm deletion", + JOptionPane.QUESTION_MESSAGE, + JOptionPane.YES_NO_OPTION); + optionPane.setVisible(true); + int n = + JOptionPane.showConfirmDialog(null, + String.valueOf(warning) + + " steps are empty. Save file while skipping empty steps?", + "Confirm Saving", + JOptionPane.YES_NO_OPTION); + if (n == JOptionPane.NO_OPTION || n == JOptionPane.CLOSED_OPTION) { + return; + } + } + + // --- Start saving, prepare a string + + // --- Select and save file + + saveFileAs(workingDirectory, fileName, getGJFAsString()); + + } + + public String toString() { + return getGJFAsString(); + } + + public String getGJFAsString() { + StringWriter sWriter = new StringWriter(); + + for (int i = 0; i < stepsComboBox.getItemCount(); i++) { + SimpleG03EditorPanel ref = getSimpleEditor(i); + if (i > 0) { + sWriter.write("--Link1--\n"); + } + sWriter.write(ref.getStepAsString()); + } + + String text = sWriter.toString(); + + try { + sWriter.close(); + } + catch (Exception ex) {} + + return text; + } + + void saveFileAs(String directory, String file_name, String text) { + + FileDialog fd = new FileDialog(new Frame(), "Save Gaussian Job File", + FileDialog.SAVE); + fd.setDirectory(directory); + fd.setFile(file_name); + fd.setVisible(true); + if (fd.getFile() == null) { + return; + } + + String newFileName = new String(fd.getFile()); + String newWorkingDirectory = new String(fd.getDirectory()); + + try { + IOUtils.saveStringIntoFile(text, newWorkingDirectory + newFileName); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + fileName = newFileName; + workingDirectory = newWorkingDirectory; + + } + + public void saveStepButton_actionPerformed(ActionEvent e) { + // --- Start saving, prepare a string + + StringWriter sWriter = new StringWriter(); + + int index = stepsComboBox.getSelectedIndex(); + SimpleG03EditorPanel ref = getSimpleEditor(index); + sWriter.write(ref.getStepAsString()); + + // --- Select and save file + + String stepFile = fileName.substring(0, fileName.lastIndexOf(".")); + stepFile += "-" + String.valueOf( (index + 1)) + ".gjf"; + + saveFileAs(workingDirectory, stepFile, sWriter.toString()); + + try { + sWriter.close(); + } + catch (Exception ex) {} + + } + + public void openSelectedFileButton_actionPerformed(ActionEvent e) { + if (fileComboBox.getItemCount() < 1) { + return; + } + String file_name = (String) fileComboBox.getSelectedItem(); + + if (file_name.equals(workingDirectory + fileName)) { + JOptionPane optionPane = new JOptionPane( + "Confirm deletion", + JOptionPane.QUESTION_MESSAGE, + JOptionPane.YES_NO_OPTION); + optionPane.setVisible(true); + int n = + JOptionPane.showConfirmDialog(null, + "Reload " + file_name, + "Confirm reloading file", + JOptionPane.YES_NO_OPTION); + if (n == JOptionPane.NO_OPTION || n == JOptionPane.CLOSED_OPTION) { + return; + } + } + + parseNewFile(file_name); + } + + public void resetButton_actionPerformed(ActionEvent e) { + + CardLayout cl = (CardLayout) cardPanel.getLayout(); + cl.show(cardPanel, "step0"); + + if (stepsComboBox.getItemCount() > 1) { + for (int i = stepsComboBox.getItemCount() - 1; i > 0; i--) { + cardPanel.remove(i); + } + additionalEntries.clear(); + entryLabels.clear(); + } + + simpleG03EditorPanel1.resetPanel(); + + deleteEntryButton.setEnabled(true); + + stepsComboBox.setEnabled(false); + stepsComboBox.removeAllItems(); + setStep(stepsComboBox, 0 ); + previousStepButton.setIcon(arrowUpFaded); + previousStepButton.setEnabled(false); + stepsComboBox.setEnabled(true); + + nextStepButton.setIcon(arrowDownFaded); + nextStepButton.setEnabled(false); + } + + public int getSelectedStep() { + return stepsComboBox.getSelectedIndex(); + } + + class GaussianInputEditorFrame_saveStepButton_actionAdapter + implements ActionListener { + private GaussianInputEditorFrame adaptee; + GaussianInputEditorFrame_saveStepButton_actionAdapter( + GaussianInputEditorFrame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.saveStepButton_actionPerformed(e); + } + } + + class GaussianInputEditorFrame_openSelectedFileButton_actionAdapter + implements ActionListener { + private GaussianInputEditorFrame adaptee; + GaussianInputEditorFrame_openSelectedFileButton_actionAdapter( + GaussianInputEditorFrame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.openSelectedFileButton_actionPerformed(e); + } + } + + class GaussianInputEditorFrame_saveFileButton_actionAdapter + implements ActionListener { + private GaussianInputEditorFrame adaptee; + GaussianInputEditorFrame_saveFileButton_actionAdapter( + GaussianInputEditorFrame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.saveFileButton_actionPerformed(e); + } + } + + class GaussianInputEditorFrame_resetButton_actionAdapter + implements ActionListener { + private GaussianInputEditorFrame adaptee; + GaussianInputEditorFrame_resetButton_actionAdapter( + GaussianInputEditorFrame + adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.resetButton_actionPerformed(e); + } + } + + class GaussianInputEditorFrame_insertEntryButton_actionAdapter + implements ActionListener { + private GaussianInputEditorFrame adaptee; + GaussianInputEditorFrame_insertEntryButton_actionAdapter( + GaussianInputEditorFrame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.insertEntryButton_actionPerformed(e); + } + } + + class GaussianInputEditorFrame_jButton6_actionAdapter + implements ActionListener { + private GaussianInputEditorFrame adaptee; + GaussianInputEditorFrame_jButton6_actionAdapter(GaussianInputEditorFrame + adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.jButton6_actionPerformed(e); + } + } + + class GaussianInputEditorFrame_jMenuItem1_actionAdapter + implements ActionListener { + private GaussianInputEditorFrame adaptee; + GaussianInputEditorFrame_jMenuItem1_actionAdapter( + GaussianInputEditorFrame + adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.jMenuItem1_actionPerformed(e); + } + } + + class GaussianInputEditorFrame_nextStepButton_actionAdapter + implements ActionListener { + private GaussianInputEditorFrame adaptee; + GaussianInputEditorFrame_nextStepButton_actionAdapter( + GaussianInputEditorFrame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.nextStepButton_actionPerformed(e); + } + } + + class GaussianInputEditorFrame_previousStepButton_actionAdapter + implements ActionListener { + private GaussianInputEditorFrame adaptee; + GaussianInputEditorFrame_previousStepButton_actionAdapter( + GaussianInputEditorFrame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.previousStepButton_actionPerformed(e); + } + } + + class GaussianInputEditorFrame_stepsComboBox_itemAdapter + implements ItemListener { + private GaussianInputEditorFrame adaptee; + GaussianInputEditorFrame_stepsComboBox_itemAdapter( + GaussianInputEditorFrame + adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.stepsComboBox_itemStateChanged(e); + } + } + + class GaussianInputEditorFrame_openFileButton_actionAdapter + implements ActionListener { + private GaussianInputEditorFrame adaptee; + GaussianInputEditorFrame_openFileButton_actionAdapter( + GaussianInputEditorFrame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.openFileButton_actionPerformed(e); + } + } + + class GaussianInputEditorFrame_jMenuFileExit_ActionAdapter + implements ActionListener { + GaussianInputEditorFrame adaptee; + + GaussianInputEditorFrame_jMenuFileExit_ActionAdapter( + GaussianInputEditorFrame + adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent actionEvent) { + adaptee.jMenuFileExit_actionPerformed(actionEvent); + } + } + + class GaussianInputEditorFrame_jMenuHelpAbout_ActionAdapter + implements ActionListener { + GaussianInputEditorFrame adaptee; + + GaussianInputEditorFrame_jMenuHelpAbout_ActionAdapter( + GaussianInputEditorFrame adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent actionEvent) { + adaptee.jMenuHelpAbout_actionPerformed(actionEvent); + } + } + + public void actionPerformed(ActionEvent actionEvent) { + if (actionEvent.getSource() == increaseMenuItem) { + + Font currentFont = this.simpleG03EditorPanel1.getFontForText(); + int size = currentFont.getSize() + 1; + newFont = new Font(currentFont.getName(), currentFont.getStyle(), + size); + simpleG03EditorPanel1.setFontForText(newFont); + saveFontPreferences(); + } + else if (actionEvent.getSource() == decreaseMenuItem) { + Font currentFont = simpleG03EditorPanel1.getFontForText(); + int size = currentFont.getSize(); + size = size > 8 ? size - 1 : size; + newFont = new Font(currentFont.getName(), currentFont.getStyle(), + size); + simpleG03EditorPanel1.setFontForText(newFont); + saveFontPreferences(); + } + else if (actionEvent.getSource() == jMenuItem4) { + if (fontSelector == null) { + fontSelector = new FontSelectorDialog(this, "Select Font", true); + } + fontSelector.setVisible(true); + if (!fontSelector.isOKPressed()) { + return; + } + newFont = new Font(fontSelector.getFontName(), + fontSelector.getFontStyle(), + fontSelector.getFontSize()); + simpleG03EditorPanel1.setFontForText(newFont); + saveFontPreferences(); + } + } + + private void saveFontPreferences() { + Font currentFont = simpleG03EditorPanel1.getFontForText(); + try { + prefs.put(FontNameKey, currentFont.getFontName()); + prefs.putInt(FontSizeKey, currentFont.getSize()); + prefs.putInt(FontStyleKey, currentFont.getStyle()); + prefs.flush(); + } + catch (Exception ex) { + System.err.println("Error saving Font Preferences: " + + ex.getMessage()); + } + } + +} diff --git a/src/main/java/cct/gaussian/ui/GaussianInputEditorFrame_AboutBox.java b/src/main/java/cct/gaussian/ui/GaussianInputEditorFrame_AboutBox.java new file mode 100644 index 0000000..f5cccbe --- /dev/null +++ b/src/main/java/cct/gaussian/ui/GaussianInputEditorFrame_AboutBox.java @@ -0,0 +1,157 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian.ui; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; + +/** + *

Title: Gasussian Utility Classes

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class GaussianInputEditorFrame_AboutBox + extends JDialog implements ActionListener { + JPanel panel1 = new JPanel(); + JPanel panel2 = new JPanel(); + JPanel insetsPanel1 = new JPanel(); + JPanel insetsPanel2 = new JPanel(); + JPanel insetsPanel3 = new JPanel(); + JButton button1 = new JButton(); + JLabel imageLabel = new JLabel(); + JLabel label1 = new JLabel(); + JLabel label2 = new JLabel(); + JLabel label3 = new JLabel(); + JLabel label4 = new JLabel(); + ImageIcon image1 = new ImageIcon(); + BorderLayout borderLayout1 = new BorderLayout(); + BorderLayout borderLayout2 = new BorderLayout(); + FlowLayout flowLayout1 = new FlowLayout(); + GridLayout gridLayout1 = new GridLayout(); + String product = "Simple Gaussian Editor"; + String version = "Version 0.1"; + String copyright = "Copyright (c) 2007 ANU"; + String comments = "Computational Chemistry Toolkit"; + JLabel jLabel1 = new JLabel(); + + public GaussianInputEditorFrame_AboutBox(Frame parent) { + super(parent); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public GaussianInputEditorFrame_AboutBox() { + this(null); + } + + /** + * Component initialization. + * + * @throws Exception + */ + private void jbInit() throws Exception { + image1 = new ImageIcon(GaussianInputEditorFrame.class. + getResource("gaussian-1-64x64.png")); + imageLabel.setIcon(image1); + setTitle("About"); + panel1.setLayout(borderLayout1); + panel2.setLayout(borderLayout2); + insetsPanel1.setLayout(flowLayout1); + insetsPanel2.setLayout(flowLayout1); + insetsPanel2.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + gridLayout1.setRows(5); + gridLayout1.setColumns(1); + label1.setText(product); + label2.setText(version); + label3.setText(copyright); + label4.setText(comments); + insetsPanel3.setLayout(gridLayout1); + insetsPanel3.setBorder(BorderFactory.createEmptyBorder(10, 60, 10, 10)); + button1.setText("OK"); + button1.addActionListener(this); + jLabel1.setText("Dr. V. Vasilyev, vvv900@gmail.com"); + insetsPanel2.add(imageLabel, null); + panel2.add(insetsPanel2, BorderLayout.WEST); + getContentPane().add(panel1, null); + insetsPanel3.add(label1, null); + insetsPanel3.add(label2, null); + insetsPanel3.add(label3, null); + insetsPanel3.add(label4, null); + insetsPanel3.add(jLabel1); + panel2.add(insetsPanel3, BorderLayout.CENTER); + insetsPanel1.add(button1, null); + panel1.add(insetsPanel1, BorderLayout.SOUTH); + panel1.add(panel2, BorderLayout.NORTH); + setResizable(true); + } + + /** + * Close the dialog on a button event. + * + * @param actionEvent ActionEvent + */ + @Override + public void actionPerformed(ActionEvent actionEvent) { + if (actionEvent.getSource() == button1) { + dispose(); + } + } +} diff --git a/src/main/java/cct/gaussian/ui/GaussianInputEditorImpl.java b/src/main/java/cct/gaussian/ui/GaussianInputEditorImpl.java new file mode 100644 index 0000000..3e62509 --- /dev/null +++ b/src/main/java/cct/gaussian/ui/GaussianInputEditorImpl.java @@ -0,0 +1,117 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian.ui; + +import java.awt.Dimension; +import java.awt.Toolkit; + +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +import cct.gaussian.Gaussian; +import cct.j3d.SimpleRenderer; + +/** + *

Title: Gasussian Utility Classes

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class GaussianInputEditorImpl { + boolean packFrame = false; + + /** + * Construct and show the application. + */ + public GaussianInputEditorImpl() { + Gaussian g = new Gaussian(); + SimpleRenderer r = new SimpleRenderer(); + g.setGraphicsRenderer(r); + GaussianInputEditorFrame frame = new GaussianInputEditorFrame(g); + // Validate frames that have preset sizes + // Pack frames that have useful preferred size info, e.g. from their layout + if (packFrame) { + frame.pack(); + } + else { + frame.validate(); + } + + // Center the window + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension frameSize = frame.getSize(); + if (frameSize.height > screenSize.height) { + frameSize.height = screenSize.height; + } + if (frameSize.width > screenSize.width) { + frameSize.width = screenSize.width; + } + frame.setLocation( (screenSize.width - frameSize.width) / 2, + (screenSize.height - frameSize.height) / 2); + frame.setVisible(true); + } + + /** + * Application entry point. + * + * @param args String[] + */ + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } + catch (Exception exception) { + exception.printStackTrace(); + } + + //logger.info(cct.gaussian.ui.GaussianInputEditorFrame.class. + // getResource("about.png")); + new GaussianInputEditorImpl(); + } + }); + } +} diff --git a/src/main/java/cct/gaussian/ui/Link0Panel.java b/src/main/java/cct/gaussian/ui/Link0Panel.java new file mode 100644 index 0000000..26fa16f --- /dev/null +++ b/src/main/java/cct/gaussian/ui/Link0Panel.java @@ -0,0 +1,136 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian.ui; + +import java.awt.Font; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +import javax.swing.JScrollPane; +import javax.swing.JTextArea; + +/** + *

Title: Gasussian Utility Classes

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Link0Panel + extends JScrollPane { + + JTextArea jTextArea1 = new JTextArea(); + boolean newInput = true; + + public Link0Panel() { + try { + jbInit(); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + + private void jbInit() throws Exception { + jTextArea1.setToolTipText(""); + jTextArea1.setText("Link 0 Commands are Here"); + jTextArea1.setRows(2); + jTextArea1.addMouseListener(new Link0Panel_jTextArea1_mouseAdapter(this)); + this.getViewport().add(jTextArea1); + } + + public void setFontForText(Font newFont) { + jTextArea1.setFont(newFont); + } + + public Font getFontForText() { + return jTextArea1.getFont(); + } + + public void setText(String text) { + jTextArea1.setEnabled(false); + newInput = false; + jTextArea1.setText(text); + jTextArea1.setCaretPosition(0); + jTextArea1.setEnabled(true); + } + + public String getText() { + String lines[] = jTextArea1.getText().split("\n"); + String text = ""; + for (int i = 0; i < lines.length; i++) { + String trimmed = lines[i].trim(); + if (trimmed.length() != 0) { + text += trimmed + "\n"; + } + } + return text; + } + + public void resetPanel() { + jTextArea1.setEnabled(false); + newInput = true; + jTextArea1.setText("Link 0 Commands are Here"); + jTextArea1.setEnabled(true); + } + + public void jTextArea1_mouseClicked(MouseEvent e) { + if (newInput) { + newInput = false; + jTextArea1.setText(""); + } + } +} + +class Link0Panel_jTextArea1_mouseAdapter + extends MouseAdapter { + private Link0Panel adaptee; + Link0Panel_jTextArea1_mouseAdapter(Link0Panel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void mouseClicked(MouseEvent e) { + adaptee.jTextArea1_mouseClicked(e); + } +} diff --git a/src/main/java/cct/gaussian/ui/ManageCubesFrame.java b/src/main/java/cct/gaussian/ui/ManageCubesFrame.java new file mode 100644 index 0000000..7fbbb38 --- /dev/null +++ b/src/main/java/cct/gaussian/ui/ManageCubesFrame.java @@ -0,0 +1,749 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian.ui; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.Insets; +import java.awt.SystemColor; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.text.NumberFormat; +import java.util.ArrayList; +import java.util.logging.Logger; + +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JFormattedTextField; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.border.TitledBorder; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; + +import cct.chart.ChartFrame; +import cct.dialogs.JamberooCore; +import cct.gaussian.GaussianCube; +import cct.gaussian.java3d.GaussianJava3dFactory; +import cct.interfaces.AtomInterface; +import cct.interfaces.GraphicsObjectInterface; +import cct.interfaces.MoleculeInterface; +import cct.j3d.ColorRangeScheme; +import cct.j3d.Java3dUniverse; +import cct.j3d.ui.VertexObjectsDialog; +import cct.math.VolumeData; +import cct.modelling.CCTAtomTypes; +import cct.modelling.Molecule; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class ManageCubesFrame + extends JFrame { + private BorderLayout borderLayout1 = new BorderLayout(); + private JPanel jPanel1 = new JPanel(); + private JPanel jPanel2 = new JPanel(); + private JList cubeList = new JList(); + private BorderLayout borderLayout2 = new BorderLayout(); + private JPanel jPanel3 = new JPanel(); + private FlowLayout flowLayout1 = new FlowLayout(); + private JPanel jPanel4 = new JPanel(); + private BorderLayout borderLayout3 = new BorderLayout(); + private JButton hideButton = new JButton(); + private JPanel jPanel5 = new JPanel(); + private JButton loadButton = new JButton(); + private JButton deleteButton = new JButton(); + private JButton saveButton = new JButton(); + private JButton isosurfaceButton = new JButton(); + + //private GraphicsObjectPropertiesFrame graphicsObjectPropertiesFrame = null; + private JamberooCore jamberooCore = null; + private java.util.List Cubes; + private java.util.List info; + private Java3dUniverse java3dUniverse = null; + private JLabel jLabel3 = new JLabel(); + private float isovalue = 0.02f; + private NumberFormat isovalueFormat; + private JFormattedTextField isovalueFormattedTextField = new JFormattedTextField(isovalueFormat); + private JCheckBox useReverseCheckBox = new JCheckBox(); + private JScrollPane jScrollPane1 = new JScrollPane(); + private JButton helpButton = new JButton(); + private JButton mappedSurfaceButton = new JButton(); + private JPanel surfaceButtonsPanel = new JPanel(); + private JButton histogramButton = new JButton(); + private int nBins = 5000; + private ImageIcon histogramImage = new ImageIcon(cct.resources.Resources.class.getResource("cct/images/icons16x16/line-chart.png")); + static final Logger logger = Logger.getLogger(ManageCubesFrame.class.getCanonicalName()); + + public ManageCubesFrame(String title, java.util.List cubes) { + super(title); + Cubes = cubes; + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + getContentPane().setLayout(borderLayout1); + jPanel1.setLayout(borderLayout2); + jPanel3.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + jPanel2.setLayout(borderLayout3); + hideButton.setToolTipText("Hide Dialog"); + hideButton.setText("Hide"); + hideButton.addActionListener(new ManageCubesFrame_hideButton_actionAdapter(this)); + loadButton.setToolTipText("Load Gaussian Cube file"); + loadButton.setText("Load Cube"); + loadButton.addActionListener(new ManageCubesFrame_loadButton_actionAdapter(this)); + deleteButton.setToolTipText("Delete Gaussian Cube file from the list"); + deleteButton.setText("Delete Cube"); + deleteButton.addActionListener(new ManageCubesFrame_deleteButton_actionAdapter(this)); + saveButton.setToolTipText("Save Gaussian Cube to file"); + saveButton.setText("Save Cube"); + saveButton.addActionListener(new ManageCubesFrame_saveButton_actionAdapter(this)); + isosurfaceButton.setToolTipText("Create Isosurface for selected Cube"); + isosurfaceButton.setText("Create Isosurface"); + isosurfaceButton.addActionListener(new + ManageCubesFrame_isosurfaceButton_actionAdapter(this)); + jPanel1.setBorder(new TitledBorder(BorderFactory.createLineBorder(SystemColor.controlShadow, 1), + "Gaussian Cubes Description")); + jLabel3.setToolTipText(""); + jLabel3.setText("Isovalue: "); + isovalueFormattedTextField.setToolTipText("Value for building isosurface"); + isovalueFormattedTextField.setMargin(new Insets(1, 5, 2, 10)); + isovalueFormattedTextField.setText("0.025"); + useReverseCheckBox.setToolTipText("Whether to build isosurface for -isovalue as well"); + useReverseCheckBox.setSelected(true); + useReverseCheckBox.setText("Use Opposite Value as well"); + cubeList.addListSelectionListener(new ManageCubesFrame_cubeList_listSelectionAdapter(this)); + helpButton.setEnabled(false); + helpButton.setToolTipText("Get Help"); + helpButton.setText("Help"); + mappedSurfaceButton.setToolTipText("Map the values on the Surface(s)"); + mappedSurfaceButton.setText("Mapped Surface"); + mappedSurfaceButton.addActionListener(new ManageCubesFrame_mappedSurfaceButton_actionAdapter(this)); + histogramButton.setToolTipText("Plot Cube Values Distribution"); + histogramButton.setText("Histogram"); + histogramButton.addActionListener(new ManageCubesFrame_histogramButton_actionAdapter(this)); + this.getContentPane().add(jPanel1, BorderLayout.CENTER); + this.getContentPane().add(jPanel2, BorderLayout.SOUTH); + jPanel1.add(jPanel3, BorderLayout.SOUTH); + jPanel3.add(jLabel3); + jPanel3.add(isovalueFormattedTextField); + jPanel3.add(useReverseCheckBox); + jPanel1.add(jScrollPane1, BorderLayout.NORTH); + jScrollPane1.getViewport().add(cubeList); + jPanel4.add(hideButton); + jPanel4.add(helpButton); + jPanel5.add(loadButton); + jPanel5.add(deleteButton); + jPanel5.add(saveButton); + jPanel2.add(jPanel4, BorderLayout.SOUTH); + jPanel2.add(surfaceButtonsPanel, BorderLayout.CENTER); + surfaceButtonsPanel.add(isosurfaceButton); + surfaceButtonsPanel.add(mappedSurfaceButton); + surfaceButtonsPanel.add(histogramButton); + jPanel2.add(jPanel5, BorderLayout.NORTH); + if (Cubes != null && Cubes.size() > 0) { + _setCubeList(Cubes); + } + + cubeList.setVisibleRowCount(10); + + isovalueFormattedTextField.setValue(new Float(isovalue)); + isovalueFormattedTextField.setColumns(10); + } + + public void setCubeList(java.util.List elements) { + Cubes = elements; + _setCubeList(elements); + } + + private void _setCubeList(java.util.List elements) { + cubeList.removeAll(); + if (elements == null || elements.size() < 1) { + cubeList.setListData(new Object[0]); + return; + } + + info = null; + info = new ArrayList(); + int count = 0; + for (int i = 0; i < elements.size(); i++) { + GaussianCube cube = (GaussianCube) elements.get(i); + count += cube.countCubes(); + } + + String el[] = new String[count]; + + count = 0; + for (int i = 0; i < elements.size(); i++) { + GaussianCube cube = (GaussianCube) elements.get(i); + String name = cube.getCubeDescription(); + for (int j = 0; j < cube.countCubes(); j++, count++) { + String cubeLabel = cube.getCubeLabel(j); + if (cubeLabel == null) { + el[count] = name + " " + (j + 1); + } + else { + el[count] = name + " " + cubeLabel; + } + int ref[] = new int[2]; + ref[0] = i; + ref[1] = j; + info.add(ref); + } + } + + //Arrays.sort(el); + cubeList.setListData(el); + //Monomers.updateUI(); + this.pack(); + } + + public static void main(String[] args) { + ManageCubesFrame managecubesframe = new ManageCubesFrame( + "Manage Gaussian cubes", null); + } + + public void hideButton_actionPerformed(ActionEvent e) { + this.setVisible(false); + } + + public void isosurfaceButton_actionPerformed(ActionEvent e) { + if (!isosurfaceButton.isEnabled()) { + return; + } + + if (cubeList.getModel().getSize() < 1) { + JOptionPane.showMessageDialog(this, "Load Gaussian Cube file first", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + if (java3dUniverse == null) { + JOptionPane.showMessageDialog(this, "INTERNAL ERROR: Java3dUniverse is not set", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + isosurfaceButton.setEnabled(false); + validate(); + + int cubes[] = cubeList.getSelectedIndices(); + + if (cubes == null || cubes.length < 1) { + if (info.size() > 1) { + JOptionPane.showMessageDialog(this, "Select cube(s) first!", "Warning", JOptionPane.WARNING_MESSAGE); + isosurfaceButton.setEnabled(true); + return; + } + + cubes = new int[1]; + cubes[0] = 0; + } + + isovalue = ( (Number) isovalueFormattedTextField.getValue()).floatValue(); + + for (int i = 0; i < cubes.length; i++) { + int ref[] = (int[]) info.get(cubes[i]); + GaussianCube cube = (GaussianCube) Cubes.get(ref[0]); + + if (isovalue < 0 && cube.isPositiveValuesOnly()) { + JOptionPane.showMessageDialog(this, "Values from cube \"" + cube.getCubeDescription() + "\" can be only positive", + "Warning", JOptionPane.WARNING_MESSAGE); + + continue; + } + + //GaussianJava3dFactory.getSurface(cube,ref[1],0.02f); + GraphicsObjectInterface graphics = GaussianJava3dFactory.getGraphicsObject(cube, ref[1], isovalue, + useReverseCheckBox.isSelected()); + String cubeLabel = cube.getCubeLabel(ref[1]); + if (cubeLabel == null || cubeLabel.length() < 1) { + graphics.setName(cube.getCubeDescription()); + } + else { + graphics.setName(cube.getCubeDescription() + " " + cubeLabel); + } + java3dUniverse.addGraphics(graphics); + + //if (graphicsObjectPropertiesFrame != null) { + // graphicsObjectPropertiesFrame.updateTree(); + //} + jamberooCore.updateGraphicsObjectsDialog(); + + } + + isosurfaceButton.setEnabled(true); + } + + public void loadButton_actionPerformed(ActionEvent e) { + + if (java3dUniverse == null) { + JOptionPane.showMessageDialog(this, "Internal Error: java3dUniverse is not set", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + if (Cubes == null) { + JOptionPane.showMessageDialog(this, "Internal Error: Cubes is not set", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + GaussianCube gCube = new GaussianCube(); + try { + MoleculeInterface mol = new Molecule(); + gCube.parseGaussianCube(); + gCube.getMolecule(mol); + Molecule.guessCovalentBonds(mol); + Molecule.guessAtomTypes(mol, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + java3dUniverse.addMolecule(mol); + Cubes.add(gCube); + + JOptionPane.showMessageDialog(this, gCube.getTitle() + "\n" + gCube.getCubeDescription() + "\n" + "Number of atoms: " + + mol.getNumberOfAtoms() + "\n" + "Number of cubes: " + gCube.countCubes() + , "Gaussian cube info", JOptionPane.INFORMATION_MESSAGE); + this._setCubeList(Cubes); + } + catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(this, "Error Loading Gaussian Cube file : " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + } + + public void cubeList_valueChanged(ListSelectionEvent e) { + if (e.getValueIsAdjusting()) { + return; + } + + int cubes[] = cubeList.getSelectedIndices(); + if (cubes == null || cubes.length < 1) { + return; + } + boolean positiveOnly = true; + float isovalue = 0; + for (int i = 0; i < cubes.length; i++) { + int ref[] = (int[]) info.get(cubes[i]); + GaussianCube cube = (GaussianCube) Cubes.get(ref[0]); + positiveOnly &= cube.isPositiveValuesOnly(); + if (i == 0) { + isovalue = cube.getDefaultIsovalue(); + } + else if (isovalue > cube.getDefaultIsovalue()) { + isovalue = cube.getDefaultIsovalue(); + } + } + + this.isovalueFormattedTextField.setValue(new Float(isovalue)); + + useReverseCheckBox.setSelected(!positiveOnly); + } + + public void deleteButton_actionPerformed(ActionEvent e) { + if (!deleteButton.isEnabled()) { + return; + } + + int cubes[] = cubeList.getSelectedIndices(); + if (cubes == null || cubes.length < 1) { + JOptionPane.showMessageDialog(this, "Select cube(s) first", "Warning", JOptionPane.WARNING_MESSAGE); + return; + } + + deleteButton.setEnabled(false); + + for (int i = cubes.length - 1; i > -1; i--) { + int ref[] = (int[]) info.get(cubes[i]); + GaussianCube cube = (GaussianCube) Cubes.get(ref[0]); + + if (cube.countCubes() == 1) { + Cubes.remove(ref[0]); + continue; + } + + cube.removeVolumetricData(ref[1]); + } + + _setCubeList(Cubes); + deleteButton.setEnabled(true); + } + + public void saveButton_actionPerformed(ActionEvent e) { + if (!saveButton.isEnabled()) { + return; + } + + int cubes[] = cubeList.getSelectedIndices(); + if (cubes == null || cubes.length < 1) { + JOptionPane.showMessageDialog(this, "Select a cube first", "Warning", JOptionPane.WARNING_MESSAGE); + return; + } + + if (cubes.length > 1) { + JOptionPane.showMessageDialog(this, "Select only one cube for saving", "Warning", JOptionPane.WARNING_MESSAGE); + return; + } + + int ref[] = (int[]) info.get(cubes[0]); + VolumeData cube = (VolumeData) Cubes.get(ref[0]); + + try { + if (cube instanceof GaussianCube) { + cube.saveVolumeData(ref[1]); + } + else { + cube.saveVolumeData(ref[1]); + } + //cube.saveGaussianCube(ref[1]); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Error saving Gaussian cube: " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + } + + saveButton.setEnabled(false); + saveButton.setEnabled(true); + } + + public JButton getHelpButton() { + return helpButton; + } + + public void mappedSurfaceButton_actionPerformed(ActionEvent e) { + + if (cubeList.getModel().getSize() < 1) { + JOptionPane.showMessageDialog(this, "Load Gaussian Cube file first", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + if (java3dUniverse == null) { + JOptionPane.showMessageDialog(this, "INTERNAL ERROR: Java3dUniverse is not set", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + int cubes[] = cubeList.getSelectedIndices(); + + if (cubes == null || cubes.length < 1) { + JOptionPane.showMessageDialog(this, "Select a cube first!", "Warning", JOptionPane.WARNING_MESSAGE); + return; + } + else if (cubes.length != 1) { + JOptionPane.showMessageDialog(this, "Only one cube should be selected for mapped surface", "Warning", + JOptionPane.WARNING_MESSAGE); + return; + } + + java.util.List graphicsObjects = java3dUniverse.getGraphicsObjects(); + if (graphicsObjects == null || graphicsObjects.size() < 1) { + JOptionPane.showMessageDialog(this, "No Surface(s) to map the values", "Warning", JOptionPane.WARNING_MESSAGE); + return; + } + VertexObjectsDialog vod = new VertexObjectsDialog(this, "Select Surfaces", true); + vod.setTree(graphicsObjects); + + vod.setLocationRelativeTo(this); + + vod.setVisible(true); + + if (!vod.isOKPressed()) { + return; + } + + java.util.List shape3ds = vod.getSelectedGraphicsObjects(); + + if (shape3ds == null || shape3ds.size() < 1) { + JOptionPane.showMessageDialog(this, "Select surfaces first", "Warning", JOptionPane.WARNING_MESSAGE); + return; + } + + int ref[] = (int[]) info.get(cubes[0]); + GaussianCube cube = (GaussianCube) Cubes.get(ref[0]); + + float Min = 0, Max = 0; + for (int i = 0; i < shape3ds.size(); ) { + Object object = shape3ds.get(i); + // --- Could be GraphicsObjectInterface or BranchGroup + if (object instanceof GraphicsObjectInterface) { + GraphicsObjectInterface graphics = (GraphicsObjectInterface) object; + float[] minMax = GaussianJava3dFactory.calcPropertyOnSurface(graphics, cube, ref[1]); + //GaussianJava3dFactory.mapSurface(graphics, cube, ref[1]); + if (i == 0) { + Min = minMax[0]; + Max = minMax[1]; + } + else { + if (Min > minMax[0]) { + Min = minMax[0]; + } + if (Max < minMax[1]) { + Max = minMax[1]; + } + } + } + else if (object != null) { + float[] minMax = GaussianJava3dFactory.calcPropertyOnSurface(object, cube, ref[1]); + //GaussianJava3dFactory.mapSurface(graphics, cube, ref[1]); + if (i == 0) { + Min = minMax[0]; + Max = minMax[1]; + } + else { + if (Min > minMax[0]) { + Min = minMax[0]; + } + if (Max < minMax[1]) { + Max = minMax[1]; + } + } + + } + i++; + } + + logger.info("Min value on surface: " + Min + " max: " + Max); + ColorRangeScheme crs = new ColorRangeScheme(Min, Max); + logger.info("Adjusted Min&Max values on surface : " + crs.getClipMin() + " - " + crs.getClipMax()); + + for (int i = 0; i < shape3ds.size(); ) { + Object object = shape3ds.get(i); + // --- Could be GraphicsObjectInterface or BranchGroup + if (object instanceof GraphicsObjectInterface) { + GraphicsObjectInterface graphics = (GraphicsObjectInterface) object; + GaussianJava3dFactory.mapSurface(graphics, crs); + //GaussianJava3dFactory.mapSurface(graphics, cube, ref[1]); + } + else if (object != null) { + + } + i++; + } + + } + + + public JamberooCore getJamberooCore() { + return jamberooCore; + } + + public void setJamberooCore(JamberooCore jamberooCore) { + this.jamberooCore = jamberooCore; + this.java3dUniverse = this.jamberooCore.getJamberooRenderer(); + } + + + public void histogramButton_actionPerformed(ActionEvent e) { + if (cubeList.getModel().getSize() < 1) { + JOptionPane.showMessageDialog(this, "Load Gaussian Cube file first", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + int cubes[] = cubeList.getSelectedIndices(); + + if (cubes == null || cubes.length < 1) { + if (info.size() > 1) { + JOptionPane.showMessageDialog(this, "Select cube(s) first!", "Warning", JOptionPane.WARNING_MESSAGE); + isosurfaceButton.setEnabled(true); + return; + } + + cubes = new int[1]; + cubes[0] = 0; + } + + for (int i = 0; i < cubes.length; i++) { + int ref[] = (int[]) info.get(cubes[i]); + VolumeData cube = (VolumeData) Cubes.get(ref[0]); + + double[] x = new double[nBins]; + double[] y = new double[nBins]; + + ChartFrame chart = null; + try { + cube.getNormalizedHistogram(x, y, nBins, ref[0]); + chart = new ChartFrame(); + chart.addDataSeries(x, y, "Values frequency"); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Cannot create chart: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return; + } + chart.setIconImage(histogramImage.getImage()); + chart.setChartTitle("Function Value Frequencies"); + chart.setXAxisTitle("Function Value"); + chart.enableAnimationPanel(false); + + String cubeLabel = cube.getCubeLabel(ref[1]); + if (cubeLabel == null || cubeLabel.length() < 1) { + chart.setTitle("Function Value Histogram: " + cube.getCubeDescription()); + } + else { + chart.setTitle("Function Value Histogram: " + cube.getCubeDescription() + " " + cubeLabel); + } + + chart.validate(); + chart.setLocationRelativeTo(this); + chart.showChart(true); + } + + } + + private class ManageCubesFrame_isosurfaceButton_actionAdapter + implements ActionListener { + private ManageCubesFrame adaptee; + ManageCubesFrame_isosurfaceButton_actionAdapter(ManageCubesFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.isosurfaceButton_actionPerformed(e); + } + } + + private class ManageCubesFrame_hideButton_actionAdapter + implements ActionListener { + private ManageCubesFrame adaptee; + ManageCubesFrame_hideButton_actionAdapter(ManageCubesFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.hideButton_actionPerformed(e); + } + } + + private class ManageCubesFrame_saveButton_actionAdapter + implements ActionListener { + private ManageCubesFrame adaptee; + ManageCubesFrame_saveButton_actionAdapter(ManageCubesFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.saveButton_actionPerformed(e); + } + } + + private class ManageCubesFrame_deleteButton_actionAdapter + implements ActionListener { + private ManageCubesFrame adaptee; + ManageCubesFrame_deleteButton_actionAdapter(ManageCubesFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.deleteButton_actionPerformed(e); + } + } + + private class ManageCubesFrame_cubeList_listSelectionAdapter + implements ListSelectionListener { + private ManageCubesFrame adaptee; + ManageCubesFrame_cubeList_listSelectionAdapter(ManageCubesFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void valueChanged(ListSelectionEvent e) { + adaptee.cubeList_valueChanged(e); + } + } + + private class ManageCubesFrame_loadButton_actionAdapter + implements ActionListener { + private ManageCubesFrame adaptee; + ManageCubesFrame_loadButton_actionAdapter(ManageCubesFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.loadButton_actionPerformed(e); + } + } + +} + +class ManageCubesFrame_histogramButton_actionAdapter + implements ActionListener { + private ManageCubesFrame adaptee; + ManageCubesFrame_histogramButton_actionAdapter(ManageCubesFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.histogramButton_actionPerformed(e); + } +} + +class ManageCubesFrame_mappedSurfaceButton_actionAdapter + implements ActionListener { + private ManageCubesFrame adaptee; + ManageCubesFrame_mappedSurfaceButton_actionAdapter(ManageCubesFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.mappedSurfaceButton_actionPerformed(e); + } +} diff --git a/src/main/java/cct/gaussian/ui/MoleculeSpecsPanel.java b/src/main/java/cct/gaussian/ui/MoleculeSpecsPanel.java new file mode 100644 index 0000000..ceef4ac --- /dev/null +++ b/src/main/java/cct/gaussian/ui/MoleculeSpecsPanel.java @@ -0,0 +1,133 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian.ui; + +import java.awt.Font; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +import javax.swing.JScrollPane; +import javax.swing.JTextArea; + +/** + *

Title: Gasussian Utility Classes

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class MoleculeSpecsPanel + extends JScrollPane { + + boolean newInput = true; + JTextArea jTextArea1 = new JTextArea(); + + public MoleculeSpecsPanel() { + try { + jbInit(); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + + private void jbInit() throws Exception { + jTextArea1.setToolTipText(""); + jTextArea1.setText("Molecule Specifications are here"); + jTextArea1.setColumns(60); + jTextArea1.setRows(10); + jTextArea1.addMouseListener(new + MoleculeSpecsPanel_jTextArea1_mouseAdapter(this)); + this.getViewport().add(jTextArea1); + } + + public void setFontForText(Font newFont) { + jTextArea1.setFont(newFont); + } + + public Font getFontForText() { + return jTextArea1.getFont(); + } + + public void setText(String text) { + newInput = false; + jTextArea1.setText(text); + jTextArea1.setCaretPosition(0); + } + + public void startEditing() { + if (newInput) { + newInput = false; + jTextArea1.setText(""); + } + } + + public void jTextArea1_mouseClicked(MouseEvent e) { + startEditing(); + } + + public void resetPanel() { + jTextArea1.setEnabled(false); + newInput = true; + jTextArea1.setText("Molecule Specifications are here"); + jTextArea1.setEnabled(true); + } + + public String getText() { + return jTextArea1.getText(); + } + +} + +class MoleculeSpecsPanel_jTextArea1_mouseAdapter + extends MouseAdapter { + private MoleculeSpecsPanel adaptee; + MoleculeSpecsPanel_jTextArea1_mouseAdapter(MoleculeSpecsPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void mouseClicked(MouseEvent e) { + adaptee.jTextArea1_mouseClicked(e); + } +} diff --git a/src/main/java/cct/gaussian/ui/RouteSectionPanel.java b/src/main/java/cct/gaussian/ui/RouteSectionPanel.java new file mode 100644 index 0000000..86251ab --- /dev/null +++ b/src/main/java/cct/gaussian/ui/RouteSectionPanel.java @@ -0,0 +1,134 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian.ui; + +import java.awt.Font; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +import javax.swing.JScrollPane; +import javax.swing.JTextArea; + +/** + *

Title: Gasussian Utility Classes

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class RouteSectionPanel + extends JScrollPane { + + boolean newInput = true; + JTextArea jTextArea1 = new JTextArea(); + + public RouteSectionPanel() { + try { + jbInit(); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + + private void jbInit() throws Exception { + jTextArea1.setToolTipText(""); + jTextArea1.setText("Route Section Options are Here"); + jTextArea1.setRows(2); + jTextArea1.addMouseListener(new RouteSectionPanel_jTextArea1_mouseAdapter(this)); + this.getViewport().add(jTextArea1); + } + + public void setFontForText(Font newFont) { + jTextArea1.setFont(newFont); + } + + public Font getFontForText() { + return jTextArea1.getFont(); + } + + public void setText(String text) { + newInput = false; + jTextArea1.setText(text); + } + + public String getText() { + String lines[] = jTextArea1.getText().split("\n"); + String text = ""; + for (int i = 0; i < lines.length; i++) { + String trimmed = lines[i].trim(); + if (trimmed.length() != 0) { + text += trimmed + "\n"; + } + } + return text; + } + + public void jTextArea1_mouseClicked(MouseEvent e) { + if (newInput) { + newInput = false; + jTextArea1.setText("# "); + } + } + + public void resetPanel() { + jTextArea1.setEnabled(false); + newInput = true; + jTextArea1.setText("Route Section Options are Here"); + jTextArea1.setEnabled(true); + } + +} + +class RouteSectionPanel_jTextArea1_mouseAdapter + extends MouseAdapter { + private RouteSectionPanel adaptee; + RouteSectionPanel_jTextArea1_mouseAdapter(RouteSectionPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void mouseClicked(MouseEvent e) { + adaptee.jTextArea1_mouseClicked(e); + } +} diff --git a/src/main/java/cct/gaussian/ui/SaveG03GJFDialog.java b/src/main/java/cct/gaussian/ui/SaveG03GJFDialog.java new file mode 100644 index 0000000..6f1297f --- /dev/null +++ b/src/main/java/cct/gaussian/ui/SaveG03GJFDialog.java @@ -0,0 +1,274 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian.ui; + +import java.awt.Font; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JOptionPane; +import javax.swing.JPanel; + +import cct.gaussian.GJFParserInterface; +import cct.interfaces.MoleculeInterface; +import cct.tools.FileFilterImpl; +import cct.tools.IOUtils; +import cct.tools.Utils; +import cct.tools.ui.FileChooserDialog; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class SaveG03GJFDialog + extends JDialog { + + final static String lastPWDKey = "lastPWD"; + + boolean OK_pressed = false; + GJFParserInterface gjfParser = null; + SimpleG03EditorPanel simpleG03EditorPanel1 = new SimpleG03EditorPanel(gjfParser); + FileChooserDialog fileChooser = null; + String workingDirectory = null; + JButton helpButton = new JButton(); + JPanel buttonPanel = new JPanel(); + JButton cancelButton = new JButton(); + JButton saveButton = new JButton(); + + public SaveG03GJFDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private SaveG03GJFDialog() { + this(new Frame(), "SaveG03GJFDialog", false); + } + + public boolean isOKPressed() { + return OK_pressed; + } + + private void jbInit() throws Exception { + helpButton.setEnabled(false); + helpButton.setToolTipText(""); + helpButton.setText("Help"); + saveButton.setToolTipText(""); + saveButton.setText("Save"); + saveButton.addActionListener(new + SaveG03GJFDialog_saveButton_actionAdapter(this)); + buttonPanel.setToolTipText(""); + cancelButton.addActionListener(new + SaveG03GJFDialog_cancelButton_actionAdapter(this)); + cancelButton.setText("Cancel"); + buttonPanel.add(saveButton); + buttonPanel.add(cancelButton); + buttonPanel.add(helpButton); + this.getContentPane().add(simpleG03EditorPanel1, + java.awt.BorderLayout.CENTER); + + this.getContentPane().add(buttonPanel, java.awt.BorderLayout.SOUTH); + + simpleG03EditorPanel1.enableValidateGeometry(false); + + Font currentFont = simpleG03EditorPanel1.getFontForText(); + int size = currentFont.getSize(); + int style = currentFont.getStyle(); + String fontName = currentFont.getFontName(); + + if (size < 12) { + size = 12; + Font newFont = new Font(fontName, style, size); + simpleG03EditorPanel1.setFontForText(newFont); + } + /* + simpleG03EditorPanel1.setLinkZeroCommands(buffer); + simpleG03EditorPanel1.setRouteSection(parser.getRouteSection(0)); + simpleG03EditorPanel1.setTitleSection(parser.getTitleSection(0)); + simpleG03EditorPanel1.setChargeSection(parser.getChargeSection(0)); + simpleG03EditorPanel1.setMoleculeSpecsSection(parser. + getMoleculeSpecsSection(0)); + */ + + } + + public void setGJFParser(GJFParserInterface parser) { + gjfParser = parser; + simpleG03EditorPanel1.setGeometryValidator(gjfParser); + } + + public void setupMolecule(MoleculeInterface mol) { + + simpleG03EditorPanel1.setupMolecule(mol); + + } + + public void setLinkZeroCommands(String buffer) { + simpleG03EditorPanel1.setLinkZeroCommands(buffer); + } + + public void setRouteSection(String text) { + simpleG03EditorPanel1.setRouteSection(text); + } + + public void setTitleSection(String text) { + simpleG03EditorPanel1.setTitleSection(text); + } + + public void setChargeSection(String text) { + simpleG03EditorPanel1.setChargeSection(text); + } + + public void setMoleculeSpecsSection(String text) { + simpleG03EditorPanel1.setMoleculeSpecsSection(text); + } + + public JButton getHelpButton() { + return this.helpButton; + } + + public void saveButton_actionPerformed(ActionEvent e) { + + if (fileChooser == null) { + FileFilterImpl filters[] = new FileFilterImpl[1]; + filters[0] = new FileFilterImpl(); + filters[0].addExtension("gjf"); + filters[0].addExtension("GJF"); + filters[0].addExtension("com"); + filters[0].addExtension("COM"); + filters[0].setDescription("Gaussian Input Files"); + + workingDirectory = Utils.getPreference(this, lastPWDKey); + + fileChooser = new FileChooserDialog(filters, this, "Select file to save", JFileChooser.SAVE_DIALOG); + fileChooser.setWorkingDirectory(workingDirectory); + } + + String fileName = fileChooser.getFile(); + + if (fileName == null) { + return; + } + + String pwd = fileChooser.getCurrentDirectory().getAbsolutePath(); + Utils.savePreference(this, lastPWDKey, pwd); + + /* + FileDialog fd = new FileDialog(new Frame(), "Save Gaussian Job File", + FileDialog.SAVE); + //fd.setDirectory(directory); + fd.setFile("*.gjf;*.com"); + + fd.setVisible(true); + if (fd.getFile() == null) { + return; + } + String fileName = fd.getFile().indexOf(".") == -1 ? fd.getFile() + ".gjf" : + fd.getFile(); + */ + + if (fileName.indexOf(".") == -1) { + fileName += ".gjf"; + } + + try { + //IOUtils.saveStringIntoFile(simpleG03EditorPanel1.getStepAsString(), + // fd.getDirectory() + fileName); + IOUtils.saveStringIntoFile(simpleG03EditorPanel1.getStepAsString(), + fileName); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Error saving file: " + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + setVisible(false); + } + + public void cancelButton_actionPerformed(ActionEvent e) { + setVisible(false); + } + + class SaveG03GJFDialog_cancelButton_actionAdapter + implements ActionListener { + private SaveG03GJFDialog adaptee; + SaveG03GJFDialog_cancelButton_actionAdapter(SaveG03GJFDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.cancelButton_actionPerformed(e); + } + } + + class SaveG03GJFDialog_saveButton_actionAdapter + implements ActionListener { + private SaveG03GJFDialog adaptee; + SaveG03GJFDialog_saveButton_actionAdapter(SaveG03GJFDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.saveButton_actionPerformed(e); + } + } + +} diff --git a/src/main/java/cct/gaussian/ui/SimpleG03EditorPanel.java b/src/main/java/cct/gaussian/ui/SimpleG03EditorPanel.java new file mode 100644 index 0000000..7d76a4e --- /dev/null +++ b/src/main/java/cct/gaussian/ui/SimpleG03EditorPanel.java @@ -0,0 +1,534 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian.ui; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.StringTokenizer; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.border.Border; +import javax.swing.border.TitledBorder; + +import cct.gaussian.GJFParserInterface; +import cct.gaussian.Gaussian; +import cct.gaussian.GaussianAtom; +import cct.interfaces.MoleculeInterface; +import cct.modelling.Molecule; + +/** + *

Title: Gasussian Utility Classes

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class SimpleG03EditorPanel + extends JPanel { + + Link0Panel link0Panel1 = new Link0Panel(); + RouteSectionPanel routeSectionPanel1 = new RouteSectionPanel(); + MoleculeSpecsPanel moleculeSpecsPanel1 = new MoleculeSpecsPanel(); + JLabel jLabel1 = new JLabel(); + JTextField jTextField1 = new JTextField(); + JPanel lowerPanel = new JPanel(); + JPanel centralPanel = new JPanel(); + TitleSectionPanel titleSectionPanel1 = new TitleSectionPanel(); + GridBagLayout gridBagLayout2 = new GridBagLayout(); + GridBagLayout gridBagLayout3 = new GridBagLayout(); + Border border1 = BorderFactory.createLineBorder(Color.gray, 1); + Border border2 = new TitledBorder(border1, "Route section (# lines)"); + + boolean fieldsEdited = false; + GJFParserInterface gjfParser = null; + + //ImageIcon arrowUp = new ImageIcon(cct.gaussian.ui.SimpleG03EditorPanel.class. + // getResource( + // "../../resources/images/icons32x32/arrowUp.gif")); + BorderLayout borderLayout1 = new BorderLayout(); + JButton validateGeomButton = new JButton(); + + //ImageIcon arrowUp = new ImageIcon("../../resources/images/icons32x32/arrowUp.gif"); + + + public boolean isEdited() { + return fieldsEdited; + } + + public SimpleG03EditorPanel(GJFParserInterface parser) { + gjfParser = parser; + try { + jbInit(); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + + public void setGeometryValidator(GJFParserInterface parser) { + gjfParser = parser; + if (gjfParser != null) { + this.enableValidateGeometry(true); + } + } + + private void jbInit() throws Exception { + jLabel1.setToolTipText(""); + jLabel1.setText("Charge & Multiplicity"); + this.setLayout(borderLayout1); + lowerPanel.setLayout(gridBagLayout2); + centralPanel.setLayout(gridBagLayout3); + moleculeSpecsPanel1.setBorder(new TitledBorder(BorderFactory. + createLineBorder(Color.gray, 1), "Molecule specifications ")); + link0Panel1.setBorder(new TitledBorder(BorderFactory.createLineBorder( + Color. + gray, 1), "Link 0 Commands")); + routeSectionPanel1.getViewport().setBackground(Color.black); + routeSectionPanel1.setBorder(new TitledBorder(BorderFactory. + createLineBorder(Color.gray, + 1), "Route section (# lines)")); + titleSectionPanel1.setBorder(new TitledBorder(BorderFactory. + createLineBorder(Color.gray, + 1), "Title section")); + jTextField1.setToolTipText("Enter Charge and Multiplicity"); + validateGeomButton.setMaximumSize(new Dimension(300, 300)); + validateGeomButton.setMinimumSize(new Dimension(130, 23)); + validateGeomButton.setPreferredSize(new Dimension(160, 23)); + validateGeomButton.setToolTipText("Click to Check Molecular Geometry"); + validateGeomButton.setBorderPainted(false); + validateGeomButton.setMnemonic('0'); + validateGeomButton.setText("Validate Geometry"); + validateGeomButton.addActionListener(new + SimpleG03EditorPanel_validateGeomButton_actionAdapter(this)); + this.add(centralPanel, BorderLayout.NORTH); + centralPanel.add(link0Panel1, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + centralPanel.add(routeSectionPanel1, + new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(0, 5, 0, 5), 0, 0)); + centralPanel.add(titleSectionPanel1, + new GridBagConstraints(0, 2, 1, 1, 1.0, 1.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(lowerPanel, BorderLayout.CENTER); + lowerPanel.add(validateGeomButton + , new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(0, 0, 0, 0), 0, 0)); + lowerPanel.add(jLabel1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(0, 5, 5, 5), 0, 0)); + lowerPanel.add(jTextField1, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + lowerPanel.add(moleculeSpecsPanel1, + new GridBagConstraints(0, 2, 3, 1, 1.0, 1.0 + , GridBagConstraints.CENTER, + GridBagConstraints.BOTH, + new Insets(5, 5, 5, 5), 0, 0)); + } + + public void setLinkZeroCommands(java.util.List cmd) { + link0Panel1.setText(getText(cmd)); + fieldsEdited = true; + } + + public void setLinkZeroCommands(String cmd) { + link0Panel1.setText(cmd); + fieldsEdited = true; + } + + public String getLinkZeroCommands() { + return link0Panel1.getText(); + } + + public void setRouteSection(String options) { + routeSectionPanel1.setText(options); + fieldsEdited = true; + } + + public String getRouteSection() { + return routeSectionPanel1.getText(); + } + + public void setTitleSection(String options) { + titleSectionPanel1.setText(options); + fieldsEdited = true; + } + + public String getTitleSection() { + return titleSectionPanel1.getText(); + } + + public void setChargeSection(String options) { + jTextField1.setText(options); + fieldsEdited = true; + } + + public String getChargeSection() { + String lines[] = jTextField1.getText().split("\n"); + String text = ""; + for (int i = 0; i < lines.length; i++) { + String trimmed = lines[i].trim(); + if (trimmed.length() != 0) { + text += trimmed + "\n"; + } + } + return text; + //return jTextField1.getText(); + } + + public void setMoleculeSpecsSection(String options) { + moleculeSpecsPanel1.setText(options); + fieldsEdited = true; + } + + public String getMoleculeSpecsSection() { + return moleculeSpecsPanel1.getText(); + } + + public void resetPanel() { + link0Panel1.resetPanel(); + routeSectionPanel1.resetPanel(); + titleSectionPanel1.resetPanel(); + jTextField1.setText("0 1"); + moleculeSpecsPanel1.resetPanel(); + fieldsEdited = false; + } + + public String getStepAsString() { + String step = ""; + step = getLinkZeroCommands() + getRouteSection() + "\n" + getTitleSection() + + "\n" + getChargeSection() + getMoleculeSpecsSection(); + return step; + } + + String getText(java.util.List cmd) { + if (cmd == null || cmd.size() < 1) { + return ""; + } + String text = ""; + for (int i = 0; i < cmd.size(); i++) { + text += (String) cmd.get(i); + } + return text; + } + + public void enableValidateGeometry(boolean enable) { + validateGeomButton.setEnabled(enable); + } + + public void validateGeomButton_actionPerformed(ActionEvent e) { + if (gjfParser == null) { + JOptionPane.showMessageDialog(null, + "No geometry validator was specified!", + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + moleculeSpecsPanel1.startEditing(); + java.util.List atoms = null; + try { + atoms = gjfParser.validateMolecularGeometry(this.getMoleculeSpecsSection()); + this.validate(); + if (atoms.size() > 0) { + /* + JOptionPane.showMessageDialog(null, + "Found "+atoms.size()+" atoms", + "Success", + JOptionPane.INFORMATION_MESSAGE); + */ + } + else { + JOptionPane.showMessageDialog(null, + "No atoms found", + "No atoms", + JOptionPane.INFORMATION_MESSAGE); + return; + } + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + // --- check charge and multiplicity + + int ch = 0, multiplicity = 1; + String chargeSection = this.getChargeSection(); + StringTokenizer st = new StringTokenizer(chargeSection, " ,\t\n"); + if (st.countTokens() < 2) { + ch = 0; + multiplicity = 1; + } + else { + try { + ch = Integer.parseInt(st.nextToken()); + multiplicity = Integer.parseInt(st.nextToken()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, + "Wrong value(s) for charge or/and multiplicity " + + chargeSection + " : " + ex.getMessage() + + "\nProgram will try to fix it...", + "Error", + JOptionPane.ERROR_MESSAGE); + } + } + + if (multiplicity < 1) { + JOptionPane.showMessageDialog(null, + "Multiplicity cannot be less than 1\n" + + "Program will fix it...", + "Error", + JOptionPane.ERROR_MESSAGE); + multiplicity = 1; + } + + int[] elements = new int[atoms.size()]; + for (int i = 0; i < atoms.size(); i++) { + GaussianAtom atom = atoms.get(i); + elements[i] = atom.getElement(); + } + + int charge = ch; + try { + Molecule.validateTotalCharge(elements, charge, multiplicity); + } + catch (Exception ex) { + try { + charge = Molecule.guessTotalCharge(elements, multiplicity); + } + catch (Exception exx) {} + + JOptionPane.showMessageDialog(this, + "Current values for charge " + ch + + " and multiplicity " + + multiplicity + + " do not make sense\n" + + "Check new values for charge " + charge + + " and multiplicity " + multiplicity + + " suggested by a program" + , "Warning", + JOptionPane.WARNING_MESSAGE); + } + + if (st.hasMoreTokens()) { + String newChargeSection = String.valueOf(charge) + " " + + String.valueOf(multiplicity); + while (st.hasMoreTokens()) { + newChargeSection += " " + st.nextToken(); + } + setChargeSection(newChargeSection); + } + else { + this.setChargeSection(String.valueOf(charge) + " " + + String.valueOf(multiplicity)); + } + + // --- Check link0 Section + + try { + gjfParser.validateLink0Section(this.getLinkZeroCommands()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, + "Error(s) in Link0 Section:\n" + + ex.getMessage(), + "Error(s) in Link0 Section", + JOptionPane.ERROR_MESSAGE); + } + + } + + public void setupMolecule(MoleculeInterface mol) { + + // --- Set link0 section + + Object props = mol.getProperty(cct.gaussian.Gaussian. + LINK_ZERO_COMMANDS_KEY); + + if (props != null) { + if (props instanceof java.util.List) { + java.util.List link0 = (java.util.List) props; + String text = ""; + for (int i = 0; i < link0.size(); i++) { + text += link0.get(i).toString() + "\n"; + } + setLinkZeroCommands(text); + } + else { + setLinkZeroCommands(props.toString()); + } + } + else { + setLinkZeroCommands("%nproc=1"); + } + + // --- Set route section + + props = mol.getProperty(cct.gaussian.Gaussian.ROUTE_COMMANDS_KEY); + if (props != null) { + setRouteSection(props.toString()); + } + else { + setRouteSection("# Opt HF/6-31g"); + } + + // --- Set title section + + setTitleSection(mol.getName()); + + // --- Set charge section + + Integer multiplicity = (Integer) mol.getProperty(MoleculeInterface.MultiplicityProperty); + + if (multiplicity == null) { + multiplicity = 1; + System.err.println("Set multiplicity to " + multiplicity); + } + else if (multiplicity < 1) { + JOptionPane.showMessageDialog(null, + "Multiplicity cannot be less than 1\n" + + "Program will fix it...", + "Error", + JOptionPane.ERROR_MESSAGE); + } + + Integer ch = (Integer) mol.getProperty(MoleculeInterface.ChargeProperty); + if (ch == null) { + try { + ch = Molecule.guessTotalCharge(mol, multiplicity.intValue()); + } + catch (Exception ex) {} + + System.err.println("Set total charge to " + ch); + } + + int charge = ch; + try { + //charge = Molecule.guessTotalCharge(mol, multiplicity.intValue()); + Molecule.validateTotalCharge(mol, ch, multiplicity.intValue()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Current combination of total charge " + + ch.intValue() + " and multiplicity " + + multiplicity + " does not make sense" + + "\nCheck values " + charge + " and " + + multiplicity.intValue() + + " suggested by a program" + , "Error", + JOptionPane.ERROR_MESSAGE); + + try { + charge = Molecule.guessTotalCharge(mol, multiplicity.intValue()); + } + catch (Exception exx) {} + } + + setChargeSection(charge + " " + multiplicity); + + // --- Set molecule specs + + try { + setMoleculeSpecsSection(Gaussian.getMoleculeSpecsAsString(mol)); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Error generating molecule specifications: " + + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + } + + public void setFontForText(Font newFont) { + link0Panel1.setFontForText(newFont); + this.routeSectionPanel1.setFontForText(newFont); + this.titleSectionPanel1.setFontForText(newFont); + this.moleculeSpecsPanel1.setFontForText(newFont); + } + + public Font getFontForText() { + return link0Panel1.getFontForText(); + } + +} + +class SimpleG03EditorPanel_validateGeomButton_actionAdapter + implements ActionListener { + private SimpleG03EditorPanel adaptee; + SimpleG03EditorPanel_validateGeomButton_actionAdapter( + SimpleG03EditorPanel + adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.validateGeomButton_actionPerformed(e); + } +} diff --git a/src/main/java/cct/gaussian/ui/TitleSectionPanel.java b/src/main/java/cct/gaussian/ui/TitleSectionPanel.java new file mode 100644 index 0000000..0264c4c --- /dev/null +++ b/src/main/java/cct/gaussian/ui/TitleSectionPanel.java @@ -0,0 +1,109 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gaussian.ui; + +import java.awt.Font; + +import javax.swing.JScrollPane; +import javax.swing.JTextArea; + +/** + *

Title: Gasussian Utility Classes

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class TitleSectionPanel + extends JScrollPane { + + JTextArea jTextArea1 = new JTextArea(); + + public TitleSectionPanel() { + try { + jbInit(); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + + private void jbInit() throws Exception { + jTextArea1.setToolTipText(""); + jTextArea1.setText("My Gaussian Job"); + jTextArea1.setRows(2); + this.getViewport().add(jTextArea1); + } + + public void resetPanel() { + jTextArea1.setEnabled(false); + jTextArea1.setText("My Gaussian Job"); + jTextArea1.setEnabled(true); + } + + public void setFontForText(Font newFont) { + jTextArea1.setFont(newFont); + } + + public Font getFontForText() { + return jTextArea1.getFont(); + } + + public void setText(String text) { + jTextArea1.setText(text); + jTextArea1.setCaretPosition(0); + } + + public String getText() { + String lines[] = jTextArea1.getText().split("\n"); + String text = ""; + for (int i = 0; i < lines.length; i++) { + String trimmed = lines[i].trim(); + if (trimmed.length() != 0) { + text += trimmed + "\n"; + } + } + return text; + } + +} diff --git a/src/main/java/cct/gaussian/ui/about.png b/src/main/java/cct/gaussian/ui/about.png new file mode 100644 index 0000000..754005c Binary files /dev/null and b/src/main/java/cct/gaussian/ui/about.png differ diff --git a/src/main/java/cct/gaussian/ui/closeFile.png b/src/main/java/cct/gaussian/ui/closeFile.png new file mode 100644 index 0000000..81cc1a6 Binary files /dev/null and b/src/main/java/cct/gaussian/ui/closeFile.png differ diff --git a/src/main/java/cct/gaussian/ui/gaussian-1-64x64.png b/src/main/java/cct/gaussian/ui/gaussian-1-64x64.png new file mode 100644 index 0000000..2ef600f Binary files /dev/null and b/src/main/java/cct/gaussian/ui/gaussian-1-64x64.png differ diff --git a/src/main/java/cct/gaussian/ui/help.png b/src/main/java/cct/gaussian/ui/help.png new file mode 100644 index 0000000..d7a33f8 Binary files /dev/null and b/src/main/java/cct/gaussian/ui/help.png differ diff --git a/src/main/java/cct/gaussian/ui/openFile.png b/src/main/java/cct/gaussian/ui/openFile.png new file mode 100644 index 0000000..d4f742a Binary files /dev/null and b/src/main/java/cct/gaussian/ui/openFile.png differ diff --git a/src/main/java/cct/grid/.DS_Store b/src/main/java/cct/grid/.DS_Store new file mode 100644 index 0000000..7b99a69 Binary files /dev/null and b/src/main/java/cct/grid/.DS_Store differ diff --git a/src/main/java/cct/grid/._.DS_Store b/src/main/java/cct/grid/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/cct/grid/._.DS_Store differ diff --git a/src/main/java/cct/grid/CheckPoint.java b/src/main/java/cct/grid/CheckPoint.java new file mode 100644 index 0000000..e086bbd --- /dev/null +++ b/src/main/java/cct/grid/CheckPoint.java @@ -0,0 +1,1051 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.grid; + +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; + +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; + +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +import cct.tools.IOUtils; +import cct.tools.ui.JobProgressInterface; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class CheckPoint + extends HashMap implements CheckPointInterface { + + final static String outputStatusPrefix = "local"; + final static String inputStatusPrefix = "local"; + Map resourcesUsed = null; + + //final static HashMap firstLevelTags = new HashMap(); + //final static HashMap serviceTags = new HashMap(); + //final static HashMap JobSpecificationTags = new HashMap(); + static { + firstLevelTags.put(jobNameTag, "MyJob"); + firstLevelTags.put(softwareTag, "Unspecified"); + firstLevelTags.put(programTag, "Unspecified"); + firstLevelTags.put(statusTag, "Unknown"); + firstLevelTags.put(overallJobStatusTag, "Unknown"); + firstLevelTags.put(submittedTimeTag, "Unknown"); + firstLevelTags.put(serviceTag, serviceTags); + firstLevelTags.put(JobSpecificationTag, JobSpecificationTags); + + serviceTags.put(handleTag, "unknown"); + serviceTags.put(providerTag, "unknown"); + serviceTags.put(computerTag, "unknown"); + + JobSpecificationTags.put(executableTag, ""); + JobSpecificationTags.put(localExecutableTag, "true"); + JobSpecificationTags.put(stdOutputTag, "/dev/stdout"); + JobSpecificationTags.put(stdErrorTag, "/dev/stderr"); + JobSpecificationTags.put(remoteDirectoryTag, ""); + JobSpecificationTags.put(localDirectoryTag, ""); + JobSpecificationTags.put(outputFilesTag, null); + JobSpecificationTags.put(inputFilesTag, null); + } + static boolean Debug = false; + boolean outputFilesStatusUpdated = false; + String Message = ""; + private JobProgressInterface progress = null; + static final Logger logger = Logger.getLogger(JobProgressInterface.class.getCanonicalName()); + + public JobProgressInterface getProgress() { + return progress; + } + + public void setProgress(JobProgressInterface progress) { + this.progress = progress; + } + + public CheckPoint() { + } + + /** + * Returns all possible specifications of checkpoint + * @return HashMap + */ + public static Map getCheckPointSpecifications() { + return firstLevelTags; + } + + /** + * Returns checkpoint as a HashMap + * @return HashMap checkpoint + */ + public Map getHashMap() { + return this; + } + + public String getMessage() { + return Message; + } + + public Map getResourcesUsed() { + return resourcesUsed; + } + + public void setResourcesUsed(Map rused) { + resourcesUsed = rused; + } + + public String getJobStatus() { + return (String) get(statusTag); + } + + public String getJobName() { + return (String) get(jobNameTag); + } + + public String getProgram() { + return (String) get(programTag); + } + + public String getJobSubmitTime() { + return (String) get(CheckPointInterface.submittedTimeTag); + } + + public void setJobStatus(String status) { + put(statusTag, status); + } + + public void setOverallJobStatus(String status) { + put(overallJobStatusTag, status); + } + + public String getOverallJobStatus() { + if (!containsKey(overallJobStatusTag)) { + return "Unknown"; + } + return (String) get(overallJobStatusTag); + } + + public String getJobHandle() { + Map service = (Map) get(serviceTag); + if (service == null) { + return null; + } + return (String) service.get(handleTag); + } + + public String getTaskProvider() { + Map service = (Map) get(serviceTag); + if (service == null) { + return null; + } + return (String) service.get(providerTag); + } + + public String getComputer() { + Map service = (Map) get(serviceTag); + if (service == null) { + return null; + } + return (String) service.get(computerTag); + } + + public String getRemoteDirectory() { + Map service = (Map) get(JobSpecificationTag); + if (service == null) { + return null; + } + return (String) service.get(remoteDirectoryTag); + } + + public String getExecutable() { + Map service = (Map) get(JobSpecificationTag); + if (service == null) { + return null; + } + return (String) service.get(CheckPointInterface.executableTag); + + } + + public String getLocalDirectory() { + Map service = (Map) get(JobSpecificationTag); + if (service == null) { + return null; + } + return (String) service.get(localDirectoryTag); + } + + public String updateJobStatus() throws Exception { + if (!containsKey(statusTag)) { + return null; + } + if (getTaskProvider() == null) { + return null; + } + + String status = getJobStatus(); + if (status.equalsIgnoreCase(JOB_STATUS_DONE)) { + return status; + } + + String handle = getJobHandle(); + + if (handle == null) { + return JOB_STATUS_UNKNOWN; + } + + String jobName = this.getJobName(); + + String provider = this.getTaskProvider(); + if (provider == null) { + logger.warning("Task " + jobName + " does not have a provider record"); + throw new Exception("Task " + jobName + " does not have a provider record"); + } + + if (progress != null) { + progress.setProgressText("Getting job status for " + handle); + } + status = TaskProvider.getJobStatus(this); + /* + GramJob gj = null; + try { + gj = GRAM.getJobStatus(handle); + } + catch (Exception e) { + //throw e; + System.err.println("Quering handle : " + handle + " : " + e.getMessage()); + } + + if (gj.getStatus() == 0) { + status = JOB_STATUS_DONE; + } + else { + status = gj.getStatusAsString(); + } + */ + + setJobStatus(status); + + // Update (if needed) overall job status (only if a submitted job completed) + + + if (status.equalsIgnoreCase(JOB_STATUS_DONE)) { + if (hasOutputFiles()) { + if (areOutputFilesLoaded()) { + setOverallJobStatus(JOB_STATUS_DONE); + } else { + setOverallJobStatus(JOB_STATUS_PENDING); + } + } else { + setOverallJobStatus(JOB_STATUS_DONE); + } + } + + return status; + } + + public void downloadOutputFiles(FileTransferInterface fileTransferHandler) throws + MalformedCheckPointException { + + outputFilesStatusUpdated = false; + + // Error check + if (!hasOutputFiles()) { + logger.info("Warning: attempt to download output file(s) from the checkpoint without ones"); + return; + } + + if (areOutputFilesLoaded()) { + logger.info("Warning: downloadOutputFiles: output files are already downloaded"); + return; + } + + if (getTaskProvider() == null) { + System.err.println("Error: downloadOutputFiles: no provider name in checkpoint file"); + throw new MalformedCheckPointException("No provider name in checkpoint file"); + } + + // --- Creating valid URLs + /* + if (this.getComputer() == null) { + System.err.println("Error: downloadOutputFiles: no computer name in checkpoint file"); + throw new MalformedCheckPointException("No computer name in checkpoint file"); + } + */ + + if (this.getLocalDirectory() == null) { + System.err.println("Error: downloadOutputFiles: no local directory in checkpoint file"); + throw new MalformedCheckPointException("No local directory in checkpoint file"); + } + + String localDir = getLocalDirectory(); + + if (!localDir.endsWith("/") && !localDir.endsWith("\\")) { + localDir = localDir + "/"; + } + + //String fromURL = getComputer() + remoteDir; + String fromURL = ""; + String toURL = localDir; + + String errorMessage = ""; + + // --- Go through output files + Map out = getOutputFilesEntry(); + Set set = out.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Entry me = (Entry) iter.next(); + String Key = me.getKey().toString(); + String outputFile = me.getValue().toString(); + if (Key.startsWith(outputStatusPrefix)) { + continue; + } + String status_tag = outputStatusPrefix + Key; + if (!out.containsKey(status_tag)) { + System.err.println("Internal Error: tag " + Key + " should be complemented with tag " + outputStatusPrefix + Key); + throw new RuntimeException("Internal Error: tag " + Key + " should be complemented with tag " + outputStatusPrefix + + Key); + //continue; + } + + String status_value = (String) out.get(outputStatusPrefix + Key); + + // --- Download it + if (status_value.equalsIgnoreCase("false")) { + logger.info("Copying\n From: " + fromURL + outputFile); + logger.info(" To: " + toURL + outputFile); + + if (fileTransferHandler.tranferFile(fromURL + outputFile, toURL + outputFile, this)) { + out.put(outputStatusPrefix + Key, "true"); + outputFilesStatusUpdated = true; + } else { + errorMessage += "Unable to download " + fromURL + outputFile + "\n"; + } + + } + } + + // --- Update overal job status + if (errorMessage.length() == 0) { + setOverallJobStatus(JOB_STATUS_DONE); + outputFilesStatusUpdated = true; + } + + if (errorMessage.length() > 0) { + throw new MalformedCheckPointException(errorMessage); + } + + } + + public boolean isOutputFilesStatusUpdated() { + return outputFilesStatusUpdated; + } + + /** + * Informs whether remote output files are downloaded on a local computer + * @return boolean "true" if ALL output files are downloaded on local computer, + * and "false" otherwise + */ + public boolean areOutputFilesLoaded() { + Map out = getOutputFilesEntry(); + Set set = out.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Entry me = (Entry) iter.next(); + String Key = me.getKey().toString(); + if (Key.startsWith(outputStatusPrefix)) { + continue; + } + String status_tag = outputStatusPrefix + Key; + if (!out.containsKey(status_tag)) { + System.err.println("Internal Error: tag " + Key + + " should be complemented with tag " + + outputStatusPrefix + Key); + throw new RuntimeException("Internal Error: tag " + Key + + " should be complemented with tag " + + outputStatusPrefix + Key); + //continue; + } + String status_value = (String) out.get(outputStatusPrefix + Key); + if (status_value.equalsIgnoreCase("false")) { + return false; + } + } + return true; + } + + /** + * + * @return HashMap Entry for Output Files + */ + public Map getOutputFilesEntry() { + if (!containsKey(JobSpecificationTag)) { + return null; + } + Map js = (Map) get(JobSpecificationTag); + if (!js.containsKey(outputFilesTag)) { + return null; + } + return (Map) js.get(outputFilesTag); + } + + public boolean hasOutputFiles() { + return getOutputFilesEntry() != null; + } + + public boolean hasOutputFile(String fileName) { + Map output = getOutputFilesEntry(); + if (output == null) { + return false; + } + + if (!output.containsValue(fileName)) { + return false; + } + + Set set = output.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Entry me = (Entry) iter.next(); + String tag = me.getKey().toString(); + if (tag.startsWith("local")) { + continue; + } + String fName = me.getValue().toString(); + if (fileName.equals(fName)) { + return true; + } + } + return false; + } + + public boolean isOutputFileDownloaded(String fileName) throws Exception { + Map output = getOutputFilesEntry(); + if (output == null) { + throw new Exception("No output files in a given checkpoint"); + } + + if (!output.containsValue(fileName)) { + throw new Exception("No output file " + fileName + + " in a given checkpoint"); + } + + Set set = output.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Entry me = (Entry) iter.next(); + String tag = me.getKey().toString(); + if (tag.startsWith("local")) { + continue; + } + String fName = me.getValue().toString(); + if (fileName.equals(fName)) { + if (output.containsKey("local" + tag)) { + String state = output.get("local" + tag).toString(); + try { + boolean local = Boolean.valueOf(state); + return local; + } catch (Exception ex) { + throw ex; + } + } + } + } + throw new Exception("No output file " + fileName + " in a given checkpoint"); + } + + public String getFullLocalPath(String fileName) throws Exception { + Map output = getOutputFilesEntry(); + if (output == null) { + throw new Exception("No output files in a given checkpoint"); + } + + if (!output.containsValue(fileName)) { + throw new Exception("No output file " + fileName + + " in a given checkpoint"); + } + + if (!isOutputFileDownloaded(fileName)) { + throw new Exception("File " + fileName + " is not downloaded"); + } + + return getLocalDirectory() + fileName; + } + + public String getOutputFileType(String fileName) throws Exception { + Map output = getOutputFilesEntry(); + if (output == null) { + throw new Exception("No output files in a given checkpoint"); + } + + if (!output.containsValue(fileName)) { + throw new Exception("No output file " + fileName + + " in a given checkpoint"); + } + + Set keys = output.keySet(); + Iterator iter = keys.iterator(); + while (iter.hasNext()) { + String key = (String) iter.next(); + if (output.get(key).toString().equals(fileName)) { + return key; + } + } + return null; + } + + /** + * + * @param tag String + * @param value String + * @throws MalformedCheckPointException + */ + public void setOutputFile(String tag, String value) throws + Exception { + + try { + setOutputFile(tag, value, false); + } catch (Exception ex) { + throw ex; + } + } + + /** + * + * @param tag String + * @param value String + * @param local_file boolean + * @throws MalformedCheckPointException + */ + public void setOutputFile(String tag, String value, boolean local_file) throws + MalformedCheckPointException { + if (!this.containsKey(JobSpecificationTag)) { + throw new MalformedCheckPointException("Error adding " + outputFilesTag + " tag: no " + JobSpecificationTag + " tag"); + } + + if (tag.indexOf(" ") != -1) { + throw new MalformedCheckPointException( + "Error adding output file tag: tag must not contain blanks: \"" + tag + "\""); + } + + Map jsp = (Map) get(JobSpecificationTag); + + if (!jsp.containsKey(outputFilesTag)) { + Map out = new HashMap(); + jsp.put(outputFilesTag, out); + if (Debug) { + logger.info("Creating specific entry: " + outputFilesTag); + } + } + Map out = (Map) jsp.get(outputFilesTag); + out.put(tag, value); + // Add a flag + out.put(outputStatusPrefix + tag, Boolean.toString(local_file)); + + if (Debug) { + logger.info(" Adding " + tag + "=" + value + " inside tag " + outputFilesTag); + } + } + + /** + * Query spesific "service" tags + * @param tag String - Tag + * @return String - Value, or null is no such tag + */ + public String getServiceTag(String tag) { + if (!this.containsKey(serviceTag)) { + return null; + } + Map service = (Map) this.get(serviceTag); + return service.get(tag).toString(); + } + + /** + * Sets service tag which is in general could be some custom value + * @param tag String - tag + * @param value String - value + * @throws MalformedCheckPointException + */ + public void setServiceTag(String tag, String value, boolean overwrite) throws Exception { + + if (tag.indexOf(" ") != -1) { + throw new MalformedCheckPointException("Error adding output file tag: tag must not contain blanks: \"" + tag + "\""); + } + + // --- Get service hashmap + + Map service = null; + if (!this.containsKey(serviceTag)) { + service = new HashMap(); + this.put(serviceTag, service); + } else { + service = (Map) this.get(serviceTag); + } + + if (overwrite || (!service.containsKey(tag))) { + service.put(tag, value); + if (Debug) { + logger.info(" Adding service tag: " + tag + "=" + value); + } + } else { + throw new MalformedCheckPointException("Cannot add service tag " + tag + " : it's already exists. Use overwrite option..."); + } + } + + public void setInputFile(String tag, String value, boolean local_file) throws + MalformedCheckPointException { + + if (!this.containsKey(JobSpecificationTag)) { + throw new MalformedCheckPointException("Error adding " + inputFilesTag + " tag: no " + JobSpecificationTag + " tag"); + } + + if (tag.indexOf(" ") != -1) { + throw new MalformedCheckPointException("Error adding input file tag: tag must not contain blanks: \"" + tag + "\""); + } + + Map jsp = (Map) get(JobSpecificationTag); + + if (!jsp.containsKey(inputFilesTag)) { + Map out = new HashMap(); + jsp.put(inputFilesTag, out); + if (Debug) { + logger.info("Creating specific entry: " + inputFilesTag); + } + } + Map out = (Map) jsp.get(inputFilesTag); + out.put(tag, value); + // Add a flag + out.put(inputStatusPrefix + tag, Boolean.toString(local_file)); + + if (Debug) { + logger.info(" Adding " + tag + "=" + value + " inside tag " + + inputFilesTag); + } + } + + /** + * + * @param options String + * @param devider String + * @throws MalformedCheckPointException + */ + public CheckPoint(String options, String devider) throws + MalformedCheckPointException { + super(); + if (options == null || options.trim().length() == 0) { + throw new MalformedCheckPointException("No parameters"); + } + String[] tokens = options.split(devider); + if (tokens.length % 2 == 1) { + throw new MalformedCheckPointException("Odd number of parameters:"); + } + + for (int i = 0; i < tokens.length; i++) { + tokens[i] = tokens[i].trim(); + } + + for (int i = 0; i < tokens.length / 2; i++) { + if (Debug) { + logger.info("Parsing: " + tokens[2 * i] + " = " + tokens[2 * i + 1]); + } + try { + if (!addElement(tokens[2 * i], tokens[2 * i + 1], this, firstLevelTags)) { + throw new MalformedCheckPointException("Parsing paramaters: Wrong tag: " + tokens[2 * i]); + } + } catch (MalformedCheckPointException e) { + throw e; + } + } + + // Set defaults values + + Set set = firstLevelTags.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Entry me = (Entry) iter.next(); + String targetKey = me.getKey().toString(); + Object type = me.getValue(); + if (type instanceof Map) { + continue; + } + + if (containsKey(targetKey)) { + continue; + } + + put(targetKey, type); + } + } + + /** + * + * @param keyword String + * @param value String + * @param target HashMap + * @param reference HashMap + * @return boolean + * @throws MalformedCheckPointException + */ + private boolean addElement(String keyword, String value, Map target, Map reference) throws + MalformedCheckPointException { + + // --- Check for "root" tags + + if (reference.containsKey(keyword)) { + Object obj = reference.get(keyword); + if (obj instanceof Map) { + throw new MalformedCheckPointException("Tag " + keyword + " is only a container for tags"); + } else { + target.put(keyword, value); + return true; + } + } + + // --- Check for inclosed tag containers + + Set set = reference.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Entry me = (Entry) iter.next(); + String targetKey = me.getKey().toString(); + Object type = me.getValue(); + + if (!(type instanceof Map)) { + continue; + } + + Map new_entry = null; + if (!target.containsKey(targetKey)) { + new_entry = new HashMap(); + target.put(targetKey, new_entry); + } + + new_entry = (Map) target.get(targetKey); + Map next_ref_entry = (Map) type; + + try { + if (addElement(keyword, value, new_entry, next_ref_entry)) { + new_entry.put(keyword, value); + target.put(targetKey, new_entry); + return true; + } + } catch (MalformedCheckPointException e) { + throw e; + } + + } + + return false; + } + + /** + * + * @param file_name String + * @return int + */ + public int saveCheckPoint(String file_name) throws Exception { + List task = new ArrayList(); + task.add(this.getHashMap()); + String xml_string = null; + try { + xml_string = CreateCheckpointString(task); + } catch (Exception ex) { + throw ex; + } + IOUtils.saveStringIntoFile(xml_string, file_name); + return 0; + } + + public static String CreateCheckpointString(List Tasks) throws + MalformedCheckPointException, SAXException { + //Message = ""; + StringWriter sWriter = new StringWriter(); + + StreamResult streamResult = new StreamResult(sWriter); + SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); + + // SAX2.0 ContentHandler. + TransformerHandler hd = null; + try { + hd = tf.newTransformerHandler(); + } catch (TransformerConfigurationException e) { + //Message = e.getMessage(); + System.err.println(e.getMessage()); + throw new MalformedCheckPointException("Error: " + e.getMessage()); + //return null; + } + Transformer serializer = hd.getTransformer(); + //serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); + //serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "users.dtd"); + serializer.setOutputProperty(OutputKeys.INDENT, "yes"); + hd.setResult(streamResult); + try { + hd.startDocument(); + AttributesImpl atts = new AttributesImpl(); + //atts.addAttribute("","","ID","CDATA",id[i]); + //atts.addAttribute("","","TYPE","CDATA",type[i]); + + // TASKS tag. + hd.startElement("", "", tasksTag, atts); + + for (int i = 0; i < Tasks.size(); i++) { + Map Level_1 = (Map) Tasks.get(i); + atts.clear(); + hd.startElement("", "", taskTag, atts); + + //if (!createElements(hd, firstLevelTags, Level_1)) { + if (!createElements(hd, CheckPoint.getCheckPointSpecifications(), + Level_1)) { + return null; + } + + hd.endElement("", "", taskTag); + } + + hd.endElement("", "", tasksTag); + hd.endDocument(); + + } catch (SAXException e) { + //Message = e.getMessage(); + System.err.println(e.getMessage()); + throw e; + //return null; + } + + return sWriter.toString(); + } + + static boolean createElements(TransformerHandler hd, Map list, Map elements) throws + MalformedCheckPointException, SAXException { + AttributesImpl atts = new AttributesImpl(); + + if (Debug) { + logger.info("Enter createElements..."); + } + + Set set = elements.entrySet(); + Iterator iter = set.iterator(); + try { + while (iter.hasNext()) { + Entry me = (Entry) iter.next(); + String keyWord = me.getKey().toString(); + Object obj = me.getValue(); + if (Debug) { + logger.info("Parsing: " + keyWord); + } + + atts.clear(); + + hd.startElement("", "", keyWord, atts); + + if (obj instanceof Map) { + if (Debug) { + logger.info(" Key " + keyWord + " is an entry..."); + } + + Map child = (Map) obj; + createElements(hd, child, child); + } // Process regular entry + else { + String value = obj.toString(); + if (Debug) { + logger.info(" Key is a value: " + value); + } + if (value == null) { + hd.characters("".toCharArray(), 0, 0); + } else { + hd.characters(value.toCharArray(), 0, value.length()); + } + } + + hd.endElement("", "", keyWord); + } + } catch (SAXException e) { + System.err.println(e.getMessage()); + throw e; + } + /* + Set set = list.entrySet(); + Iterator iter = set.iterator(); + //Iterator iter = list.iterator(); + try { + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String keyWord = me.getKey().toString(); + Object type = me.getValue(); + if (Debug) { + logger.info("Parsing: " + keyWord); + } + + if (!elements.containsKey(keyWord)) { + if (Debug) { + logger.info(" No such key in elements. Continuing..."); + } + continue; + } + + atts.clear(); + + hd.startElement("", "", keyWord, atts); + + Object obj = elements.get(keyWord); + + if (type instanceof HashMap) { + if (Debug) { + logger.info(" Key is an entry..."); + } + + // --- Error check + if (! (type instanceof HashMap)) { + throw new MalformedCheckPointException("Tag " + keyWord + " must be an hashmap entry! Got " + + type.getClass().getName()); + } + + if (obj instanceof HashMap) { + HashMap parent = (HashMap) type; + HashMap child = (HashMap) obj; + if (!createElements(hd, parent, child)) { + return false; + } + } + else { + String mess = "Instance of user's HashMap different from the reference one"; + System.err.println(mess); + throw new MalformedCheckPointException(mess); + //return false; + } + } + + // Process specific entry + else if (type == null) { + if (Debug) { + logger.info(" Key is a specific entry..."); + } + HashMap child = (HashMap) obj; + if (!createElements(hd, child)) { + return false; + } + + } + + // Process regular entry + else { + Object xxx = elements.get(keyWord); + if (Debug) { + logger.info(" Key is a value: " + xxx.toString()); + } + String value = (String) elements.get(keyWord); + hd.characters(value.toCharArray(), 0, value.length()); + } + + hd.endElement("", "", keyWord); + } + } + catch (org.xml.sax.SAXException e) { + //Message = e.getMessage(); + System.err.println(e.getMessage()); + throw e; + //return false; + } + */ + return true; + } + + /** + * Prints all tags and their values of "entries" + * @param hd TransformerHandler + * @param entries HashMap + * @return boolean + */ + static boolean createElements(TransformerHandler hd, Map entries) throws + SAXException { + AttributesImpl atts = new AttributesImpl(); + Set set = entries.entrySet(); + Iterator iter = set.iterator(); + //Iterator iter = list.iterator(); + try { + while (iter.hasNext()) { + Entry me = (Entry) iter.next(); + String keyWord = me.getKey().toString(); + String value = (String) me.getValue(); + if (Debug) { + logger.info("Parsing: " + keyWord); + } + + atts.clear(); + + hd.startElement("", "", keyWord, atts); + + hd.characters(value.toCharArray(), 0, value.length()); + + hd.endElement("", "", keyWord); + } + } catch (SAXException e) { + //Message = e.getMessage(); + System.err.println(e.getMessage()); + throw e; + //return false; + } + return true; + } + + /* + public static void main(String[] args) { + CheckPoint checkpoint = new CheckPoint(); + } + */ +} diff --git a/src/main/java/cct/grid/CheckPointInterface.java b/src/main/java/cct/grid/CheckPointInterface.java new file mode 100644 index 0000000..ecc6474 --- /dev/null +++ b/src/main/java/cct/grid/CheckPointInterface.java @@ -0,0 +1,103 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid; + +import java.util.HashMap; +import java.util.Map; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface CheckPointInterface { + int PARSE_TASK_TAGS = 1; + int PARSE_SERVICE_TAGS = 2; + int PARSE_JOB_SPECIFICATION_TAGS = 3; + int PARSE_OUTPUT_FILES_TAGS = 4; + + String JOB_STATUS_DONE = "DONE"; + String JOB_STATUS_PENDING = "PENDING"; + String JOB_STATUS_UNKNOWN = "UNKNOWN"; + + //final static String serviceEntriesTag = "serviceTags"; + //final static String jobSpecificationEntriesTag = "jobSpecificationTags"; + //final static String outputFilesEntriesTag = "outputFilesTags"; + + String tasksTag = "tasks"; + String taskTag = "task"; + String jobNameTag = "jobName"; + String serviceTag = "service"; + String handleTag = "handle"; + String providerTag = "provider"; + String computerTag = "computer"; + String softwareTag = "software"; + String programTag = "program"; + String JobSpecificationTag = "JobSpecification"; + String executableTag = "executable"; + String localExecutableTag = "localExecutable"; + String stdOutputTag = "stdOutput"; + String stdErrorTag = "stdError"; + String batchJobTag = "batchJob"; + String remoteDirectoryTag = "remoteDirectory"; + String localDirectoryTag = "localDirectory"; + String outputFilesTag = "outputFiles"; + String inputFilesTag = "inputFiles"; + String statusTag = "status"; + String overallJobStatusTag = "jobStatus"; + String submittedTimeTag = "submittedTime"; + + // Some specific tags + + Map firstLevelTags = new HashMap(); + Map serviceTags = new HashMap(); + Map JobSpecificationTags = new HashMap(); + + // --- member functions + + void setOutputFile(String tag, String value) throws Exception; + + void setServiceTag(String tag, String value, boolean overwrite) throws Exception; +} diff --git a/src/main/java/cct/grid/ClientProgramInterface.java b/src/main/java/cct/grid/ClientProgramInterface.java new file mode 100644 index 0000000..161c809 --- /dev/null +++ b/src/main/java/cct/grid/ClientProgramInterface.java @@ -0,0 +1,100 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid; + +import java.awt.Component; + +import cct.interfaces.FileChooserInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface ClientProgramInterface { + void enableInputFile(boolean enable); + + void enableLocalDir(boolean enable); + + String getCommandsAsString() throws Exception; + + String getInputFile(); + + String getJobName(); + + String getLocalDirectory(); + + String getOutputFile(); + + String getExecutable(); + + String getRemoteDirectory(); + + String getScriptFile(); + + String getSoftwareName(); + + String getStdoutFileName(); + + String getStderrFileName(); + + Component getVisualComponent(); + + void setCheckPointFile(CheckPoint chkp); + + void setInputFile(String inputFile); + + void setLocalDirectory(String localDir); + + void setRemoteDirectory(String remoteDir); + + void setRemoteFileChooser(FileChooserInterface fci); + + void setResourcesInterface(ResourcesProviderInterface resources); + + void setTaskProviderInterface(GridProviderInterface provider); + + void setJobDescription(JobDescription job) throws Exception; +} diff --git a/src/main/java/cct/grid/FileTransferInterface.java b/src/main/java/cct/grid/FileTransferInterface.java new file mode 100644 index 0000000..2d1b6ec --- /dev/null +++ b/src/main/java/cct/grid/FileTransferInterface.java @@ -0,0 +1,54 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface FileTransferInterface { + boolean tranferFile(String source, String destination, CheckPoint chkp); +} diff --git a/src/main/java/cct/grid/FileViewerInterface.java b/src/main/java/cct/grid/FileViewerInterface.java new file mode 100644 index 0000000..a922cf4 --- /dev/null +++ b/src/main/java/cct/grid/FileViewerInterface.java @@ -0,0 +1,54 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface FileViewerInterface { + void setFileInfo(CheckPoint chk, String fileName); +} diff --git a/src/main/java/cct/grid/GridProviderInterface.java b/src/main/java/cct/grid/GridProviderInterface.java new file mode 100644 index 0000000..25e0d17 --- /dev/null +++ b/src/main/java/cct/grid/GridProviderInterface.java @@ -0,0 +1,87 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid; + +import java.awt.Component; + +import cct.interfaces.FileChooserInterface; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006-2008

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface GridProviderInterface { + + String getCommandsAsString(); + + String getGatekeeper(); + + String getName(); + + OperationalSystems getOS(); + + String getRemoteHost(); + + FileChooserInterface getRemoteFileChooser(); + + boolean isRemoteDirectorySelectable(); + + Component getVisualComponent(); + + boolean isPassOptionsToScheduler(); + + String submitTask(JobDescription job) throws Exception; + + String getJobStatus(CheckPoint chkp) throws Exception; + + CheckPointInterface setCheckPoint(CheckPointInterface checkp); + + void killJob(CheckPoint chkp) throws Exception; + + boolean transferFile(String source, String destination, CheckPoint chkp) throws Exception; + + GridProviderInterface newInstance(); +} diff --git a/src/main/java/cct/grid/JobDescription.java b/src/main/java/cct/grid/JobDescription.java new file mode 100644 index 0000000..f98a09c --- /dev/null +++ b/src/main/java/cct/grid/JobDescription.java @@ -0,0 +1,948 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.grid; + +import java.io.BufferedReader; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class JobDescription + extends HashMap { + + // Local Declarations + final static String transferPrefix = "transfer"; + final static String PREPROCESS_DIRECTIVES = "preProcessDirectives"; + final static String POSTPROCESS_DIRECTIVES = "postProcessDirectives"; + final static String SERVICE_PROVIDER = "serviceProvider"; + final static String LOCAL_DIRECTORY = "localDirectory"; + final static String LOCAL_EXECUTABLE = "localExecutable"; + final static String ABS_PATH_EXECUTABLE = "absPathExecutable"; + final static String JOBFS = "jobfs"; + final static String SOFTWARE = "software"; + final static String PROVIDER_OBJECT = "providerObject"; + // Global Declarations + public final static String PBS_SCHEDULER = "pbs"; + final static String ARGUMENT = "argument"; + final static String COUNT = "count"; + final static String DIRECTORY = "directory"; + final static String ENVIRONMENT = "environment"; + final static String EXECUTABLE = "executable"; + final static String EXTENSIONS = "extensions"; + final static String FACTORYENDPOINT = "factoryEndpoint"; + final static String FILECLEANUP = "fileCleanUp"; + final static String FILESTAGEIN = "fileStageIn"; + final static String FILESTAGEOUT = "fileStageOut"; + final static String HOSTCOUNT = "hostCount"; + final static String JOB = "job"; + final static String JOBCREDENTIAL = "jobCredentialEndpoint"; + final static String JOBTYPE = "jobType"; + final static String LIBRARYPATH = "libraryPath"; + final static String MAXCPUTIME = "maxCpuTime"; + final static String MAXMEMORY = "maxMemory"; + final static String MAXTIME = "maxTime"; + final static String MAXWALLTIME = "maxWallTime"; + final static String MINMEMORY = "minMemory"; + final static String MULTIJOB = "multiJob"; + final static String PROJECT = "project"; + final static String QUEUE = "queue"; + final static String SERVICELEVEL = "serviceLevelAgreement"; + final static String STAGINGCREDENTIAL = "stagingCredentialEndpoint"; + final static String STDERR = "stderr"; + final static String STDIN = "stdin"; + final static String STDOUT = "stdout"; + // Other + final static String RESOURCE_ID = "ResourceID"; + final static String ADDRESS = "Address"; + final static String CLUSTER_ADDRESS = "clusterAddress"; + final static String SHELL = "shell"; + final static String ALLLORNONE = "allOrNone"; + final static String SOURCE_URL = "sourceUrl"; + final static String DESTINATION_URL = "destinationUrl"; + final static String USE_GASS = "useGASS"; + final static String PBS_JOB_SCRIPT = "pbsjobscript"; + final static String PBS_OTHER = "pbsother"; + // Transfer Request Type + final static String TRANSFER = "transfer"; + final static String MUL_PATTERN = ".*?@@MUL[(]\\d+?[.]{0,1}?\\d*?,\\d+?[.]{0,1}?\\d*?[)]@@.*?"; + final static String MUL_PATTERN_REPLACE = "@@MUL[(]\\d+?[.]{0,1}?\\d*?,\\d+?[.]{0,1}?\\d*?[)]@@"; + + public JobDescription() { + } + + public void setExecutable(String executable) { + put(EXECUTABLE, executable); + } + + public String getExecutable() { + Object obj = get(EXECUTABLE); + if (obj == null) { + return null; + } + return (String) obj; + } + + public void setPBSOther(String other) { + put(PBS_OTHER, other); + } + + public String getShell() { + Object obj = get(SHELL); + if (obj == null) { + return null; + } + return (String) obj; + } + + public void setShell(String other) { + put(SHELL, other); + } + + public String getPBSOther() { + Object obj = get(PBS_OTHER); + if (obj == null) { + return null; + } + return (String) obj; + } + + public void setPbsJobScript(boolean enable) { + put(PBS_JOB_SCRIPT, new Boolean(enable)); + } + + public boolean isPbsJobScript() { + Object obj = get(PBS_JOB_SCRIPT); + if (obj == null) { + return false; + } + return ((Boolean) obj).booleanValue(); + } + + public void setTaskProvider(String provider) { + put(SERVICE_PROVIDER, provider); + } + + public String getTaskProvider() { + Object obj = get(SERVICE_PROVIDER); + if (obj == null) { + return null; + } + return (String) obj; + } + + public void setTaskProviderObject(Object provider) { + put(PROVIDER_OBJECT, provider); + } + + public Object getTaskProviderObject() { + Object obj = get(PROVIDER_OBJECT); + if (obj == null) { + return null; + } + return obj; + } + + public void setRemoteDirectory(String dir) { + put( DIRECTORY, dir); + } + + public String getRemoteDirectory() { + Object obj = get(DIRECTORY); + if (obj == null) { + return null; + } + return (String) obj; + + } + + public void setStdout(String dir) { + put(STDOUT, dir); + } + + public String getStdout() { + Object obj = get(STDOUT); + if (obj == null) { + return null; + } + return (String) obj; + } + + public void setStderr(String dir) { + put(STDERR, dir); + } + + public String getStderr() { + Object obj = get(STDERR); + if (obj == null) { + return null; + } + return (String) obj; + } + + public void setJobName(String dir) { + put(JOB, dir); + } + + public String getJobName() { + Object obj = get(JOB); + if (obj == null) { + return null; + } + return (String) obj; + } + + public void setQueue(String dir) { + put(QUEUE, dir); + } + + public String getQueue() { + Object obj = get(QUEUE); + if (obj == null) { + return null; + } + return (String) obj; + + } + + public void setLocalDirectory(String dir) { + put( LOCAL_DIRECTORY, dir); + } + + public String getLocalDirectory() { + Object obj = get(LOCAL_DIRECTORY); + if (obj == null) { + return null; + } + return (String) obj; + } + + public void setNCPU(int ncpu) { + put(COUNT, new Integer(ncpu)); + } + + public int getNCPU() { + Object obj = get(COUNT); + if (obj == null) { + return 1; + } + return ((Integer) obj).intValue(); + } + + /** + * Time is in seconds + * @param time float + */ + public void setMaxWallTime(float time) { + int t = (int) time; + put(MAXWALLTIME, new Integer(t)); + } + + /** + * Time is in seconds + * @param time float + */ + public void setMaxWallTime(int time) { + put(MAXWALLTIME, new Integer(time)); + } + + public int getMaxWallTime() { + Object obj = get(MAXWALLTIME); + if (obj == null) { + return 0; + } + return ((Integer) obj).intValue(); + } + + /** + * Returns time in the format [[hours:]minutes:]seconds + * @return String + */ + public String getMaxWallTimeFormatted() { + Object obj = get(MAXWALLTIME); + if (obj == null) { + return "0"; + } + + int value = ((Integer) obj).intValue(); + String time = ""; + + if ((value / 3600) > 0) { + time += String.valueOf((value / 3600)) + ":"; + value -= (value / 3600) * 3600; // What left in minutes + if ((value / 60) > 0) { + String minutes = String.valueOf((value / 60)); + if (minutes.length() == 1) { + minutes = "0" + minutes; + } + time += minutes + ":"; + value -= (value / 60) * 60; // What left in seconds + time += value; + } else { + if (value >= 10) { + time += "00:" + value; + } else { + time += "00:0" + value; + } + } + } // --- Time is in minutes (and seconds) + else if ((value / 60) > 0) { + String minutes = String.valueOf((value / 60)); + if (minutes.length() == 1) { + minutes = "0" + minutes; + } + time += minutes + ":"; + value -= (value / 60) * 60; // What left in seconds + if (value >= 10) { + time += value; + } else { + time += "0" + value; + } + + } // --- Time in seconds only + else { + if (value >= 10) { + time += value; + } else { + time += "0" + value; + } + } + + return time; + } + + public void setMaxCpuTime(float time) { + put(MAXCPUTIME, new Float(time)); + } + + public float getMaxCpuTime() { + Object obj = get(MAXCPUTIME); + if (obj == null) { + return 0; + } + return ((Float) obj).floatValue(); + } + + public void setMaxTime(float time) { + put(MAXTIME, new Float(time)); + } + + public float getMaxTime() { + Object obj = get(MAXTIME); + if (obj == null) { + return 0; + } + return ((Float) obj).floatValue(); + } + + /** + * Memory is in MB + * @param mem int + */ + public void setMaxMemory(int mem) { + put(MAXMEMORY, new Integer(mem)); + } + + public int getMaxMemory() { + Object obj = get(MAXMEMORY); + if (obj == null) { + return 0; + } + return ((Integer) obj).intValue(); + } + + public void setProject(String proj) { + put(PROJECT, proj); + } + + public String getProject() { + Object obj = get(PROJECT); + if (obj == null) { + return null; + } + return (String) obj; + } + + public void setJobFS(int jobfs) { + put(JOBFS, new Integer(jobfs)); + } + + public int getJobFS() { + Object obj = get(JOBFS); + if (obj == null) { + return 0; + } + return ((Integer) obj).intValue(); + } + + public void setSoftware(String soft) { + put(SOFTWARE, soft); + } + + public String getSoftware() { + Object obj = get(SOFTWARE); + if (obj == null) { + return null; + } + return (String) obj; + } + + /** + * + * @param source String - Remote file + * @param destination String - Local file + */ + public void setFileStageIn(String source, String destination) { + Map stageIn = null; + if (!this.containsKey(FILESTAGEIN)) { + stageIn = new HashMap(); + put(FILESTAGEIN, stageIn); + } + + stageIn = (Map) get(FILESTAGEIN); + + Map transfer = new HashMap(2); + + transfer.put(SOURCE_URL, source); + transfer.put(DESTINATION_URL, destination); + + stageIn.put(transferPrefix + stageIn.size(), transfer); + + put(FILESTAGEIN, stageIn); + } + + /** + * + * @param source String - Local file + * @param destination String - Remote file + */ + public void setFileStageOut(String source, String destination) { + Map stageOut = null; + if (!this.containsKey(FILESTAGEOUT)) { + stageOut = new HashMap(); + put(FILESTAGEOUT, stageOut); + } + + stageOut = (Map) get(FILESTAGEOUT); + + Map transfer = new HashMap(2); + + transfer.put(SOURCE_URL, source); + transfer.put(DESTINATION_URL, destination); + + stageOut.put(transferPrefix + stageOut.size(), transfer); + + put(FILESTAGEOUT, stageOut); + } + + public void setScheduler(String scheduler) { + put(RESOURCE_ID, scheduler); + } + + public String getScheduler() { + Object obj = get(RESOURCE_ID); + if (obj == null) { + return null; + } + return (String) obj; + } + + public void setRemoteHost(String host) { + put(ADDRESS, host); + } + + public void setClusterAddress(String host) { + put(CLUSTER_ADDRESS, host); + } + + public String getRemoteHost() { + Object obj = get(ADDRESS); + if (obj == null) { + return null; + } + return (String) obj; + } + + public String getClusterAddress() { + Object obj = get(CLUSTER_ADDRESS); + if (obj == null) { + return null; + } + return (String) obj; + } + + public void enableGASS(boolean enable) { + put(USE_GASS, new Boolean(enable)); + } + + public boolean isGASSEnabled() { + Object obj = get(USE_GASS); + if (obj == null) { + return false; + } + return ((Boolean) obj).booleanValue(); + } + + /** + * Returns number of files for staging in + * @return int - number of files for staging in + */ + public int getFileStageInCount() { + if (!this.containsKey(FILESTAGEIN)) { + return 0; + } + + Map stageIn = (Map) get(FILESTAGEIN); + + int count = 0; + Set set = stageIn.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Entry me = (Entry) iter.next(); + String targetKey = me.getKey().toString(); + if (targetKey.startsWith(transferPrefix)) { + ++count; + } + } + + return count; + } + + /** + * Returns source and destination files + * @param n int - 0 <= n < getFileStageInCount() + * @return String[] - index 0 - destination file (remote) + * index 1 - source file (local) + */ + public String[] getFileStageIn(int n) { + if (n < 0 || n >= getFileStageInCount()) { + System.err.println("getFileStageIn: Internal Error: n < 0 || n >= getFileStageInCount() - Ignored..."); + return null; + } + + Map stageIn = (Map) get(FILESTAGEIN); + + String key = transferPrefix + n; + if (!stageIn.containsKey(key)) { + System.err.println("getFileStageIn: Internal Error: !stageIn.containsKey(" + key + ") - Ignored..."); + return null; + } + + Map transfer = (Map) stageIn.get(key); + String[] files = new String[2]; + files[0] = transfer.get(SOURCE_URL).toString(); + files[1] = transfer.get(DESTINATION_URL).toString(); + + return files; + } + + /** + * Adds argument for the executable + * @param argument String + */ + public void addArgument(String argument) { + List arguments = null; + if (!this.containsKey(ARGUMENT)) { + arguments = new ArrayList(); + put(ARGUMENT, arguments); + } + + arguments = (List) get(ARGUMENT); + + arguments.add(argument); + + put(ARGUMENT, arguments); + } + + /** + * Returns number of arguments + * @return int + */ + public int getArgumentCount() { + if (!this.containsKey(ARGUMENT)) { + return 0; + } + + List arguments = (List) get(ARGUMENT); + + return arguments.size(); + } + + /** + * Returns n-th argument + * @param n int + * @return String + */ + public String getArgument(int n) { + if (n < 0 || n >= getArgumentCount()) { + System.err.println( + "getArgument: Internal Error: n < 0 || n >= getArgumentCount() - Ignored..."); + return null; + } + + List arguments = (List) get(ARGUMENT); + + return (String) arguments.get(n); + } + + public void setLocalExecutable(boolean local) { + put(LOCAL_EXECUTABLE, new Boolean(local)); + } + + public void setAbsPathExecutable(boolean local) { + put(ABS_PATH_EXECUTABLE, new Boolean(local)); + } + + public boolean isAbsPathExecutable() { + Object obj = get(ABS_PATH_EXECUTABLE); + if (obj == null) { + return false; + } + return ((Boolean) obj).booleanValue(); + } + + public boolean isLocalExecutable() { + Object obj = get(LOCAL_EXECUTABLE); + if (obj == null) { + return false; + } + return ((Boolean) obj).booleanValue(); + } + + public void addPreprocessDirective(String argument) { + List arguments = null; + if (!this.containsKey(PREPROCESS_DIRECTIVES)) { + arguments = new ArrayList(); + put(PREPROCESS_DIRECTIVES, arguments); + } + + arguments = (List) get(PREPROCESS_DIRECTIVES); + + arguments.add(argument); + + put(PREPROCESS_DIRECTIVES, arguments); + } + + /** + * Returns number of preprocess directives + * @return int + */ + public int getPreprocessDirCount() { + if (!this.containsKey(PREPROCESS_DIRECTIVES)) { + return 0; + } + + List arguments = (List) get(PREPROCESS_DIRECTIVES); + + return arguments.size(); + } + + public String getPreprocessDir(int n) { + if (n < 0 || n >= getPreprocessDirCount()) { + System.err.println( + "getPreprocessDir: Internal Error: n < 0 || n >= getPreprocessDirCount() - Ignored..."); + return null; + } + + List arguments = (List) get(PREPROCESS_DIRECTIVES); + + return (String) arguments.get(n); + } + + public static String createRunScript(GridProviderInterface provider, SchedulerInterface scheduler, + ClientProgramInterface program) throws Exception { + + StringWriter sWriter = new StringWriter(); + + // --- Get command(s) from task provider + + sWriter.write(provider.getCommandsAsString()); + + // --- Get scheduler-specific commands + + sWriter.write(scheduler.getCommandsAsString()); + + // --- Get program-specific commands + + sWriter.write(program.getCommandsAsString()); + + sWriter.close(); + return sWriter.toString(); + } + + /** + * + * @param job JobDescription + * @throws Exception + */ + public static String createUnixScript(JobDescription job, SchedulerInterface scheduler) throws Exception { + StringWriter sWriter = new StringWriter(); + + if (job.getShell() != null) { + sWriter.write("#!" + job.getShell() + "\n"); // --- Shell + } + + // --- Get scheduler-specific commands + + sWriter.write(scheduler.getCommandsAsString()); + + // --- Commands to be executed before main job + + if (job.getPreprocessDirCount() > 0) { + for (int i = 0; i < job.getPreprocessDirCount(); i++) { + sWriter.write(job.getPreprocessDir(i) + "\n\n"); + } + } + + // --- Main command + + sWriter.write("echo 'Running " + job.getExecutable() + "'\n"); + + if (job.getExecutable() != null) { + sWriter.write(job.getExecutable()); + } + + // --- its arguments + + if (job.getArgumentCount() > 0) { + sWriter.write(" " + job.getArgument(0)); + for (int i = 1; i < job.getArgumentCount(); i++) { + sWriter.write(" \\\n " + job.getArgument(i)); + } + sWriter.write("\n\n"); + } else { + sWriter.write("\n\n"); + } + + sWriter.write("echo 'Finish Running " + job.getExecutable() + "'\n"); + + sWriter.close(); + return sWriter.toString(); + } + + public static String createUnixScript(JobDescription job) throws Exception { + StringWriter sWriter = new StringWriter(); + + if (job.getShell() != null) { + sWriter.write("#!" + job.getShell() + "\n"); // --- Shell + } + + if (job.getScheduler() != null && job.getScheduler().equalsIgnoreCase("pbs")) { + + if (job.getProject() != null && job.getProject().length() > 0) { + sWriter.write("#PBS -P " + job.getProject() + "\n"); + } + if (job.getQueue() != null) { + sWriter.write("#PBS -q " + job.getQueue() + "\n"); + } + if (job.getMaxWallTime() != 0) { + sWriter.write("#PBS -l walltime=" + job.getMaxWallTimeFormatted() + + "\n"); + } + if (job.getMaxMemory() != 0) { + sWriter.write("#PBS -l vmem=" + job.getMaxMemory() + "MB\n"); + } + if (job.getSoftware() != null) { + sWriter.write("#PBS -l software=" + job.getSoftware() + "\n"); + } + if (job.getJobFS() != 0) { + sWriter.write("#PBS -l jobfs=" + job.getJobFS() + "Gb\n"); + } + + if (job.getPBSOther() != null) { + sWriter.write("#PBS -l other=" + job.getPBSOther() + "\n"); + } + if (job.getNCPU() != 0) { + sWriter.write("#PBS -l ncpus=" + job.getNCPU() + "\n"); + } + if (job.getStdout() != null) { + sWriter.write("#PBS -o " + job.getStdout() + "\n"); + } + if (job.getStderr() != null) { + sWriter.write("#PBS -e " + job.getStderr() + "\n"); + } + + sWriter.write("#PBS -wd\n\n"); + + } + + // --- Commands to be executed before main job + + if (job.getPreprocessDirCount() > 0) { + for (int i = 0; i < job.getPreprocessDirCount(); i++) { + sWriter.write(job.getPreprocessDir(i) + "\n\n"); + } + } + + // --- Main command + + sWriter.write("echo 'Running " + job.getExecutable() + "'\n"); + + if (job.getExecutable() != null) { + sWriter.write(job.getExecutable()); + } + + // --- its arguments + + if (job.getArgumentCount() > 0) { + sWriter.write(" " + job.getArgument(0)); + for (int i = 1; i < job.getArgumentCount(); i++) { + sWriter.write(" \\\n " + job.getArgument(i)); + } + sWriter.write("\n\n"); + } else { + sWriter.write("\n\n"); + } + + sWriter.write("echo 'Finish Running " + job.getExecutable() + "'\n"); + + sWriter.close(); + return sWriter.toString(); + } + + public static String createUnixScript(JobDescription job, String template, Map patterns) throws Exception { + StringWriter sWriter = new StringWriter(); + BufferedReader in = new BufferedReader(new StringReader(template)); + String line; + while ((line = in.readLine()) != null) { + + // --- First replace static constants, if any... + + if (line.matches(".*?@@.+?@@.*?")) { + Iterator it = patterns.keySet().iterator(); + while (it.hasNext()) { + String key = it.next(); + String val = patterns.get(key); + line = line.replaceAll(key, val); + } + } + + // --- Now replace math operators, if any + + while (line.matches(MUL_PATTERN)) { + line = doMul(line); + } + + sWriter.write(line + "\n"); + } + sWriter.close(); + return sWriter.toString(); + } + + public static String doMul(String line) throws Exception { + String result = null; + int start = line.indexOf("@@MUL("); + if (start == -1) { + return result; + } + int end = line.indexOf(")@@"); + if (end == -1) { + throw new Exception("Didn't find end of expression )@@"); + } + + String args = line.substring(start + "@@MUL(".length(), end); + String twoArgs[] = args.split("[ ,\t]"); + if (twoArgs.length != 2) { + throw new Exception("Expected two args divided by comma, got " + args); + } + + boolean isFirstInteger = false; + int firstInt = 0; + try { + firstInt = Integer.parseInt(twoArgs[0]); + isFirstInteger = true; + } catch (Exception ex) { + } + + + double first = 0.0; + if (!isFirstInteger) { + try { + first = Double.parseDouble(twoArgs[0]); + } catch (Exception ex) { + throw new Exception("Expected the float or int type for the first argument, got " + args); + } + } + + boolean isSecondInteger = false; + int secondInt = 0; + try { + secondInt = Integer.parseInt(twoArgs[1]); + isSecondInteger = true; + } catch (Exception ex) { + } + + double second = 0.0; + if (!isSecondInteger) { + try { + second = Double.parseDouble(twoArgs[1]); + } catch (Exception ex) { + throw new Exception("Expected the float or int type for the second argument, got " + args); + } + } + + if (isFirstInteger && isSecondInteger) { + result = String.valueOf(firstInt * secondInt); + } else if (isFirstInteger) { + result = String.valueOf((double) firstInt * second); + } else if (isSecondInteger) { + result = String.valueOf(first * (double) secondInt); + } else { + result = String.valueOf(first * second); + } + + result = line.replaceFirst(MUL_PATTERN_REPLACE, result); + + return result; + } +} diff --git a/src/main/java/cct/grid/JobStatusInterface.java b/src/main/java/cct/grid/JobStatusInterface.java new file mode 100644 index 0000000..ad2877b --- /dev/null +++ b/src/main/java/cct/grid/JobStatusInterface.java @@ -0,0 +1,69 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid; + +import cct.tools.ui.JobProgressInterface; + + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface JobStatusInterface { + String[] getColumnNames(); + + CheckPoint getCheckPoint(int n); + + Object[][] getData(); + + void killSelectedJobs(int[] jobsToKill); + + void removeSelectedCheckpoints(int[] jobsToRemove); + + void downloadRemoteFiles(int[] jobsWithDownloads); + + void setJobProgressInterface(JobProgressInterface jpi); +} diff --git a/src/main/java/cct/grid/LocalServiceProvider.java b/src/main/java/cct/grid/LocalServiceProvider.java new file mode 100644 index 0000000..41f92c2 --- /dev/null +++ b/src/main/java/cct/grid/LocalServiceProvider.java @@ -0,0 +1,354 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.grid; + +import java.awt.Component; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.StringWriter; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import javax.swing.JPanel; + +import cct.interfaces.FileChooserInterface; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class LocalServiceProvider + implements GridProviderInterface { + + protected JPanel nativeDialog = new JPanel(); + String osName = "Linux"; + boolean windowsOS = false; + static final Logger logger = Logger.getLogger(LocalServiceProvider.class.getCanonicalName()); + + public LocalServiceProvider() { + try { + osName = System.getProperty("os.name"); + if (osName.toUpperCase().contains("WINDOWS")) { + windowsOS = true; + } + } catch (SecurityException e) { + System.err.println("Cannot get OS type : " + e.getMessage() + + " Assuming Linux"); + // Ignore it + } + + } + private boolean interactive = true; + private boolean overwiteAlways = true; + private String jobHandle; + private int jobID = -1; + + public void submitJob(JobDescription job) throws Exception { + + // --- Checking whether executable exists + + String path = null; + if (job.isAbsPathExecutable()) { + path = job.getExecutable(); + } else if (job.isLocalExecutable()) { + //path = job.getLocalDirectory() + File.separator + job.getExecutable(); + path = job.getLocalDirectory() + "/" + job.getExecutable(); + } else { + //path = job.getRemoteDirectory() + File.separator + job.getExecutable(); + path = job.getRemoteDirectory() + "/" + job.getExecutable(); + } + + File exec = new File(path); + + // --- Check for it's existence + + if (!exec.exists()) { + throw new Exception("Executable " + path + " does not exists"); + } + + // --- Check existence of a remote directory + + File remoteDir = new File(job.getRemoteDirectory()); + + if (!remoteDir.exists()) { + throw new Exception("Working directory " + job.getRemoteDirectory() + + " does not exists"); + } + + boolean isDir = remoteDir.isDirectory(); + if (!isDir) { + throw new Exception(job.getRemoteDirectory() + + " should be a directory"); + } + + // --- Check staging in (copying files to remote directory + + for (int i = 0; i < job.getFileStageInCount(); i++) { + String[] files = job.getFileStageIn(i); + String inPath = job.getLocalDirectory() + "/" + files[1]; + File in = new File(inPath); + if (!in.exists()) { + throw new Exception("Input file " + inPath + " does not exists"); + } + + String destPath = job.getRemoteDirectory() + "/" + files[0]; + File dest = new File(destPath); + + // --- Skip check in remote directory for the file with the same name + + try { + copy(in, dest); + } catch (Exception ex) { + throw new Exception("Error transfering " + inPath + " to " + + destPath + + " : " + ex.getMessage()); + } + } + + try { + // Execute a command without arguments + String command = null; + if (job.getScheduler() != null + && job.getScheduler().equalsIgnoreCase(JobDescription.PBS_SCHEDULER)) { + command = "qsub " + job.getExecutable(); + } else { + command = job.getExecutable(); + } + //Process child = Runtime.getRuntime().exec(command, null, remoteDir); + String[] cmdarray = new String[2]; + cmdarray[0] = "C:/MOPAC2000/mopac2002.exe"; + cmdarray[1] = "bpti.dat"; + Process child = Runtime.getRuntime().exec(cmdarray, null, remoteDir); + child.waitFor(); + logger.info("Exit code: " + child.exitValue()); + // Get the output stream and read from it + + + InputStream err = child.getErrorStream(); + + // Get the input stream and read from it + InputStream in = child.getInputStream(); + int c; + StringWriter outWriter = new StringWriter(); + logger.info("Output stream:"); + while ((c = in.read()) != -1) { + outWriter.write(c); + System.out.print((char) c); + } + in.close(); + outWriter.close(); + + logger.info("Stderr stream:"); + StringWriter errWriter = new StringWriter(); + while ((c = err.read()) != -1) { + errWriter.write(c); + System.err.print((char) c); + } + err.close(); + errWriter.close(); + String stderr = errWriter.toString(); + if (stderr.length() > 0) { + throw new Exception(stderr); + } + + // Inspect stdout for the job handle in the case of PBS + if (job.getScheduler() != null && job.getScheduler().equalsIgnoreCase(JobDescription.PBS_SCHEDULER)) { + String stdout = outWriter.toString(); + if (stdout.length() < 1) { + throw new Exception("No job identifier was returned"); + } + + StringTokenizer st = new StringTokenizer(stdout, " .", true); + // Look for a number + while (st.hasMoreTokens()) { + try { + int number = Integer.parseInt(st.nextToken()); + jobHandle = String.valueOf(number); + jobID = number; + return; + } catch (Exception ex) { + } + } + } + + } catch (IOException e) { + throw e; + } + + // --- If we are here - there is an error + if (job.getScheduler() != null && job.getScheduler().equalsIgnoreCase(JobDescription.PBS_SCHEDULER)) { + throw new Exception("No job identifier was returned"); + } + } + + public String getJobHandle() { + return jobHandle; + } + + // Copies src file to dst file. + // If the dst file does not exist, it is created + private void copy(File src, File dst) throws IOException { + InputStream in = new FileInputStream(src); + OutputStream out = new FileOutputStream(dst); + + // Transfer bytes from in to out + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + in.close(); + out.close(); + } + + // implementation of GridProviderInterface functions + @Override + public String getName() { + return "local"; + } + + @Override + public Component getVisualComponent() { + return nativeDialog; + } + + @Override + public FileChooserInterface getRemoteFileChooser() { + return null; + } + + @Override + public String getRemoteHost() { + return null; + } + + @Override + public boolean isPassOptionsToScheduler() { + return true; + } + + @Override + public String submitTask(JobDescription job) throws Exception { + submitJob(job); + System.err.println(this.getClass().getName() + + ": Warning : Job Handle is not set..."); + return null; + } + + @Override + public String getCommandsAsString() { + if (windowsOS) { + return ""; + } + return "#!sh\n"; + } + + @Override + public OperationalSystems getOS() { + if (windowsOS) { + return OperationalSystems.WindowsOS; + } + return OperationalSystems.Linux; // !!! + } + + @Override + public String getGatekeeper() { + return null; + } + + @Override + public CheckPointInterface setCheckPoint(CheckPointInterface checkp) { + return checkp; + } + + @Override + public String getJobStatus(CheckPoint chkp) throws Exception { + return "getJobStatus is not implemented yet for Local provider"; + } + + @Override + public void killJob(CheckPoint chkp) throws Exception { + throw new Exception("Kill Job is not implemented for local provider"); + } + + @Override + public boolean isRemoteDirectorySelectable() { + return true; + } + + public boolean transferFile(String source, String destination) throws Exception { + throw new Exception("transferFile is not implemented for local provider"); + } + + @Override + public boolean transferFile(String source, String destination, CheckPoint chkp) throws Exception { + throw new Exception("transferFile is not implemented for local provider"); + } + + public static void main(String[] args) { + JobDescription job = new JobDescription(); + job.setExecutable("C:/MOPAC2000/mopac2002.exe"); + job.setAbsPathExecutable(true); + job.setLocalDirectory("C:/MOPAC2000"); + job.setRemoteDirectory("C:/TEMP"); + job.setFileStageIn("bpti.dat", "bpti.dat"); + + LocalServiceProvider provider = new LocalServiceProvider(); + try { + provider.submitJob(job); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + @Override + public GridProviderInterface newInstance() { + return new LocalServiceProvider(); + } +} diff --git a/src/main/java/cct/grid/MalformedCheckPointException.java b/src/main/java/cct/grid/MalformedCheckPointException.java new file mode 100644 index 0000000..937d827 --- /dev/null +++ b/src/main/java/cct/grid/MalformedCheckPointException.java @@ -0,0 +1,60 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class MalformedCheckPointException + extends Exception { + public MalformedCheckPointException() { + } + + public MalformedCheckPointException(String message) { + super(message); + } +} diff --git a/src/main/java/cct/grid/OperationalSystems.java b/src/main/java/cct/grid/OperationalSystems.java new file mode 100644 index 0000000..98d5b1a --- /dev/null +++ b/src/main/java/cct/grid/OperationalSystems.java @@ -0,0 +1,56 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public enum OperationalSystems { + WindowsOS, MacOS, Linux; + OperationalSystems() { + } +} diff --git a/src/main/java/cct/grid/PBSJobStatus.java b/src/main/java/cct/grid/PBSJobStatus.java new file mode 100644 index 0000000..c89f5d4 --- /dev/null +++ b/src/main/java/cct/grid/PBSJobStatus.java @@ -0,0 +1,163 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid; + +import java.io.BufferedReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class PBSJobStatus { + + String Job_Name = null; + String Job_Owner = null; + String job_state = null; + String queue = null; + String server = null; + String Account_Name = null; + Map resourcesUsed = new HashMap(); + + public PBSJobStatus() { + } + + /** + * Parses a full status display in (qstat -f xxx) the form: + * > qstat -f 598103.ac-pbs + Job Id: 598103.ac-pbs + Job_Name = pbs.eq36smd + Job_Owner = pcc562@ac + job_state = H + queue = normal + server = ac-pbs + Account_Name = f91 + Checkpoint = u + ctime = Mon Jul 31 14:24:56 2006 + depend = afterok:598101.ac-pbs@ac-pbs + Error_Path = ac:/short/f91/poker/toxSMD/pbs.eq36smd.e598103 + group_list = f91 + Hold_Types = s + Join_Path = oe + Keep_Files = n + Mail_Points = a + mtime = Mon Jul 31 14:24:56 2006 + Output_Path = ac:/short/f91/poker/toxSMD/pbs.eq36smd.o598103 + Priority = 25 + qtime = Mon Jul 31 14:24:56 2006 + Rerunable = False + Resource_List.jobfs = 100mb + Resource_List.ncpus = 32 + Resource_List.nodect = 32 + Resource_List.nodes = 32:ppn=1 + Resource_List.other = mpi + Resource_List.software = namd + Resource_List.vmem = 6000mb + Resource_List.walltime = 08:29:00 + Shell_Path_List = /bin/bash + Variable_List = PBS_O_HOME=/home/562/pcc562,PBS_O_LOGNAME=pcc562, + PBS_O_PATH=/opt/grace-5.1.18/grace/bin:/opt/nedit-5.5/bin:/opt/vmd-1.8 + .2/bin:/opt/netpbm-10.26.26/bin:/opt/intel-cc/8.1.035/bin:/opt/intel-fc + /8.1.031/bin:/opt/anumpirun/2.1.14/bin:/opt/mpt-1.12/bin:/opt/pbs/bin:/ + opt/rash/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/bin:.:/opt/lesstif-0.93 + .94/gcc-3.3.3/bin:/home/562/pcc562/scripts:./, + PBS_O_MAIL=/var/mail/pcc562,PBS_O_SHELL=/bin/bash,PBS_O_HOST=ac, + PBS_O_WORKDIR=/short/f91/poker/toxSMD,PROJECT=f91,PBS_O_QUEUE=normal + cwd = 1 + + + * @return PBSJobStatus + */ + public String parsePBSJobStatus(BufferedReader in) throws Exception { + String line; + String value = "Unknown"; + try { + while ( (line = in.readLine()) != null) { + if (line.matches("(?i).*job_state.*=.*")) { + value = getValue(line); + + } + else if (line.matches("(?i).*resources_used.*=.*")) { + String key = line.substring(0, line.indexOf("=")).trim(); + String temp = line.substring(line.indexOf("=") + 1, line.length()).trim(); + resourcesUsed.put(key, temp); + } + } // --- End of while + return value; + } + catch (IOException e) { + System.err.println(e.getMessage()); + throw e; + //return error; + } + //return null; + } + + /** + * Parsing line of a PBS full display output, for example: job_state = R and returning "R" + * @param line String + * @return String + */ + public String getValue(String line) { + if (line.indexOf("=") == -1) { + return null; + } + else if (line.indexOf("=") >= line.length()) { + return null; + } + return line.substring(line.indexOf("=") + 1).trim(); + } + + public Map getResourcesUsed() { + return resourcesUsed; + } + + public static void main(String[] args) { + PBSJobStatus pbsjobstatus = new PBSJobStatus(); + } +} diff --git a/src/main/java/cct/grid/ParseCheckpointFile.java b/src/main/java/cct/grid/ParseCheckpointFile.java new file mode 100644 index 0000000..14da680 --- /dev/null +++ b/src/main/java/cct/grid/ParseCheckpointFile.java @@ -0,0 +1,1097 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.grid; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.StringWriter; +import java.io.Writer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.logging.Logger; + +import javax.swing.Timer; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; +import org.xml.sax.helpers.DefaultHandler; + +import cct.tools.IOUtils; +import cct.tools.ui.JobProgressInterface; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class ParseCheckpointFile { + + static String checkPointFile = "checkpoint.xml"; + static final String CHECKPOINT_FILE = "checkpointFile"; + /* + final static HashMap firstLevelTags = CheckPoint.getCheckPointSpecifications(); + final static HashMap serviceTags = (HashMap)firstLevelTags.get(serviceTag); + final static HashMap JobSpecificationTags = (HashMap)firstLevelTags.get(JobSpecificationTag); + */ + static boolean debug = false; + boolean finish_parsing = false; + boolean yes_tasks = false; + boolean yes_parsing_task = false; + int parseLevel = 0; + static String Message = ""; + String currentTag = null; + List tasks = new ArrayList(); + CheckPoint checkPoint = null; + //HashMap taskEntries = null; + Map serviceEntries = null; + Map jobSpecificationEntries = null; + Map outputFilesEntries = null; + static private Writer out; + private JobProgressInterface progress = null; + private StatusUpdateTask statusUpdateTask; + private int queryTime = 60000; + static final Logger logger = Logger.getLogger(JobProgressInterface.class.getCanonicalName()); + + public void setJobProgressInterface(JobProgressInterface jpi) { + progress = jpi; + } + + public int getQueryTime() { + return queryTime; + } + + public void setQueryTime(int queryTime) { + this.queryTime = queryTime; + } + + public JobProgressInterface getProgress() { + return progress; + } + + public void setProgress(JobProgressInterface progress) { + this.progress = progress; + } + + public ParseCheckpointFile() { + } + + public void parseCheckpointFile() throws Exception { + String checkpf = ""; + try { + checkpf = getCheckPointFile(); + } catch (Exception ex) { + throw ex; + } + parseCheckpointFile(checkpf); + } + + public List getTasks() { + return tasks; + } + + public void parseCheckpointFile(String file_name) { + Message = ""; + + File chk = new File(file_name); + if (!chk.exists()) { + List temp = new ArrayList(); + try { + saveCheckPointFile(temp, file_name); + } catch (Exception ex) { + System.err.println("Error: Cannot create checkpoint file: " + file_name + + " : " + ex.getMessage()); + } + } + + // --- Using DOM + try { + // Create a factory + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + // Use the factory to create a builder + DocumentBuilder builder = factory.newDocumentBuilder(); + Document doc = builder.parse(chk); + // Get a list of all elements in the document + NodeList list = doc.getElementsByTagName(CheckPointInterface.taskTag); + for (int i = 0; i < list.getLength(); i++) { + checkPoint = new CheckPoint(); + serviceEntries = new HashMap(); + jobSpecificationEntries = new HashMap(); + outputFilesEntries = new HashMap(); + + // Get element + Node node = list.item(i); + if (debug) { + logger.info(node.getNodeName() + " : " + node.getNodeValue()); + } + + NodeList taskNodes = node.getChildNodes(); + for (int j = 0; j < taskNodes.getLength(); j++) { + Node taskNode = taskNodes.item(j); + if (debug) { + logger.info("Node: " + taskNode.getNodeName() + " Text content: " + taskNode.getTextContent()); + } + if (taskNode.getNodeName().startsWith("#")) { + continue; + } + + if (taskNode.getNodeName().equals(CheckPointInterface.serviceTag)) { // Service tag + NodeList serviceNodes = taskNode.getChildNodes(); + for (int k = 0; k < serviceNodes.getLength(); k++) { + Node serviceNode = serviceNodes.item(k); + if (serviceNode.getNodeName().startsWith("#")) { + continue; + } + + serviceEntries.put(serviceNode.getNodeName(), serviceNode.getTextContent()); + if (debug) { + logger.info(" " + CheckPointInterface.serviceTag + ": " + serviceNode.getNodeName() + " : " + + serviceNode.getTextContent()); + } + } + } else if (taskNode.getNodeName().equals(CheckPointInterface.JobSpecificationTag)) { // JobSpecification tag + NodeList jsNodes = taskNode.getChildNodes(); + for (int k = 0; k < jsNodes.getLength(); k++) { + Node jsNode = jsNodes.item(k); + if (jsNode.getNodeName().startsWith("#")) { + continue; + } + + if (jsNode.getNodeName().equals(CheckPointInterface.outputFilesTag)) { // outputFiles tag + NodeList outFilesNodes = jsNode.getChildNodes(); + for (int kk = 0; kk < outFilesNodes.getLength(); kk++) { + Node outNode = outFilesNodes.item(kk); + if (outNode.getNodeName().startsWith("#")) { + continue; + } + outputFilesEntries.put(outNode.getNodeName(), outNode.getTextContent()); + if (debug) { + logger.info(" " + CheckPointInterface.outputFilesTag + ": " + outNode.getNodeName() + " : " + + outNode.getTextContent()); + } + } + } else { + jobSpecificationEntries.put(jsNode.getNodeName(), jsNode.getTextContent()); + if (debug) { + logger.info(" " + CheckPointInterface.JobSpecificationTag + ": " + jsNode.getNodeName() + " : " + + jsNode.getTextContent()); + } + } + } + } else { + checkPoint.put(taskNode.getNodeName(), taskNode.getTextContent()); + if (debug) { + logger.info(CheckPointInterface.taskTag + ": " + taskNode.getNodeName() + " : " + + taskNode.getTextContent()); + } + } + } + + /* + Element element = (Element) list.item(i); + logger.info(element.getNodeName()); + NodeList childNodes = element.getChildNodes(); + + NodeList serviceNode = element.getElementsByTagName(serviceTag); + if (serviceNode.getLength() > 0) { + Element childElement = (Element) serviceNode.item(0); + logger.info(childElement.getNodeName()); + NodeList serviceNodes = childElement.getElementsByTagName(handleTag); + if (serviceNodes.getLength() > 0) { + childElement = (Element) serviceNodes.item(0); + serviceEntries.put(childElement.getNodeName(), childElement.getNodeValue()); + } + } + + for (int j = 0; j < childNodes.getLength(); j++) { + Object obj = childNodes.item(j); + logger.info(obj.getClass().getCanonicalName()); + Element childElement = (Element) childNodes.item(j); + logger.info(childElement.getNodeName()); + + if (childElement.getNodeName().equals(serviceTag)) { // "service" tag + NodeList serviceNodes = childElement.getChildNodes(); + for (int k = 0; k < serviceNodes.getLength(); k++) { + Element serviceElement = (Element) serviceNodes.item(k); + logger.info(serviceElement.getNodeName()); + serviceEntries.put(serviceElement.getNodeName(), serviceElement.getNodeValue()); + } + } + } + */ + + checkPoint.put(CheckPointInterface.serviceTag, serviceEntries); + jobSpecificationEntries.put(CheckPointInterface.outputFilesTag, outputFilesEntries); + checkPoint.put(CheckPointInterface.JobSpecificationTag, jobSpecificationEntries); + tasks.add(checkPoint); + } + + } catch (Exception ex) { + ex.printStackTrace(); + } + + if (true) { + return; + } + + // --- Using SAX... + + if (file_name.endsWith(".xml") || file_name.endsWith(".XML")) { + // Use an instance of ourselves as the SAX event handler + DefaultHandler handler = new HandleSAXEvents(); + // Use the default (non-validating) parser + SAXParserFactory factory = SAXParserFactory.newInstance(); + + try { + // Set up output stream + out = new OutputStreamWriter(System.out, "UTF8"); + + // Parse the input + SAXParser saxParser = factory.newSAXParser(); + saxParser.parse(new File(file_name), handler); + + } catch (Throwable t) { + //logger.error("Parsing error " + t.getMessage()); + t.printStackTrace(); + } + } + } + + public static String CreateCheckpointString(List Tasks) { + String Content = ""; + Message = ""; + StringWriter sWriter = new StringWriter(); + + StreamResult streamResult = new StreamResult(sWriter); + SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance(); + + // SAX2.0 ContentHandler. + TransformerHandler hd = null; + try { + hd = tf.newTransformerHandler(); + } catch (TransformerConfigurationException e) { + Message = e.getMessage(); + System.err.println(e.getMessage()); + return null; + } + Transformer serializer = hd.getTransformer(); + //serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); + //serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "users.dtd"); + serializer.setOutputProperty(OutputKeys.INDENT, "yes"); + hd.setResult(streamResult); + try { + hd.startDocument(); + AttributesImpl atts = new AttributesImpl(); + //atts.addAttribute("","","ID","CDATA",id[i]); + //atts.addAttribute("","","TYPE","CDATA",type[i]); + + // TASKS tag. + hd.startElement("", "", CheckPointInterface.tasksTag, atts); + + for (int i = 0; i < Tasks.size(); i++) { + Map Level_1 = (Map) Tasks.get(i); + atts.clear(); + hd.startElement("", "", CheckPointInterface.taskTag, atts); + + //if (!createElements(hd, firstLevelTags, Level_1)) { + if (!createElements(hd, CheckPoint.getCheckPointSpecifications(), Level_1)) { + return null; + } + + hd.endElement("", "", CheckPointInterface.taskTag); + } + + hd.endElement("", "", CheckPointInterface.tasksTag); + hd.endDocument(); + + } catch (SAXException e) { + Message = e.getMessage(); + System.err.println(e.getMessage()); + return null; + } + + return sWriter.toString(); + } + + static public boolean createElements(TransformerHandler hd, Map list, Map elements) { + AttributesImpl atts = new AttributesImpl(); + Set set = list.entrySet(); + Iterator iter = set.iterator(); + //Iterator iter = list.iterator(); + try { + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String keyWord = me.getKey().toString(); + Object type = me.getValue(); + if (debug) { + logger.info("Parsing: " + keyWord); + } + + if (!elements.containsKey(keyWord)) { + if (debug) { + logger.info(" No such key in elements. Continuing..."); + } + continue; + } + + atts.clear(); + + hd.startElement("", "", keyWord, atts); + + Object obj = elements.get(keyWord); + + if (type instanceof Map) { + if (debug) { + logger.info(" Key is an entry..."); + } + if (obj instanceof Map) { + Map parent = (Map) type; + Map child = (Map) obj; + if (!createElements(hd, parent, child)) { + return false; + } + } else { + Message += + "Instance of user's HashMap different from the reference one"; + System.err.println(Message); + return false; + } + } else { + Object xxx = elements.get(keyWord); + if (debug) { + logger.info(" Key is a value: " + xxx.toString()); + } + String value = (String) elements.get(keyWord); + hd.characters(value.toCharArray(), 0, value.length()); + } + + hd.endElement("", "", keyWord); + } + } catch (SAXException e) { + Message = e.getMessage(); + System.err.println(e.getMessage()); + return false; + } + return true; + } + + public static String getCheckPointFile() throws Exception { + + // --- + + try { + Properties props = cct.GlobalSettings.getCustomProperties(); + + //--- Checkpoint file location + + if (props != null) { + String checkpoint = props.getProperty(CHECKPOINT_FILE); + if (checkpoint != null) { + if (checkpoint.endsWith("/")) { + return checkpoint + checkPointFile; + } + return checkpoint; + } + } + } catch (Exception ex) { + logger.warning("Cannot get checkpoint file location from the custom properties file : " + ex.getMessage()); + } + + String baseDir = ""; + try { + baseDir = cct.tools.Utils.getCCTDirectory(); + } catch (Exception ex) { + throw ex; + } + + //String pathS = File.separator; + String pathS = "/"; + if (!baseDir.endsWith(pathS)) { + // it means that path contains checkpoint file name + return baseDir; + } + + + + + + return baseDir + checkPointFile; + } + + public void addCheckPoint(CheckPoint checkPoint) throws + MalformedCheckPointException { + if (checkPoint == null) { + throw new MalformedCheckPointException("checkPoint == null"); + + + } + + String checkpf = ""; + + + try { + checkpf = getCheckPointFile(); + + + } catch (Exception ex) { + throw new MalformedCheckPointException(ex.getMessage()); + + + } + parseCheckpointFile(checkpf); + + + + if (debug) { + logger.info("there are " + tasks.size() + " tasks in checkpoint file"); + + + } + + tasks.add(checkPoint); + + + + try { + saveCheckPointFile(tasks, checkpf); + + + } catch (MalformedCheckPointException ex) { + throw ex; + + + } + } + + public static void saveCheckPointFile(List jobs, String file_name) throws + MalformedCheckPointException { + String xml_string = null; + + + try { + xml_string = CheckPoint.CreateCheckpointString(jobs); + + + } catch (SAXException ex) { + throw new MalformedCheckPointException(ex.getMessage()); + + + } + try { + IOUtils.saveStringIntoFile(xml_string, file_name); + + + } catch (Exception ex) { + throw new MalformedCheckPointException(ex.getMessage()); + + + } + + } + + public static void saveCheckPointFile(List jobs) throws + MalformedCheckPointException { + String xml_string = null; + + + try { + xml_string = CheckPoint.CreateCheckpointString(jobs); + + + } catch (SAXException ex) { + throw new MalformedCheckPointException(ex.getMessage()); + + + } + + try { + String file_name = getCheckPointFile(); + IOUtils.saveStringIntoFile(xml_string, file_name); + + + } catch (Exception ex) { + throw new MalformedCheckPointException(ex.getMessage()); + + + } + + } + + public void updateSelectedCheckPoints(List checkpoints) throws + MalformedCheckPointException { + + String file_name = ""; + + + try { + file_name = getCheckPointFile(); + + + } catch (Exception ex) { + throw new MalformedCheckPointException(ex.getMessage()); + + + } + updateSelectedCheckPoints(checkpoints, file_name); + + + } + + public void updateSelectedCheckPoints(List checkpoints, String fileName) throws + MalformedCheckPointException { + + if (checkpoints == null || checkpoints.size() == 0) { + return; + + + } + + try { + parseCheckpointFile(fileName); + + + } catch (Exception ex) { + } + + if (tasks.size() == 0) { + throw new MalformedCheckPointException("Checkpoint file is empty"); + + + } + + Map current = new HashMap(tasks.size()); + + + for (int i = 0; i + < tasks.size(); i++) { + CheckPoint chk = (CheckPoint) tasks.get(i); + String handle = chk.getJobHandle(); + current.put(handle, new Integer(i)); + + + } + + Map update = new HashMap(checkpoints.size()); + + + for (int i = 0; i + < checkpoints.size(); i++) { + CheckPoint chk = (CheckPoint) checkpoints.get(i); + String handle = chk.getJobHandle(); + update.put(handle, new Integer(i)); + + + } + + Set set = update.entrySet(); + Iterator iter = set.iterator(); + //Iterator iter = list.iterator(); + + + + boolean no_update = true; + + + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String handle = me.getKey().toString(); + Integer index = (Integer) me.getValue(); + + + if (!current.containsKey(handle)) { + System.err.println("Checkpoint file does not contain handle " + handle + + ". Ignored..."); + + + } + Integer index_2 = (Integer) current.get(handle); + tasks.remove(index_2.intValue()); + CheckPoint chk = (CheckPoint) checkpoints.get(index.intValue()); + tasks.add(index_2.intValue(), chk); + no_update = false; + + + } + + if (no_update) { + return; + + + } + + saveCheckPointFile(tasks); + + + } + + public void getJobStatuses() throws MalformedCheckPointException { + try { + parseCheckpointFile(); + + + } catch (Exception ex) { + throw new MalformedCheckPointException(ex.getMessage()); + + + } + for (int i = 0; i + < tasks.size(); i++) { + CheckPoint chk = (CheckPoint) tasks.get(i); + + + if (chk.getJobStatus().equalsIgnoreCase(CheckPointInterface.JOB_STATUS_DONE)) { + continue; + } + + + try { + //chk.updateJobStatus(); + + statusUpdateTask = new StatusUpdateTask(chk, queryTime); + statusUpdateTask.execute(); + + + while (!(statusUpdateTask.isDone() || statusUpdateTask.isCancelled())) { + try { + Thread.sleep(500); + + + } catch (Exception ex) { + } + } + + + if (statusUpdateTask.isDone()) { + logger.info("Job status query completed successfully"); + + + } else if (statusUpdateTask.isCancelled()) { + logger.info("Job status query was cancelled"); + + + } else { + logger.info("Job status query was not finished after " + queryTime + " msec. Force to finish..."); + + + if (statusUpdateTask.cancel(true)) { + logger.info("Job status query was cancelled"); + + + } else { + logger.info("Job status query could not be cancelled (maybe it has already completed normally)"); + + + } + } + + if (progress != null) { + progress.setProgress((int) ((float) i / (float) tasks.size() * 100.0f)); + + + } + + } catch (Exception e) { + //throw new MalformedCheckPointException("Quering job statuses: "+e.getMessage()); + System.err.println("getJobStatuses: Quering job statuses: " + e.getMessage()); + + + } + } + + if (progress != null) { + progress.setProgress(100); + progress.setProgressText("Job status query completed"); + + + } + + try { + saveCheckPointFile(tasks); + + + } catch (MalformedCheckPointException ex) { + throw ex; + + + } + } + + public static void main(String[] args) { + ParseCheckpointFile parsecheckpointfile = new ParseCheckpointFile(); + parsecheckpointfile.parseCheckpointFile(args[0]); + + + + + + + } + + class HandleSAXEvents + extends DefaultHandler { + + //=========================================================== + // SAX DocumentHandler methods + //=========================================================== + @Override + public void startDocument() throws SAXException { + if (debug) { + emit(""); + nl(); + } + } + + @Override + public void endDocument() throws SAXException { + try { + nl(); + out.flush(); + } catch (IOException e) { + throw new SAXException("I/O error", e); + } + } + + @Override + public void startElement(String namespaceURI, + String lName, // local name + String qName, // qualified name + Attributes attrs) throws SAXException { + + if (finish_parsing) { + return; + } + + String eName = lName; // element name + if ("".equals(eName)) { + eName = qName; // namespaceAware = false + } + if (debug) { + emit("<" + eName); + } + if (attrs != null) { + for (int i = 0; i < attrs.getLength(); i++) { + String aName = attrs.getLocalName(i); // Attr name + if ("".equals(aName)) { + aName = attrs.getQName(i); + } + if (debug) { + emit(" "); + emit(aName + "=\"" + attrs.getValue(i) + "\""); + } + } + } + if (debug) { + emit(">"); + } + // Parse elements... + + currentTag = eName; + + if (eName.equalsIgnoreCase(CheckPointInterface.tasksTag)) { + yes_tasks = true; + return; + } + if (!yes_tasks) { + return; // Don't find tag yet... + } + + if (eName.equalsIgnoreCase(CheckPointInterface.taskTag)) { + if (debug) { + logger.info("Starting parsing new task..."); + } + parseLevel = CheckPointInterface.PARSE_TASK_TAGS; + yes_parsing_task = true; + checkPoint = new CheckPoint(); + //taskEntries = new HashMap(); + serviceEntries = new HashMap(); + jobSpecificationEntries = new HashMap(); + outputFilesEntries = new HashMap(); + return; + } + + if (!yes_parsing_task) { + return; // Don't find tag yet... + } + + switch (parseLevel) { + case CheckPointInterface.PARSE_TASK_TAGS: + if (!CheckPointInterface.firstLevelTags.containsKey(eName)) { + Message += "No such first level tag :" + eName + "\n"; + //logger.error("No such first level tag :" + eName); + return; + } + if (eName.equalsIgnoreCase(CheckPointInterface.serviceTag)) { + parseLevel = CheckPointInterface.PARSE_SERVICE_TAGS; + } else if (eName.equalsIgnoreCase(CheckPointInterface.JobSpecificationTag)) { + parseLevel = CheckPointInterface.PARSE_JOB_SPECIFICATION_TAGS; + } + + break; + case CheckPointInterface.PARSE_SERVICE_TAGS: + if (!CheckPointInterface.serviceTags.containsKey(eName)) { + Message += "No such service tag :" + eName + "\n"; + //logger.error("No such service tag :" + eName); + return; + } + break; + case CheckPointInterface.PARSE_JOB_SPECIFICATION_TAGS: + if (!CheckPointInterface.JobSpecificationTags.containsKey(eName)) { + Message += "No such JobSpecification tag :" + eName + "\n"; + //logger.error("No such JobSpecification Tag :" + eName); + return; + } + if (eName.equalsIgnoreCase(CheckPointInterface.outputFilesTag)) { + parseLevel = CheckPointInterface.PARSE_OUTPUT_FILES_TAGS; + } + + break; + case CheckPointInterface.PARSE_OUTPUT_FILES_TAGS: + break; + } + + } + + @Override + public void endElement(String namespaceURI, + String sName, // simple name + String qName // qualified name + ) throws SAXException { + + if (finish_parsing) { + return; + } + + String eName = sName; // element name + if ("".equals(eName)) { + eName = qName; // namespaceAware = false + } + + if (debug) { + emit(""); + } + // --- Parsing + + if (eName.equalsIgnoreCase(CheckPointInterface.tasksTag)) { + finish_parsing = true; + //throw new SAXException("OK"); + return; + } + + if (yes_parsing_task && eName.equalsIgnoreCase(CheckPointInterface.taskTag)) { + if (debug) { + logger.info("Finish parsing " + (tasks.size() + 1) + " task"); + } + yes_parsing_task = false; + checkPoint.put(CheckPointInterface.serviceTag, serviceEntries); + //taskEntries.put(serviceTag, serviceEntries); + jobSpecificationEntries.put(CheckPointInterface.outputFilesTag, outputFilesEntries); + //taskEntries.put(JobSpecificationTag, jobSpecificationEntries); + checkPoint.put(CheckPointInterface.JobSpecificationTag, jobSpecificationEntries); + tasks.add(checkPoint); + //tasks.add(taskEntries); + return; + } + + if (parseLevel == CheckPointInterface.PARSE_SERVICE_TAGS + && eName.equalsIgnoreCase(CheckPointInterface.serviceTag)) { + parseLevel = CheckPointInterface.PARSE_TASK_TAGS; + return; + } + + if (parseLevel == CheckPointInterface.PARSE_JOB_SPECIFICATION_TAGS + && eName.equalsIgnoreCase(CheckPointInterface.JobSpecificationTag)) { + parseLevel = CheckPointInterface.PARSE_TASK_TAGS; + return; + } + + if (parseLevel == CheckPointInterface.PARSE_OUTPUT_FILES_TAGS + && eName.equalsIgnoreCase(CheckPointInterface.outputFilesTag)) { + parseLevel = CheckPointInterface.PARSE_JOB_SPECIFICATION_TAGS; + return; + } + + } + + @Override + public void characters(char buf[], int offset, int len) throws + SAXException { + String s = new String(buf, offset, len); + if (debug) { + emit(s); + } + s = s.trim(); + if (s.length() == 0) { + return; + } + + //logger.info("Characters: Tag: " + currentTag); + + switch (parseLevel) { + case CheckPointInterface.PARSE_TASK_TAGS: + checkPoint.put(currentTag, s); + + //taskEntries.put(currentTag, s); + //logger.info("Task Entries: " + taskEntries); + break; + case CheckPointInterface.PARSE_SERVICE_TAGS: + serviceEntries.put(currentTag, s); + + //logger.info("Service Entries: " + serviceEntries); + break; + case CheckPointInterface.PARSE_JOB_SPECIFICATION_TAGS: + jobSpecificationEntries.put(currentTag, s); + + //logger.info("Job Specs Entries: " + jobSpecificationEntries); + break; + case CheckPointInterface.PARSE_OUTPUT_FILES_TAGS: + outputFilesEntries.put(currentTag, s); + + //logger.info("Output files Entries: " + outputFilesEntries); + break; + + } + } + + //=========================================================== + // Utility Methods ... + //=========================================================== + // Wrap I/O exceptions in SAX exceptions, to + // suit handler signature requirements + private void emit(String s) throws SAXException { + try { + out.write(s); + out.flush(); + } catch (IOException e) { + throw new SAXException("I/O error", e); + } + } + + /* + private void emit(String s) throws SAXException { + try { + out.write(s); + out.flush(); + } + catch (IOException e) { + throw new SAXException("I/O error", e); + } + } + */ + // Start a new line + private void nl() throws SAXException { + String lineEnd = System.getProperty("line.separator"); + try { + out.write(lineEnd); + } catch (IOException e) { + throw new SAXException("I/O error", e); + } + } + /* + class tasksEndException + extends Exception { + + } + */ + } +} + +class StatusUpdateTask extends javax.swing.SwingWorker implements ActionListener { + /* + * Main task. Executed in background thread. + */ + + CheckPoint chk; + private Timer timer; + + public StatusUpdateTask(CheckPoint chk, int maxWorkTime) { + this.chk = chk; + timer = new Timer(maxWorkTime, this); + timer.setRepeats(false); + } + + public void actionPerformed(ActionEvent e) { + this.cancel(true); + } + + @Override + public Void doInBackground() { + timer.start(); + try { + chk.updateJobStatus(); + } catch (Exception ex) { + //logger.severe("Error querying Job status: " + ex.getMessage()); + } + return null; + } + + /* + * Executed in event dispatching thread + */ + @Override + public void done() { + //taskOutput.append("Done!\n"); + } +} diff --git a/src/main/java/cct/grid/ResourcesProviderInterface.java b/src/main/java/cct/grid/ResourcesProviderInterface.java new file mode 100644 index 0000000..a7b985d --- /dev/null +++ b/src/main/java/cct/grid/ResourcesProviderInterface.java @@ -0,0 +1,64 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface ResourcesProviderInterface { + int getNCPUs(); + + float getTimeInSeconds(); + + float getMaxMemoryInMb(); + + void setJobDescription(JobDescription job) throws Exception; + + void setMaxMemoryInMb(int memory); + + void setNCPUs(int n); +} diff --git a/src/main/java/cct/grid/SchedulerInterface.java b/src/main/java/cct/grid/SchedulerInterface.java new file mode 100644 index 0000000..8efe30a --- /dev/null +++ b/src/main/java/cct/grid/SchedulerInterface.java @@ -0,0 +1,66 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid; + +import java.awt.Component; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface SchedulerInterface { + Component getVisualComponent(); + + String getProject(); + + Object getOption(String option); + + String getCommandsAsString(); + + void setResourcesProvider(ResourcesProviderInterface resources); + + void setJobDescription(JobDescription job) throws Exception; +} diff --git a/src/main/java/cct/grid/ScriptSubmitterDialogInterface.java b/src/main/java/cct/grid/ScriptSubmitterDialogInterface.java new file mode 100644 index 0000000..47a4ddc --- /dev/null +++ b/src/main/java/cct/grid/ScriptSubmitterDialogInterface.java @@ -0,0 +1,75 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid; + +import java.util.Map; + +import javax.swing.JDialog; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface ScriptSubmitterDialogInterface { + JDialog getDialog(); + + /** + * Sets any custom options for a given class + * @param options String - custom options + * @throws Exception + */ + void setCustomOptions(String options) throws Exception; + + void setInputFile(String inputFile); + + void setLocalDirectory(String localDir); + + void setRemoteDirectory(String remoteDir); + + void setTaskProviders(Map providers); + + ScriptSubmitterDialogInterface newInstance(); +} diff --git a/src/main/java/cct/grid/TaskProvider.java b/src/main/java/cct/grid/TaskProvider.java new file mode 100644 index 0000000..4bf3dc9 --- /dev/null +++ b/src/main/java/cct/grid/TaskProvider.java @@ -0,0 +1,562 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.grid; + +import java.io.InputStream; +import java.net.URL; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Properties; +import java.util.logging.Logger; + +import cct.interfaces.FileChooserInterface; +import cct.ssh.SSHServiceProvider; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class TaskProvider { + + public static final String CCT_PROVIDER_PROPERTY_FILE = "cct-provider.properties"; + public final static String GLOBUS_2_PROVIDER = "gt2"; + public final static String GLOBUS_4_PROVIDER = "gt4"; + public final static String SSH_PROVIDER = "ssh"; + public final static String LOCAL_PROVIDER = "local"; + private static boolean overwriteStaticProvider = true; + private static Map availableProviders = new LinkedHashMap(); + + static { + //availableProviders.put(GLOBUS_2_PROVIDER, new GatekeeperPanel()); + //availableProviders.put(GLOBUS_4_PROVIDER, new GT4Panel()); + //availableProviders.put(SSH_PROVIDER, new SSHPanel()); + //availableProviders.put(LOCAL_PROVIDER, new JPanel()); + //availableProviders.put(GLOBUS_2_PROVIDER, new GT2ServiceProvider()); // !!! Temporary + //availableProviders.put(GLOBUS_4_PROVIDER, new GT4ServiceProvider()); // !!! Temporary + availableProviders.put(SSH_PROVIDER, new SSHServiceProvider()); + //availableProviders.put(LOCAL_PROVIDER, new LocalServiceProvider()); + } + private String jobHandle = null; + private int jobID; + private static TaskProvider tp = new TaskProvider(); + static final Logger logger = Logger.getLogger(TaskProvider.class.getCanonicalName()); + + private TaskProvider() { + loadProviderProperties(); + } + + private void loadProviderProperties() { + try { + Enumeration e = TaskProvider.class.getClassLoader().getResources(CCT_PROVIDER_PROPERTY_FILE); + while (e.hasMoreElements()) { + try { + loadProviderProperties(((URL) e.nextElement()).openStream()); + } catch (Exception ee) { + System.err.println("Error reading from provider properties: " + ee.getMessage()); + } + } + } catch (Exception e) { + System.err.println("Warning: No " + CCT_PROVIDER_PROPERTY_FILE + " resource found"); + } + } + + private void loadProviderProperties(InputStream is) { + Properties props = new Properties(); + try { + props.load(is); + String provider = null; + String providerClass = null; + + Enumeration e = props.propertyNames(); + while (e.hasMoreElements()) { + String prop = e.nextElement().toString(); + + if (prop.equalsIgnoreCase("provider")) { + provider = props.getProperty(prop); + } else if (prop.equalsIgnoreCase("taskHandler")) { + providerClass = props.getProperty(prop); + } + + } + if (provider == null || provider.length() < 1) { + System.err.println("Provider name missing from provider properties file"); + return; + } + if (providerClass == null || providerClass.length() < 1) { + System.err.println("Provider class name missing from provider properties file"); + return; + } + + logger.info("Loading provider " + provider + " : " + providerClass); + Class cl = this.getClass().getClassLoader().loadClass(providerClass); + Object obj = cl.newInstance(); + logger.info("Provider " + provider + " : " + providerClass + " was loaded"); + + GridProviderInterface gpi = (GridProviderInterface) obj; + + if (overwriteStaticProvider) { + availableProviders.put(provider, gpi); + } else if (availableProviders.containsKey(provider)) { + System.err.println("Provider " + provider + " is already loaded. Use overwrite option"); + return; + } else { + availableProviders.put(provider, gpi); + } + } catch (Exception e) { + System.err.println("Could not load provider: " + e.getMessage()); + } + } + + public static void setAvailableTaskProviders(Map providers) { + availableProviders = new LinkedHashMap(providers); + } + + public static void addTaskProviders(Map providers) { + if (availableProviders == null) { + availableProviders = new LinkedHashMap(providers); + } else { + availableProviders.putAll(providers); + } + } + + public static GridProviderInterface getProvider(String provider) { + return availableProviders.get(provider).newInstance(); + } + + public static Map getAvailableTaskProviders() { + LinkedHashMap temp = new LinkedHashMap(availableProviders.size()); + Iterator iter = availableProviders.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String key = me.getKey().toString(); + GridProviderInterface pr = (GridProviderInterface) me.getValue(); + if (pr != null) { + pr = pr.newInstance(); + } + temp.put(key, pr); + } + return new LinkedHashMap(availableProviders); + } + + public static boolean isValidServiceProvider(String provider) { + return availableProviders.get( provider ) != null; + } + + public String submitJob(JobDescription job) throws Exception { + + String provider = job.getTaskProvider(); + if (provider == null) { + throw new Exception("No service provider specified"); + } + + if (!isValidServiceProvider(provider)) { + throw new Exception(provider + " is not currently supported"); + } + + // --- Submit task + + GridProviderInterface taskProvider = availableProviders.get(provider); + + try { + jobHandle = taskProvider.submitTask(job); + } catch (Exception ex) { + throw ex; + } + + return jobHandle; + /* + if (provider.equalsIgnoreCase(GLOBUS_2_PROVIDER)) { + + GT2ServiceProvider jobSubmit = new GT2ServiceProvider(); + try { + jobSubmit.submitJob(job); + } + catch (Exception ex) { + throw ex; + } + + jobHandle = jobSubmit.getJobHandle(); + } + + else if (provider.equalsIgnoreCase(GLOBUS_4_PROVIDER)) { + GT4ServiceProvider jobSubmit = new GT4ServiceProvider(); + try { + jobSubmit.submitJob(job); + } + catch (Exception ex) { + throw ex; + } + + } + + else if (provider.equalsIgnoreCase(SSH_PROVIDER)) { + SSHServiceProvider jobSubmit = new SSHServiceProvider(); + try { + jobSubmit.submitJob(job); + } + catch (Exception ex) { + throw ex; + } + jobHandle = jobSubmit.getJobHandle(); + } + + else if (provider.equalsIgnoreCase(LOCAL_PROVIDER)) { + LocalServiceProvider jobSubmit = new LocalServiceProvider(); + try { + jobSubmit.submitJob(job); + } + catch (Exception ex) { + throw ex; + } + jobHandle = jobSubmit.getJobHandle(); + + } + */ + } + + public String getJobHandle() { + return jobHandle; + } + + /** + * Returns job status as a string for a given checkpoint + * @param chkp CheckPoint + * @return String + * @throws Exception + */ + public static String getJobStatus(CheckPoint chkp) throws Exception { + if (!chkp.containsKey(CheckPointInterface.statusTag)) { + System.err.println("!chkp.containsKey(CheckPointInterface.statusTag)"); + chkp.setJobStatus(CheckPointInterface.JOB_STATUS_UNKNOWN); + } + + if (chkp.getTaskProvider() == null) { + System.err.println("chkp.getTaskProvider() == null"); + return CheckPointInterface.JOB_STATUS_UNKNOWN; + } + + String status = chkp.getJobStatus(); + if (status.equalsIgnoreCase(CheckPointInterface.JOB_STATUS_DONE)) { + return CheckPointInterface.JOB_STATUS_DONE; + } + + String handle = chkp.getJobHandle(); + + if (handle == null) { + System.err.println("Job handle == null"); + return CheckPointInterface.JOB_STATUS_UNKNOWN; + } + + String jobName = chkp.getJobName(); + + String provider = chkp.getTaskProvider(); + if (provider == null) { + System.err.println("Task " + jobName + " does not have a provider record"); + throw new Exception("Task " + jobName + " does not have a provider record"); + } + + if (!isValidServiceProvider(provider)) { + System.err.println(provider + " is not currently supported/loaded"); + return CheckPointInterface.JOB_STATUS_UNKNOWN; + } + + // --- Query job status + + GridProviderInterface taskProvider = availableProviders.get(provider); + status = taskProvider.getJobStatus(chkp); + /* + if (provider.equalsIgnoreCase(GLOBUS_2_PROVIDER)) { + + status = GT2ServiceProvider.getJobStatus(chkp); + return status; + } + + else if (provider.equalsIgnoreCase(GLOBUS_4_PROVIDER)) { + } + + else if (provider.equalsIgnoreCase(SSH_PROVIDER)) { + status = SSHServiceProvider.getJobStatus(chkp); + return status; + } + + else if (provider.equalsIgnoreCase(LOCAL_PROVIDER)) { + } + */ + return status; + } + + public static void downloadOutputFiles(CheckPoint chkp) throws Exception { + boolean outputFilesStatusUpdated = false; + /* + // Error check + if (!chkp.hasOutputFiles()) { + System.err.println("Warning: attempt to download output file(s) from the checkpoint without ones"); + return; + } + + if (chkp.areOutputFilesLoaded()) { + System.err.println("Warning: downloadOutputFiles: output files are already downloaded"); + return; + } + + if (chkp.getTaskProvider() == null) { + System.err.println("Error: downloadOutputFiles: no provider name in checkpoint file"); + throw new MalformedCheckPointException("No provider name in checkpoint file"); + } + + // --- Creating valid URLs + + if (this.getComputer() == null) { + System.err.println( + "Error: downloadOutputFiles: no computer name in checkpoint file"); + throw new MalformedCheckPointException( + "No computer name in checkpoint file"); + } + + String remoteDir = ""; + if (this.getRemoteDirectory() == null) { + //System.err.println( + // "Error: downloadOutputFiles: no remote directory in checkpoint file"); + //throw new MalformedCheckPointException( + // "No remote directory in checkpoint file"); + remoteDir += "/"; + } + else { + remoteDir = getRemoteDirectory(); + if (!remoteDir.endsWith("/")) { + remoteDir = remoteDir + "/"; + } + } + + if (chkp.getLocalDirectory() == null) { + System.err.println( + "Error: downloadOutputFiles: no local directory in checkpoint file"); + throw new MalformedCheckPointException( + "No local directory in checkpoint file"); + } + + String localDir = chkp.getLocalDirectory(); + + if (!localDir.endsWith("/") && !localDir.endsWith("\\")) { + localDir = localDir + "/"; + } + + String fromURL = getComputer() + remoteDir; + String toURL = localDir; + + String errorMessage = ""; + + // --- Go through output files + HashMap out = chkp.getOutputFilesEntry(); + Set set = out.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String Key = me.getKey().toString(); + String outputFile = me.getValue().toString(); + if (Key.startsWith(chkp.outputStatusPrefix)) { + continue; + } + String status_tag = chkp.outputStatusPrefix + Key; + if (!out.containsKey(status_tag)) { + System.err.println("Internal Error: tag " + Key + " should be complemented with tag " + chkp.outputStatusPrefix + Key); + throw new RuntimeException("Internal Error: tag " + Key + " should be complemented with tag " + chkp.outputStatusPrefix + + Key); + //continue; + } + + String status_value = (String) out.get(chkp.outputStatusPrefix + Key); + + // --- Download it + if (status_value.equalsIgnoreCase("false")) { + logger.info("Copying\n From: " + fromURL + outputFile); + logger.info(" To: " + toURL + outputFile); + + if (fileTransferHandler.tranferFile(fromURL + outputFile, toURL + outputFile, chkp.getTaskProvider())) { + out.put(chkp.outputStatusPrefix + Key, "true"); + outputFilesStatusUpdated = true; + } + else { + errorMessage += "Unable to download " + fromURL + outputFile + "\n"; + } + + } + } + + // --- Update overal job status + if (errorMessage.length() == 0) { + chkp.setOverallJobStatus(chkp.JOB_STATUS_DONE); + outputFilesStatusUpdated = true; + } + + if (errorMessage.length() > 0) { + throw new MalformedCheckPointException(errorMessage); + } + */ + } + + /* + public static boolean transferFile(String source, String destination, String provider) throws Exception { + + if (provider == null) { + throw new Exception("No service provider specified"); + } + + if (!isValidServiceProvider(provider)) { + throw new Exception(provider + " is not currently supported"); + } + + GridProviderInterface taskProvider = availableProviders.get(provider); + + return taskProvider.transferFile(source, destination); + } + */ + public static boolean transferFile(String source, String destination, CheckPoint chkp) throws Exception { + + // Error check + if (!chkp.hasOutputFiles()) { + System.err.println("Warning: attempt to download output file(s) from the checkpoint without ones"); + return false; + } + + if (chkp.areOutputFilesLoaded()) { + System.err.println("Warning: downloadOutputFiles: output files are already downloaded"); + return false; + } + + if (chkp.getTaskProvider() == null) { + System.err.println("Error: downloadOutputFiles: no provider name in checkpoint file"); + throw new Exception("No provider name in checkpoint file"); + } + + String provider = chkp.getTaskProvider(); + if (provider == null) { + throw new Exception("No service provider specified"); + } + + if (!isValidServiceProvider(provider)) { + throw new Exception(provider + " is not currently supported"); + } + + GridProviderInterface taskProvider = availableProviders.get(provider); + return taskProvider.transferFile(source, destination, chkp); + } + + /** + * Kills a job + * @param chkp CheckPoint + * @return boolean + * @throws Exception + */ + public static void killJob(CheckPoint chkp) throws Exception { + String jobName = chkp.getJobName(); + + String provider = chkp.getTaskProvider(); + if (provider == null) { + System.err.println("Task " + jobName + " does not have a provider record"); + throw new Exception("Task " + jobName + " does not have a provider record"); + } + + if (!isValidServiceProvider(provider)) { + System.err.println(provider + " is not currently supported/loaded"); + throw new Exception(provider + " is not currently supported/loaded"); + } + + GridProviderInterface taskProvider = availableProviders.get(provider); + + try { + taskProvider.killJob(chkp); + } catch (Exception ex) { + throw ex; + } + + /* + if (chkp.getTaskProvider().equalsIgnoreCase(GLOBUS_2_PROVIDER)) { + try { + GT2ServiceProvider.killJob(chkp); + + } + catch (Exception ex) { + System.err.println(ex.getMessage()); + throw ex; + } + } + + else if (chkp.getTaskProvider().equalsIgnoreCase(GLOBUS_4_PROVIDER)) { + throw new Exception("Killing jobs using " + chkp.getTaskProvider() + + " is not implemented yet"); + } + + else if (chkp.getTaskProvider().equalsIgnoreCase(SSH_PROVIDER)) { + try { + SSHServiceProvider.killJob(chkp); + } + catch (Exception ex) { + System.err.println(ex.getMessage()); + throw ex; + } + } + + else if (chkp.getTaskProvider().equalsIgnoreCase(LOCAL_PROVIDER)) { + throw new Exception("Killing jobs using " + chkp.getTaskProvider() + + " is not implemented yet"); + } + + else { + throw new Exception("Unknown task provider: " + chkp.getTaskProvider()); + } + */ + + } + + public static FileChooserInterface getRemoteFileChooser(String provider) { + if (provider.equalsIgnoreCase(SSH_PROVIDER)) { + } + + return null; + } +} diff --git a/src/main/java/cct/grid/TaskProviderInterface.java b/src/main/java/cct/grid/TaskProviderInterface.java new file mode 100644 index 0000000..dd82537 --- /dev/null +++ b/src/main/java/cct/grid/TaskProviderInterface.java @@ -0,0 +1,54 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public interface TaskProviderInterface { + void submitJob(JobDescription job) throws Exception; +} diff --git a/src/main/java/cct/grid/TaskProviderPanel.java b/src/main/java/cct/grid/TaskProviderPanel.java new file mode 100644 index 0000000..04db1c2 --- /dev/null +++ b/src/main/java/cct/grid/TaskProviderPanel.java @@ -0,0 +1,157 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid; + +import java.awt.BorderLayout; +import java.awt.CardLayout; +import java.awt.Component; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class TaskProviderPanel + extends JPanel { + BorderLayout borderLayout1 = new BorderLayout(); + JComboBox providerComboBox = new JComboBox(); + JPanel providerPanel = new JPanel(); + JPanel jPanel2 = new JPanel(); + FlowLayout flowLayout1 = new FlowLayout(); + JLabel providerLabel = new JLabel(); + CardLayout cardLayout1 = new CardLayout(); + + public TaskProviderPanel() { + try { + jbInit(); + setTaskProviders(TaskProvider.getAvailableTaskProviders()); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + providerPanel.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + providerLabel.setToolTipText(""); + providerLabel.setText(" Provider: "); + jPanel2.setLayout(cardLayout1); + providerComboBox.addActionListener(new + TaskProviderPanel_providerComboBox_actionAdapter(this)); + providerPanel.add(providerLabel); + providerPanel.add(providerComboBox); + this.add(jPanel2, BorderLayout.CENTER); + this.add(providerPanel, BorderLayout.NORTH); + } + + public void setTaskProviders(TaskProvider providers) { + setTaskProviders(TaskProvider.getAvailableTaskProviders()); + } + + public String getTaskProvider() { + return providerComboBox.getSelectedItem().toString(); + } + + public void setTaskProviders(Map providers) { + providerComboBox.setEnabled(false); + providerComboBox.removeAllItems(); + + Set set = providers.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String providerName = me.getKey().toString(); + providerComboBox.addItem(providerName); + Component panel = (Component) me.getValue(); + + jPanel2.add(panel, providerName); + } + + providerComboBox.setSelectedIndex(0); + + CardLayout cl = (CardLayout) jPanel2.getLayout(); + cl.show(jPanel2, providerComboBox.getSelectedItem().toString()); + + providerComboBox.setEnabled(true); + } + + public void providerComboBox_actionPerformed(ActionEvent e) { + if (!providerComboBox.isEnabled()) { + return; + } + providerComboBox.setEnabled(false); + + CardLayout cl = (CardLayout) jPanel2.getLayout(); + cl.show(jPanel2, providerComboBox.getSelectedItem().toString()); + + providerComboBox.setEnabled(true); + + } +} + +class TaskProviderPanel_providerComboBox_actionAdapter + implements ActionListener { + private TaskProviderPanel adaptee; + TaskProviderPanel_providerComboBox_actionAdapter(TaskProviderPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.providerComboBox_actionPerformed(e); + } +} diff --git a/src/main/java/cct/grid/TaskScheduler.java b/src/main/java/cct/grid/TaskScheduler.java new file mode 100644 index 0000000..7b6ba80 --- /dev/null +++ b/src/main/java/cct/grid/TaskScheduler.java @@ -0,0 +1,76 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid; + +import java.util.LinkedHashMap; +import java.util.Map; + +import cct.grid.ui.PBS_Panel; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class TaskScheduler { + + public final static String FORK_SCHEDULER = "fork"; + public final static String PBS_SCHEDULER = "pbs"; + + private static Map availableSchedulers = new LinkedHashMap(); + + static { + availableSchedulers.put(PBS_SCHEDULER, new PBS_Panel()); + + } + + public TaskScheduler() { + } + + public static Map getAvailableTaskSchedulers() { + return availableSchedulers; + } + +} diff --git a/src/main/java/cct/grid/ui/.DS_Store b/src/main/java/cct/grid/ui/.DS_Store new file mode 100644 index 0000000..f3bbdcb Binary files /dev/null and b/src/main/java/cct/grid/ui/.DS_Store differ diff --git a/src/main/java/cct/grid/ui/._.DS_Store b/src/main/java/cct/grid/ui/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/cct/grid/ui/._.DS_Store differ diff --git a/src/main/java/cct/grid/ui/CheckPointStatus.java b/src/main/java/cct/grid/ui/CheckPointStatus.java new file mode 100644 index 0000000..7830d0b --- /dev/null +++ b/src/main/java/cct/grid/ui/CheckPointStatus.java @@ -0,0 +1,450 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.grid.ui; + +import java.util.ArrayList; +import java.util.List; + +import javax.swing.JOptionPane; + +import cct.globus.CoGFileTransfer; +import cct.grid.CheckPoint; +import cct.grid.CheckPointInterface; +import cct.grid.FileTransferInterface; +import cct.grid.JobStatusInterface; +import cct.grid.ParseCheckpointFile; +import cct.grid.TaskProvider; +import cct.tools.ui.JobProgressInterface; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class CheckPointStatus + implements JobStatusInterface, FileTransferInterface { + + List Tasks = null; + private JobProgressInterface jpi; + + public CheckPointStatus() { + } + + @Override + public String[] getColumnNames() { + return new String[]{ + "Job Name", "Program ", "Computer", "Job Status", "Output Downloaded"}; + } + + @Override + public void setJobProgressInterface(JobProgressInterface jpi) { + this.jpi = jpi; + } + + @Override + public Object[][] getData() { + + ParseCheckpointFile pchk = new ParseCheckpointFile(); + try { + pchk.getJobStatuses(); + } catch (cct.grid.MalformedCheckPointException ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Job Status Query Error", JOptionPane.ERROR_MESSAGE); + return null; + } + + Tasks = pchk.getTasks(); + + Object[][] data = new Object[Tasks.size()][]; + + for (int i = 0; i < Tasks.size(); i++) { + CheckPoint chk = (CheckPoint) Tasks.get(i); + data[i] = new Object[5]; + + data[i][0] = chk.getJobName(); // Job Name + if (data[i][0] == null) { + data[i][0] = "Unknown"; + } + + data[i][1] = chk.getProgram(); // + if (data[i][1] == null) { + data[i][1] = "Unknown"; + } + + data[i][2] = chk.getComputer(); // Computer + if (data[i][2] == null) { + data[i][2] = "Unknown"; + } + + data[i][3] = chk.getJobStatus(); // Job Status as a String + if (data[i][3] == null) { + data[i][3] = "Unknown"; + } + + data[i][4] = chk.getOverallJobStatus(); + if (data[i][4] == null) { + data[i][4] = "Unknown"; + } + + } + + return data; + } + + @Override + public CheckPoint getCheckPoint(int n) { + if (Tasks != null && Tasks.size() > 0 && n >= 0 && n < Tasks.size()) { + return (CheckPoint) Tasks.get(n); + } + return null; + } + + @Override + public void killSelectedJobs(int[] jobsToKill) { + if (Tasks == null || Tasks.size() < 1) { + return; + } + + for (int i = 0; i < jobsToKill.length; i++) { + if (jobsToKill[i] < 0 || jobsToKill[i] >= Tasks.size()) { + // Just ingnore malformed requests + jobsToKill[i] = -1; + continue; + } + CheckPoint chk = (CheckPoint) Tasks.get(jobsToKill[i]); + if (chk.getJobStatus().equalsIgnoreCase(CheckPointInterface.JOB_STATUS_DONE)) { + jobsToKill[i] = -1; + } + } + + ParseCheckpointFile pchk = new ParseCheckpointFile(); + try { + pchk.getJobStatuses(); + } catch (cct.grid.MalformedCheckPointException ex) { + JOptionPane.showMessageDialog(null, + ex.getMessage(), + "Job Status Query Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + List newTasks = pchk.getTasks(); + String errors = ""; + + for (int i = 0; i < jobsToKill.length; i++) { + if (jobsToKill[i] < 0) { + continue; + } + CheckPoint chk = (CheckPoint) Tasks.get(jobsToKill[i]); + String handle = chk.getJobHandle(); + + for (int j = 0; j < newTasks.size(); j++) { + CheckPoint new_chk = (CheckPoint) newTasks.get(j); + String new_handle = new_chk.getJobHandle(); + if (new_handle.equals(handle)) { + if (!new_chk.getJobStatus().equalsIgnoreCase(CheckPointInterface.JOB_STATUS_DONE)) { + + try { + TaskProvider.killJob(new_chk); + } catch (Exception ex) { + errors += ex.getMessage(); + } + /* + if (GRAM.killJob(handle) != 0) { + errors += handle + " : " + GRAM.getMessage() + "\n"; + } + */ + } + break; + } + } + } + + if (errors.length() > 0) { + JOptionPane.showMessageDialog(null, + errors, + "Notice", + JOptionPane.WARNING_MESSAGE); + } + + } + + @Override + public void removeSelectedCheckpoints(int[] jobsToRemove) { + if (Tasks == null || Tasks.size() < 1) { + return; + } + + boolean warning = false; + for (int i = 0; i < jobsToRemove.length; i++) { + if (jobsToRemove[i] < 0 || jobsToRemove[i] >= Tasks.size()) { + // Just ingnore malformed requests + jobsToRemove[i] = -1; + continue; + } + CheckPoint chk = (CheckPoint) Tasks.get(jobsToRemove[i]); + if (chk.getJobStatus().equalsIgnoreCase(CheckPointInterface.JOB_STATUS_DONE) + && chk.getOverallJobStatus().equalsIgnoreCase(CheckPointInterface.JOB_STATUS_DONE)) { + continue; + } + warning = true; + } + + if (warning) { + final JOptionPane optionPane = new JOptionPane( + "Some jobs are not completed yet\n" + + "Do you still want to delete their checkpoints?", + JOptionPane.QUESTION_MESSAGE, + JOptionPane.YES_NO_OPTION); + optionPane.setVisible(true); + int n = + JOptionPane.showConfirmDialog(null, + "Some jobs are not completed yet\n" + + "Do you still want to delete their checkpoints?", + "Confirm Removal", + JOptionPane.YES_NO_OPTION); + if (n == JOptionPane.NO_OPTION || n == JOptionPane.CLOSED_OPTION) { + return; + } + } + + ParseCheckpointFile pchk = new ParseCheckpointFile(); + try { + pchk.parseCheckpointFile(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, + "Error parsing checkpoint file: " + + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + List newTasks = pchk.getTasks(); + + for (int i = 0; i < jobsToRemove.length; i++) { + if (jobsToRemove[i] < 0) { + continue; + } + CheckPoint chk = (CheckPoint) Tasks.get(jobsToRemove[i]); + String handle = chk.getJobHandle(); + + int to_remove = -1; + for (int j = 0; j < newTasks.size(); j++) { + CheckPoint new_chk = (CheckPoint) newTasks.get(j); + String new_handle = new_chk.getJobHandle(); + if (new_handle.equals(handle)) { + to_remove = j; + break; + } + } + + if (to_remove > -1) { + newTasks.remove(to_remove); + } + } + + Tasks = newTasks; + try { + ParseCheckpointFile.saveCheckPointFile(Tasks); + } catch (cct.grid.MalformedCheckPointException ex) { + JOptionPane.showMessageDialog(null, + "Error while saving updated checkpoint file: " + + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + } + } + + @Override + public void downloadRemoteFiles(int[] jobsWithDownloads) { + if (Tasks == null || Tasks.size() < 1) { + return; + } + + // --- Check whether all output files are already downloaded + + for (int i = 0; i < jobsWithDownloads.length; i++) { + if (jobsWithDownloads[i] < 0 || jobsWithDownloads[i] >= Tasks.size()) { + // Just ingnore malformed requests + jobsWithDownloads[i] = -1; + continue; + } + + CheckPoint chk = (CheckPoint) Tasks.get(jobsWithDownloads[i]); + + if (chk.getJobStatus().equalsIgnoreCase(CheckPointInterface.JOB_STATUS_DONE) + && chk.getOverallJobStatus().equalsIgnoreCase(CheckPointInterface.JOB_STATUS_DONE)) { + jobsWithDownloads[i] = -1; + continue; + } + + } + + boolean warning = true; + for (int i = 0; i < jobsWithDownloads.length; i++) { + if (jobsWithDownloads[i] > -1) { + warning = false; + break; + } + } + + // --- if they are already downloaded - return + + if (warning) { + JOptionPane.showMessageDialog(null, "The output files for selected job(s) are/is already downloaded", "Warning", + JOptionPane.WARNING_MESSAGE); + return; + } + + // --- Get updated job status and download output files (if needed) + + String message = ""; + warning = false; + boolean updateCheckpoint = false; + for (int i = 0; i < jobsWithDownloads.length; i++) { + if (jobsWithDownloads[i] == -1) { + continue; + } + + CheckPoint chk = (CheckPoint) Tasks.get(jobsWithDownloads[i]); + try { + chk.updateJobStatus(); + } catch (Exception e) { + JOptionPane.showMessageDialog(null, "Error Quering Job Statuses: " + e.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + // --- Ignore jobs which are not completed yet + if (!chk.getJobStatus().equalsIgnoreCase(CheckPointInterface.JOB_STATUS_DONE)) { + warning = true; + continue; + } + if (warning) { + message += "Some jobs are not completed yet\n"; + } + + if (chk.getComputer() == null) { + message += "Uknown computer for job handle " + chk.getJobHandle() + + "\n"; + } + + // Now try to download files + try { + chk.downloadOutputFiles(this); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + message += ex.getMessage(); + } + + if (chk.isOutputFilesStatusUpdated()) { + updateCheckpoint = true; + } + } + + // --- If nothing to update - return + + if (!updateCheckpoint) { + if (message.length() > 0) { + JOptionPane.showMessageDialog(null, message, "Warning", JOptionPane.WARNING_MESSAGE); + } + return; + } + + // --- Update checkpoint file + + // --- Collect checkpoint for update + + ArrayList tasksToUpdate = new ArrayList(); + for (int i = 0; i < Tasks.size(); i++) { + CheckPoint chk = (CheckPoint) Tasks.get(i); + if (!chk.isOutputFilesStatusUpdated()) { + continue; + } + tasksToUpdate.add(chk); + } + + // --- Update them + + ParseCheckpointFile pchk = new ParseCheckpointFile(); + try { + pchk.updateSelectedCheckPoints(Tasks); + } catch (Exception ex) { + message += ex.getMessage(); + } + + if (message.length() > 0) { + JOptionPane.showMessageDialog(null, + message, + "Warning", + JOptionPane.WARNING_MESSAGE); + } + } + + @Override + public boolean tranferFile(String source, String destination, CheckPoint chkp) { + try { + return TaskProvider.transferFile(source, destination, chkp); + } catch (Exception ex) { + System.err.println(this.getClass().getCanonicalName() + " : transferFile: " + ex.getMessage()); + return false; + } + } + + static class FTransferWithProgress + implements ThreadInterface { + + String Source, Destination; + + public FTransferWithProgress(String source, String destination) { + Source = source; + Destination = destination; + } + + @Override + public void performTask() { + CoGFileTransfer transfer = new CoGFileTransfer(); + } + } +} diff --git a/src/main/java/cct/grid/ui/EditScriptDialog.java b/src/main/java/cct/grid/ui/EditScriptDialog.java new file mode 100644 index 0000000..1458edc --- /dev/null +++ b/src/main/java/cct/grid/ui/EditScriptDialog.java @@ -0,0 +1,182 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid.ui; + +import java.awt.BorderLayout; +import java.awt.Font; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.prefs.Preferences; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; + +import cct.tools.ui.FontSelectorDialog; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class EditScriptDialog + extends JDialog implements ActionListener { + + Preferences prefs; + FontSelectorDialog fontSelector = null; + static String FontNameKey = "FontName"; + static String FontSizeKey = "FontSize"; + static String FontStyleKey = "FontStyle"; + static String defaultFontName = "default"; + + JPanel panel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JPanel jPanel1 = new JPanel(); + JScrollPane jScrollPane1 = new JScrollPane(); + public JTextArea scriptTextArea = new JTextArea(); + JButton cancelButton = new JButton(); + JButton submitButton = new JButton(); + public boolean submitPressed = false; + + public EditScriptDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public EditScriptDialog() { + this(new Frame(), "EditScriptDialog", false); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + scriptTextArea.setText("Your Script is Here"); + cancelButton.setText("Cancel"); + submitButton.setToolTipText(""); + submitButton.setText("Submit"); + this.setDefaultCloseOperation(javax.swing.WindowConstants. + DO_NOTHING_ON_CLOSE); + this.setModal(true); + this.setTitle("Edit Script"); + getContentPane().add(panel1); + panel1.add(jPanel1, BorderLayout.SOUTH); + jPanel1.add(submitButton); + jPanel1.add(cancelButton); + panel1.add(jScrollPane1, BorderLayout.CENTER); + jScrollPane1.getViewport().add(scriptTextArea); + + submitButton.addActionListener(this); + cancelButton.addActionListener(this); + + this.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + submitPressed = false; + setVisible(false); + } + } + ); + + // --- Retrieving font properties + + Font currentFont = scriptTextArea.getFont(); + int size = currentFont.getSize(); + int style = currentFont.getStyle(); + String fontName = currentFont.getFontName(); + + try { + prefs = Preferences.userNodeForPackage(this.getClass()); + fontName = prefs.get(FontNameKey, currentFont.getFontName()); + size = prefs.getInt(FontSizeKey, 12); + if (size < 12) { + size = 12; + } + style = prefs.getInt(FontStyleKey, 0); + } + catch (Exception ex) { + System.err.println("Error retrieving Font Preferences: " + + ex.getMessage()); + return; + } + + Font newFont = new Font(fontName, style, size); + scriptTextArea.setFont(newFont); + + currentFont = scriptTextArea.getFont(); + try { + prefs.put(FontNameKey, currentFont.getFontName()); + prefs.putInt(FontSizeKey, currentFont.getSize()); + prefs.putInt(FontStyleKey, currentFont.getStyle()); + prefs.flush(); + } + catch (Exception ex) { + System.err.println("Error saving Font Preferences: " + + ex.getMessage()); + } + + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == cancelButton) { + submitPressed = false; + } + else if (e.getSource() == submitButton) { + submitPressed = true; + } + setVisible(false); + } +} diff --git a/src/main/java/cct/grid/ui/JobOutputInterface.java b/src/main/java/cct/grid/ui/JobOutputInterface.java new file mode 100644 index 0000000..ecf01b9 --- /dev/null +++ b/src/main/java/cct/grid/ui/JobOutputInterface.java @@ -0,0 +1,54 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid.ui; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface JobOutputInterface { + void appendOutput(String output); +} diff --git a/src/main/java/cct/grid/ui/JobStatusDialog.java b/src/main/java/cct/grid/ui/JobStatusDialog.java new file mode 100644 index 0000000..682c8d5 --- /dev/null +++ b/src/main/java/cct/grid/ui/JobStatusDialog.java @@ -0,0 +1,686 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.grid.ui; + +import java.awt.BorderLayout; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ArrayList; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JProgressBar; +import javax.swing.SwingUtilities; +import javax.swing.Timer; +import javax.swing.UIManager; + +import cct.globus.GRAM; +import cct.grid.FileViewerInterface; +import cct.grid.JobStatusInterface; +import cct.tools.ui.JobProgressInterface; + +/** + *

+ * Title: Molecular Structure Viewer/Editor

+ * + *

+ * Description: Computational Chemistry Toolkit

+ * + *

+ * Copyright: Copyright (c) 2006

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class JobStatusDialog + extends JDialog { + + public final static int JSD_NO_TASK = 0; + public final static int JSD_QUERY_STATUS = 1; + public final static int JSD_KILL_JOBS = 2; + public final static int JSD_DOWNLOAD_JOBS = 3; + JPanel mainPanel = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JobStatusPanel jobStatusPanel1 = new JobStatusPanel(); + JPanel jPanel1 = new JPanel(); + JButton updateButton = new JButton(); + JButton hideButton = new JButton(); + boolean queryIsDone = true; + int taskType = JSD_NO_TASK; + JobStatusInterface jobStatusInterface = null; + JButton removeButton = new JButton(); + JButton killButton = new JButton(); + JButton HelpButton = new JButton(); + JButton downloadButton = new JButton(); + + public JobStatusDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(HIDE_ON_CLOSE); + jbInit(); + pack(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JobStatusDialog(Frame owner, String title, boolean modal, JobStatusInterface jsi) { + super(owner, title, modal); + jobStatusInterface = jsi; + try { + setDefaultCloseOperation(HIDE_ON_CLOSE); + jbInit(); + pack(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JobStatusDialog() { + this(new Frame(), "Query Job Statuses", false); + } + + private void jbInit() throws Exception { + mainPanel.setLayout(borderLayout1); + this.setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); + this.setTitle("Job Status"); + updateButton.setToolTipText("Update Job Status"); + updateButton.setText("Update"); + updateButton.addActionListener(new JobStatusDialog_updateButton_actionAdapter(this)); + hideButton.setToolTipText("Hide Panel"); + hideButton.setText("Hide"); + hideButton.addActionListener(new JobStatusDialog_hideButton_actionAdapter(this)); + removeButton.setToolTipText("Remove Selected Jobs from the Log"); + removeButton.setText("Remove Selected"); + removeButton.addActionListener(new JobStatusDialog_removeButton_actionAdapter(this)); + killButton.setToolTipText("Kill Selected Job(s)"); + killButton.setText("Kill Selected Jobs"); + killButton.addActionListener(new JobStatusDialog_killButton_actionAdapter(this)); + HelpButton.setToolTipText("Help"); + HelpButton.setText("Help"); + HelpButton.addActionListener(new JobStatusDialog_HelpButton_actionAdapter(this)); + downloadButton.setToolTipText("Download Output Files for Completed Jobs"); + downloadButton.setText("Download"); + downloadButton.addActionListener(new JobStatusDialog_downloadButton_actionAdapter(this)); + getContentPane().add(mainPanel); + mainPanel.add(jPanel1, BorderLayout.SOUTH); + jPanel1.add(hideButton); + jPanel1.add(updateButton); + jPanel1.add(downloadButton); + jPanel1.add(removeButton); + jPanel1.add(killButton); + jPanel1.add(HelpButton); + mainPanel.add(jobStatusPanel1, BorderLayout.CENTER); + //queryJobStatus(); + } + + public void hideButton_actionPerformed(ActionEvent e) { + setVisible(false); + } + + public void performTask(String winTitle, String labelTitle, int jobType) { + taskType = jobType; + performTask(winTitle, labelTitle); + } + + void performTask(String winTitle, String labelTitle) { + FileTranferWorker worker = new FileTranferWorker(this, taskType, labelTitle); + jobStatusInterface.setJobProgressInterface(worker); + worker.start(); + if (true) { + return; + } + + final int MAX = 10; + final JLabel msgLabel = new JLabel(labelTitle); + final JProgressBar progressBar = new JProgressBar(0, MAX); + + progressBar.setValue(0); + + Object[] comp = { + msgLabel, progressBar}; + Object[] options = { + "Cancel"}; + + JOptionPane pane = new JOptionPane(comp, + JOptionPane.DEFAULT_OPTION, + JOptionPane.INFORMATION_MESSAGE, + null, + options, + options[0]); + + final JDialog dialog = pane.createDialog(this, winTitle); + //dialog.setVisible(true); + + final Task task = new Task(); + + Timer timer = new Timer(250, new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + if (task.isDone()) { + dialog.setVisible(false); + } else { + progressBar.setValue((progressBar.getValue() + 1) % MAX); + } + } + }); + + timer.start(); + task.start(); + + try { + Thread.sleep(500); + } catch (Exception e) { + } + + if (task.getException() == null) { + dialog.setVisible(true); + } else { + } + + timer.stop(); + } + + public void queryJobStatus() { + taskType = JSD_QUERY_STATUS; + performTask("Quering Job Status", "Quering job status..."); + } + + /** + * Kills selected jobs + */ + void killJobs() { + int[] rows = jobStatusPanel1.jobStatusTable.getSelectedRows(); + if (jobStatusInterface == null) { + String errors = ""; + for (int i = 0; i < rows.length; i++) { + String handle = (String) jobStatusPanel1.jobStatusTable.getValueAt(rows[i], 0); + + try { + //GRAM.killJob(handle); + System.err.println("This options is not implemented"); + } catch (Exception ex) { + //errors += GRAM.getMessage() + "\n"; + errors += ex.getMessage() + "\n"; + } + + } + if (errors.length() > 0) { + JOptionPane.showMessageDialog(null, errors, "Notice", JOptionPane.WARNING_MESSAGE); + } + } else { + jobStatusInterface.killSelectedJobs(rows); + updateJobStatus(); + } + } + + public void setFileViewer(FileViewerInterface fileviewer) { + jobStatusPanel1.setFileViewer(fileviewer); + } + + void downloadOutputFiles() { + int[] rows = jobStatusPanel1.jobStatusTable.getSelectedRows(); + if (jobStatusInterface == null) { + } else { + jobStatusInterface.downloadRemoteFiles(rows); + updateJobStatus(); + } + } + + synchronized void updateJobStatus() { + if (jobStatusInterface == null) { + ArrayList statuses = null; + try { + //statuses = GRAM.getStatusLoggedJobs(); + System.err.println("This option is not implemented"); + } catch (Exception e) { + JOptionPane.showMessageDialog(null, "Error Quering Job Statuses: " + e.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE); + //return; + } + + JobStatusTableModel jstm = new JobStatusTableModel(statuses); + jobStatusPanel1.jobStatusTable.setModel(jstm); + } else { + + JobStatusTableModel jstm = new JobStatusTableModel(jobStatusInterface); + jobStatusPanel1.updateTable(jstm); + } + } + + synchronized void getUpdatedJobStatus() { + if (jobStatusInterface == null) { + JOptionPane.showMessageDialog(null, "Job Status Interface is not set", "Internal Error", JOptionPane.ERROR_MESSAGE); + return; + } + + //if (progressBarDialog == null) { + // progressBarDialog = new ProgressBarDialog(null, false); + // progressBarDialog.setLocationRelativeTo(this); + //} + //progressBarDialog.setVisible(true); + Object[][] data = jobStatusInterface.getData(); + JobStatusTableModel jstm = new JobStatusTableModel(jobStatusInterface.getColumnNames(), data, jobStatusInterface); + jobStatusPanel1.updateTable(jstm); + + //progressBarDialog.setVisible(false); + } + + public void updateButton_actionPerformed(ActionEvent e) { + taskType = JSD_QUERY_STATUS; + performTask("Quering Job Status", "Quering job status..."); + //queryJobStatus(); + } + + public void removeButton_actionPerformed(ActionEvent e) { + int[] rows = jobStatusPanel1.jobStatusTable.getSelectedRows(); + if (jobStatusInterface == null) { + if (jobStatusPanel1.jobStatusTable.getSelectedRowCount() < 1) { + JOptionPane.showMessageDialog(null, "Select Row(s) First!", "Advice", JOptionPane.WARNING_MESSAGE); + return; + } + + //java.util.List ids = GRAM.getJobIdsFromLog(); + System.err.println("Function is not implemented"); + java.util.List ids = new ArrayList(); + ArrayList new_ids = new ArrayList(); + String errors = ""; + for (int j = 0; j < ids.size(); j++) { + String id = (String) ids.get(j); + boolean to_delete = false; + + for (int i = 0; i < rows.length; i++) { + String handle = (String) jobStatusPanel1.jobStatusTable.getValueAt( + rows[i], 0); + if (handle.equalsIgnoreCase(id)) { + to_delete = true; + break; + } + } + + if (!to_delete) { + new_ids.add(id); + //errors += "Id " + handle + " is not in log file\n"; + } + } + + System.err.println("Function is not implemented"); + if (true) { + //if (GRAM.recordNewLog(new_ids) != 0) { + //JOptionPane.showMessageDialog(null, GRAM.getMessage(), "Log Update", JOptionPane.ERROR_MESSAGE); + return; + } + + queryJobStatus(); + + if (errors.length() > 0) { + JOptionPane.showMessageDialog(null, errors, "Notice", JOptionPane.WARNING_MESSAGE); + } + } else { + jobStatusInterface.removeSelectedCheckpoints(rows); + queryJobStatus(); + } + } + + public void killButton_actionPerformed(ActionEvent e) { + if (jobStatusPanel1.jobStatusTable.getSelectedRowCount() < 1) { + JOptionPane.showMessageDialog(null, + "Select Row(s) First!", + "Advice", + JOptionPane.WARNING_MESSAGE); + return; + } + + taskType = JSD_KILL_JOBS; + performTask("Killing Jobs", "Killing job(s)..."); + //queryJobStatus(); + + } + + public void HelpButton_actionPerformed(ActionEvent e) { + JOptionPane.showMessageDialog(null, + jobStatusPanel1.getHelp(), + "Help", + JOptionPane.INFORMATION_MESSAGE); + } + + public void downloadButton_actionPerformed(ActionEvent e) { + if (jobStatusPanel1.jobStatusTable.getSelectedRowCount() < 1) { + JOptionPane.showMessageDialog(null, + "Select Row(s) First!", + "Advice", + JOptionPane.WARNING_MESSAGE); + return; + } + taskType = JSD_DOWNLOAD_JOBS; + performTask("Downloading Output Files", "Downloading Output File(s)..."); + //queryJobStatus(); + + } + + private class FileTranferWorker + extends cct.tools.SwingWorker implements JobProgressInterface { + + JDialog parent = null; + int jobType; + ProgressDialog pd; + + FileTranferWorker(JDialog p, int jobtype, String jobDesc) { + parent = p; + jobType = jobtype; + pd = new ProgressDialog(new Frame(), "Progress", false); + pd.setLocationRelativeTo(parent); + pd.setAlwaysOnTop(true); + pd.jobTypeLabel.setText(jobDesc); + pd.cancelButton.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + cancelTranfer(); + } + }); + + } + + public boolean isCanceled() { + return false; + } + + public void setTaskDescription(String taskDescription) { + } + + @Override + public void setProgress(int p) { + pd.setProgressValue(p); + } + + public void setProgress(double p) { + setProgress((int) p); + } + + public void setProgress(float p) { + setProgress((int) p); + } + + @Override + public void setProgressText(String text) { + pd.setProgressText(text); + } + + @Override + public Object construct() { + pd.setVisible(true); + try { + Thread.sleep(500); + } catch (Exception ex) { + } + + if (jobType == JSD_QUERY_STATUS) { + getUpdatedJobStatus(); + //updateJobStatus(); + } else if (jobType == JSD_KILL_JOBS) { + killJobs(); + queryJobStatus(); + } else if (jobType == JSD_DOWNLOAD_JOBS) { + downloadOutputFiles(); + queryJobStatus(); + } + + pd.setVisible(false); + return "done"; + } + + void cancelTranfer() { + pd.setVisible(false); + interrupt(); + } + + @Override + public void finished() { + pd.setVisible(false); + } + } + + public static void main(String[] args) { + + SwingUtilities.invokeLater(new Runnable() { + + @Override + public void run() { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (Exception exception) { + exception.printStackTrace(); + } + + CheckPointStatus chk = new CheckPointStatus(); + JobStatusDialog frame = new JobStatusDialog(new Frame(), "Job Status", false, + chk); + frame.performTask("Quering Job Status...", "Quering Job Status...", JobStatusDialog.JSD_QUERY_STATUS); //.queryJobStatus(); + frame.validate(); + frame.hideButton.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + System.exit(0); + } + }); + frame.setDefaultCloseOperation(EXIT_ON_CLOSE); + frame.setVisible(true); + + } + }); + } + + //********************************************************************** + /** + * + *

+ * Title: Molecular Structure Viewer/Editor

+ * + *

+ * Description: Computational Chemistry Toolkit

+ * + *

+ * Copyright: Copyright (c) 2006

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ + class Task + extends Thread { + + private boolean done = false; + private Exception exception = null; + private boolean cancel = false; + + public boolean isDone() { + return done; + } + + public void cancel() { + cancel = true; + } + + public boolean isCancelled() { + return cancel; + } + + @Override + public void run() { + + try { + queryIsDone = false; + if (taskType == JSD_QUERY_STATUS) { + updateJobStatus(); + //ArrayList statuses = GRAM.getStatusLoggedJobs(); + //JobStatusTableModel jstm = new JobStatusTableModel(statuses); + //jobStatusPanel1.jobStatusTable.setModel(jstm); + } else if (taskType == JSD_KILL_JOBS) { + killJobs(); + } else if (taskType == JSD_DOWNLOAD_JOBS) { + downloadOutputFiles(); + } + + queryIsDone = true; + } catch (Exception e) { + exception = e; + done = true; + return; + } + + /* + * try { proxy = model.createProxy(new String(passwordTF.getPassword())); } catch (Exception e) { exception = e; done = true; + * return; } + */ + if (cancel) { + return; + } + + // send the event.... + //if (proxyListener != null) { + // proxyListener.proxyCreated(proxy); + //} + done = true; + } + + public Exception getException() { + return exception; + } + } +} + +class JobStatusDialog_downloadButton_actionAdapter + implements ActionListener { + + private JobStatusDialog adaptee; + + JobStatusDialog_downloadButton_actionAdapter(JobStatusDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.downloadButton_actionPerformed(e); + } +} + +class JobStatusDialog_HelpButton_actionAdapter + implements ActionListener { + + private JobStatusDialog adaptee; + + JobStatusDialog_HelpButton_actionAdapter(JobStatusDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.HelpButton_actionPerformed(e); + } +} + +class JobStatusDialog_killButton_actionAdapter + implements ActionListener { + + private JobStatusDialog adaptee; + + JobStatusDialog_killButton_actionAdapter(JobStatusDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.killButton_actionPerformed(e); + } +} + +class JobStatusDialog_removeButton_actionAdapter + implements ActionListener { + + private JobStatusDialog adaptee; + + JobStatusDialog_removeButton_actionAdapter(JobStatusDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.removeButton_actionPerformed(e); + } +} + +class JobStatusDialog_updateButton_actionAdapter + implements ActionListener { + + private JobStatusDialog adaptee; + + JobStatusDialog_updateButton_actionAdapter(JobStatusDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.updateButton_actionPerformed(e); + } +} + +class JobStatusDialog_hideButton_actionAdapter + implements ActionListener { + + private JobStatusDialog adaptee; + + JobStatusDialog_hideButton_actionAdapter(JobStatusDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.hideButton_actionPerformed(e); + } +} diff --git a/src/main/java/cct/grid/ui/JobStatusPanel.java b/src/main/java/cct/grid/ui/JobStatusPanel.java new file mode 100644 index 0000000..793f813 --- /dev/null +++ b/src/main/java/cct/grid/ui/JobStatusPanel.java @@ -0,0 +1,374 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid.ui; + +import java.awt.BorderLayout; +import java.awt.IllegalComponentStateException; +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.Popup; +import javax.swing.PopupFactory; + +import cct.grid.CheckPoint; +import cct.grid.FileViewerInterface; +import cct.grid.JobStatusInterface; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class JobStatusPanel + extends JPanel implements MouseMotionListener, ActionListener, + MouseListener { + BorderLayout borderLayout1 = new BorderLayout(); + + JScrollPane jScrollPane1 = new JScrollPane(); + + JobStatusTableModel dataSource = null; + JobStatusInterface jsi = null; + javax.swing.Timer popupTimer = null; + PopupFactory factory = null; + Popup popup; + Point mousePoint; + FileViewerInterface fileViewer = null; + + public static String downloadPrefix = "Download "; + + JPopupMenu popupMenu = new JPopupMenu("File download"); + //JMenu downloadMenu = new JMenu("Download"); + PopupListener popupListener = new PopupListener(); + CheckPoint currentCheckPoint = null; + + JobStatusPopupPanel popupPanel = new JobStatusPopupPanel(); + + public JTable jobStatusTable = null; + + boolean DEBUG = false; + + final static String helpText = + "Use cntrl or shfit keys and mouse to select/unselect the rows"; + JLabel jLabel1 = new JLabel(); + + public JobStatusPanel() { + jobStatusTable = new JTable(); + + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JobStatusPanel(JobStatusTableModel data) { + dataSource = data; + jsi = dataSource.getJobStatusInterface(); + jobStatusTable = new JTable(data); + + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public void updateTable(JobStatusTableModel data) { + dataSource = data; + jsi = dataSource.getJobStatusInterface(); + jobStatusTable.setModel(data); + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + jobStatusTable.addMouseMotionListener(this); + jobStatusTable.addMouseListener(this); + jLabel1.setText(" "); + jScrollPane1.getViewport().add(jobStatusTable); + this.add(jScrollPane1, BorderLayout.NORTH); + this.add(jLabel1, BorderLayout.CENTER); + //generalPopup.add(this.downloadMenu); + } + + public String getHelp() { + return helpText; + } + + /** + * Invoked when a mouse button is pressed on a component and then dragged. + * @param e MouseEvent + */ + @Override + public void mouseDragged(MouseEvent e) { + doWork(e); + } + + /** + * Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed. + * @param e MouseEvent + */ + @Override + public void mouseMoved(MouseEvent e) { + doWork(e); + } + + private void doWork(MouseEvent e) { + + if (popupMenu.isShowing()) { + return; + } + + if (popupMenu.isVisible()) { + return; + } + + if (popupTimer != null && popupTimer.isRunning()) { + popupTimer.stop(); + if (popup != null) { + popup.hide(); + popup = null; + } + //logger.info("Stop old timer"); + } + else if (popupTimer != null) { + mousePoint = e.getPoint(); + popupTimer.restart(); + //logger.info("Restart timer"); + return; + } + + mousePoint = e.getPoint(); + popupTimer = new javax.swing.Timer(1000, this); + popupTimer.setRepeats(false); + popupTimer.start(); + //logger.info("Start new timer"); + + //logger.info("x="+e.getX()+" y="+e.getY()); + //daddy.findClosestAtom(e.getX(),e.getY()); + + } + + @Override + public void actionPerformed(ActionEvent e) { + + if (dataSource == null) { + return; + } + + if (popup != null) { + popup.hide(); + popup = null; + } + else { + if (factory == null) { + factory = PopupFactory.getSharedInstance(); + //factory = new PopupFactory(); + } + Point point; + try { + point = this.getLocationOnScreen(); + } + catch (IllegalComponentStateException ex) { + return; + } + int row = jobStatusTable.rowAtPoint(mousePoint); + CheckPoint chk = jsi.getCheckPoint(row); + popupPanel.jobNameLabel.setText(chk.getJobName()); + popupPanel.taskProviderLabel.setText(chk.getTaskProvider()); + popupPanel.hostLabel.setText(chk.getComputer()); + popupPanel.softLabel.setText(chk.getProgram()); + popupPanel.submitTimeLabel.setText(chk.getJobSubmitTime()); + popupPanel.localDirLabel.setText(chk.getLocalDirectory()); + popupPanel.remoteDirLabel.setText(chk.getRemoteDirectory()); + popupPanel.executableLabel.setText(chk.getExecutable()); + popupPanel.setupOutputFiles(chk.getOutputFilesEntry()); + popupPanel.setupResourcesUsed(chk.getResourcesUsed()); + popup = factory.getPopup(this, popupPanel, + point.x + mousePoint.x + 15, + point.y + mousePoint.y + 30); + popup.show(); + + } + + } + + /** + * Invoked when the mouse button has been clicked (pressed and released) on a component. + * @param e MouseEvent + */ + @Override + public void mouseClicked(MouseEvent e) { + + } + + /** + * Invoked when the mouse enters a component. + * @param e MouseEvent + */ + @Override + public void mouseEntered(MouseEvent e) { + + } + + /** + * Invoked when the mouse exits a component. + * @param e MouseEvent + */ + @Override + public void mouseExited(MouseEvent e) { + if (popup != null) { + popup.hide(); + popup = null; + } + } + + /** + * Invoked when a mouse button has been pressed on a component. + * @param e MouseEvent + */ + @Override + public void mousePressed(MouseEvent e) { + if (popup != null) { + popup.hide(); + popup = null; + } + + maybeShowPopup(e); + } + + @Override + public void mouseReleased(MouseEvent e) { + if (popup != null) { + popup.hide(); + popup = null; + } + + maybeShowPopup(e); + } + + public void jobStatusTable_mouseExited(MouseEvent e) { + if (popup != null) { + popup.hide(); + popup = null; + } + } + + private void maybeShowPopup(MouseEvent e) { + if (e.isPopupTrigger()) { + + int row = jobStatusTable.rowAtPoint(e.getPoint()); + CheckPoint chk = jsi.getCheckPoint(row); + Map output = chk.getOutputFilesEntry(); + if (output == null || output.size() < 1) { + return; + } + + //JMenu submenu = new JMenu("Download files"); + //downloadMenu.add(popupPanel); + + this.currentCheckPoint = chk; + //downloadMenu.removeAll(); + popupMenu.removeAll(); + Set set = output.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String tag = me.getKey().toString(); + if (tag.startsWith("local")) { + continue; + } + Object obj = me.getValue(); + String fileName = obj.toString(); + + JMenuItem menuItem = new JMenuItem(downloadPrefix + fileName); + menuItem.addActionListener(this.popupListener); + //submenu.add(menuItem); + //downloadMenu.add(menuItem); + popupMenu.add(menuItem); + } + //downloadMenu.add(submenu); + + if (popup != null) { + popup.hide(); + popup = null; + } + + popupMenu.show(e.getComponent(), e.getX(), e.getY()); + } + } + + public void setFileViewer(FileViewerInterface fileviewer) { + fileViewer = fileviewer; + } + + private class PopupListener + implements ActionListener { + PopupListener() {} + + @Override + public void actionPerformed(ActionEvent e) { + String arg = e.getActionCommand(); + arg = arg.substring(downloadPrefix.length()); + fileViewer.setFileInfo(currentCheckPoint, arg); + } + + } + +} diff --git a/src/main/java/cct/grid/ui/JobStatusPopupPanel.java b/src/main/java/cct/grid/ui/JobStatusPopupPanel.java new file mode 100644 index 0000000..bf7a277 --- /dev/null +++ b/src/main/java/cct/grid/ui/JobStatusPopupPanel.java @@ -0,0 +1,272 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid.ui; + +import java.awt.Color; +import java.awt.GridLayout; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import javax.swing.BorderFactory; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.border.BevelBorder; +import javax.swing.border.TitledBorder; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class JobStatusPopupPanel + extends JPanel { + JLabel jLabel1 = new JLabel(); + JLabel jobNameLabel = new JLabel(); + JLabel jLabel3 = new JLabel(); + JLabel hostLabel = new JLabel(); + JLabel jLabel5 = new JLabel(); + JLabel taskProviderLabel = new JLabel(); + JLabel jLabel7 = new JLabel(); + JLabel softLabel = new JLabel(); + JLabel jLabel9 = new JLabel(); + JLabel submitTimeLabel = new JLabel(); + GridLayout gridLayout1 = new GridLayout(); + JLabel jLabel2 = new JLabel(); + JLabel localDirLabel = new JLabel(); + JLabel jLabel4 = new JLabel(); + JLabel remoteDirLabel = new JLabel(); + JLabel jLabel8 = new JLabel(); + JLabel executableLabel = new JLabel(); + + JLabel outputFilesLabel = new JLabel("Output Files"); + JLabel resourcesUsedLabel = new JLabel("Resources Used"); + JLabel emptyLabel = new JLabel(" "); + JLabel emptyLabel2 = new JLabel(" "); + + java.util.List labelStore = new ArrayList (); + java.util.List resourcesLabelStore = new ArrayList (); + + public JobStatusPopupPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(gridLayout1); + jLabel1.setToolTipText(""); + jLabel1.setText("Job Name: "); + jobNameLabel.setToolTipText(""); + jobNameLabel.setText("Unknown Name"); + jLabel3.setToolTipText(""); + jLabel3.setText("Remote Host: "); + hostLabel.setToolTipText(""); + hostLabel.setText("Uknown Host"); + jLabel5.setToolTipText(""); + jLabel5.setText("Task Provider: "); + taskProviderLabel.setToolTipText(""); + taskProviderLabel.setText("Unknown Task Provider"); + jLabel7.setToolTipText(""); + jLabel7.setText("Software: "); + softLabel.setToolTipText(""); + softLabel.setText("Unknown software"); + jLabel9.setToolTipText(""); + jLabel9.setText("Submit Time: "); + submitTimeLabel.setToolTipText(""); + submitTimeLabel.setText("Unknown Submit Time"); + gridLayout1.setColumns(2); + gridLayout1.setRows(0); + this.setBackground(new Color(176, 235, 228)); + this.setBorder(new TitledBorder(BorderFactory.createBevelBorder(BevelBorder. + RAISED, Color.white, new Color(251, 255, 255), new Color(86, 114, 111), + new Color(123, 164, 159)), "Extended Task Info")); + jLabel2.setToolTipText(""); + jLabel2.setText("Local Directory: "); + localDirLabel.setToolTipText(""); + localDirLabel.setText("Unknown Local Directory"); + jLabel4.setToolTipText(""); + jLabel4.setText("Remote Directory: "); + remoteDirLabel.setToolTipText(""); + remoteDirLabel.setText("Unknown Local Directory"); + jLabel8.setToolTipText(""); + jLabel8.setText("Executable: "); + executableLabel.setToolTipText(""); + executableLabel.setText("Unknown Executable"); + this.add(jLabel1, null); + this.add(jobNameLabel, null); + this.add(jLabel3); + this.add(hostLabel); + this.add(jLabel5); + this.add(taskProviderLabel); + this.add(jLabel7); + this.add(softLabel); + this.add(jLabel9); + this.add(submitTimeLabel); + this.add(jLabel2); + this.add(localDirLabel); + this.add(jLabel4); + this.add(remoteDirLabel); + this.add(jLabel8); + this.add(executableLabel); + } + + public void setupOutputFiles(Map outFiles) { + + if (outFiles == null || outFiles.size() < 1) { + this.remove(outputFilesLabel); + this.remove(emptyLabel); + + for (Iterator iter = labelStore.iterator(); iter.hasNext(); ) { + JLabel label = (JLabel) iter.next(); + remove(label); + } + + this.validate(); + return; + } + + // ---- Set title + + add(outputFilesLabel); + add(emptyLabel); + + Set set = outFiles.entrySet(); + Iterator iter = set.iterator(); + int count = 0; + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String tag = me.getKey().toString(); + if (tag.startsWith("local")) { + continue; + } + Object obj = me.getValue(); + String fileName = obj.toString(); + + if (labelStore.size() >= count + 2) { + JLabel label = labelStore.get(count); + label.setText(tag); + add(label); + label = labelStore.get(count + 1); + //JMenuItem jmenu = new JMenuItem(fileName); + label.setText(fileName); + add(label); + //add(jmenu); + } + else { + JLabel label = new JLabel(tag); + labelStore.add(label); + add(label); + label = new JLabel(fileName); + labelStore.add(label); + //JMenuItem jmenu = new JMenuItem(fileName); + //add(jmenu); + add(label); + } + + count += 2; + } + this.validate(); + } + + public void setupResourcesUsed(Map rUsed) { + + if (rUsed == null || rUsed.size() < 1) { + this.remove(resourcesUsedLabel); + this.remove(emptyLabel2); + + for (Iterator iter = resourcesLabelStore.iterator(); iter.hasNext(); ) { + JLabel label = (JLabel) iter.next(); + remove(label); + } + + this.validate(); + return; + } + + // ---- Set title + + add(resourcesUsedLabel); + add(emptyLabel2); + + Set set = rUsed.entrySet(); + Iterator iter = set.iterator(); + int count = 0; + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String tag = me.getKey().toString(); + String value = me.getValue().toString(); + + if (resourcesLabelStore.size() >= count + 2) { + JLabel label = resourcesLabelStore.get(count); + label.setText(tag); + add(label); + label = resourcesLabelStore.get(count + 1); + //JMenuItem jmenu = new JMenuItem(fileName); + label.setText(value); + add(label); + //add(jmenu); + } + else { + JLabel label = new JLabel(tag); + resourcesLabelStore.add(label); + add(label); + label = new JLabel(value); + resourcesLabelStore.add(label); + //JMenuItem jmenu = new JMenuItem(fileName); + //add(jmenu); + add(label); + } + + count += 2; + } + this.validate(); + } + +} diff --git a/src/main/java/cct/grid/ui/JobStatusTableModel.java b/src/main/java/cct/grid/ui/JobStatusTableModel.java new file mode 100644 index 0000000..f85c617 --- /dev/null +++ b/src/main/java/cct/grid/ui/JobStatusTableModel.java @@ -0,0 +1,198 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.grid.ui; + +import java.util.logging.Logger; + +import javax.swing.table.AbstractTableModel; + +import cct.grid.JobStatusInterface; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class JobStatusTableModel + extends AbstractTableModel { + + String[] columnNames = null; + boolean DEBUG = true; + Object[][] data = null; + JobStatusInterface jobStatusInterface = null; + static final Logger logger = Logger.getLogger(JobStatusTableModel.class.getCanonicalName()); + + public JobStatusTableModel(Object[][] new_data) { + data = new_data; + } + + public JobStatusInterface getJobStatusInterface() { + return jobStatusInterface; + } + public JobStatusTableModel(java.util.List statuses) { + if (statuses.size() < 1) { + data = null; + return; + } + columnNames = new String[]{ + "Handle", "Status", "Selection"}; + data = new Object[statuses.size()][]; + for (int i = 0; i < statuses.size(); i++) { + java.util.List job = (java.util.List) statuses.get(i); + data[i] = new Object[3]; + data[i][0] = job.get(0); // Job Handle + data[i][1] = job.get(1); // Job Status as a String + data[i][2] = new Boolean(false); + } + } + + public JobStatusTableModel(JobStatusInterface jsi) { + jobStatusInterface = jsi; + columnNames = jsi.getColumnNames(); + data = jsi.getData(); + for (int i = 0; i < data.length; i++) { + if (columnNames.length != data[i].length) { + System.err.println("columnNames.length != data[0].length"); + } + } + } + + public JobStatusTableModel(String[] cn, Object[][] dat, JobStatusInterface jsi) { + jobStatusInterface = jsi; + columnNames = cn; + data = dat; + for (int i = 0; i < data.length; i++) { + if (columnNames.length != data[i].length) { + System.err.println("columnNames.length != data[0].length"); + } + } + } + + @Override + public int getColumnCount() { + return columnNames.length; + } + + @Override + public int getRowCount() { + if (data == null) { + return 0; + } + return data.length; + } + + @Override + public String getColumnName(int col) { + return columnNames[col]; + } + + @Override + public Object getValueAt(int row, int col) { + return data[row][col]; + } + + /* + * JTable uses this method to determine the default renderer/ + * editor for each cell. If we didn't implement this method, + * then the last column would contain text ("true"/"false"), + * rather than a check box. + */ + @Override + public Class getColumnClass(int c) { + return getValueAt(0, c).getClass(); + } + + /* + * Don't need to implement this method unless your table's + * editable. + */ + @Override + public boolean isCellEditable(int row, int col) { + //Note that the data/cell address is constant, + //no matter where the cell appears onscreen. + + //if (col < 2) { + return false; + //} + //else { + // return true; + //} + } + + /* + * Don't need to implement this method unless your table's + * data can change. + */ + @Override + public void setValueAt(Object value, int row, int col) { + if (DEBUG) { + logger.info("Setting value at " + row + "," + col + + " to " + value + + " (an instance of " + + value.getClass() + ")"); + } + + data[row][col] = value; + fireTableCellUpdated(row, col); + + if (DEBUG) { + logger.info("New value of data:"); + printDebugData(); + } + } + + private void printDebugData() { + int numRows = getRowCount(); + int numCols = getColumnCount(); + + for (int i = 0; i < numRows; i++) { + System.out.print(" row " + i + ":"); + for (int j = 0; j < numCols; j++) { + System.out.print(" " + data[i][j]); + } + System.out.print("\n"); + } + logger.info("--------------------------"); + } +} diff --git a/src/main/java/cct/grid/ui/NoSchedulerPanel.java b/src/main/java/cct/grid/ui/NoSchedulerPanel.java new file mode 100644 index 0000000..f456827 --- /dev/null +++ b/src/main/java/cct/grid/ui/NoSchedulerPanel.java @@ -0,0 +1,110 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid.ui; + +import java.awt.BorderLayout; +import java.awt.Component; + +import javax.swing.JPanel; + +import cct.grid.JobDescription; +import cct.grid.ResourcesProviderInterface; +import cct.grid.SchedulerInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class NoSchedulerPanel + extends JPanel implements SchedulerInterface { + BorderLayout borderLayout1 = new BorderLayout(); + ResourcesProviderInterface Resources = null; + + public NoSchedulerPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + } + + @Override + public Component getVisualComponent() { + return this; + } + + @Override + public String getProject() { + return null; + } + + @Override + public Object getOption(String option) { + return null; + } + + @Override + public String getCommandsAsString() { + return null; + } + + @Override + public void setResourcesProvider(ResourcesProviderInterface resources) { + Resources = resources; + } + + @Override + public void setJobDescription(JobDescription job) throws Exception { + + } + + +} diff --git a/src/main/java/cct/grid/ui/PBSPanel.java b/src/main/java/cct/grid/ui/PBSPanel.java new file mode 100644 index 0000000..7991ae8 --- /dev/null +++ b/src/main/java/cct/grid/ui/PBSPanel.java @@ -0,0 +1,539 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.grid.ui; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.FlowLayout; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.StringWriter; +import java.net.URL; +import java.util.Properties; +import java.util.prefs.Preferences; + +import javax.swing.JCheckBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTabbedPane; +import javax.swing.JTextField; +import javax.swing.SwingConstants; + +import cct.GlobalSettings; +import cct.grid.ClientProgramInterface; +import cct.grid.JobDescription; +import cct.grid.ResourcesProviderInterface; +import cct.grid.SchedulerInterface; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + * Call validateValues() before querying for values + * Setup ResourcesProviderInterface and ClientProgramInterface before calling getCommandsAsString() + * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class PBSPanel + extends JPanel implements SchedulerInterface { + + static final String ENABLE_EXTENSIONS = "enableExtensions"; + static final String ENABLE_EDIT_EXTENSIONS = "enableEditExtensions"; + static final String DEFAULT_QUEUE = "defaultQueue"; + static final String ENABLE_EDIT_QUEUE = "enableEditQueue"; + //cct.grid.ui.PBSPanel@enableExtensions = true + //cct.grid.ui.PBSPanel@enableEditExtensions = true + //cct.grid.ui.PBSPanel@defaultQueue = titan + //cct.grid.ui.PBSPanel@enableEditQueue = false + ResourcesProviderInterface resourcesProvider = null; + ClientProgramInterface clientProgram = null; + Preferences prefs = Preferences.userNodeForPackage(getClass()); + JLabel queueLabel = new JLabel(); + JLabel jobfsLabel = new JLabel(); + JLabel softLabel = new JLabel(); + JLabel projectLabel = new JLabel(); + public JTextField ProjectTextField = new JTextField(); + public JTextField QueueTextField = new JTextField(); + public JTextField JobfsTextField = new JTextField(); + public JTextField SoftwareTextField = new JTextField(); + public JCheckBox extCheckBox = new JCheckBox(); + static final String projectKey = "project"; + static final String queueKey = "queue"; + static final String timeKey = "time"; + static final String memoryKey = "memory"; + static final String jobfsKey = "jobfs"; + static final String softwareKey = "software"; + static final String cpuKey = "cpu"; + JPanel jPanel1 = new JPanel(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + BorderLayout borderLayout1 = new BorderLayout(); + JTabbedPane jTabbedPane1 = new JTabbedPane(); + JPanel jPanel2 = new JPanel(); + JPanel extensionsPanel = new JPanel(); + FlowLayout flowLayout1 = new FlowLayout(); + + public PBSPanel() { + try { + jbInit(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public PBSPanel(String project, String queue, int time, int memory, + int jobfs, String software) { + try { + jbInit(); + if (project == null) { + setDefaultProject(); + } else { + ProjectTextField.setText(project); + } + QueueTextField.setText(queue); + JobfsTextField.setText(String.valueOf(jobfs)); + SoftwareTextField.setText(software); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + queueLabel.setToolTipText(""); + queueLabel.setHorizontalAlignment(SwingConstants.RIGHT); + queueLabel.setText("Queue: "); + jobfsLabel.setToolTipText(""); + jobfsLabel.setHorizontalAlignment(SwingConstants.RIGHT); + jobfsLabel.setText("Jobfs (GB): "); + softLabel.setToolTipText(""); + softLabel.setHorizontalAlignment(SwingConstants.RIGHT); + softLabel.setText("Software: "); + projectLabel.setToolTipText(""); + projectLabel.setHorizontalAlignment(SwingConstants.RIGHT); + projectLabel.setText("Project: "); + extCheckBox.setText("Enable pbs extensions"); + extCheckBox.setSelected(true); + + ProjectTextField.setToolTipText(""); + ProjectTextField.setColumns(6); + ProjectTextField.addActionListener(new PBSPanel_ProjectTextField_actionAdapter(this)); + QueueTextField.setToolTipText(""); + QueueTextField.setText("normal"); + QueueTextField.setColumns(6); + JobfsTextField.setToolTipText(""); + JobfsTextField.setText("5"); + JobfsTextField.setColumns(6); + SoftwareTextField.setToolTipText(""); + SoftwareTextField.setColumns(6); + jPanel1.setLayout(gridBagLayout1); + extensionsPanel.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + this.add(jTabbedPane1, BorderLayout.NORTH); + jTabbedPane1.add(jPanel1, "Basic"); + jTabbedPane1.add(extensionsPanel, "Extensions"); + extensionsPanel.add(jobfsLabel); + extensionsPanel.add(JobfsTextField); + extensionsPanel.add(softLabel); + extensionsPanel.add(SoftwareTextField); + jTabbedPane1.add(jPanel2, "Other"); + jPanel1.add(projectLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + jPanel1.add(queueLabel, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + jPanel1.add(QueueTextField, new GridBagConstraints(3, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + jPanel1.add(extCheckBox, new GridBagConstraints(0, 1, 3, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + jPanel1.add(ProjectTextField, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + String value; + + setDefaultProject(); + + value = prefs.get(projectKey, ""); + ProjectTextField.setText(value); + + value = prefs.get(queueKey, "normal"); + QueueTextField.setText(value); + + value = prefs.get(timeKey, "60"); + value = prefs.get(memoryKey, "1024"); + value = prefs.get(jobfsKey, "5"); + JobfsTextField.setText(value); + + value = prefs.get(softwareKey, "g03"); + SoftwareTextField.setText(value); + + value = prefs.get(cpuKey, "1"); + + // --- + + URL custom = null; + String className = this.getClass().getCanonicalName(); + try { + custom = PBSPanel.class.getClassLoader().getResource(GlobalSettings.CCT_PROPERTY_FILE); + Properties props = new Properties(); + props.load(custom.openStream()); + + //--- Default enable extensions + + String enableExt = props.getProperty(className + GlobalSettings.DIVIDER + ENABLE_EXTENSIONS); + if (enableExt != null) { + Boolean editable; + try { + editable = Boolean.parseBoolean(enableExt); + extCheckBox.setSelected(editable); + } catch (Exception exx) { + } + } + + // --- Enable edit extension + enableExt = props.getProperty(className + GlobalSettings.DIVIDER + ENABLE_EDIT_EXTENSIONS); + if (enableExt != null) { + Boolean editable; + try { + editable = Boolean.parseBoolean(enableExt); + extCheckBox.setEnabled(editable); + } catch (Exception exx) { + } + } + + // --- Default queue + + enableExt = props.getProperty(className + GlobalSettings.DIVIDER + DEFAULT_QUEUE); + if (enableExt != null) { + QueueTextField.setText(enableExt); + } + + // --- Enable to edit queue + + enableExt = props.getProperty(className + GlobalSettings.DIVIDER + ENABLE_EDIT_QUEUE); + if (enableExt != null) { + Boolean editable; + try { + editable = Boolean.parseBoolean(enableExt); + QueueTextField.setEditable(editable); + } catch (Exception exx) { + } + } + + } catch (Exception ex) { + } + + } + + public void saveCurrentSettings() { + prefs.put(projectKey, ProjectTextField.getText()); + prefs.put(queueKey, QueueTextField.getText()); + prefs.put(jobfsKey, JobfsTextField.getText()); + prefs.put(softwareKey, SoftwareTextField.getText()); + + } + + public void setDefaultProject() { + String value = prefs.get(projectKey, ""); + ProjectTextField.setText(value); + } + + @Override + public String getProject() { + return ProjectTextField.getText().trim(); + } + + public String getQueue() { + return QueueTextField.getText().trim(); + } + + public String getSoftware() { + return SoftwareTextField.getText().trim(); + } + + /* + public RslAttributes getRSL() throws Exception { + RslAttributes rsl = new RslAttributes(); + rsl.add("project", ProjectTextField.getText().trim()); + rsl.add("queue", QueueTextField.getText().trim()); + int test = 0; + + try { + test = getJobFS(); + rsl.add("jobfs", JobfsTextField.getText()); + } + catch (Exception ex) { + throw ex; + } + + rsl.add("software", SoftwareTextField.getText()); + + return rsl; + } + */ + public int getJobFS() { + if (JobfsTextField.getText().trim().length() < 1) { + return 0; + } + int test = 0; + try { + test = (int) Float.parseFloat(JobfsTextField.getText().trim()); + } catch (Exception ex) { + System.err.println("Internal error: Wrong value for jobfs: " + + ex.getMessage() + + " Use validateValues() before calling getJobFS"); + //throw new Exception("Wrong value for jobfs: " + ex.getMessage()); + } finally { + if (test < 0) { + System.err.println( + "Internal error: Wrong value for jobfs: it should be positive. Use validateValues() before calling getJobFS"); + //throw new Exception("Value for time should be positive"); + } + } + return test; + } + + public boolean areExtensionsEnabled() { + return this.extCheckBox.isSelected(); + } + + public void ProjectTextField_actionPerformed(ActionEvent e) { + String value = ProjectTextField.getText(); + try { + prefs.put(projectKey, value); + } catch (Exception ex) { + System.err.println("Warning: Unable to save project: " + ex.getMessage()); + } + } + + @Override + public void setResourcesProvider(ResourcesProviderInterface resources) { + resourcesProvider = resources; + } + + public void setClientProgram(ClientProgramInterface client) { + clientProgram = client; + } + + /** + * Returns time in the format [[hours:]minutes:]seconds + * @return String + */ + static public String getMaxWallTimeFormatted(int timeInSeconds) { + String time = ""; + + if ((timeInSeconds / 3600) > 0) { + time += String.valueOf((timeInSeconds / 3600)) + ":"; + timeInSeconds -= (timeInSeconds / 3600) * 3600; // What left in minutes + if ((timeInSeconds / 60) > 0) { + String minutes = String.valueOf((timeInSeconds / 60)); + if (minutes.length() == 1) { + minutes = "0" + minutes; + } + time += minutes + ":"; + timeInSeconds -= (timeInSeconds / 60) * 60; // What left in seconds + time += timeInSeconds; + } else { + if (timeInSeconds >= 10) { + time += "00:" + timeInSeconds; + } else { + time += "00:0" + timeInSeconds; + } + } + } // --- Time is in minutes (and seconds) + else if ((timeInSeconds / 60) > 0) { + String minutes = String.valueOf((timeInSeconds / 60)); + if (minutes.length() == 1) { + minutes = "0" + minutes; + } + time += minutes + ":"; + timeInSeconds -= (timeInSeconds / 60) * 60; // What left in seconds + if (timeInSeconds >= 10) { + time += timeInSeconds; + } else { + time += "0" + timeInSeconds; + } + + } // --- Time in seconds only + else { + if (timeInSeconds >= 10) { + time += timeInSeconds; + } else { + time += "0" + timeInSeconds; + } + } + + return time; + } + + @Override + public String getCommandsAsString() { + StringWriter sWriter = new StringWriter(); + if (resourcesProvider == null) { + System.err.println("Warning: resources provider is not set"); + } + + if (ProjectTextField.getText().trim().length() > 0) { + sWriter.write("#PBS -P " + ProjectTextField.getText().trim() + "\n"); + } + if (QueueTextField.getText().trim().length() > 0) { + sWriter.write("#PBS -q " + QueueTextField.getText().trim() + "\n"); + } + + if (resourcesProvider != null) { + + sWriter.write("#PBS -l walltime=" + + getMaxWallTimeFormatted((int) resourcesProvider.getTimeInSeconds()) + "\n"); + sWriter.write("#PBS -l vmem=" + + ((int) resourcesProvider.getMaxMemoryInMb()) + "MB\n"); + + sWriter.write("#PBS -l ncpus=" + resourcesProvider.getNCPUs() + "\n"); + + } + + if (this.extCheckBox.isSelected()) { + + if (this.SoftwareTextField.getText().trim().length() > 0) { + sWriter.write("#PBS -l software=" + + SoftwareTextField.getText().trim() + "\n"); + } + + if (this.JobfsTextField.getText().trim().length() > 0) { + sWriter.write("#PBS -l jobfs=" + this.getJobFS() + "Gb\n"); + } + + if (this.SoftwareTextField.getText().trim().length() > 0) { + sWriter.write("#PBS -l other=" + SoftwareTextField.getText().trim() + + "\n"); + } + } + + if (clientProgram != null) { + if (clientProgram.getStdoutFileName() != null + && clientProgram.getStdoutFileName().length() > 0) { + sWriter.write("#PBS -o " + clientProgram.getStdoutFileName() + "\n"); + } + if (clientProgram.getStderrFileName() != null + && clientProgram.getStderrFileName().length() > 0) { + sWriter.write("#PBS -e " + clientProgram.getStderrFileName() + "\n"); + } + + } + + sWriter.write("#PBS -wd\n\n"); + + return sWriter.toString(); + } + + public void validateValues() throws Exception { + + // --- Check jobfs field + + if (JobfsTextField.getText().trim().length() > 0) { + int test = 0; + try { + test = (int) Float.parseFloat(JobfsTextField.getText().trim()); + } catch (Exception ex) { + throw new Exception("Wrong value for jobfs: " + ex.getMessage()); + } finally { + if (test < 0) { + throw new Exception("Value for time should be positive"); + } + } + } + + } + + @Override + public Component getVisualComponent() { + return this; + } + + @Override + public Object getOption(String option) { + return null; + } + + @Override + public void setJobDescription(JobDescription job) throws Exception { + + // --- Setup jobfs + + int jobFS = 0; + if (areExtensionsEnabled()) { + try { + jobFS = getJobFS(); + if (jobFS > 0) { + job.setJobFS(jobFS); + } + } catch (Exception ex) { + throw new Exception(ex.getMessage()); + } + } + + // --- Setup software + + if (this.areExtensionsEnabled() && getSoftware().length() > 0) { + job.setSoftware(getSoftware()); + } + + job.setPbsJobScript(true); + job.setProject(this.getProject()); + job.setQueue(this.getQueue()); + } + + private class PBSPanel_ProjectTextField_actionAdapter + implements ActionListener { + + private PBSPanel adaptee; + + PBSPanel_ProjectTextField_actionAdapter(PBSPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.ProjectTextField_actionPerformed(e); + } + } +} diff --git a/src/main/java/cct/grid/ui/PBS_Panel.java b/src/main/java/cct/grid/ui/PBS_Panel.java new file mode 100644 index 0000000..d24f981 --- /dev/null +++ b/src/main/java/cct/grid/ui/PBS_Panel.java @@ -0,0 +1,414 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid.ui; + +import java.awt.BorderLayout; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.prefs.Preferences; + +import javax.swing.JCheckBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.SwingConstants; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class PBS_Panel + extends JPanel { + Preferences prefs = Preferences.userNodeForPackage(getClass()); + JLabel memoryLabel = new JLabel(); + JLabel timeLabel = new JLabel(); + JLabel queueLabel = new JLabel(); + JLabel jobfsLabel = new JLabel(); + JLabel softLabel = new JLabel(); + JLabel projectLabel = new JLabel(); + JLabel cpuLabel = new JLabel(); + public JTextField ProjectTextField = new JTextField(); + public JTextField QueueTextField = new JTextField(); + public JTextField TimeTextField = new JTextField(); + public JTextField MemoryTextField = new JTextField(); + public JTextField JobfsTextField = new JTextField(); + public JTextField SoftwareTextField = new JTextField(); + public JTextField CPUTextField = new JTextField(); + + public JCheckBox extCheckBox = new JCheckBox(); + + static final String projectKey = "project"; + static final String queueKey = "queue"; + static final String timeKey = "time"; + static final String memoryKey = "memory"; + static final String jobfsKey = "jobfs"; + static final String softwareKey = "software"; + static final String cpuKey = "cpu"; + + JPanel jPanel1 = new JPanel(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + BorderLayout borderLayout1 = new BorderLayout(); + + public PBS_Panel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public PBS_Panel(String project, String queue, int time, int memory, + int jobfs, String software) { + try { + jbInit(); + if (project == null) { + setDefaultProject(); + } + else { + ProjectTextField.setText(project); + } + QueueTextField.setText(queue); + TimeTextField.setText(String.valueOf(time)); + MemoryTextField.setText(String.valueOf(memory)); + JobfsTextField.setText(String.valueOf(jobfs)); + SoftwareTextField.setText(software); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + memoryLabel.setToolTipText(""); + memoryLabel.setHorizontalAlignment(SwingConstants.RIGHT); + memoryLabel.setText("Memory (MB): "); + timeLabel.setToolTipText(""); + timeLabel.setHorizontalAlignment(SwingConstants.RIGHT); + timeLabel.setText("Time (min): "); + queueLabel.setToolTipText(""); + queueLabel.setHorizontalAlignment(SwingConstants.RIGHT); + queueLabel.setText("Queue: "); + jobfsLabel.setToolTipText(""); + jobfsLabel.setHorizontalAlignment(SwingConstants.RIGHT); + jobfsLabel.setText("Jobfs (GB): "); + softLabel.setToolTipText(""); + softLabel.setHorizontalAlignment(SwingConstants.RIGHT); + softLabel.setText("Software: "); + projectLabel.setToolTipText(""); + projectLabel.setHorizontalAlignment(SwingConstants.RIGHT); + projectLabel.setText("Project: "); + cpuLabel.setToolTipText(""); + cpuLabel.setHorizontalAlignment(SwingConstants.RIGHT); + cpuLabel.setText("CPUs: "); + + extCheckBox.setText("Enable pbs extensions"); + extCheckBox.setEnabled(false); + extCheckBox.setSelected(true); + + ProjectTextField.setToolTipText(""); + ProjectTextField.setColumns(6); + ProjectTextField.addActionListener(new + PBS_Panel_ProjectTextField_actionAdapter(this)); + QueueTextField.setToolTipText(""); + QueueTextField.setText("normal"); + QueueTextField.setColumns(6); + TimeTextField.setToolTipText(""); + TimeTextField.setText("60"); + TimeTextField.setColumns(6); + MemoryTextField.setToolTipText(""); + MemoryTextField.setText("1024"); + MemoryTextField.setColumns(6); + JobfsTextField.setToolTipText(""); + JobfsTextField.setText("5"); + JobfsTextField.setColumns(6); + SoftwareTextField.setToolTipText(""); + SoftwareTextField.setColumns(6); + CPUTextField.setToolTipText(""); + CPUTextField.setText("1"); + CPUTextField.setColumns(6); + jPanel1.setLayout(gridBagLayout1); + jPanel1.add(projectLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + jPanel1.add(queueLabel, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + jPanel1.add(timeLabel, new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + jPanel1.add(memoryLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + jPanel1.add(cpuLabel, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + jPanel1.add(jobfsLabel, new GridBagConstraints(4, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + jPanel1.add(softLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(jPanel1, BorderLayout.NORTH); + jPanel1.add(SoftwareTextField, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + jPanel1.add(MemoryTextField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + jPanel1.add(ProjectTextField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + jPanel1.add(QueueTextField, new GridBagConstraints(3, 0, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + jPanel1.add(CPUTextField, new GridBagConstraints(3, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + jPanel1.add(TimeTextField, new GridBagConstraints(5, 0, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + jPanel1.add(JobfsTextField, new GridBagConstraints(5, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + + jPanel1.add(extCheckBox, new GridBagConstraints(0, 3, 2, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + String value; + + setDefaultProject(); + + value = prefs.get(projectKey, ""); + ProjectTextField.setText(value); + + value = prefs.get(queueKey, "normal"); + QueueTextField.setText(value); + + value = prefs.get(timeKey, "60"); + TimeTextField.setText(value); + + value = prefs.get(memoryKey, "1024"); + MemoryTextField.setText(value); + + value = prefs.get(jobfsKey, "5"); + JobfsTextField.setText(value); + + value = prefs.get(softwareKey, "g03"); + SoftwareTextField.setText(value); + + value = prefs.get(cpuKey, "1"); + CPUTextField.setText(value); + + } + + public void saveCurrentSettings() { + prefs.put(projectKey, ProjectTextField.getText()); + prefs.put(queueKey, QueueTextField.getText()); + prefs.put(timeKey, TimeTextField.getText()); + prefs.put(memoryKey, MemoryTextField.getText()); + prefs.put(jobfsKey, JobfsTextField.getText()); + prefs.put(softwareKey, SoftwareTextField.getText()); + prefs.put(cpuKey, CPUTextField.getText()); + + } + + public void setDefaultProject() { + String value = prefs.get(projectKey, ""); + ProjectTextField.setText(value); + } + + public String getProject() { + return ProjectTextField.getText().trim(); + } + + public String getQueue() { + return QueueTextField.getText().trim(); + } + + public String getSoftware() { + return SoftwareTextField.getText(); + } + + /* + public RslAttributes getRSL() throws Exception { + RslAttributes rsl = new RslAttributes(); + rsl.add("project", ProjectTextField.getText().trim()); + rsl.add("queue", QueueTextField.getText().trim()); + int test = 0; + + try { + test = (int) getMaxTime(); + rsl.add("max_wall_time", String.valueOf(test)); + } + catch (Exception ex) { + throw ex; + } + + try { + test = (int) getMaxMemory(); + rsl.add("maxMemory", MemoryTextField.getText()); + } + catch (Exception ex) { + throw ex; + } + + try { + test = getJobFS(); + rsl.add("jobfs", JobfsTextField.getText()); + } + catch (Exception ex) { + throw ex; + } + + rsl.add("software", SoftwareTextField.getText()); + + try { + test = getNCPUs(); + rsl.add("count", CPUTextField.getText()); + } + catch (Exception ex) { + throw ex; + } + + return rsl; + } + */ + public int getJobFS() throws Exception { + int test = 0; + try { + test = (int) Float.parseFloat(JobfsTextField.getText().trim()); + } + catch (Exception ex) { + throw new Exception("Wrong value for jobfs: " + ex.getMessage()); + } + finally { + if (test < 0) { + throw new Exception("Value for time should be positive"); + } + } + return test; + } + + public int getNCPUs() throws Exception { + int test = 0; + try { + + test = Integer.parseInt(CPUTextField.getText().trim()); + } + catch (Exception ex) { + throw new Exception("Wrong value for cpu: " + ex.getMessage()); + } + finally { + if (test < 1) { + throw new Exception("Value for number of cpu's should be > 0"); + } + } + return test; + } + + public float getMaxTime() throws Exception { + float test = 0; + try { + test = Float.parseFloat(TimeTextField.getText().trim()); + } + catch (Exception ex) { + throw new Exception("Wrong value for time: " + ex.getMessage()); + } + finally { + if (test < 1) { + throw new Exception("Value for time should be > 0"); + } + } + return test; + } + + public int getMaxMemory() throws Exception { + int test = 0; + try { + test = Integer.parseInt(MemoryTextField.getText().trim()); + } + catch (Exception ex) { + throw new Exception("Wrong value for memory: " + ex.getMessage()); + } + finally { + if (test < 1) { + throw new Exception("Value for memory should be > 0"); + } + } + return test; + } + + public void ProjectTextField_actionPerformed(ActionEvent e) { + String value = ProjectTextField.getText(); + try { + prefs.put(projectKey, value); + } + catch (Exception ex) { + System.err.println("Warning: Unable to save project: " + ex.getMessage()); + } + } +} + +class PBS_Panel_ProjectTextField_actionAdapter + implements ActionListener { + private PBS_Panel adaptee; + PBS_Panel_ProjectTextField_actionAdapter(PBS_Panel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.ProjectTextField_actionPerformed(e); + } +} diff --git a/src/main/java/cct/grid/ui/ProgressDialog.java b/src/main/java/cct/grid/ui/ProgressDialog.java new file mode 100644 index 0000000..d985a5c --- /dev/null +++ b/src/main/java/cct/grid/ui/ProgressDialog.java @@ -0,0 +1,112 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.grid.ui; + +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JProgressBar; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class ProgressDialog + extends JDialog { + + JPanel panel1 = new JPanel(); + JProgressBar jProgressBar1 = new JProgressBar(); + public JLabel jobTypeLabel = new JLabel(); + public JButton cancelButton = new JButton(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + + public ProgressDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public ProgressDialog() { + this(new Frame(), "ProgressDialog", false); + } + + private void jbInit() throws Exception { + panel1.setLayout(gridBagLayout1); + this.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); + jobTypeLabel.setText("Progress in doing something..."); + cancelButton.setToolTipText(""); + cancelButton.setText("Cancel"); + getContentPane().add(panel1); + panel1.add(jobTypeLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + panel1.add(jProgressBar1, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + panel1.add(cancelButton, new GridBagConstraints(0, 2, 1, 1, 0.0, 1.0, GridBagConstraints.NORTH, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + jProgressBar1.setIndeterminate(true); + } + + void setProgressValue(int n) { + jProgressBar1.setValue(n < 0 ? 0 : n > 100 ? 100 : n); + } + + void setProgressText(String text) { + jobTypeLabel.setText(text); + this.pack(); + } +} diff --git a/src/main/java/cct/grid/ui/ResourcesPanel.java b/src/main/java/cct/grid/ui/ResourcesPanel.java new file mode 100644 index 0000000..d950879 --- /dev/null +++ b/src/main/java/cct/grid/ui/ResourcesPanel.java @@ -0,0 +1,332 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid.ui; + +import java.awt.FlowLayout; +import java.awt.SystemColor; + +import javax.swing.BorderFactory; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.border.TitledBorder; + +import cct.grid.JobDescription; +import cct.grid.ResourcesProviderInterface; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class ResourcesPanel + extends JPanel implements ResourcesProviderInterface { + + public static final String SECONDS_TIME_UNITS = "Secs"; + public static final String MINUTES_TIME_UNITS = "Mins"; + public static final String HOURS_TIME_UNITS = "Hours"; + + public static final String IN_MEGABYTES = "Mb"; + public static final String IN_GIGABYTES = "Gb"; + + FlowLayout flowLayout1 = new FlowLayout(); + JLabel jLabel1 = new JLabel(); + public JTextField cpuTextField = new JTextField(); + JLabel jLabel2 = new JLabel(); + JLabel jLabel3 = new JLabel(); + public JTextField memoryTextField = new JTextField(); + public JTextField timeTextField = new JTextField(); + public JComboBox memoryComboBox = new JComboBox(); + public JComboBox timeComboBox = new JComboBox(); + + public ResourcesPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + jLabel1.setText("CPUs: "); + cpuTextField.setToolTipText(""); + cpuTextField.setText("1"); + cpuTextField.setColumns(4); + jLabel2.setToolTipText(""); + jLabel2.setText(" Memory: "); + jLabel3.setToolTipText(""); + jLabel3.setText(" Time: "); + memoryTextField.setToolTipText(""); + memoryTextField.setText("1024"); + memoryTextField.setColumns(5); + timeTextField.setToolTipText(""); + timeTextField.setText("1"); + timeTextField.setColumns(4); + this.setBorder(new TitledBorder(BorderFactory.createLineBorder( + SystemColor. + controlDkShadow, 1), "Resources")); + this.add(jLabel1); + this.add(cpuTextField); + this.add(jLabel2); + this.add(memoryTextField); + this.add(memoryComboBox); + this.add(jLabel3); + this.add(timeTextField); + this.add(timeComboBox); + + timeComboBox.addItem(ResourcesPanel.SECONDS_TIME_UNITS); + timeComboBox.addItem(ResourcesPanel.MINUTES_TIME_UNITS); + timeComboBox.addItem(ResourcesPanel.HOURS_TIME_UNITS); + timeComboBox.setSelectedItem(ResourcesPanel.HOURS_TIME_UNITS); + + memoryComboBox.addItem(ResourcesPanel.IN_MEGABYTES); + memoryComboBox.addItem(ResourcesPanel.IN_GIGABYTES); + memoryComboBox.setSelectedItem(ResourcesPanel.IN_MEGABYTES); + } + + @Override + public int getNCPUs() { + int test = 0; + try { + + test = Integer.parseInt(cpuTextField.getText().trim()); + } + catch (Exception ex) { + System.err.println("getNCPU: Internal error: wrong cpu number"); + } + finally { + if (test < 1) { + System.err.println("getNCPU: Internal error: wrong cpu number: <0"); + } + } + return test; + } + + @Override + public float getMaxMemoryInMb() { + float test = 0; + try { + test = Float.parseFloat(memoryTextField.getText().trim()); + } + catch (Exception ex) { + System.err.println("getMaxMemoryInMb: Internal conversion error"); + } + finally { + if (test < 0) { + System.err.println("getMaxMemoryInMb: Internal error: <0"); + } + } + + String units = memoryComboBox.getSelectedItem().toString(); + if (units.equals(IN_MEGABYTES)) { + return test; + } + else if (units.equals(IN_GIGABYTES)) { + return test * 1024.0f; + } + System.err.println("getMaxMemoryInMb: Internal error: wrong units"); + return test; + } + + @Override + public float getTimeInSeconds() { + float intTime = 0; + try { + intTime = this.getNumber(timeTextField); + } + catch (Exception ex) { + System.err.println("getTimeInSeconds: Internal conversion error"); + } + + if (intTime <= 0) { + System.err.println("getTimeInSeconds: Internal error: <=0"); + } + + String units = timeComboBox.getSelectedItem().toString(); + if (units.equals(SECONDS_TIME_UNITS)) { + return intTime; + } + else if (units.equals(MINUTES_TIME_UNITS)) { + intTime *= 60.0f; + } + else if (units.equals(HOURS_TIME_UNITS)) { + intTime *= 3600.0f; + } + else { + System.err.println("getTimeInSeconds: Internal error: wrong conversion units"); + } + + return intTime; + } + + float getNumber(JTextField field) throws Exception { + float number = 0; + try { + number = Float.parseFloat(field.getText().trim()); + } + catch (Exception ex) { + throw ex; + } + return number; + } + + public void validateValues() throws Exception { + //getTimeInSeconds(); + + float intTime = 0; + try { + intTime = this.getNumber(timeTextField); + } + catch (Exception ex) { + throw new Exception("Wrong number for time: " + ex.getMessage()); + } + + if (intTime <= 0) { + throw new Exception("Time should be positive number. Got " + + timeTextField.getText()); + } + + String units = timeComboBox.getSelectedItem().toString(); + if (units.equals(SECONDS_TIME_UNITS)) { + } + else if (units.equals(MINUTES_TIME_UNITS)) { + } + else if (units.equals(HOURS_TIME_UNITS)) { + } + else { + throw new Exception("Internal error while getting time"); + } + + //getMaxMemoryInMb(); + + float test = 0; + try { + test = Float.parseFloat(memoryTextField.getText().trim()); + } + catch (Exception ex) { + throw new Exception("Wrong value for memory: " + ex.getMessage()); + } + finally { + if (test < 0) { + throw new Exception("Value for memory should be > 0"); + } + } + + units = memoryComboBox.getSelectedItem().toString(); + if (units.equals(IN_MEGABYTES)) { + } + else if (units.equals(IN_GIGABYTES)) { + } + else { + throw new Exception("Internal error while getting max memory"); + } + + //getNCPUs(); + + test = 0; + try { + test = Integer.parseInt(cpuTextField.getText().trim()); + } + catch (Exception ex) { + throw new Exception("Wrong value for cpu: " + ex.getMessage()); + } + finally { + if (test < 1) { + throw new Exception("Value for number of cpu's should be > 0"); + } + } + } + + @Override + public void setJobDescription(JobDescription job) throws Exception { + + // --- Setup max (wall) time + + float maxWallTimeInMins = -1; + try { + float time_in_secs = getTimeInSeconds(); + maxWallTimeInMins = time_in_secs / 60.0f; + job.setMaxWallTime(maxWallTimeInMins); + } + catch (Exception ex) { + throw new Exception("Error getting time: " + ex.getMessage()); + } + + // --- Setup max memory + + int maxMemory = 0; // in MB + try { + maxMemory = (int) getMaxMemoryInMb(); + job.setMaxMemory(maxMemory); + } + catch (Exception ex) { + throw new Exception("Error setting max memory: " + ex.getMessage()); + } + + } + + @Override + public void setNCPUs(int n) { + if (n < 1) { + n = 1; + } + cpuTextField.setText(String.valueOf(n)); + } + + @Override + public void setMaxMemoryInMb(int memory) { + if (memory < 1) { + memory = 1; + } + + memoryTextField.setText(String.valueOf(memory)); + + memoryComboBox.setSelectedItem(IN_MEGABYTES); + } +} diff --git a/src/main/java/cct/grid/ui/SubmitTaskDialog.java b/src/main/java/cct/grid/ui/SubmitTaskDialog.java new file mode 100644 index 0000000..1c2010f --- /dev/null +++ b/src/main/java/cct/grid/ui/SubmitTaskDialog.java @@ -0,0 +1,938 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid.ui; + +import java.awt.BorderLayout; +import java.awt.CardLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.SystemColor; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.util.Date; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JProgressBar; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.border.Border; +import javax.swing.border.TitledBorder; + +import cct.globus.ui.GridProxyInitDialog; +import cct.grid.CheckPoint; +import cct.grid.CheckPointInterface; +import cct.grid.ClientProgramInterface; +import cct.grid.GridProviderInterface; +import cct.grid.JobDescription; +import cct.grid.ParseCheckpointFile; +import cct.grid.SchedulerInterface; +import cct.grid.ScriptSubmitterDialogInterface; +import cct.grid.TaskProvider; +import cct.grid.TaskScheduler; +import cct.grid.ui.gaussian.SubmitGaussianPanel; +import cct.interfaces.FileChooserInterface; +import cct.tools.IOUtils; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class SubmitTaskDialog + extends JDialog implements ScriptSubmitterDialogInterface { + + JPanel MainPanel = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + ClientProgramInterface ClientProgram = null; + JPanel ButtonPanel = new JPanel(); + JButton Cancel_Button = new JButton(); + JButton Submit_Button = new JButton(); + + JComboBox providerComboBox = new JComboBox(); + JPanel providerPanel = new JPanel(); + FlowLayout flowLayout1 = new FlowLayout(); + JLabel providerLabel = new JLabel(); + + ProgressDialog progressDialog = null; + + //private GridProxyInterface getGridProxy = null; + int taskType = 0; + private static Logger logger = Logger.getLogger(SubmitTaskDialog.class.getName()); + + Map allProviders = new LinkedHashMap (); + Map allSchedulers = new LinkedHashMap (); + + JobOutputInterface jobOutput = null; + JPanel cardPanel = new JPanel(); + JPanel schedulerCardPanel = new JPanel(); + JPanel comboPanel = new JPanel(); + FlowLayout flowLayout2 = new FlowLayout(); + BorderLayout borderLayout2 = new BorderLayout(); + CardLayout cardLayout1 = new CardLayout(); + CardLayout cardLayout2 = new CardLayout(); + JLabel schedulerLabel = new JLabel(); + JComboBox schedulerComboBox = new JComboBox(); + ResourcesPanel resourcesPanel = new ResourcesPanel(); + JPanel topPanel = new JPanel(); + BorderLayout borderLayout3 = new BorderLayout(); + //PBSPanel pbsPanel = new PBSPanel(); + Border border1 = BorderFactory.createLineBorder(Color.darkGray, 2); + Border border2 = new TitledBorder(border1, "PBS Parameters"); + JButton submitWithEditButton = new JButton(); + EditScriptDialog editScriptDialog = new EditScriptDialog(new Frame(), + "Edit Script before Submission", true); + + public static void main(String[] args) { + + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } + catch (Exception exception) { + exception.printStackTrace(); + } + + ClientProgramInterface client_program = new SubmitGaussianPanel(); + SubmitTaskDialog frame = new SubmitTaskDialog(null, client_program, null, "Task Submission", true); + + Map schedulers = new LinkedHashMap (); + SchedulerInterface pbs = new PBSPanel(); + schedulers.put("pbs", pbs); + pbs = new NoSchedulerPanel(); + schedulers.put("none", pbs); + frame.setSchedulers(schedulers); + + frame.setTaskProviders(TaskProvider.getAvailableTaskProviders()); + frame.validate(); + frame.pack(); + frame.Cancel_Button.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + System.exit(0); + } + } + ); + frame.setDefaultCloseOperation(EXIT_ON_CLOSE); + frame.setVisible(true); + + } + }); + } + + @Override + public JDialog getDialog() { + return this; + } + + @Override + public ScriptSubmitterDialogInterface newInstance() { + return new SubmitTaskDialog(new Frame(), null, null, "Submit Gaussian Script", false); + } + + @Override + public void setCustomOptions(String options) throws Exception { + throw new Exception("setCustomOptions is not implemented in " + this.getClass().getCanonicalName()); + } + + @Override + public void setLocalDirectory(String localDir) { + ClientProgram.setLocalDirectory(localDir); + //submitGaussianPanel.LocalDirTextField.setText(localDir); + } + + @Override + public void setRemoteDirectory(String remoteDir) { + ClientProgram.setRemoteDirectory(remoteDir); + //submitGaussianPanel.RemoteDirTextField.setText(remoteDir); + } + + public JButton getCancelButton() { + return this.Cancel_Button; + } + + public SubmitTaskDialog(Frame owner, ClientProgramInterface client_program, JobOutputInterface redir, + String title, boolean modal) { + super(owner, title, modal); + jobOutput = redir; + ClientProgram = client_program; + ClientProgram.setResourcesInterface(resourcesPanel); + + try { + setDefaultCloseOperation(HIDE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private SubmitTaskDialog() { + this(new Frame(), null, null, "Submit Gaussian Script", false); + } + + // public void setProxyHandler(GridProxyInterface proxyHandler) { + // getGridProxy = proxyHandler; + //} + + private void jbInit() throws Exception { + MainPanel.setLayout(borderLayout1); + //submitGaussianPanel.setBorder(new TitledBorder(BorderFactory. + // createLineBorder(Color.darkGray, 1), "Job Specifications")); + Cancel_Button.setToolTipText("Cancel Submission"); + Cancel_Button.setText("Cancel"); + Cancel_Button.addActionListener(new + SubmitTaskDialog_Cancel_Button_actionAdapter(this)); + Submit_Button.setToolTipText("Submit Job for Execution"); + Submit_Button.setText("Submit"); + Submit_Button.addActionListener(new + SubmitTaskDialog_Submit_Button_actionAdapter(this)); + submitWithEditButton.addActionListener(new + SubmitTaskDialog_Submit_Button_actionAdapter(this)); + this.setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); + providerLabel.setToolTipText(""); + providerLabel.setText(" Provider: "); + comboPanel.setLayout(flowLayout2); + flowLayout2.setAlignment(FlowLayout.LEFT); + providerPanel.setLayout(borderLayout2); + cardPanel.setLayout(cardLayout1); + schedulerCardPanel.setLayout(cardLayout2); + providerComboBox.addActionListener(new + SubmitTaskDialog_providerComboBox_actionAdapter(this)); + schedulerLabel.setToolTipText(""); + schedulerLabel.setText(" Scheduler: "); + cardPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder(SystemColor.controlDkShadow, 1), "Task Provider")); + cardPanel.setMinimumSize(new Dimension(255, 150)); + schedulerComboBox.setEnabled(false); + schedulerComboBox.addActionListener(new + SubmitTaskDialog_schedulerComboBox_actionAdapter(this)); + topPanel.setLayout(borderLayout3); + //pbsPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color. + // darkGray, 1), "PBS Parameters")); + submitWithEditButton.setToolTipText("Edit Script Before Submission"); + submitWithEditButton.setText("Edit & Submit"); + //MainPanel.add(taskProviderPanel, java.awt.BorderLayout.NORTH); + this.getContentPane().add(MainPanel, BorderLayout.CENTER); + ButtonPanel.add(Submit_Button); + ButtonPanel.add(submitWithEditButton); + ButtonPanel.add(Cancel_Button); + this.getContentPane().add(ButtonPanel, BorderLayout.SOUTH); + comboPanel.add(providerLabel); + comboPanel.add(providerComboBox); + comboPanel.add(schedulerLabel); + comboPanel.add(schedulerComboBox); + providerPanel.add(cardPanel, BorderLayout.CENTER); + providerPanel.add(comboPanel, BorderLayout.NORTH); + topPanel.add(providerPanel, BorderLayout.CENTER); + MainPanel.add(schedulerCardPanel, BorderLayout.CENTER); + MainPanel.add(resourcesPanel, BorderLayout.NORTH); + this.getContentPane().add(topPanel, BorderLayout.NORTH); + if (ClientProgram == null) { + MainPanel.add(new JPanel(), BorderLayout.SOUTH); + } + else { + MainPanel.add(ClientProgram.getVisualComponent(), BorderLayout.SOUTH); + } + WindowListener l = new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + logger.info("Exiting..."); + //Deactivator.deactivateAll(); + System.exit(0); + } + }; + + addWindowListener(l); + + setTaskSchedulers(TaskScheduler.getAvailableTaskSchedulers()); + + progressDialog = new ProgressDialog(new Frame(), + "Task Submission Progress", false); + progressDialog.cancelButton.setVisible(false); + progressDialog.setAlwaysOnTop(true); + progressDialog.setLocationRelativeTo(this); + + editScriptDialog.setLocationRelativeTo(this); + editScriptDialog.setSize(320, 480); + + schedulerCardPanel.add(new JPanel(), "Test"); + cardPanel.add(new JPanel(), "Test"); + + this.validate(); + } + + public void enableLocalDir(boolean enable) { + ClientProgram.enableLocalDir(enable); + } + + public void enableInputFile(boolean enable) { + ClientProgram.enableInputFile(enable); + } + + public void setLocalDir(String locDir) { + ClientProgram.setLocalDirectory(locDir); + //submitGaussianPanel.LocalDirTextField.setText(locDir); + } + + @Override + public void setInputFile(String inputFile) { + ClientProgram.setInputFile(inputFile); + } + + public void setGatekeepers(String[] gk) { + + } + + public void setHosts(String[] gk) { + } + + public void Cancel_Button_actionPerformed(ActionEvent e) { + setVisible(false); + } + + public void setClientProgram(ClientProgramInterface client_program) { + ClientProgram = client_program; + } + + @Override + public void setTaskProviders(Map providers) { + providerComboBox.setEnabled(false); + providerComboBox.removeAllItems(); + cardPanel.removeAll(); + allProviders = new LinkedHashMap(providers); + + Set set = providers.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String providerName = me.getKey().toString(); + providerComboBox.addItem(providerName); + //Component panel = (Component) me.getValue(); + GridProviderInterface provider = (GridProviderInterface) me.getValue(); + Component panel = provider.getVisualComponent(); + panel.validate(); + + cardPanel.add(panel, providerName); + } + + providerComboBox.setSelectedIndex(0); + + CardLayout cl = (CardLayout) cardPanel.getLayout(); + cl.show(cardPanel, providerComboBox.getSelectedItem().toString()); + cardPanel.validate(); + cardPanel.updateUI(); + + providerComboBox.setEnabled(true); + + String provider = providerComboBox.getSelectedItem().toString(); + GridProviderInterface gpi = allProviders.get(provider); + FileChooserInterface fci = gpi.getRemoteFileChooser(); + ClientProgram.setTaskProviderInterface(gpi); + + this.validate(); + } + + public void setSchedulers(Map providers) { + schedulerComboBox.setEnabled(false); + schedulerCardPanel.removeAll(); + schedulerComboBox.removeAllItems(); + + allSchedulers = new LinkedHashMap(providers); + + Set set = providers.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String schedulerName = me.getKey().toString(); + schedulerComboBox.addItem(schedulerName); + //Component panel = (Component) me.getValue(); + SchedulerInterface scheduler = (SchedulerInterface) me.getValue(); + Component panel = scheduler.getVisualComponent(); + panel.validate(); + + schedulerCardPanel.add(panel, schedulerName); + } + + schedulerComboBox.setSelectedIndex(0); + + CardLayout cl = (CardLayout) schedulerCardPanel.getLayout(); + cl.show(schedulerCardPanel, schedulerComboBox.getSelectedItem().toString()); + schedulerCardPanel.validate(); + schedulerCardPanel.updateUI(); + + schedulerComboBox.setEnabled(true); + + this.validate(); + } + + // !!! It's only a prototype yet !!! + public void setTaskSchedulers(Map schedulers) { + schedulerComboBox.setEnabled(false); + schedulerComboBox.removeAllItems(); + + Set set = schedulers.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String schedulerName = me.getKey().toString(); + schedulerComboBox.addItem(schedulerName); + //Component panel = (Component) me.getValue(); + + //cardPanel.add(panel, schedulerName); + } + + schedulerComboBox.setSelectedIndex(0); + + //CardLayout cl = (CardLayout) cardPanel.getLayout(); + //cl.show(cardPanel, providerComboBox.getSelectedItem().toString()); + + schedulerComboBox.setEnabled(true); + } + + public void Submit_Button_actionPerformed(ActionEvent e) { + validate(); + + // --- test all data + + try { + resourcesPanel.validateValues(); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Wrong input data: " + ex.getMessage(), "Error in input data", + JOptionPane.ERROR_MESSAGE); + return; + } + + boolean submitWithEdit = false; + if (e.getSource() == submitWithEditButton) { + submitWithEdit = true; + } + + String provider = providerComboBox.getSelectedItem().toString(); + + GridProviderInterface taskProvider = allProviders.get(provider); + + String scheduler = schedulerComboBox.getSelectedItem().toString(); + SchedulerInterface schedulerProvider = allSchedulers.get(scheduler); + + // --- "Inform" scheduler about chosen resources... + + schedulerProvider.setResourcesProvider(resourcesPanel); + + // --- "Inform" client program about task provider + + ClientProgram.setTaskProviderInterface(taskProvider); + + JobDescription jobDescription = new JobDescription(); + JobDescription submitDescription = new JobDescription(); + + // --- Start to build job description for submission... + + try { + resourcesPanel.setJobDescription(submitDescription); + schedulerProvider.setJobDescription(submitDescription); + ClientProgram.setJobDescription(submitDescription); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, "Cannot create job description object: " + ex.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + // --- Start to build a run script + + String script_file = ClientProgram.getScriptFile(); + try { + String scriptContent = JobDescription.createRunScript(taskProvider, schedulerProvider, ClientProgram); + if (submitWithEdit) { + editScriptDialog.scriptTextArea.setText(scriptContent); + editScriptDialog.setVisible(true); + if (!editScriptDialog.submitPressed) { + return; + } + scriptContent = editScriptDialog.scriptTextArea.getText(); + } + + IOUtils.saveStringIntoFile(scriptContent, ClientProgram.getLocalDirectory() + script_file); + + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, "Cannot create script file: " + ex.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + // --- Preparing final job description for submitting + + submitDescription.setTaskProvider(provider); + submitDescription.setScheduler(scheduler); + + //submitDescription.setRemoteHost(remote_host); // Task provider already knows about that... + + + + + // --- Non-standard + + // submitDescription.setPbsJobScript(taskProvider.isPassOptionsToScheduler()); /// Disabled + + // --- Submitting job + + String jobId = null; + + try { + jobId = taskProvider.submitTask(submitDescription); + } + catch (Exception ex) { + String message = "Error submitting job: " + ex.getMessage(); + JOptionPane.showMessageDialog(null, "Error submitting job: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + System.err.println(message); + return; + } + + JOptionPane.showMessageDialog(null, "Job submitted successfully", "Success", JOptionPane.INFORMATION_MESSAGE); + + Date subDate = new Date(); + + CheckPointInterface chkp = null; + + if (jobId == null) { + System.err.println("No job handle was returned. Job is not included into checkpoint file"); + return; + } + + if (provider.equals(TaskProvider.LOCAL_PROVIDER)) { + System.err.println("Checkpoint is not written for a local provider"); + return; + } + + if (provider.equals(TaskProvider.GLOBUS_4_PROVIDER)) { + System.err.println("Checkpoint is not written for a gt4 provider"); + return; + } + + try { + chkp = new CheckPoint(CheckPointInterface.jobNameTag + "@" + ClientProgram.getJobName() + "@" + + CheckPointInterface.handleTag + "@" + jobId + "@" + + CheckPointInterface.providerTag + "@" + provider + "@" + + CheckPointInterface.computerTag + "@" + + taskProvider.getRemoteHost() + "@" + + CheckPointInterface.softwareTag + "@" + ClientProgram.getSoftwareName() + "@" + + CheckPointInterface.programTag + "@" + ClientProgram.getExecutable() + "@" + + CheckPointInterface.executableTag + "@" + script_file + "@" + + CheckPointInterface.localExecutableTag + "@true@" + + CheckPointInterface.remoteDirectoryTag + "@" + + ClientProgram.getRemoteDirectory() + + "@" + + CheckPointInterface.localDirectoryTag + "@" + + ClientProgram.getLocalDirectory() + + "@" + + CheckPointInterface.statusTag + "@Submitted@" + + CheckPointInterface.overallJobStatusTag + "@Pending@" + + CheckPointInterface.submittedTimeTag + "@" + subDate.toString(), + "@" // Divider + ); + + ClientProgram.setCheckPointFile( (CheckPoint) chkp); + + if (ClientProgram.getStdoutFileName() != null && ClientProgram.getStdoutFileName().length() > 0) { + chkp.setOutputFile(CheckPointInterface.stdOutputTag, ClientProgram.getStdoutFileName()); + } + if (ClientProgram.getStderrFileName() != null && ClientProgram.getStderrFileName().length() > 0) { + chkp.setOutputFile(CheckPointInterface.stdErrorTag, ClientProgram.getStderrFileName()); + } + + chkp = taskProvider.setCheckPoint(chkp); + + } + catch (Exception ex) { + System.err.println(ex.getMessage()); + return; + } + + ParseCheckpointFile pcf = new ParseCheckpointFile(); + try { + pcf.addCheckPoint( (CheckPoint) chkp); /// !!! Bad !!! + } + catch (cct.grid.MalformedCheckPointException ex) { + JOptionPane.showMessageDialog(null, + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + } + + /* + void shutdownGASS(GassServer gass) { + try { + gass.shutdown(); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + */ + + public void getProxy_Button_actionPerformed(ActionEvent e) { + GridProxyInitDialog.openGetProxyDialog(); + } + + public void providerComboBox_actionPerformed(ActionEvent e) { + if (!providerComboBox.isEnabled()) { + return; + } + providerComboBox.setEnabled(false); + + CardLayout cl = (CardLayout) cardPanel.getLayout(); + cl.show(cardPanel, providerComboBox.getSelectedItem().toString()); + + String provider = providerComboBox.getSelectedItem().toString(); + //if (provider.equalsIgnoreCase(cct.grid.TaskProvider.SSH_PROVIDER)) { + //SSHPanel ssh = (SSHPanel) allProviders.get(provider); + GridProviderInterface gpi = allProviders.get(provider); + FileChooserInterface fci = gpi.getRemoteFileChooser(); + ClientProgram.setTaskProviderInterface(gpi); + //ClientProgram.setRemoteFileChooser(fci); + + providerComboBox.setEnabled(true); + pack(); + } + + public void schedulerComboBox_actionPerformed(ActionEvent e) { + if (!schedulerComboBox.isEnabled()) { + return; + } + schedulerComboBox.setEnabled(false); + + CardLayout cl = (CardLayout) schedulerCardPanel.getLayout(); + cl.show(schedulerCardPanel, schedulerComboBox.getSelectedItem().toString()); + + String provider = schedulerComboBox.getSelectedItem().toString(); + SchedulerInterface si = allSchedulers.get(provider); + schedulerComboBox.setEnabled(true); + pack(); + } + + private class JustProgress + extends cct.tools.SwingWorker { + + JDialog parent = null; + int jobType; + ProgressDialog pd; + + JustProgress(JDialog p, String jobDesc) { + parent = p; + pd = new ProgressDialog(new Frame(), "Job Submission Progress", false); + pd.setLocationRelativeTo(parent); + pd.setAlwaysOnTop(true); + pd.jobTypeLabel.setText(jobDesc); + pd.cancelButton.setVisible(false); + /* + pd.cancelButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + cancelTranfer(); + } + } + ); + */ + + } + + @Override + public Object construct() { + pd.setVisible(true); + try { + while (true) { + Thread.sleep(1000); + } + } + catch (Exception ex) {} + return "done"; + } + + void cancelShow() { + pd.setVisible(false); + interrupt(); + } + + @Override + public void finished() { + pd.setVisible(false); + } + + } + + // Does not work properly + class JobSubProgress + extends java.util.TimerTask { + int MAX = 10; + JLabel msgLabel = new JLabel("Submitting Job..."); + JProgressBar progressBar = new JProgressBar(0, MAX); + JOptionPane pane = null; + JDialog dialog = null; + + public JobSubProgress() { + progressBar.setValue(0); + + Object[] comp = { + msgLabel, progressBar}; + //Object[] options = { + // "Cancel"}; + + pane = new JOptionPane(comp, + JOptionPane.DEFAULT_OPTION, + JOptionPane.INFORMATION_MESSAGE, + null); + //options, + //options[0]); + + dialog = pane.createDialog(null, "Submitting a Job"); + } + + @Override + public void run() { + if (!dialog.isVisible()) { + dialog.setVisible(true); + } + progressBar.setValue( (progressBar.getValue() + 1) % MAX); + } + + @Override + public boolean cancel() { + dialog.setVisible(false); + return false; + } + } + + class Task + extends Thread { + private boolean done = false; + private Exception exception = null; + private boolean cancel = false; + + public boolean isDone() { + return done; + } + + public void cancel() { + cancel = true; + } + + public boolean isCancelled() { + return cancel; + } + + @Override + public void run() { + + try { + //queryIsDone = false; + //if (taskType == 0) { + // updateJobStatus(); + // } + //else if ( taskType == JSD_KILL_JOBS ) { + // killJobs(); + //} + //queryIsDone = true; + } + catch (Exception e) { + exception = e; + done = true; + return; + } + + /* + try { + proxy = model.createProxy(new String(passwordTF.getPassword())); + } + catch (Exception e) { + exception = e; + done = true; + return; + } + */ + + if (cancel) { + return; + } + + // send the event.... + //if (proxyListener != null) { + // proxyListener.proxyCreated(proxy); + //} + + done = true; + } + + public Exception getException() { + return exception; + } + } + + private class SubmitTaskDialog_providerComboBox_actionAdapter + implements ActionListener { + private SubmitTaskDialog adaptee; + SubmitTaskDialog_providerComboBox_actionAdapter( + SubmitTaskDialog + adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.providerComboBox_actionPerformed(e); + } + } + + private class SubmitTaskDialog_schedulerComboBox_actionAdapter + implements ActionListener { + private SubmitTaskDialog adaptee; + SubmitTaskDialog_schedulerComboBox_actionAdapter(SubmitTaskDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.schedulerComboBox_actionPerformed(e); + } + } + + private class SubmitTaskDialog_Submit_Button_actionAdapter + implements ActionListener { + private SubmitTaskDialog adaptee; + SubmitTaskDialog_Submit_Button_actionAdapter(SubmitTaskDialog + adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Submit_Button_actionPerformed(e); + } + } + + private class SubmitTaskDialog_Cancel_Button_actionAdapter + implements ActionListener { + private SubmitTaskDialog adaptee; + SubmitTaskDialog_Cancel_Button_actionAdapter(SubmitTaskDialog + adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Cancel_Button_actionPerformed(e); + } + + } + + /* + class gaussianJobSubOutputListener + implements JobOutputListener { + JobOutputInterface textPane = null; + + public gaussianJobSubOutputListener(JobOutputInterface text_pane) { + textPane = text_pane; + } + + public void outputClosed() { +//Job has finished; no more output is available + //String text = textPane.getText(); + //text += "\nEnd of output\n"; + textPane.appendOutput("\nEnd of output\n"); + + } + + public void outputChanged(String output) { + logger.info("output: " + output); + //String text = textPane.getText(); + //text += output; + textPane.appendOutput(output); + } + } + */ + +} + +/* + class JobOutputListenerImpl + implements JobOutputListener { + String jobOutput = ""; + + public JobOutputListenerImpl() { + } + + public void outputClosed() { +//Job has finished; no more output is available + logger.info("Job finished: " + jobOutput); + } + + public void outputChanged(String output) { + jobOutput += output; + logger.info("output: " + output); + } + } + */ diff --git a/src/main/java/cct/grid/ui/ThreadExec.java b/src/main/java/cct/grid/ui/ThreadExec.java new file mode 100644 index 0000000..627b076 --- /dev/null +++ b/src/main/java/cct/grid/ui/ThreadExec.java @@ -0,0 +1,158 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid.ui; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JProgressBar; +import javax.swing.Timer; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class ThreadExec + extends Thread { + + ThreadInterface threadInterface = null; + boolean done = false; + Exception exception = null; + boolean cancel = false; + + int MAX = 10; + String winTitle = "Performing Task"; + JLabel msgLabel = new JLabel("Performing task..."); + JProgressBar progressBar = new JProgressBar(0, MAX); + + public ThreadExec(ThreadInterface ti) { + threadInterface = ti; + } + + public boolean isDone() { + return done; + } + + public void cancel() { + cancel = true; + } + + public boolean isCancelled() { + return cancel; + } + + @Override + public void run() { + + progressBar.setValue(0); + + Object[] comp = { + msgLabel, progressBar}; + Object[] options = { + "Cancel"}; + + JOptionPane pane = new JOptionPane(comp, + JOptionPane.DEFAULT_OPTION, + JOptionPane.INFORMATION_MESSAGE, + null, + options, + options[0]); + + final JDialog dialog = pane.createDialog(null, winTitle); + + Timer timer = new Timer(250, new TimerListener(this, dialog)); + + try { + threadInterface.performTask(); + } + catch (Exception e) { + exception = e; + done = true; + return; + } + + if (cancel) { + return; + } + + // send the event.... + //if (proxyListener != null) { + // proxyListener.proxyCreated(proxy); + //} + + done = true; + + } + + public Exception getException() { + return exception; + } + + class TimerListener + implements ActionListener { + ThreadExec task = null; + JDialog dialog = null; + public TimerListener(ThreadExec t, JDialog d) { + task = t; + dialog = d; + } + + @Override + public void actionPerformed(ActionEvent e) { + if (task.isDone()) { + dialog.setVisible(false); + } + else { + progressBar.setValue( (progressBar.getValue() + 1) % MAX); + } + } + + } + +} diff --git a/src/main/java/cct/grid/ui/ThreadInterface.java b/src/main/java/cct/grid/ui/ThreadInterface.java new file mode 100644 index 0000000..4ffbc3d --- /dev/null +++ b/src/main/java/cct/grid/ui/ThreadInterface.java @@ -0,0 +1,54 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid.ui; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface ThreadInterface { + void performTask(); +} diff --git a/src/main/java/cct/grid/ui/gaussian/SubmitGaussPanel.java b/src/main/java/cct/grid/ui/gaussian/SubmitGaussPanel.java new file mode 100644 index 0000000..3f0baad --- /dev/null +++ b/src/main/java/cct/grid/ui/gaussian/SubmitGaussPanel.java @@ -0,0 +1,94 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + + + +package cct.grid.ui.gaussian; + +//~--- non-JDK imports -------------------------------------------------------- + +import java.awt.BorderLayout; +import java.awt.Color; + +import javax.swing.BorderFactory; +import javax.swing.JPanel; +import javax.swing.border.TitledBorder; + +import cct.globus.ui.GatekeeperPanel; +import cct.grid.ui.PBS_Panel; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class SubmitGaussPanel extends JPanel { + BorderLayout borderLayout1 = new BorderLayout(); + GatekeeperPanel gatekeeperPanel1 = new GatekeeperPanel(); + PBS_Panel pBS_Panel1 = new PBS_Panel(); + SubmitGaussianPanel submitGaussianPanel1 = new SubmitGaussianPanel(); + + public SubmitGaussPanel() { + try { + jbInit(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + gatekeeperPanel1.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color.gray, 1), + "Gatekeeper Options")); + pBS_Panel1.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color.gray, 1), "PBS Options")); + submitGaussianPanel1.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color.gray, 1), + "Job Specifications")); + this.add(gatekeeperPanel1, BorderLayout.NORTH); + this.add(submitGaussianPanel1, BorderLayout.SOUTH); + this.add(pBS_Panel1, BorderLayout.CENTER); + } +} + + +//~ Formatted by Jindent --- http://www.jindent.com diff --git a/src/main/java/cct/grid/ui/gaussian/SubmitGaussianAppl.java b/src/main/java/cct/grid/ui/gaussian/SubmitGaussianAppl.java new file mode 100644 index 0000000..58be2ff --- /dev/null +++ b/src/main/java/cct/grid/ui/gaussian/SubmitGaussianAppl.java @@ -0,0 +1,275 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + + + +package cct.grid.ui.gaussian; + +//~--- non-JDK imports -------------------------------------------------------- + +import java.awt.Dimension; +import java.awt.FileDialog; +import java.awt.Frame; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.WindowConstants; + +import cct.gaussian.Gaussian; +import cct.gaussian.ui.GaussianInputEditorFrame; +import cct.globus.ui.GridProxyInitDialog; +import cct.grid.ui.CheckPointStatus; +import cct.grid.ui.JobOutputInterface; +import cct.grid.ui.JobStatusDialog; +import cct.j3d.SimpleRenderer; +import cct.tools.IOUtils; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class SubmitGaussianAppl implements ActionListener { + static boolean useGraphics = true; + GridProxyInitDialog gpiFrame = null; + IOFrame jio = null; + JobStatusDialog jstatusd = null; + boolean packFrame = false; + private SubmitGaussianDialog sgd = null; + JMenuItem jobStatusItem = new JMenuItem("Job Status"); + JMenuItem gridSubmitItem = new JMenuItem("Submit to Grid"); + JMenuItem getProxyItem = new JMenuItem("Get Proxy"); + private GaussianInputEditorFrame frame; + + /** + * Construct and show the application. + */ + public SubmitGaussianAppl() { + + // SubmitGaussianFrame frame = new SubmitGaussianFrame(); + Gaussian g = new Gaussian(); + + if (useGraphics) { + SimpleRenderer r = new SimpleRenderer(); + + g.setGraphicsRenderer(r); + } + + frame = new GaussianInputEditorFrame(g); + gridSubmitItem.addActionListener(this); + getProxyItem.addActionListener(this); + jobStatusItem.addActionListener(this); + + JMenu fileMenu = frame.getFileMenu(); + int n = fileMenu.getItemCount(); + + if (n <= 2) { + n = 0; + } else { + n -= 2; + } + + fileMenu.insertSeparator(n); + fileMenu.insert(getProxyItem, n + 1); + fileMenu.insert(gridSubmitItem, n + 1); + fileMenu.insert(jobStatusItem, n + 1); + + JToolBar toolBar = frame.getToolBar(); + + // jio = new IOFrame(); + // Validate frames that have preset sizes + // Pack frames that have useful preferred size info, e.g. from their layout + if (packFrame) { + frame.pack(); + } else { + frame.validate(); + } + + // Center the window + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension frameSize = frame.getSize(); + + if (frameSize.height > screenSize.height) { + frameSize.height = screenSize.height; + } + + if (frameSize.width > screenSize.width) { + frameSize.width = screenSize.width; + } + + frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2); + frame.setVisible(true); + } + + /** + * Application entry point. + * + * @param args String[] + */ + public static void main(String[] args) { + if (args.length > 0) { + if (args[0].equalsIgnoreCase("-nographics")) { + useGraphics = false; + } + } + + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (Exception exception) { + exception.printStackTrace(); + } + + new SubmitGaussianAppl(); + } + }); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == gridSubmitItem) { + + // --- Save gjf file + FileDialog fd = new FileDialog(new Frame(), "Save Gaussian Job File", FileDialog.SAVE); + + fd.setFile("*.gjf;*.com;*.g03"); + + // fd.setDirectory(directory); + // fd.setFile(file_name); + fd.setVisible(true); + + if (fd.getFile() == null) { + return; + } + + String newFileName = new String(fd.getFile()); + String newWorkingDirectory = new String(fd.getDirectory()); + + try { + IOUtils.saveStringIntoFile(frame.toString(), newWorkingDirectory + newFileName); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + + return; + } + + // --- Open job submit dialog + if (sgd == null) { + if (jio != null) { + jio.setVisible(true); + } + + sgd = new SubmitGaussianDialog(new Frame(), jio, "Submit Gaussian Job", false); + sgd.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); + sgd.enableLocalDir(false); + sgd.enableInputFile(false); + + String[] gk = { "ng1.apac.edu.au" }; + + sgd.setGatekeepers(gk); + + String[] hosts = { "lc.apac.edu.au", "ac.apac.edu.au" }; + + sgd.setHosts(hosts); + } + + sgd.setInputFile(newFileName); + sgd.setLocalDir(newWorkingDirectory); + sgd.setVisible(true); + } else if (e.getSource() == getProxyItem) { + if (gpiFrame == null) { + gpiFrame = new GridProxyInitDialog(new Frame(), true, false); + } + + gpiFrame.setVisible(true); + } else if (e.getSource() == jobStatusItem) { + if (jstatusd == null) { + CheckPointStatus chk = new CheckPointStatus(); + + jstatusd = new JobStatusDialog(new Frame(), "Job Status", false, chk); + } + + jstatusd.queryJobStatus(); + jstatusd.setVisible(true); + } + } + + class IOFrame extends JFrame implements JobOutputInterface { + JScrollPane jScrollPane1 = new JScrollPane(); + JTextArea jTextArea1 = new JTextArea(); + JPanel contentPane; + + public IOFrame() { + contentPane = (JPanel) getContentPane(); + this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); + setSize(new Dimension(400, 300)); + setTitle("Job Input/Output"); + jTextArea1.setToolTipText(""); + jTextArea1.setEditable(false); + contentPane.add(jScrollPane1, java.awt.BorderLayout.CENTER); + jScrollPane1.getViewport().add(jTextArea1); + } + + @Override + public void appendOutput(String output) { + jTextArea1.append(output); + } + } +} + + +//~ Formatted by Jindent --- http://www.jindent.com diff --git a/src/main/java/cct/grid/ui/gaussian/SubmitGaussianDialog.java b/src/main/java/cct/grid/ui/gaussian/SubmitGaussianDialog.java new file mode 100644 index 0000000..08e1eb3 --- /dev/null +++ b/src/main/java/cct/grid/ui/gaussian/SubmitGaussianDialog.java @@ -0,0 +1,1147 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.grid.ui.gaussian; + +import java.awt.BorderLayout; +import java.awt.CardLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.util.Date; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; +import java.util.regex.PatternSyntaxException; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JProgressBar; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.border.TitledBorder; + +import cct.globus.ui.GatekeeperPanel; +import cct.globus.ui.GridProxyInitDialog; +import cct.grid.CheckPoint; +import cct.grid.CheckPointInterface; +import cct.grid.GridProviderInterface; +import cct.grid.JobDescription; +import cct.grid.ParseCheckpointFile; +import cct.grid.ScriptSubmitterDialogInterface; +import cct.grid.TaskProvider; +import cct.grid.TaskScheduler; +import cct.grid.ui.JobOutputInterface; +import cct.grid.ui.PBS_Panel; +import cct.grid.ui.ProgressDialog; +import cct.grid.ui.ResourcesPanel; +import cct.interfaces.FileChooserInterface; +import cct.tools.IOUtils; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class SubmitGaussianDialog + extends JDialog implements ScriptSubmitterDialogInterface { + + JPanel MainPanel = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + SubmitGaussianPanel submitGaussianPanel1 = new SubmitGaussianPanel(); + PBS_Panel pBS_Panel1 = new PBS_Panel(null, "normal", 60, 1024, 5, + "g03"); + JPanel ButtonPanel = new JPanel(); + JButton Cancel_Button = new JButton(); + JButton Submit_Button = new JButton(); + JComboBox providerComboBox = new JComboBox(); + JPanel providerPanel = new JPanel(); + FlowLayout flowLayout1 = new FlowLayout(); + JLabel providerLabel = new JLabel(); + ProgressDialog progressDialog = null; + //private GridProxyInterface getGridProxy = null; + int taskType = 0; + private static Logger logger = Logger.getLogger(SubmitGaussianDialog.class.getName()); + Map allProviders = new LinkedHashMap(); + JobOutputInterface jobOutput = null; + JButton getProxy_Button = new JButton(); + JPanel cardPanel = new JPanel(); + JPanel comboPanel = new JPanel(); + FlowLayout flowLayout2 = new FlowLayout(); + BorderLayout borderLayout2 = new BorderLayout(); + CardLayout cardLayout1 = new CardLayout(); + JLabel schedulerLabel = new JLabel(); + JComboBox schedulerComboBox = new JComboBox(); + ResourcesPanel resourcesPanel1 = new ResourcesPanel(); + JPanel topPanel = new JPanel(); + BorderLayout borderLayout3 = new BorderLayout(); + + public static void main(String[] args) { + + SwingUtilities.invokeLater(new Runnable() { + + @Override + public void run() { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (Exception exception) { + exception.printStackTrace(); + } + + SubmitGaussianDialog frame = new SubmitGaussianDialog(); + frame.setTaskProviders(TaskProvider.getAvailableTaskProviders()); + frame.validate(); + frame.pack(); + frame.Cancel_Button.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + System.exit(0); + } + }); + frame.setDefaultCloseOperation(EXIT_ON_CLOSE); + frame.setVisible(true); + + } + }); + } + + @Override + public ScriptSubmitterDialogInterface newInstance() { + return new SubmitGaussianDialog(new Frame(), null, "Submit Gaussian Script", false); + } + + @Override + public void setCustomOptions(String options) throws Exception { + throw new Exception("setCustomOptions is not implemented in " + this.getClass().getCanonicalName()); + } + + @Override + public JDialog getDialog() { + return this; + } + + @Override + public void setLocalDirectory(String localDir) { + submitGaussianPanel1.LocalDirTextField.setText(localDir); + } + + @Override + public void setRemoteDirectory(String remoteDir) { + submitGaussianPanel1.RemoteDirTextField.setText(remoteDir); + } + + public SubmitGaussianDialog(Frame owner, JobOutputInterface redir, + String title, boolean modal) { + super(owner, title, modal); + jobOutput = redir; + try { + setDefaultCloseOperation(HIDE_ON_CLOSE); + jbInit(); + pack(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public SubmitGaussianDialog() { + this(new Frame(), null, "Submit Gaussian Script", false); + } + + // public void setProxyHandler(GridProxyInterface proxyHandler) { + // getGridProxy = proxyHandler; + //} + private void jbInit() throws Exception { + MainPanel.setLayout(borderLayout1); + submitGaussianPanel1.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color.lightGray, 1), "Job Specifications")); + pBS_Panel1.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color.lightGray, 2), "PBS Options")); + pBS_Panel1.setMinimumSize(new Dimension(254, 150)); + Cancel_Button.setToolTipText(""); + Cancel_Button.setText("Cancel"); + Cancel_Button.addActionListener(new SubmitGaussianDialog_Cancel_Button_actionAdapter(this)); + Submit_Button.setToolTipText(""); + Submit_Button.setText("Submit"); + Submit_Button.addActionListener(new SubmitGaussianDialog_Submit_Button_actionAdapter(this)); + this.setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); + getProxy_Button.setToolTipText(""); + getProxy_Button.setText("Get new Proxy"); + getProxy_Button.addActionListener(new SubmitGaussianDialog_getProxy_Button_actionAdapter(this)); + providerLabel.setToolTipText(""); + providerLabel.setText(" Provider: "); + comboPanel.setLayout(flowLayout2); + flowLayout2.setAlignment(FlowLayout.LEFT); + providerPanel.setLayout(borderLayout2); + cardPanel.setLayout(cardLayout1); + providerComboBox.addActionListener(new SubmitGaussianDialog_providerComboBox_actionAdapter(this)); + schedulerLabel.setToolTipText(""); + schedulerLabel.setText(" Scheduler: "); + cardPanel.setMinimumSize(new Dimension(255, 150)); + schedulerComboBox.setEnabled(false); + topPanel.setLayout(borderLayout3); + MainPanel.add(submitGaussianPanel1, BorderLayout.SOUTH); + //MainPanel.add(taskProviderPanel, java.awt.BorderLayout.NORTH); + this.getContentPane().add(MainPanel, BorderLayout.CENTER); + ButtonPanel.add(Submit_Button); + ButtonPanel.add(getProxy_Button); + ButtonPanel.add(Cancel_Button); + this.getContentPane().add(ButtonPanel, BorderLayout.SOUTH); + MainPanel.add(pBS_Panel1, BorderLayout.CENTER); + MainPanel.add(resourcesPanel1, BorderLayout.NORTH); + comboPanel.add(providerLabel); + comboPanel.add(providerComboBox); + comboPanel.add(schedulerLabel); + comboPanel.add(schedulerComboBox); + providerPanel.add(cardPanel, BorderLayout.CENTER); + providerPanel.add(comboPanel, BorderLayout.NORTH); + this.getContentPane().add(topPanel, BorderLayout.NORTH); + topPanel.add(providerPanel, BorderLayout.CENTER); + pBS_Panel1.JobfsTextField.setEditable(true); + pBS_Panel1.SoftwareTextField.setEditable(false); + + WindowListener l = new WindowAdapter() { + + @Override + public void windowClosing(WindowEvent e) { + logger.info("Exiting..."); + //Deactivator.deactivateAll(); + System.exit(0); + } + }; + + addWindowListener(l); + + setTaskSchedulers(TaskScheduler.getAvailableTaskSchedulers()); + + progressDialog = new ProgressDialog(new Frame(), "Task Submission Progress", false); + progressDialog.cancelButton.setVisible(false); + progressDialog.setAlwaysOnTop(true); + progressDialog.setLocationRelativeTo(this); + + this.validate(); + } + + public void enableLocalDir(boolean enable) { + submitGaussianPanel1.LocalDirTextField.setEnabled(enable); + } + + public void enableInputFile(boolean enable) { + submitGaussianPanel1.inputFileTextField.setEnabled(enable); + } + + public void setLocalDir(String locDir) { + submitGaussianPanel1.LocalDirTextField.setText(locDir); + } + + @Override + public void setInputFile(String inputFile) { + submitGaussianPanel1.setInputFile(inputFile); + } + + public void setGatekeepers(String[] gk) { + } + + public void setHosts(String[] gk) { + } + + public void Cancel_Button_actionPerformed(ActionEvent e) { + setVisible(false); + } + + @Override + public void setTaskProviders(Map providers) { + providerComboBox.setEnabled(false); + providerComboBox.removeAllItems(); + + allProviders = new LinkedHashMap(providers); + + Set set = providers.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String providerName = me.getKey().toString(); + providerComboBox.addItem(providerName); + //Component panel = (Component) me.getValue(); + GridProviderInterface provider = (GridProviderInterface) me.getValue(); + Component panel = provider.getVisualComponent(); + panel.validate(); + + cardPanel.add(panel, providerName); + } + + providerComboBox.setSelectedIndex(0); + + CardLayout cl = (CardLayout) cardPanel.getLayout(); + cl.show(cardPanel, providerComboBox.getSelectedItem().toString()); + cardPanel.validate(); + cardPanel.updateUI(); + + providerComboBox.setEnabled(true); + + this.validate(); + } + + // !!! It's only a prototype yet !!! + public void setTaskSchedulers(Map schedulers) { + schedulerComboBox.setEnabled(false); + schedulerComboBox.removeAllItems(); + + Set set = schedulers.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String schedulerName = me.getKey().toString(); + schedulerComboBox.addItem(schedulerName); + //Component panel = (Component) me.getValue(); + + //cardPanel.add(panel, schedulerName); + } + + schedulerComboBox.setSelectedIndex(0); + + //CardLayout cl = (CardLayout) cardPanel.getLayout(); + //cl.show(cardPanel, providerComboBox.getSelectedItem().toString()); + + schedulerComboBox.setEnabled(true); + } + + public void Submit_Button_actionPerformed(ActionEvent e) { + validate(); + /* + if (gass == null) { + int server_options = + org.globus.io.gass.server.GassServer.STDOUT_ENABLE | + org.globus.io.gass.server.GassServer.STDERR_ENABLE; + + //if ( (options & GLOBUSRUN_ARG_ALLOW_READS) != 0) { + server_options |= + org.globus.io.gass.server.GassServer.READ_ENABLE; + //} + + //if ( (options & GLOBUSRUN_ARG_ALLOW_WRITES) != 0) { + server_options |= + org.globus.io.gass.server.GassServer.WRITE_ENABLE; + //} + + try { + //gass = new GassServer(true, 0); + gass = new org.globus.io.gass.server.GassServer(); + gass.setOptions(server_options); + gass.setTimeout(0); // keep sockets open forever + + gass.registerDefaultDeactivator(); + } + catch (java.io.IOException ex) { + //logger.info("GassServer: IOException: " + ex.getMessage()); + System.err.println("Gass server initialization failed: " + + ex.getMessage()); + JOptionPane.showMessageDialog(null, + "Gass server initialization failed: " + + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + logger.info("GassServer: Passed..."); + } + */ + + String provider = providerComboBox.getSelectedItem().toString(); + + GridProviderInterface taskProvider = allProviders.get(provider); + boolean passOptionsToScheduler = taskProvider.isPassOptionsToScheduler(); + + String scheduler = schedulerComboBox.getSelectedItem().toString(); + boolean use_gatekeeper = false; + String gatekeeper = null; + String remote_host = taskProvider.getRemoteHost(); + // --- Get Script name (executable) + String script_file = script_file = submitGaussianPanel1.ScriptTextField.getText().trim(); + + JobDescription jobDescription = new JobDescription(); + + /* + if (provider.equals(TaskProvider.GLOBUS_2_PROVIDER)) { + GatekeeperPanel gkp = (GatekeeperPanel) TaskProvider.getProvider(provider); + gatekeeper = gkp.GatekeeperComboBox.getSelectedItem().toString(); + remote_host = gkp.HostComboBox.getSelectedItem().toString(); + + if (gatekeeper.length() < 1) { + use_gatekeeper = false; + } + else { + use_gatekeeper = true; + } + + if (!use_gatekeeper && remote_host.length() < 1) { + JOptionPane.showMessageDialog(null, + "Neither gatekeeper nor remote host are set", + "Error", + JOptionPane.ERROR_MESSAGE); + return; + + } + } + + else if (provider.equals(TaskProvider.GLOBUS_4_PROVIDER)) { + GT4Panel gkp = (GT4Panel) TaskProvider.getProvider(provider); + gatekeeper = gkp.GatekeeperComboBox.getSelectedItem().toString(); + remote_host = gkp.HostComboBox.getSelectedItem().toString(); + + if (gatekeeper.length() < 1) { + use_gatekeeper = false; + } + else { + use_gatekeeper = true; + } + + if (!use_gatekeeper && remote_host.length() < 1) { + JOptionPane.showMessageDialog(null, + "Neither gatekeeper nor remote host are set", + "Error", + JOptionPane.ERROR_MESSAGE); + return; + + } + } + + else if (provider.equals(TaskProvider.SSH_PROVIDER)) { + SSHPanel sshp = (SSHPanel) TaskProvider.getProvider(provider); + try { + sshp.checkConnection(); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + } + + else if (provider.equals(TaskProvider.LOCAL_PROVIDER)) { + remote_host = "local"; + + } + + else { + JOptionPane.showMessageDialog(null, + "Unknown service provider: " + provider, + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + */ + + // --- Preparing PBS Script + + // Setting up job description + + // --- Set Remote directory + + String remoteDirectory = submitGaussianPanel1.RemoteDirTextField.getText(). + trim(); + + // --- Job name + String jobName = submitGaussianPanel1.jobNameTextField.getText().trim(); + + // --- Get Local directory + String localDirectory = submitGaussianPanel1.LocalDirTextField.getText(). + trim(); + + if (localDirectory.indexOf("\\") != -1) { + localDirectory = "/" + localDirectory; + try { + //valid_dir = valid_dir.replaceAll("\\", "/"); + localDirectory = localDirectory.replace('\\', '/'); + } catch (PatternSyntaxException ex) { + while (localDirectory.indexOf("\\") != -1) { + } + logger.info("Regex error: " + localDirectory); + + } + } + + if (localDirectory.endsWith("/")) { + localDirectory = localDirectory.substring(0, localDirectory.length() - 1); + } + jobDescription.setLocalDirectory(localDirectory); + + // --- Get CPU number + + try { + jobDescription.setNCPU(pBS_Panel1.getNCPUs()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + // --- Setup max (wall) time + + float maxWallTime = -1; + try { + float time_in_secs = pBS_Panel1.getMaxTime(); + maxWallTime = time_in_secs; + jobDescription.setMaxCpuTime(time_in_secs * 60.0f); + jobDescription.setMaxTime(time_in_secs * 60.0f); + jobDescription.setMaxWallTime(time_in_secs * 60.0f); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + // --- Setup max memory + + int maxMemory = 0; // in MB + try { + maxMemory = pBS_Panel1.getMaxMemory(); + jobDescription.setMaxMemory(maxMemory); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + // --- Setup project + + jobDescription.setProject(pBS_Panel1.getProject()); + + // --- Setup jobfs + + int jobFS = 0; + try { + jobFS = pBS_Panel1.getJobFS(); + jobDescription.setJobFS(jobFS); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + String input_file = submitGaussianPanel1.inputFileTextField.getText().trim(); + String output_file = submitGaussianPanel1.OutputFileTextField.getText(). + trim(); + + // --- Setup queue + + String queue = pBS_Panel1.getQueue(); + /* + if (provider.equals(TaskProvider.GLOBUS_2_PROVIDER) && use_gatekeeper) { + queue += "@" + remote_host.substring(0, remote_host.indexOf(".")); + } + else if (provider.equals(TaskProvider.GLOBUS_4_PROVIDER) && use_gatekeeper) { + queue += "@" + remote_host.substring(0, remote_host.indexOf(".")); + } + */ + + jobDescription.setQueue(queue); + + // Stdout & stderr + + String stdout = submitGaussianPanel1.getStdoutFileName().trim(); + String stderr = submitGaussianPanel1.getStderrFileName().trim(); + + //if (provider.equals(TaskProvider.SSH_PROVIDER)) { + if (stdout.length() > 0) { + jobDescription.setStdout(stdout); + } + if (stderr.length() > 0) { + jobDescription.setStderr(stderr); + } + //} + + + // --- Setup software + + jobDescription.setSoftware(pBS_Panel1.getSoftware()); + + // --- Setup scheduler + + String sched = this.schedulerComboBox.getSelectedItem().toString(); + if (passOptionsToScheduler) { + jobDescription.setScheduler(sched); + } + + jobDescription.addPreprocessDirective("module load dos2unix"); + jobDescription.addPreprocessDirective("dos2unix " + input_file); + jobDescription.addPreprocessDirective("module load gaussian"); + + jobDescription.setExecutable("g03"); + + jobDescription.addArgument("<" + input_file); + jobDescription.addArgument(">" + output_file); + + jobDescription.setPBSOther("chemgrid"); + + jobDescription.setShell("/bin/bash"); + + // --- Save script file + try { + String scriptContent = JobDescription.createUnixScript(jobDescription); + IOUtils.saveStringIntoFile(scriptContent, + submitGaussianPanel1.LocalDirTextField.getText(). + trim() + + script_file); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, + "Error saving script file" + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + jobDescription.setTaskProvider(provider); + jobDescription.setScheduler(JobDescription.PBS_SCHEDULER); + + // --- Preparing final job description for submitting + + JobDescription submitDescription = new JobDescription(); + submitDescription.setTaskProvider(provider); + submitDescription.setScheduler(JobDescription.PBS_SCHEDULER); + submitDescription.setPbsJobScript(true); + submitDescription.setExecutable(script_file); + submitDescription.setRemoteHost(remote_host); + submitDescription.setRemoteDirectory(remoteDirectory); + submitDescription.setJobName(jobName); + submitDescription.setLocalDirectory(localDirectory); + submitDescription.setProject(pBS_Panel1.getProject()); + submitDescription.setQueue(queue); + + // --- ( File Staging In ) + + submitDescription.setFileStageIn(script_file, script_file); // Run script file + submitDescription.setFileStageIn(input_file, input_file); // Data input file + + // --- File staging out.... + + submitDescription.setFileStageOut(output_file, output_file); + + submitDescription.setExecutable(script_file); + submitDescription.setLocalExecutable(true); + + submitDescription.setSoftware(pBS_Panel1.getSoftware()); + if (jobFS > 0) { + submitDescription.setJobFS(jobFS); + } + if (maxMemory > 0) { + submitDescription.setMaxMemory(maxMemory); + } + if (maxWallTime > 0) { + submitDescription.setMaxWallTime(maxWallTime); + } + + submitDescription.setPbsJobScript(false); + + if (provider.equals(TaskProvider.GLOBUS_2_PROVIDER)) { + //jobDescription.setExecutable("/bin/csh"); + //jobDescription.addArgument(script_file); + if (use_gatekeeper) { + submitDescription.setRemoteHost(gatekeeper); + jobDescription.setRemoteDirectory(gatekeeper); // ????? BUG + } else { + submitDescription.setRemoteHost(remote_host); + jobDescription.setRemoteDirectory(remote_host); + } + GatekeeperPanel gkp = (GatekeeperPanel) TaskProvider.getProvider(provider); + submitDescription.setClusterAddress(gkp.HostComboBox.getSelectedItem(). + toString()); + submitDescription.enableGASS(gkp.gassCheckBox.isSelected()); + jobDescription.enableGASS(gkp.gassCheckBox.isSelected()); + } //else if (provider.equals(TaskProvider.GLOBUS_4_PROVIDER)) { + //jobDescription.setExecutable("/bin/csh"); + //jobDescription.addArgument(script_file); + //if (use_gatekeeper) { + // submitDescription.setRemoteHost(gatekeeper); + // submitDescription.setClusterAddress(remote_host); + //} + //else { + // submitDescription.setRemoteHost(remote_host); + // jobDescription.setRemoteDirectory(remote_host); + //} + //GT4Panel gkp4 = (GT4Panel) TaskProvider.getProvider(provider); + //submitDescription.setClusterAddress(gkp4.HostComboBox.getSelectedItem(). + // toString()); + //} + /* + else if (provider.equals(TaskProvider.SSH_PROVIDER)) { + if (stdout.length() > 0) { + submitDescription.setStdout(stdout); + } + if (stderr.length() > 0) { + submitDescription.setStderr(stderr); + } + + SSHPanel sshp = (SSHPanel) TaskProvider.getProvider(provider); + Object ssh_provider = sshp.getSSHProvider(); + submitDescription.setTaskProviderObject(ssh_provider); + remote_host = sshp.getHost(); + } + */ else if (provider.equals(TaskProvider.LOCAL_PROVIDER)) { + } + + // --- Saving settings + + pBS_Panel1.saveCurrentSettings(); + + // --- Submitting job + + //progressDialog.setLocationRelativeTo(this); + //progressDialog.setVisible(true); + //progressDialog.jobTypeLabel.setText("Submitting " + + // submitDescription.getJobName() + "..."); + + JustProgress progress = new JustProgress(this, "Submitting " + submitDescription.getJobName() + "..."); + progress.start(); + + String jobId = null; + //TaskProvider task = new TaskProvider(); + try { + jobId = taskProvider.submitTask(submitDescription); + //task.submitJob(submitDescription); + } catch (Exception ex) { + //progressDialog.setVisible(false); + progress.cancelShow(); + String message = "Error submitting job: " + ex.getMessage(); + JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE); + System.err.println(message); + return; + } + //progressDialog.setVisible(false); + + progress.cancelShow(); + + JOptionPane.showMessageDialog(null, "Job submitted successfully", "Success", JOptionPane.INFORMATION_MESSAGE); + + //jobId = task.getJobHandle(); + + Date subDate = new Date(); + + CheckPoint chkp = null; + + if (jobId == null) { + System.err.println("No job handle was returned. Job is not included into checkpoint file"); + return; + } + + if (provider.equals(TaskProvider.LOCAL_PROVIDER)) { + System.err.println("Checkpoint is not written for a local provider"); + return; + } + + if (provider.equals(TaskProvider.GLOBUS_4_PROVIDER)) { + System.err.println("Checkpoint is not written for a gt4 provider"); + return; + } + + /* + if (provider.equals(TaskProvider.SSH_PROVIDER)) { + System.err.println("Checkpoint is not written for a SSH provider"); + return; + } + */ + + try { + chkp = new CheckPoint(CheckPointInterface.jobNameTag + "@" + jobName + "@" + + CheckPointInterface.handleTag + "@" + jobId + "@" + + CheckPointInterface.providerTag + "@" + provider + "@" + + CheckPointInterface.computerTag + "@" + + remote_host + "@" + + CheckPointInterface.softwareTag + "@Gaussian@" + + CheckPointInterface.programTag + "@g03@" + + CheckPointInterface.executableTag + "@" + script_file + "@" + + CheckPointInterface.localExecutableTag + "@true@" + + CheckPointInterface.remoteDirectoryTag + "@" + + submitGaussianPanel1.RemoteDirTextField.getText(). + trim() + "@" + + CheckPointInterface.localDirectoryTag + "@" + + submitGaussianPanel1.LocalDirTextField.getText(). + trim() + "@" + + CheckPointInterface.statusTag + "@Submitted@" + + CheckPointInterface.overallJobStatusTag + "@Pending@" + + CheckPointInterface.submittedTimeTag + "@" + subDate.toString(), + "@" // Divider + ); + chkp.setOutputFile(SubmitGaussianPanel.gaussianOutputFileTag, output_file); + + if (provider.equals(TaskProvider.SSH_PROVIDER)) { + if (stdout.length() > 0) { + chkp.setOutputFile(CheckPointInterface.stdOutputTag, stdout); + } + if (stderr.length() > 0) { + chkp.setOutputFile(CheckPointInterface.stdErrorTag, stderr); + } + } + + } catch (Exception ex) { + System.err.println(ex.getMessage()); + return; + } + + ParseCheckpointFile pcf = new ParseCheckpointFile(); + try { + pcf.addCheckPoint(chkp); + } catch (cct.grid.MalformedCheckPointException ex) { + JOptionPane.showMessageDialog(null, + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + } + + /* + void shutdownGASS(GassServer gass) { + try { + gass.shutdown(); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + */ + public void getProxy_Button_actionPerformed(ActionEvent e) { + GridProxyInitDialog.openGetProxyDialog(); + } + + public void providerComboBox_actionPerformed(ActionEvent e) { + if (!providerComboBox.isEnabled()) { + return; + } + providerComboBox.setEnabled(false); + + CardLayout cl = (CardLayout) cardPanel.getLayout(); + cl.show(cardPanel, providerComboBox.getSelectedItem().toString()); + + String provider = providerComboBox.getSelectedItem().toString(); + //if (provider.equalsIgnoreCase(cct.grid.TaskProvider.SSH_PROVIDER)) { + //SSHPanel ssh = (SSHPanel) allProviders.get(provider); + GridProviderInterface gpi = allProviders.get(provider); + FileChooserInterface fci = gpi.getRemoteFileChooser(); + submitGaussianPanel1.setRemoteFileChooser(fci); + //submitGaussianPanel1.setRemoteFileChooser(ssh); + //} + + providerComboBox.setEnabled(true); + + } + + private class JustProgress + extends cct.tools.SwingWorker { + + JDialog parent = null; + int jobType; + ProgressDialog pd; + + JustProgress(JDialog p, String jobDesc) { + parent = p; + pd = new ProgressDialog(new Frame(), "Job Submission Progress", false); + pd.setLocationRelativeTo(parent); + pd.setAlwaysOnTop(true); + pd.jobTypeLabel.setText(jobDesc); + pd.cancelButton.setVisible(false); + /* + pd.cancelButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + cancelTranfer(); + } + } + ); + */ + + } + + @Override + public Object construct() { + pd.setVisible(true); + try { + while (true) { + Thread.sleep(1000); + } + } catch (Exception ex) { + } + return "done"; + } + + void cancelShow() { + pd.setVisible(false); + interrupt(); + } + + @Override + public void finished() { + pd.setVisible(false); + } + } + + // Does not work properly + class JobSubProgress + extends java.util.TimerTask { + + int MAX = 10; + JLabel msgLabel = new JLabel("Submitting Job..."); + JProgressBar progressBar = new JProgressBar(0, MAX); + JOptionPane pane = null; + JDialog dialog = null; + + public JobSubProgress() { + progressBar.setValue(0); + + Object[] comp = { + msgLabel, progressBar}; + //Object[] options = { + // "Cancel"}; + + pane = new JOptionPane(comp, + JOptionPane.DEFAULT_OPTION, + JOptionPane.INFORMATION_MESSAGE, + null); + //options, + //options[0]); + + dialog = pane.createDialog(null, "Submitting a Job"); + } + + @Override + public void run() { + if (!dialog.isVisible()) { + dialog.setVisible(true); + } + progressBar.setValue((progressBar.getValue() + 1) % MAX); + } + + @Override + public boolean cancel() { + dialog.setVisible(false); + return false; + } + } + + class Task + extends Thread { + + private boolean done = false; + private Exception exception = null; + private boolean cancel = false; + + public boolean isDone() { + return done; + } + + public void cancel() { + cancel = true; + } + + public boolean isCancelled() { + return cancel; + } + + @Override + public void run() { + + try { + //queryIsDone = false; + //if (taskType == 0) { + // updateJobStatus(); + // } + //else if ( taskType == JSD_KILL_JOBS ) { + // killJobs(); + //} + //queryIsDone = true; + } catch (Exception e) { + exception = e; + done = true; + return; + } + + /* + try { + proxy = model.createProxy(new String(passwordTF.getPassword())); + } + catch (Exception e) { + exception = e; + done = true; + return; + } + */ + + if (cancel) { + return; + } + + // send the event.... + //if (proxyListener != null) { + // proxyListener.proxyCreated(proxy); + //} + + done = true; + } + + public Exception getException() { + return exception; + } + } + + /* + class gaussianJobSubOutputListener + implements JobOutputListener { + JobOutputInterface textPane = null; + + public gaussianJobSubOutputListener(JobOutputInterface text_pane) { + textPane = text_pane; + } + + public void outputClosed() { + //Job has finished; no more output is available + //String text = textPane.getText(); + //text += "\nEnd of output\n"; + textPane.appendOutput("\nEnd of output\n"); + + } + + public void outputChanged(String output) { + logger.info("output: " + output); + //String text = textPane.getText(); + //text += output; + textPane.appendOutput(output); + } + } + */ +} + +class SubmitGaussianDialog_providerComboBox_actionAdapter + implements ActionListener { + + private SubmitGaussianDialog adaptee; + + SubmitGaussianDialog_providerComboBox_actionAdapter(SubmitGaussianDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.providerComboBox_actionPerformed(e); + } +} + +class SubmitGaussianDialog_getProxy_Button_actionAdapter + implements ActionListener { + + private SubmitGaussianDialog adaptee; + + SubmitGaussianDialog_getProxy_Button_actionAdapter(SubmitGaussianDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.getProxy_Button_actionPerformed(e); + } +} + +class SubmitGaussianDialog_Submit_Button_actionAdapter + implements ActionListener { + + private SubmitGaussianDialog adaptee; + + SubmitGaussianDialog_Submit_Button_actionAdapter(SubmitGaussianDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Submit_Button_actionPerformed(e); + } +} + +class SubmitGaussianDialog_Cancel_Button_actionAdapter + implements ActionListener { + + private SubmitGaussianDialog adaptee; + + SubmitGaussianDialog_Cancel_Button_actionAdapter(SubmitGaussianDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.Cancel_Button_actionPerformed(e); + } +} + +/* +class JobOutputListenerImpl +implements JobOutputListener { +String jobOutput = ""; + +public JobOutputListenerImpl() { +} + +public void outputClosed() { +//Job has finished; no more output is available +logger.info("Job finished: " + jobOutput); +} + +public void outputChanged(String output) { +jobOutput += output; +logger.info("output: " + output); +} +} + */ diff --git a/src/main/java/cct/grid/ui/gaussian/SubmitGaussianDialogNew.java b/src/main/java/cct/grid/ui/gaussian/SubmitGaussianDialogNew.java new file mode 100644 index 0000000..943b6fe --- /dev/null +++ b/src/main/java/cct/grid/ui/gaussian/SubmitGaussianDialogNew.java @@ -0,0 +1,1083 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.grid.ui.gaussian; + +import cct.GlobalSettings; +import cct.globus.ui.GridProxyInitDialog; +import cct.grid.*; +import cct.grid.ui.*; +import cct.interfaces.FileChooserInterface; +import cct.tools.IOUtils; +import cct.tools.Utils; + +import javax.swing.*; +import javax.swing.border.Border; +import javax.swing.border.TitledBorder; +import java.awt.*; +import java.awt.event.*; +import java.io.InputStream; +import java.io.StringWriter; +import java.util.*; +import java.util.logging.Logger; +import java.util.regex.PatternSyntaxException; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +enum CustomOptions { + + executable +} + +public class SubmitGaussianDialogNew + extends JDialog implements ScriptSubmitterDialogInterface { + + static public final String SCRIPT = "script"; + private HashMap scripts = new HashMap(); + private JPanel MainPanel = new JPanel(); + private BorderLayout borderLayout1 = new BorderLayout(); + private SubmitGaussianPanel submitGaussianPanel = new SubmitGaussianPanel(); + private JPanel ButtonPanel = new JPanel(); + private JButton Cancel_Button = new JButton(); + private JButton Submit_Button = new JButton(); + static String devider = "@"; + JComboBox providerComboBox = new JComboBox(); + JPanel providerPanel = new JPanel(); + FlowLayout flowLayout1 = new FlowLayout(); + JLabel providerLabel = new JLabel(); + ProgressDialog progressDialog = null; + //private GridProxyInterface getGridProxy = null; + int taskType = 0; + private static Logger logger = Logger.getLogger(SubmitGaussianDialogNew.class.getName()); + Map allProviders = new LinkedHashMap(); + JobOutputInterface jobOutput = null; + JPanel cardPanel = new JPanel(); + JPanel comboPanel = new JPanel(); + FlowLayout flowLayout2 = new FlowLayout(); + BorderLayout borderLayout2 = new BorderLayout(); + CardLayout cardLayout1 = new CardLayout(); + JLabel schedulerLabel = new JLabel(); + JComboBox schedulerComboBox = new JComboBox(); + ResourcesPanel resourcesPanel = new ResourcesPanel(); + JPanel topPanel = new JPanel(); + BorderLayout borderLayout3 = new BorderLayout(); + PBSPanel pbsPanel = new PBSPanel(); + Border border1 = BorderFactory.createLineBorder(Color.darkGray, 2); + Border border2 = new TitledBorder(border1, "PBS Parameters"); + JButton submitWithEditButton = new JButton(); + EditScriptDialog editScriptDialog = new EditScriptDialog(new Frame(), + "Edit Script before Submission", true); + + public static void main(String[] args) { + + SwingUtilities.invokeLater(new Runnable() { + + public void run() { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (Exception exception) { + exception.printStackTrace(); + } + + SubmitGaussianDialogNew frame = new SubmitGaussianDialogNew(); + frame.setTaskProviders(TaskProvider.getAvailableTaskProviders()); + frame.validate(); + frame.pack(); + frame.Cancel_Button.addActionListener(new ActionListener() { + + public void actionPerformed(ActionEvent e) { + System.exit(0); + } + }); + frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); + frame.setVisible(true); + + } + }); + } + + public ScriptSubmitterDialogInterface newInstance() { + return new SubmitGaussianDialogNew(new Frame(), null, "Submit Gaussian Script", false); + } + + public JDialog getDialog() { + return this; + } + + /** + * Parses a string with custom options. Options are divided with "@". + * @param options String - options + * @throws Exception + */ + public void setCustomOptions(String options) throws Exception { + if (options == null || options.trim().length() == 0) { + throw new Exception("No parameters"); + } + String[] tokens = options.split(devider); + int count = 0; + while (count < tokens.length) { + if (count < tokens.length && tokens[count].startsWith(CustomOptions.executable.name())) { + String[] opts = tokens[count].split("\\s*=\\s*"); + if (opts.length < 2) { + logger.severe("Valid form: " + CustomOptions.executable.name() + " = exec-name. Got " + tokens[count]); + logger.severe("Entire string: " + options); + throw new Exception("Valid form: " + CustomOptions.executable.name() + " = exec-name. Got " + tokens[count]); + } + submitGaussianPanel.setExecutable(opts[1]); + logger.info("Setting executable to " + opts[1]); + ++count; + continue; + } + logger.severe("Unknown option " + tokens[count]); + logger.severe("Entire string: " + options); + throw new Exception("Unknown option " + tokens[count]); + } + } + + public void setLocalDirectory(String localDir) { + submitGaussianPanel.LocalDirTextField.setText(localDir); + } + + public void setRemoteDirectory(String remoteDir) { + submitGaussianPanel.RemoteDirTextField.setText(remoteDir); + } + + public SubmitGaussianDialogNew(Frame owner, JobOutputInterface redir, String title, boolean modal) { + super(owner, title, modal); + jobOutput = redir; + try { + jbInit(); + setDefaultCloseOperation(HIDE_ON_CLOSE); + pack(); + + String className = this.getClass().getCanonicalName(); + try { + Properties props = GlobalSettings.getCustomProperties(); + + if (props != null) { + + //--- Default enable extensions + + Set properties = props.stringPropertyNames(); + Iterator iter = properties.iterator(); + String key = className + GlobalSettings.DIVIDER + SCRIPT; + logger.info("\nIterating through properties..."); + while (iter.hasNext()) { + String p = iter.next(); + logger.info("Property: " + p); + if (!p.startsWith(key)) { + continue; + } + + String new_key = "initial_new_KEY"; + try { + new_key = buildKey(p); + String body = loadScript(props.getProperty(p)); + if (scripts.containsKey(new_key)) { + logger.warning("Warning: script for key " + new_key + " already exists. Overwriting it..."); + } + scripts.put(new_key, body); + logger.info("\nKey: " + new_key + " script file: " + props.getProperty(p) + "\n=====\n" + body + "\n====="); + } catch (Exception ex) { + logger.severe("Error: Cannot load script " + props.getProperty(p) + " for key " + new_key + ": " + ex.getMessage()); + } + } + + String enableExt = props.getProperty(className + GlobalSettings.DIVIDER + SCRIPT); + if (enableExt != null) { + Boolean editable; + try { + editable = Boolean.parseBoolean(enableExt); + } catch (Exception exx) { + } + } + } + } catch (Exception ex) { + //System.err.println("Warning: cannot open " + CUSTOM_PROPERTY_FILE + + // " : " + + // ex.getMessage()); + } + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public SubmitGaussianDialogNew() { + this(new Frame(), null, "Submit Gaussian Script", false); + } + + // public void setProxyHandler(GridProxyInterface proxyHandler) { + // getGridProxy = proxyHandler; + //} + private void jbInit() throws Exception { + MainPanel.setLayout(borderLayout1); + submitGaussianPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color.darkGray, 1), "Job Specifications")); + Cancel_Button.setToolTipText("Cancel Submission"); + Cancel_Button.setText("Cancel"); + Cancel_Button.addActionListener(new SubmitGaussianDialogNew_Cancel_Button_actionAdapter(this)); + Submit_Button.setToolTipText("Submit Job for Execution"); + Submit_Button.setText("Submit"); + Submit_Button.addActionListener(new SubmitGaussianDialogNew_Submit_Button_actionAdapter(this)); + submitWithEditButton.addActionListener(new SubmitGaussianDialogNew_Submit_Button_actionAdapter(this)); + this.setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); + providerLabel.setToolTipText(""); + providerLabel.setText(" Provider: "); + comboPanel.setLayout(flowLayout2); + flowLayout2.setAlignment(FlowLayout.LEFT); + providerPanel.setLayout(borderLayout2); + cardPanel.setLayout(cardLayout1); + providerComboBox.addActionListener(new SubmitGaussianDialogNew_providerComboBox_actionAdapter(this)); + schedulerLabel.setToolTipText(""); + schedulerLabel.setText(" Scheduler: "); + cardPanel.setMinimumSize(new Dimension(255, 150)); + schedulerComboBox.setEnabled(false); + topPanel.setLayout(borderLayout3); + pbsPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color.darkGray, 1), "PBS Parameters")); + submitWithEditButton.setToolTipText("Edit Script Before Submission"); + submitWithEditButton.setText("Edit & Submit"); + //MainPanel.add(taskProviderPanel, java.awt.BorderLayout.NORTH); + this.getContentPane().add(MainPanel, BorderLayout.CENTER); + ButtonPanel.add(Submit_Button); + ButtonPanel.add(submitWithEditButton); + ButtonPanel.add(Cancel_Button); + this.getContentPane().add(ButtonPanel, BorderLayout.SOUTH); + comboPanel.add(providerLabel); + comboPanel.add(providerComboBox); + comboPanel.add(schedulerLabel); + comboPanel.add(schedulerComboBox); + providerPanel.add(cardPanel, BorderLayout.CENTER); + providerPanel.add(comboPanel, BorderLayout.NORTH); + topPanel.add(providerPanel, BorderLayout.CENTER); + MainPanel.add(pbsPanel, BorderLayout.CENTER); + MainPanel.add(resourcesPanel, BorderLayout.NORTH); + this.getContentPane().add(topPanel, BorderLayout.NORTH); + MainPanel.add(submitGaussianPanel, BorderLayout.SOUTH); + WindowListener l = new WindowAdapter() { + + public void windowClosing(WindowEvent e) { + logger.info("Exiting..."); + //Deactivator.deactivateAll(); + System.exit(0); + } + }; + + addWindowListener(l); + + setTaskSchedulers(TaskScheduler.getAvailableTaskSchedulers()); + + progressDialog = new ProgressDialog(new Frame(), "Task Submission Progress", false); + progressDialog.cancelButton.setVisible(false); + progressDialog.setAlwaysOnTop(true); + progressDialog.setLocationRelativeTo(this); + + editScriptDialog.setLocationRelativeTo(this); + editScriptDialog.setSize(320, 480); + + this.validate(); + } + + public void enableLocalDir(boolean enable) { + submitGaussianPanel.LocalDirTextField.setEnabled(enable); + } + + public void enableInputFile(boolean enable) { + submitGaussianPanel.inputFileTextField.setEnabled(enable); + } + + public void setLocalDir(String locDir) { + submitGaussianPanel.LocalDirTextField.setText(locDir); + } + + public void setInputFile(String inputFile) { + submitGaussianPanel.setInputFile(inputFile); + } + + public void setGatekeepers(String[] gk) { + } + + public void setHosts(String[] gk) { + } + + public void Cancel_Button_actionPerformed(ActionEvent e) { + setVisible(false); + } + + public void setTaskProviders(Map providers) { + providerComboBox.setEnabled(false); + providerComboBox.removeAllItems(); + + allProviders = new LinkedHashMap(providers); + + Set set = providers.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String providerName = me.getKey().toString(); + providerComboBox.addItem(providerName); + //Component panel = (Component) me.getValue(); + GridProviderInterface provider = (GridProviderInterface) me.getValue(); + Component panel = provider.getVisualComponent(); + panel.validate(); + + cardPanel.add(panel, providerName); + } + + providerComboBox.setSelectedIndex(0); + + CardLayout cl = (CardLayout) cardPanel.getLayout(); + cl.show(cardPanel, providerComboBox.getSelectedItem().toString()); + cardPanel.validate(); + cardPanel.updateUI(); + + providerComboBox.setEnabled(true); + + String provider = providerComboBox.getSelectedItem().toString(); + GridProviderInterface gpi = allProviders.get(provider); + FileChooserInterface fci = gpi.getRemoteFileChooser(); + submitGaussianPanel.setRemoteFileChooser(fci); + + this.validate(); + } + + // !!! It's only a prototype yet !!! + public void setTaskSchedulers(Map schedulers) { + schedulerComboBox.setEnabled(false); + schedulerComboBox.removeAllItems(); + + Set set = schedulers.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String schedulerName = me.getKey().toString(); + schedulerComboBox.addItem(schedulerName); + //Component panel = (Component) me.getValue(); + + //cardPanel.add(panel, schedulerName); + } + + schedulerComboBox.setSelectedIndex(0); + + //CardLayout cl = (CardLayout) cardPanel.getLayout(); + //cl.show(cardPanel, providerComboBox.getSelectedItem().toString()); + + schedulerComboBox.setEnabled(true); + } + + public void Submit_Button_actionPerformed(ActionEvent e) { + validate(); + + // --- test all data + + try { + resourcesPanel.validateValues(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Wrong input data: " + ex.getMessage(), "Error in input data", JOptionPane.ERROR_MESSAGE); + return; + } + + boolean submitWithEdit = false; + if (e.getSource() == submitWithEditButton) { + submitWithEdit = true; + } + + String provider = providerComboBox.getSelectedItem().toString(); + + GridProviderInterface taskProvider = allProviders.get(provider); + + String scheduler = schedulerComboBox.getSelectedItem().toString(); + boolean use_gatekeeper = false; + String gatekeeper = null; + String remote_host = taskProvider.getRemoteHost(); + // --- Get Script name (executable) + String script_file = submitGaussianPanel.ScriptTextField.getText().trim(); + + String executable_file = submitGaussianPanel.getExecutable(); + + JobDescription jobDescription = new JobDescription(); + JobDescription submitDescription = new JobDescription(); + + // --- Set Remote directory + + String remoteDirectory = submitGaussianPanel.RemoteDirTextField.getText().trim(); + + // --- Job name + String jobName = submitGaussianPanel.jobNameTextField.getText().trim(); + + // --- Get Local directory + String localDirectory = submitGaussianPanel.LocalDirTextField.getText().trim(); + + if (localDirectory.indexOf("\\") != -1) { + localDirectory = "/" + localDirectory; + try { + //valid_dir = valid_dir.replaceAll("\\", "/"); + localDirectory = localDirectory.replace('\\', '/'); + } catch (PatternSyntaxException ex) { + while (localDirectory.indexOf("\\") != -1) { + } + logger.warning("Regex error: " + localDirectory); + } + } + + if (localDirectory.endsWith("/")) { + localDirectory = localDirectory.substring(0, localDirectory.length() - 1); + } + jobDescription.setLocalDirectory(localDirectory); + + // --- Get CPU number + + try { + jobDescription.setNCPU(this.resourcesPanel.getNCPUs()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + // --- Setup max (wall) time + + float maxWallTimeInMins = -1; + float time_in_secs = 0; + try { + time_in_secs = this.resourcesPanel.getTimeInSeconds(); + maxWallTimeInMins = time_in_secs / 60.0f; + jobDescription.setMaxCpuTime(time_in_secs); + jobDescription.setMaxTime(time_in_secs); + jobDescription.setMaxWallTime(time_in_secs); + + submitDescription.setMaxWallTime(maxWallTimeInMins); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + // --- Setup max memory + + + int maxMemory = 0; // in MB + String memoryUnits = ""; + try { + maxMemory = (int) resourcesPanel.getMaxMemoryInMb(); + memoryUnits = "MB"; + jobDescription.setMaxMemory(maxMemory); + submitDescription.setMaxMemory(maxMemory); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + // --- Setup project + + jobDescription.setProject(pbsPanel.getProject()); + + // --- Setup jobfs + + int jobFS = 0; + if (this.pbsPanel.areExtensionsEnabled()) { + try { + jobFS = pbsPanel.getJobFS(); + if (jobFS > 0) { + jobDescription.setJobFS(jobFS); + submitDescription.setJobFS(jobFS); + } + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return; + } + } + + String input_file = submitGaussianPanel.inputFileTextField.getText().trim(); + String output_file = submitGaussianPanel.OutputFileTextField.getText().trim(); + + // --- Setup queue + + String queue = this.pbsPanel.getQueue(); + + jobDescription.setQueue(queue); + + // Stdout & stderr + + String stdout = submitGaussianPanel.getStdoutFileName().trim(); + String stderr = submitGaussianPanel.getStderrFileName().trim(); + + //if (provider.equals(TaskProvider.SSH_PROVIDER)) { + if (stdout.length() > 0) { + jobDescription.setStdout(stdout); + submitDescription.setStdout(stdout); + } + if (stderr.length() > 0) { + jobDescription.setStderr(stderr); + submitDescription.setStderr(stderr); + } + //} + + + // --- Setup software + + if (this.pbsPanel.areExtensionsEnabled() + && pbsPanel.getSoftware().length() > 0) { + jobDescription.setSoftware(pbsPanel.getSoftware()); + submitDescription.setSoftware(pbsPanel.getSoftware()); + + } + // --- Setup scheduler + + String sched = this.schedulerComboBox.getSelectedItem().toString(); + if (taskProvider.isPassOptionsToScheduler()) { + jobDescription.setScheduler(sched); + } + + java.util.List prepDirs = this.submitGaussianPanel.getPreprocessDirectives(); + for (int i = 0; i < prepDirs.size(); i++) { + jobDescription.addPreprocessDirective(prepDirs.get(i)); + } + //jobDescription.addPreprocessDirective("module load dos2unix"); + //jobDescription.addPreprocessDirective("dos2unix " + input_file); + //jobDescription.addPreprocessDirective("module load gaussian"); + + jobDescription.setExecutable(executable_file); + + jobDescription.addArgument("<" + input_file); + jobDescription.addArgument(">" + output_file); + + jobDescription.setPBSOther("jamberoo"); + + jobDescription.setShell("/bin/bash"); + + // --- Save script file + + try { + String scriptContent = "If you see this text something is wrong with script generation..."; + if (scripts.size() < 1) { + + scriptContent = JobDescription.createUnixScript(jobDescription); + + } else { + Map patterns = new HashMap(); + patterns.put("@@JOBNAME@@", jobName); + patterns.put("@@EXECUTABLE@@", executable_file); + patterns.put("@@INPUT@@", input_file); + patterns.put("@@OUTPUT@@", output_file); + patterns.put("@@STDOUT@@", stdout); + patterns.put("@@STDERR@@", stderr); + patterns.put("@@NCPUS@@", String.valueOf(resourcesPanel.getNCPUs())); + patterns.put("@@WALLTIME@@", Utils.timeInHours(time_in_secs)); + patterns.put("@@MEMORY@@", String.valueOf(maxMemory)); + patterns.put("@@MEMORY-UNITS@@", "MB"); + + String template = scripts.get(""); + scriptContent = JobDescription.createUnixScript(jobDescription, template, patterns); + } + + if (submitWithEdit) { + editScriptDialog.scriptTextArea.setText(scriptContent); + editScriptDialog.setVisible(true); + if (!editScriptDialog.submitPressed) { + return; + } + scriptContent = editScriptDialog.scriptTextArea.getText(); + } + + IOUtils.saveStringIntoFile(scriptContent, submitGaussianPanel.LocalDirTextField.getText().trim() + script_file); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, "Error saving script file" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + jobDescription.setTaskProvider(provider); + jobDescription.setScheduler(JobDescription.PBS_SCHEDULER); + + // --- Preparing final job description for submitting + + submitDescription.setTaskProvider(provider); + submitDescription.setScheduler(JobDescription.PBS_SCHEDULER); + submitDescription.setPbsJobScript(true); + submitDescription.setExecutable(script_file); + submitDescription.setRemoteHost(remote_host); + submitDescription.setRemoteDirectory(remoteDirectory); + submitDescription.setJobName(jobName); + submitDescription.setLocalDirectory(localDirectory); + submitDescription.setProject(this.pbsPanel.getProject()); + submitDescription.setQueue(queue); + + // --- ( File Staging In ) + + submitDescription.setFileStageIn(script_file, script_file); // Run script file + submitDescription.setFileStageIn(input_file, input_file); // Data input file + + // --- File staging out.... + + submitDescription.setFileStageOut(output_file, output_file); + + submitDescription.setExecutable(script_file); + submitDescription.setLocalExecutable(true); + + // --- Non-standard + + submitDescription.setPbsJobScript(taskProvider.isPassOptionsToScheduler()); + + if (provider.equals(TaskProvider.LOCAL_PROVIDER)) { + } // --- Submitting job + + String jobId = null; + //TaskProvider task = new TaskProvider(); + try { + jobId = taskProvider.submitTask(submitDescription); + //task.submitJob(submitDescription); + } catch (Exception ex) { + //progressDialog.setVisible(false); + //progress.cancelShow(); + String message = "Error submitting job: " + ex.getMessage(); + System.err.println(message); + JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE); + return; + } + //progressDialog.setVisible(false); + + //progress.cancelShow(); + + JOptionPane.showMessageDialog(null, "Job submitted successfully", "Success", JOptionPane.INFORMATION_MESSAGE); + + //jobId = task.getJobHandle(); + + Date subDate = new Date(); + CheckPointInterface chkp = null; + + if (jobId == null) { + System.err.println( + "No job handle was returned. Job is not included into checkpoint file"); + return; + } + + if (provider.equals(TaskProvider.LOCAL_PROVIDER)) { + System.err.println("Checkpoint is not written for a local provider"); + return; + } + + if (provider.equals(TaskProvider.GLOBUS_4_PROVIDER)) { + System.err.println("Checkpoint is not written for a gt4 provider"); + return; + } + + /* + if (provider.equals(TaskProvider.SSH_PROVIDER)) { + System.err.println("Checkpoint is not written for a SSH provider"); + return; + } + */ + + try { + chkp = new CheckPoint(CheckPointInterface.jobNameTag + "@" + jobName + "@" + + CheckPointInterface.handleTag + "@" + jobId + "@" + + CheckPointInterface.providerTag + "@" + provider + "@" + + CheckPointInterface.computerTag + "@" + + remote_host + "@" + + CheckPointInterface.softwareTag + "@Gaussian@" + + CheckPointInterface.programTag + "@g09@" + + CheckPointInterface.executableTag + "@" + script_file + "@" + + CheckPointInterface.localExecutableTag + "@true@" + + CheckPointInterface.remoteDirectoryTag + "@" + + submitGaussianPanel.RemoteDirTextField.getText(). + trim() + "@" + + CheckPointInterface.localDirectoryTag + "@" + + submitGaussianPanel.LocalDirTextField.getText(). + trim() + "@" + + CheckPointInterface.statusTag + "@Submitted@" + + CheckPointInterface.overallJobStatusTag + "@Pending@" + + CheckPointInterface.submittedTimeTag + "@" + subDate.toString(), + "@" // Divider + ); + chkp.setOutputFile(SubmitGaussianPanel.gaussianOutputFileTag, output_file); + + //if (provider.equals(TaskProvider.SSH_PROVIDER)) { + if (stdout.length() > 0) { + chkp.setOutputFile(CheckPointInterface.stdOutputTag, stdout); + } + if (stderr.length() > 0) { + chkp.setOutputFile(CheckPointInterface.stdErrorTag, stderr); + } + + chkp = taskProvider.setCheckPoint(chkp); + //} + + } catch (Exception ex) { + System.err.println(ex.getMessage()); + return; + } + + ParseCheckpointFile pcf = new ParseCheckpointFile(); + try { + pcf.addCheckPoint((CheckPoint) chkp); + } catch (cct.grid.MalformedCheckPointException ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + } + + /* + void shutdownGASS(GassServer gass) { + try { + gass.shutdown(); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + */ + public void getProxy_Button_actionPerformed(ActionEvent e) { + GridProxyInitDialog.openGetProxyDialog(); + } + + public void providerComboBox_actionPerformed(ActionEvent e) { + if (!providerComboBox.isEnabled()) { + return; + } + providerComboBox.setEnabled(false); + + CardLayout cl = (CardLayout) cardPanel.getLayout(); + cl.show(cardPanel, providerComboBox.getSelectedItem().toString()); + + String provider = providerComboBox.getSelectedItem().toString(); + //if (provider.equalsIgnoreCase(cct.grid.TaskProvider.SSH_PROVIDER)) { + //SSHPanel ssh = (SSHPanel) allProviders.get(provider); + GridProviderInterface gpi = allProviders.get(provider); + FileChooserInterface fci = gpi.getRemoteFileChooser(); + submitGaussianPanel.setRemoteFileChooser(fci); + //submitGaussianPanel1.setRemoteFileChooser(ssh); + //} + + providerComboBox.setEnabled(true); + + } + + /** + * + * @param raw + * @return + */ + public String buildKey(String raw) throws Exception { + int index = raw.indexOf(GlobalSettings.DIVIDER + SCRIPT); + if (index == -1) { + throw new Exception("Property does not contain sequence: " + GlobalSettings.DIVIDER + SCRIPT); + } + index += (GlobalSettings.DIVIDER + SCRIPT).length() + 1; + if (raw.length() <= index) { + return ""; + } + + String buffer = raw.substring(index); + if (buffer.length() < 1) { + return ""; + } + + return buffer; + } + + public String loadScript(String name) throws Exception { + InputStream is = null; + try { + ClassLoader cl = cct.modelling.FormatManager.class.getClassLoader(); + //logger.info("Class loader: " + cl.toString()); + //builderURL = cl.getResource(file_name); + is = cl.getResourceAsStream(name); + } catch (Exception ex) { + throw new Exception(this.getClass().getCanonicalName() + ": loadScript: cannot get resource : " + name + " : " + ex.getMessage()); + } + + StringWriter sw = new StringWriter(); + + + try { + int symbol; + while ((symbol = is.read()) != -1) { + sw.write(symbol); + } + } catch (Exception ex) { + throw new Exception(this.getClass().getCanonicalName() + ": loadScript: cannot read resource : " + name + " : " + ex.getMessage()); + } + + return sw.toString(); + } + + private class JustProgress + extends cct.tools.SwingWorker { + + JDialog parent = null; + int jobType; + ProgressDialog pd; + + JustProgress(JDialog p, String jobDesc) { + parent = p; + pd = new ProgressDialog(new Frame(), "Job Submission Progress", false); + pd.setLocationRelativeTo(parent); + pd.setAlwaysOnTop(true); + pd.jobTypeLabel.setText(jobDesc); + pd.cancelButton.setVisible(false); + /* + pd.cancelButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + cancelTranfer(); + } + } + ); + */ + + } + + public Object construct() { + pd.setVisible(true); + try { + while (true) { + Thread.sleep(1000); + } + } catch (Exception ex) { + } + return "done"; + } + + void cancelShow() { + pd.setVisible(false); + interrupt(); + } + + public void finished() { + pd.setVisible(false); + } + } + + // Does not work properly + class JobSubProgress + extends java.util.TimerTask { + + int MAX = 10; + JLabel msgLabel = new JLabel("Submitting Job..."); + JProgressBar progressBar = new JProgressBar(0, MAX); + JOptionPane pane = null; + JDialog dialog = null; + + public JobSubProgress() { + progressBar.setValue(0); + + Object[] comp = { + msgLabel, progressBar}; + //Object[] options = { + // "Cancel"}; + + pane = new JOptionPane(comp, + JOptionPane.DEFAULT_OPTION, + JOptionPane.INFORMATION_MESSAGE, + null); + //options, + //options[0]); + + dialog = pane.createDialog(null, "Submitting a Job"); + } + + public void run() { + if (!dialog.isVisible()) { + dialog.setVisible(true); + } + progressBar.setValue((progressBar.getValue() + 1) % MAX); + } + + public boolean cancel() { + dialog.setVisible(false); + return false; + } + } + + class Task + extends Thread { + + private boolean done = false; + private Exception exception = null; + private boolean cancel = false; + + public boolean isDone() { + return done; + } + + public void cancel() { + cancel = true; + } + + public boolean isCancelled() { + return cancel; + } + + public void run() { + + try { + //queryIsDone = false; + //if (taskType == 0) { + // updateJobStatus(); + // } + //else if ( taskType == JSD_KILL_JOBS ) { + // killJobs(); + //} + //queryIsDone = true; + } catch (Exception e) { + exception = e; + done = true; + return; + } + + /* + try { + proxy = model.createProxy(new String(passwordTF.getPassword())); + } + catch (Exception e) { + exception = e; + done = true; + return; + } + */ + + if (cancel) { + return; + } + + // send the event.... + //if (proxyListener != null) { + // proxyListener.proxyCreated(proxy); + //} + + done = true; + } + + public Exception getException() { + return exception; + } + } + + /* + class gaussianJobSubOutputListener + implements JobOutputListener { + JobOutputInterface textPane = null; + + public gaussianJobSubOutputListener(JobOutputInterface text_pane) { + textPane = text_pane; + } + + public void outputClosed() { + //Job has finished; no more output is available + //String text = textPane.getText(); + //text += "\nEnd of output\n"; + textPane.appendOutput("\nEnd of output\n"); + + } + + public void outputChanged(String output) { + logger.info("output: " + output); + //String text = textPane.getText(); + //text += output; + textPane.appendOutput(output); + } + } + */ +} + +class SubmitGaussianDialogNew_providerComboBox_actionAdapter + implements ActionListener { + + private SubmitGaussianDialogNew adaptee; + + SubmitGaussianDialogNew_providerComboBox_actionAdapter( + SubmitGaussianDialogNew adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.providerComboBox_actionPerformed(e); + } +} + +class SubmitGaussianDialogNew_Submit_Button_actionAdapter + implements ActionListener { + + private SubmitGaussianDialogNew adaptee; + + SubmitGaussianDialogNew_Submit_Button_actionAdapter(SubmitGaussianDialogNew adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.Submit_Button_actionPerformed(e); + } +} + +class SubmitGaussianDialogNew_Cancel_Button_actionAdapter + implements ActionListener { + + private SubmitGaussianDialogNew adaptee; + + SubmitGaussianDialogNew_Cancel_Button_actionAdapter(SubmitGaussianDialogNew adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.Cancel_Button_actionPerformed(e); + } +} + +/* +class JobOutputListenerImpl +implements JobOutputListener { +String jobOutput = ""; + +public JobOutputListenerImpl() { +} + +public void outputClosed() { +//Job has finished; no more output is available +logger.info("Job finished: " + jobOutput); +} + +public void outputChanged(String output) { +jobOutput += output; +logger.info("output: " + output); +} +} + */ diff --git a/src/main/java/cct/grid/ui/gaussian/SubmitGaussianDialogVERYOLD.java b/src/main/java/cct/grid/ui/gaussian/SubmitGaussianDialogVERYOLD.java new file mode 100644 index 0000000..6ad7a95 --- /dev/null +++ b/src/main/java/cct/grid/ui/gaussian/SubmitGaussianDialogVERYOLD.java @@ -0,0 +1,892 @@ +package cct.grid.ui.gaussian;/* + package cct.grid.ui.gaussian; + + import java.util.Date; + import java.awt.*; + import javax.swing.*; + import cct.grid.ui.*; + import java.awt.BorderLayout; + import javax.swing.border.TitledBorder; + import cct.grid.ui.PBS_Panel; + import java.awt.event.ActionEvent; + import java.awt.event.ActionListener; + import cct.tools.IOUtils; + import java.util.regex.PatternSyntaxException; + + import cct.globus.*; + import cct.globus.ui.*; + import cct.grid.*; + import java.awt.event.WindowEvent; + import java.awt.event.WindowListener; + import java.awt.event.WindowAdapter; + //import org.globus.util.deactivator.Deactivator; + + import org.apache.log4j.Logger; + import cct.grid.ui.JobOutputInterface; + import cct.globus.ui.GridProxyInitDialog; + import cct.grid.*; + import java.util.Iterator; + import java.util.Set; + import java.util.Map; + import java.util.LinkedHashMap; + import java.io.StringWriter; + import java.awt.Dimension; + import cct.ssh.*; + import cct.interfaces.FileChooserInterface; + + + public class SubmitGaussianDialog + extends JDialog implements CheckPointInterface, + ScriptSubmitterDialogInterface { + + JPanel MainPanel = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + SubmitGaussianPanel submitGaussianPanel1 = new SubmitGaussianPanel(); + PBS_Panel pBS_Panel1 = new PBS_Panel(null, "normal", 60, 1024, 5, + "g03"); + JPanel ButtonPanel = new JPanel(); + JButton Cancel_Button = new JButton(); + JButton Submit_Button = new JButton(); + + JComboBox providerComboBox = new JComboBox(); + JPanel providerPanel = new JPanel(); + FlowLayout flowLayout1 = new FlowLayout(); + JLabel providerLabel = new JLabel(); + + //private GridProxyInterface getGridProxy = null; + int taskType = 0; + private static Logger logger = + Logger.getLogger(SubmitGaussianDialog.class.getName()); + + LinkedHashMap allProviders = new LinkedHashMap(); + JobOutputInterface jobOutput = null; + JButton getProxy_Button = new JButton(); + JPanel cardPanel = new JPanel(); + JPanel comboPanel = new JPanel(); + FlowLayout flowLayout2 = new FlowLayout(); + BorderLayout borderLayout2 = new BorderLayout(); + CardLayout cardLayout1 = new CardLayout(); + JLabel schedulerLabel = new JLabel(); + JComboBox schedulerComboBox = new JComboBox(); + + public static void main(String[] args) { + + SwingUtilities.invokeLater(new Runnable() { + public void run() { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } + catch (Exception exception) { + exception.printStackTrace(); + } + + SubmitGaussianDialog frame = new SubmitGaussianDialog(); + frame.setTaskProviders(TaskProvider.getAvailableTaskProviders()); + frame.validate(); + frame.Cancel_Button.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + System.exit(0); + } + } + ); + frame.setDefaultCloseOperation(EXIT_ON_CLOSE); + frame.setVisible(true); + + } + }); + } + + public JDialog getDialog() { + return this; + } + + public SubmitGaussianDialog(Frame owner, JobOutputInterface redir, + String title, boolean modal) { + super(owner, title, modal); + jobOutput = redir; + try { + setDefaultCloseOperation(HIDE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public SubmitGaussianDialog() { + this(new Frame(), null, "SubmitGaussianDialog", false); + } + + // public void setProxyHandler(GridProxyInterface proxyHandler) { + // getGridProxy = proxyHandler; + //} + + private void jbInit() throws Exception { + MainPanel.setLayout(borderLayout1); + submitGaussianPanel1.setBorder(new TitledBorder(BorderFactory. + createLineBorder(Color.lightGray, 1), "Job Specifications")); + pBS_Panel1.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color. + lightGray, 2), "PBS Options")); + pBS_Panel1.setMinimumSize(new Dimension(254, 150)); + Cancel_Button.setToolTipText(""); + Cancel_Button.setText("Cancel"); + Cancel_Button.addActionListener(new + SubmitGaussianDialog_Cancel_Button_actionAdapter(this)); + Submit_Button.setToolTipText(""); + Submit_Button.setText("Submit"); + Submit_Button.addActionListener(new + SubmitGaussianDialog_Submit_Button_actionAdapter(this)); + this.setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); + getProxy_Button.setToolTipText(""); + getProxy_Button.setText("Get new Proxy"); + getProxy_Button.addActionListener(new + SubmitGaussianDialog_getProxy_Button_actionAdapter(this)); + providerLabel.setToolTipText(""); + providerLabel.setText(" Provider: "); + comboPanel.setLayout(flowLayout2); + flowLayout2.setAlignment(FlowLayout.LEFT); + providerPanel.setLayout(borderLayout2); + cardPanel.setLayout(cardLayout1); + providerComboBox.addActionListener(new + SubmitGaussianDialog_providerComboBox_actionAdapter(this)); + schedulerLabel.setToolTipText(""); + schedulerLabel.setText(" Scheduler: "); + cardPanel.setMinimumSize(new Dimension(255, 150)); + schedulerComboBox.setEnabled(false); + MainPanel.add(submitGaussianPanel1, java.awt.BorderLayout.SOUTH); + //MainPanel.add(taskProviderPanel, java.awt.BorderLayout.NORTH); + this.getContentPane().add(MainPanel, java.awt.BorderLayout.CENTER); + ButtonPanel.add(Submit_Button); + ButtonPanel.add(getProxy_Button); + ButtonPanel.add(Cancel_Button); + this.getContentPane().add(ButtonPanel, java.awt.BorderLayout.SOUTH); + MainPanel.add(pBS_Panel1, java.awt.BorderLayout.CENTER); + MainPanel.add(providerPanel, java.awt.BorderLayout.NORTH); + comboPanel.add(providerLabel); + comboPanel.add(providerComboBox); + comboPanel.add(schedulerLabel); + comboPanel.add(schedulerComboBox); + providerPanel.add(comboPanel, java.awt.BorderLayout.NORTH); + providerPanel.add(cardPanel, java.awt.BorderLayout.CENTER); + pBS_Panel1.JobfsTextField.setEditable(true); + pBS_Panel1.SoftwareTextField.setEditable(false); + + WindowListener l = new WindowAdapter() { + public void windowClosing(WindowEvent e) { + logger.debug("Exiting..."); + //Deactivator.deactivateAll(); + System.exit(0); + } + }; + + addWindowListener(l); + + setTaskSchedulers(TaskScheduler.getAvailableTaskSchedulers()); + + this.validate(); + } + + public void enableLocalDir(boolean enable) { + submitGaussianPanel1.LocalDirTextField.setEnabled(enable); + } + + public void enableInputFile(boolean enable) { + submitGaussianPanel1.inputFileTextField.setEnabled(enable); + } + + public void setLocalDir(String locDir) { + submitGaussianPanel1.LocalDirTextField.setText(locDir); + } + + public void setInputFile(String inputFile) { + submitGaussianPanel1.setInputFile(inputFile); + } + + public void setGatekeepers(String[] gk) { + + } + + public void setHosts(String[] gk) { + } + + public void Cancel_Button_actionPerformed(ActionEvent e) { + setVisible(false); + } + + public void setTaskProviders(LinkedHashMap providers) { + providerComboBox.setEnabled(false); + providerComboBox.removeAllItems(); + + allProviders = new LinkedHashMap(providers); + + Set set = providers.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String providerName = me.getKey().toString(); + providerComboBox.addItem(providerName); + //Component panel = (Component) me.getValue(); + GridProviderInterface provider =(GridProviderInterface)me.getValue(); + Component panel = provider.getVisualComponent(); + panel.validate(); + + cardPanel.add(panel, providerName); + } + + providerComboBox.setSelectedIndex(0); + + CardLayout cl = (CardLayout) cardPanel.getLayout(); + cl.show(cardPanel, providerComboBox.getSelectedItem().toString()); + cardPanel.validate(); + cardPanel.updateUI(); + + providerComboBox.setEnabled(true); + + this.validate(); + } + + // !!! It's only a prototype yet !!! + public void setTaskSchedulers(LinkedHashMap schedulers) { + schedulerComboBox.setEnabled(false); + schedulerComboBox.removeAllItems(); + + Set set = schedulers.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String schedulerName = me.getKey().toString(); + schedulerComboBox.addItem(schedulerName); + //Component panel = (Component) me.getValue(); + + //cardPanel.add(panel, schedulerName); + } + + schedulerComboBox.setSelectedIndex(0); + + //CardLayout cl = (CardLayout) cardPanel.getLayout(); + //cl.show(cardPanel, providerComboBox.getSelectedItem().toString()); + + schedulerComboBox.setEnabled(true); + } + + public void Submit_Button_actionPerformed(ActionEvent e) { + + String provider = providerComboBox.getSelectedItem().toString(); + + GridProviderInterface taskProvider = allProviders.get(provider); + + String scheduler = schedulerComboBox.getSelectedItem().toString(); + boolean use_gatekeeper = false; + String gatekeeper = null; + String remote_host = null; + // --- Get Script name (executable) + String script_file = script_file = submitGaussianPanel1.ScriptTextField. + getText().trim(); + + JobDescription jobDescription = new JobDescription(); + + if (provider.equals(TaskProvider.GLOBUS_2_PROVIDER)) { + GatekeeperPanel gkp = (GatekeeperPanel) TaskProvider.getProvider(provider); + gatekeeper = gkp.GatekeeperComboBox.getSelectedItem().toString(); + remote_host = gkp.HostComboBox.getSelectedItem().toString(); + + if (gatekeeper.length() < 1) { + use_gatekeeper = false; + } + else { + use_gatekeeper = true; + } + + if (!use_gatekeeper && remote_host.length() < 1) { + JOptionPane.showMessageDialog(null, + "Neither gatekeeper nor remote host are set", + "Error", + JOptionPane.ERROR_MESSAGE); + return; + + } + } + + else if (provider.equals(TaskProvider.GLOBUS_4_PROVIDER)) { + GT4Panel gkp = (GT4Panel) TaskProvider.getProvider(provider); + gatekeeper = gkp.GatekeeperComboBox.getSelectedItem().toString(); + remote_host = gkp.HostComboBox.getSelectedItem().toString(); + + if (gatekeeper.length() < 1) { + use_gatekeeper = false; + } + else { + use_gatekeeper = true; + } + + if (!use_gatekeeper && remote_host.length() < 1) { + JOptionPane.showMessageDialog(null, + "Neither gatekeeper nor remote host are set", + "Error", + JOptionPane.ERROR_MESSAGE); + return; + + } + } + + else if (provider.equals(TaskProvider.SSH_PROVIDER)) { + SSHPanel sshp = (SSHPanel) TaskProvider.getProvider(provider); + try { + sshp.checkConnection(); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + } + + else if (provider.equals(TaskProvider.LOCAL_PROVIDER)) { + remote_host = "local"; + + } + + else { + JOptionPane.showMessageDialog(null, + "Unknown service provider: " + provider, + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + // --- Preparing PBS Script + + // Setting up job description + + // --- Set Remote directory + + String remoteDirectory = submitGaussianPanel1.RemoteDirTextField.getText(). + trim(); + + // --- Job name + String jobName = submitGaussianPanel1.jobNameTextField.getText().trim(); + + // --- Get Local directory + String localDirectory = submitGaussianPanel1.LocalDirTextField.getText(). + trim(); + + if (localDirectory.indexOf("\\") != -1) { + localDirectory = "/" + localDirectory; + try { + //valid_dir = valid_dir.replaceAll("\\", "/"); + localDirectory = localDirectory.replace('\\', '/'); + } + catch (PatternSyntaxException ex) { + while (localDirectory.indexOf("\\") != -1) { + + } + logger.info("Regex error: " + localDirectory); + + } + } + + if (localDirectory.endsWith("/")) { + localDirectory = localDirectory.substring(0, localDirectory.length() - 1); + } + jobDescription.setLocalDirectory(localDirectory); + + // --- Get CPU number + + try { + jobDescription.setNCPU(pBS_Panel1.getNCPUs()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + // --- Setup max (wall) time + + float maxWallTime = -1; + try { + float time_in_secs = pBS_Panel1.getMaxTime() * 60.0f; + maxWallTime = time_in_secs; + jobDescription.setMaxCpuTime(time_in_secs); + jobDescription.setMaxTime(time_in_secs); + jobDescription.setMaxWallTime(time_in_secs); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + // --- Setup max memory + + int maxMemory = 0; // in MB + try { + maxMemory = pBS_Panel1.getMaxMemory(); + jobDescription.setMaxMemory(maxMemory); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + // --- Setup project + + jobDescription.setProject(pBS_Panel1.getProject()); + + // --- Setup jobfs + + int jobFS = 0; + try { + jobFS = pBS_Panel1.getJobFS(); + jobDescription.setJobFS(jobFS); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + String input_file = submitGaussianPanel1.inputFileTextField.getText().trim(); + String output_file = submitGaussianPanel1.OutputFileTextField.getText(). + trim(); + + // --- Setup queue + + String queue = pBS_Panel1.getQueue(); + //if (provider.equals(TaskProvider.GLOBUS_2_PROVIDER) && use_gatekeeper) { + // queue += "@" + remote_host.substring(0, remote_host.indexOf(".")); + // } + //else if (provider.equals(TaskProvider.GLOBUS_4_PROVIDER) && use_gatekeeper) { + // queue += "@" + remote_host.substring(0, remote_host.indexOf(".")); + // } + + jobDescription.setQueue(queue); + + // Stdout & stderr + + String stdout = submitGaussianPanel1.getStdoutFileName().trim(); + String stderr = submitGaussianPanel1.getStderrFileName().trim(); + + if (provider.equals(TaskProvider.SSH_PROVIDER)) { + if (stdout.length() > 0) { + jobDescription.setStdout(stdout); + } + if (stderr.length() > 0) { + jobDescription.setStderr(stderr); + } + } + + // --- Setup software + + jobDescription.setSoftware(pBS_Panel1.getSoftware()); + + //input_file.substring(0, input_file.lastIndexOf('.')) + + // ".log"; + + jobDescription.setScheduler(JobDescription.PBS_SCHEDULER); + + jobDescription.addPreprocessDirective("module load dos2unix"); + jobDescription.addPreprocessDirective("dos2unix " + input_file); + jobDescription.addPreprocessDirective("module load gaussian"); + + jobDescription.setExecutable("g03"); + + jobDescription.addArgument("<" + input_file); + jobDescription.addArgument(">" + output_file); + + jobDescription.setPBSOther("chemgrid"); + + jobDescription.setShell("/bin/bash"); + + // --- Save script file + try { + String scriptContent = JobDescription.createUnixScript(jobDescription); + IOUtils.saveStringIntoFile(scriptContent, + submitGaussianPanel1.LocalDirTextField.getText(). + trim() + + script_file); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, + "Error saving script file" + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + jobDescription.setTaskProvider(provider); + jobDescription.setScheduler(JobDescription.PBS_SCHEDULER); + + // --- Preparing final job description for submitting + + JobDescription submitDescription = new JobDescription(); + submitDescription.setTaskProvider(provider); + submitDescription.setScheduler(JobDescription.PBS_SCHEDULER); + submitDescription.setPbsJobScript(true); + submitDescription.setExecutable(script_file); + submitDescription.setRemoteHost(remote_host); + submitDescription.setRemoteDirectory(remoteDirectory); + submitDescription.setJobName(jobName); + submitDescription.setLocalDirectory(localDirectory); + submitDescription.setProject(pBS_Panel1.getProject()); + submitDescription.setQueue(queue); + + // --- ( File Staging In ) + + submitDescription.setFileStageIn(script_file, script_file); // Run script file + submitDescription.setFileStageIn(input_file, input_file); // Data input file + + // --- File staging out.... + + submitDescription.setFileStageOut(output_file, output_file); + + submitDescription.setExecutable(script_file); + submitDescription.setLocalExecutable(true); + + if (provider.equals(TaskProvider.GLOBUS_2_PROVIDER)) { + //jobDescription.setExecutable("/bin/csh"); + //jobDescription.addArgument(script_file); + if (use_gatekeeper) { + submitDescription.setRemoteHost(gatekeeper); + jobDescription.setRemoteDirectory(gatekeeper); + } + else { + submitDescription.setRemoteHost(remote_host); + jobDescription.setRemoteDirectory(remote_host); + } + GatekeeperPanel gkp = (GatekeeperPanel) TaskProvider.getProvider(provider); + submitDescription.setClusterAddress(gkp.HostComboBox.getSelectedItem(). + toString()); + submitDescription.enableGASS(gkp.gassCheckBox.isSelected()); + jobDescription.enableGASS(gkp.gassCheckBox.isSelected()); + } + + else if (provider.equals(TaskProvider.GLOBUS_4_PROVIDER)) { + //jobDescription.setExecutable("/bin/csh"); + //jobDescription.addArgument(script_file); + if (use_gatekeeper) { + submitDescription.setRemoteHost(gatekeeper); + submitDescription.setClusterAddress(remote_host); + jobDescription.setRemoteDirectory(gatekeeper); + } + else { + submitDescription.setRemoteHost(remote_host); + jobDescription.setRemoteDirectory(remote_host); + } + GT4Panel gkp4 = (GT4Panel) TaskProvider.getProvider(provider); + submitDescription.setClusterAddress(gkp4.HostComboBox.getSelectedItem(). + toString()); + submitDescription.setSoftware(pBS_Panel1.getSoftware()); + if (jobFS > 0) { + submitDescription.setJobFS(jobFS); + } + if (maxMemory > 0) { + submitDescription.setMaxMemory(maxMemory); + } + if (maxWallTime > 0) { + submitDescription.setMaxWallTime(maxWallTime/60); + } + + submitDescription.setPbsJobScript(false); + } + + else if (provider.equals(TaskProvider.SSH_PROVIDER)) { + if (stdout.length() > 0) { + submitDescription.setStdout(stdout); + } + if (stderr.length() > 0) { + submitDescription.setStderr(stderr); + } + + SSHPanel sshp = (SSHPanel) TaskProvider.getProvider(provider); + Object ssh_provider = sshp.getSSHProvider(); + submitDescription.setTaskProviderObject(ssh_provider); + remote_host = sshp.getHost(); + } + + else if (provider.equals(TaskProvider.LOCAL_PROVIDER)) { + + } + + // --- Saving settings + + pBS_Panel1.saveCurrentSettings(); + + // --- Submitting job + + String jobId = null; + TaskProvider task = new TaskProvider(); + try { + task.submitJob(submitDescription); + //task.submitJob(jobDescription); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, + "Error submitting job: " + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + JOptionPane.showMessageDialog(null, "Job submitted successfully", + "Success", + JOptionPane.INFORMATION_MESSAGE); + + jobId = task.getJobHandle(); + + Date subDate = new Date(); + + CheckPoint chkp = null; + + if (jobId == null) { + System.err.println( + "No job handle was returned. Job is not included into checkpoint file"); + return; + } + + if (provider.equals(TaskProvider.LOCAL_PROVIDER)) { + System.err.println("Checkpoint is not written for a local provider"); + return; + } + + if (provider.equals(TaskProvider.GLOBUS_4_PROVIDER)) { + System.err.println("Checkpoint is not written for a gt4 provider"); + return; + } + + try { + chkp = new CheckPoint(jobNameTag + "@" + jobName + "@" + + handleTag + "@" + jobId + "@" + + providerTag + "@" + provider + "@" + + computerTag + "@" + + remote_host + "@" + + softwareTag + "@Gaussian@" + + programTag + "@g03@" + + executableTag + "@" + script_file + "@" + + localExecutableTag + "@true@" + + remoteDirectoryTag + "@" + + submitGaussianPanel1.RemoteDirTextField.getText(). + trim() + "@" + + localDirectoryTag + "@" + + submitGaussianPanel1.LocalDirTextField.getText(). + trim() + "@" + + statusTag + "@Submitted@" + + overallJobStatusTag + "@Pending@" + + submittedTimeTag + "@" + subDate.toString(), + "@" // Divider + ); + chkp.setOutputFile(gaussianOutputFileTag, output_file); + + if (provider.equals(TaskProvider.SSH_PROVIDER)) { + if (stdout.length() > 0) { + chkp.setOutputFile(stdOutputTag, stdout); + } + if (stderr.length() > 0) { + chkp.setOutputFile(stdErrorTag, stderr); + } + } + + } + catch (MalformedCheckPointException ex) { + System.err.println(ex.getMessage()); + return; + } + + ParseCheckpointFile pcf = new ParseCheckpointFile(); + try { + pcf.addCheckPoint(chkp); + } + catch (cct.grid.MalformedCheckPointException ex) { + JOptionPane.showMessageDialog(null, + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + } + + public void getProxy_Button_actionPerformed(ActionEvent e) { + GridProxyInitDialog.openGetProxyDialog(); + } + + public void providerComboBox_actionPerformed(ActionEvent e) { + if (!providerComboBox.isEnabled()) { + return; + } + providerComboBox.setEnabled(false); + + CardLayout cl = (CardLayout) cardPanel.getLayout(); + cl.show(cardPanel, providerComboBox.getSelectedItem().toString()); + + String provider = providerComboBox.getSelectedItem().toString(); + //if (provider.equalsIgnoreCase(cct.grid.TaskProvider.SSH_PROVIDER)) { + //SSHPanel ssh = (SSHPanel) allProviders.get(provider); + GridProviderInterface gpi = allProviders.get(provider); + FileChooserInterface fci = gpi.getRemoteFileChooser(); + submitGaussianPanel1.setRemoteFileChooser(fci); + //submitGaussianPanel1.setRemoteFileChooser(ssh); + //} + + providerComboBox.setEnabled(true); + + } + + // Does not work properly + class JobSubProgress + extends java.util.TimerTask { + int MAX = 10; + JLabel msgLabel = new JLabel("Submitting Job..."); + JProgressBar progressBar = new JProgressBar(0, MAX); + JOptionPane pane = null; + JDialog dialog = null; + + public JobSubProgress() { + progressBar.setValue(0); + + Object[] comp = { + msgLabel, progressBar}; + //Object[] options = { + // "Cancel"}; + + pane = new JOptionPane(comp, + JOptionPane.DEFAULT_OPTION, + JOptionPane.INFORMATION_MESSAGE, + null); + //options, + //options[0]); + + dialog = pane.createDialog(null, "Submitting a Job"); + } + + public void run() { + if (!dialog.isVisible()) { + dialog.setVisible(true); + } + progressBar.setValue( (progressBar.getValue() + 1) % MAX); + } + + public boolean cancel() { + dialog.setVisible(false); + return false; + } + } + + class Task + extends Thread { + private boolean done = false; + private Exception exception = null; + private boolean cancel = false; + + public boolean isDone() { + return done; + } + + public void cancel() { + cancel = true; + } + + public boolean isCancelled() { + return cancel; + } + + public void run() { + + try { + //queryIsDone = false; + //if (taskType == 0) { + // updateJobStatus(); + // } + //else if ( taskType == JSD_KILL_JOBS ) { + // killJobs(); + //} + //queryIsDone = true; + } + catch (Exception e) { + exception = e; + done = true; + return; + } + + + if (cancel) { + return; + } + + // send the event.... + //if (proxyListener != null) { + // proxyListener.proxyCreated(proxy); + //} + + done = true; + } + + public Exception getException() { + return exception; + } + } + + + + } + + class SubmitGaussianDialog_providerComboBox_actionAdapter + implements ActionListener { + private SubmitGaussianDialog adaptee; + SubmitGaussianDialog_providerComboBox_actionAdapter(SubmitGaussianDialog + adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.providerComboBox_actionPerformed(e); + } + } + + class SubmitGaussianDialog_getProxy_Button_actionAdapter + implements ActionListener { + private SubmitGaussianDialog adaptee; + SubmitGaussianDialog_getProxy_Button_actionAdapter(SubmitGaussianDialog + adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.getProxy_Button_actionPerformed(e); + } + } + + class SubmitGaussianDialog_Submit_Button_actionAdapter + implements ActionListener { + private SubmitGaussianDialog adaptee; + SubmitGaussianDialog_Submit_Button_actionAdapter(SubmitGaussianDialog + adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.Submit_Button_actionPerformed(e); + } + } + + class SubmitGaussianDialog_Cancel_Button_actionAdapter + implements ActionListener { + private SubmitGaussianDialog adaptee; + SubmitGaussianDialog_Cancel_Button_actionAdapter(SubmitGaussianDialog + adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.Cancel_Button_actionPerformed(e); + } + + } + + */ diff --git a/src/main/java/cct/grid/ui/gaussian/SubmitGaussianFrame.java b/src/main/java/cct/grid/ui/gaussian/SubmitGaussianFrame.java new file mode 100644 index 0000000..62b629d --- /dev/null +++ b/src/main/java/cct/grid/ui/gaussian/SubmitGaussianFrame.java @@ -0,0 +1,224 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + + + +package cct.grid.ui.gaussian; + +//~--- JDK imports ------------------------------------------------------------ + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class SubmitGaussianFrame extends JFrame { + BorderLayout borderLayout1 = new BorderLayout(); + JMenuBar jMenuBar1 = new JMenuBar(); + JMenu jMenuFile = new JMenu(); + JMenuItem jMenuFileExit = new JMenuItem(); + JMenu jMenuHelp = new JMenu(); + JMenuItem jMenuHelpAbout = new JMenuItem(); + JToolBar jToolBar = new JToolBar(); + JButton jButton3 = new JButton(); + JButton jButton2 = new JButton(); + JButton jButton1 = new JButton(); + ImageIcon image3 = + new ImageIcon(SubmitGaussianFrame.class.getResource("help.png")); + ImageIcon image2 = + new ImageIcon(SubmitGaussianFrame.class.getResource("closeFile.png")); + ImageIcon image1 = + new ImageIcon(SubmitGaussianFrame.class.getResource("openFile.png")); + JLabel statusBar = new JLabel(); + JPanel mainPanel = new JPanel(); + BorderLayout borderLayout2 = new BorderLayout(); + SubmitGaussPanel submitGaussPanel1 = new SubmitGaussPanel(); + JButton submitButton = new JButton(); + JPanel jPanel1 = new JPanel(); + JPanel contentPane; + + public SubmitGaussianFrame() { + try { + setDefaultCloseOperation(EXIT_ON_CLOSE); + jbInit(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + /** + * Component initialization. + * + * @throws Exception + */ + private void jbInit() throws Exception { + contentPane = (JPanel) getContentPane(); + contentPane.setLayout(borderLayout1); + setSize(new Dimension(471, 467)); + setTitle("Submit Gaussian Job"); + statusBar.setText(" "); + jMenuFile.setText("File"); + jMenuFileExit.setText("Exit"); + jMenuFileExit.addActionListener(new SubmitGaussianFrame_jMenuFileExit_ActionAdapter(this)); + jMenuHelp.setText("Help"); + jMenuHelpAbout.setText("About"); + jMenuHelpAbout.addActionListener(new SubmitGaussianFrame_jMenuHelpAbout_ActionAdapter(this)); + mainPanel.setLayout(borderLayout2); + submitButton.setToolTipText("Submit Job"); + submitButton.setText("Submit"); + jMenuBar1.add(jMenuFile); + jMenuFile.add(jMenuFileExit); + jMenuBar1.add(jMenuHelp); + jMenuHelp.add(jMenuHelpAbout); + setJMenuBar(jMenuBar1); + jButton1.setIcon(image1); + jButton1.setToolTipText("Open File"); + jButton2.setIcon(image2); + jButton2.setToolTipText("Close File"); + jButton3.setIcon(image3); + jButton3.setToolTipText("Help"); + jToolBar.add(jButton1); + jToolBar.add(jButton2); + jToolBar.add(jButton3); + contentPane.add(statusBar, BorderLayout.SOUTH); + contentPane.add(mainPanel, BorderLayout.CENTER); + contentPane.add(jToolBar, BorderLayout.NORTH); + mainPanel.add(submitGaussPanel1, BorderLayout.CENTER); + mainPanel.add(jPanel1, BorderLayout.SOUTH); + jPanel1.add(submitButton); + } + + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (Exception exception) { + exception.printStackTrace(); + } + + SubmitGaussianFrame frame = new SubmitGaussianFrame(); + + frame.validate(); + frame.setVisible(true); + } + }); + } + + /** + * File | Exit action performed. + * + * @param actionEvent ActionEvent + */ + void jMenuFileExit_actionPerformed(ActionEvent actionEvent) { + System.exit(0); + } + + /** + * Help | About action performed. + * + * @param actionEvent ActionEvent + */ + void jMenuHelpAbout_actionPerformed(ActionEvent actionEvent) { + SubmitGaussianFrame_AboutBox dlg = new SubmitGaussianFrame_AboutBox(this); + Dimension dlgSize = dlg.getPreferredSize(); + Dimension frmSize = getSize(); + Point loc = getLocation(); + + dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y); + dlg.setModal(true); + dlg.pack(); + dlg.setVisible(true); + } +} + + +class SubmitGaussianFrame_jMenuFileExit_ActionAdapter implements ActionListener { + SubmitGaussianFrame adaptee; + + SubmitGaussianFrame_jMenuFileExit_ActionAdapter(SubmitGaussianFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent actionEvent) { + adaptee.jMenuFileExit_actionPerformed(actionEvent); + } +} + + +class SubmitGaussianFrame_jMenuHelpAbout_ActionAdapter implements ActionListener { + SubmitGaussianFrame adaptee; + + SubmitGaussianFrame_jMenuHelpAbout_ActionAdapter(SubmitGaussianFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent actionEvent) { + adaptee.jMenuHelpAbout_actionPerformed(actionEvent); + } +} + + +//~ Formatted by Jindent --- http://www.jindent.com diff --git a/src/main/java/cct/grid/ui/gaussian/SubmitGaussianFrame_AboutBox.java b/src/main/java/cct/grid/ui/gaussian/SubmitGaussianFrame_AboutBox.java new file mode 100644 index 0000000..fee6590 --- /dev/null +++ b/src/main/java/cct/grid/ui/gaussian/SubmitGaussianFrame_AboutBox.java @@ -0,0 +1,166 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + + + +package cct.grid.ui.gaussian; + +//~--- JDK imports ------------------------------------------------------------ + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class SubmitGaussianFrame_AboutBox extends JDialog implements ActionListener { + String comments = "Computational Chemistry Toolkit"; + String copyright = "Copyright (c) 2006"; + JPanel panel1 = new JPanel(); + JPanel panel2 = new JPanel(); + JLabel label4 = new JLabel(); + JLabel label3 = new JLabel(); + JLabel label2 = new JLabel(); + JLabel label1 = new JLabel(); + JPanel insetsPanel3 = new JPanel(); + JPanel insetsPanel2 = new JPanel(); + JPanel insetsPanel1 = new JPanel(); + JLabel imageLabel = new JLabel(); + ImageIcon image1 = new ImageIcon(); + GridLayout gridLayout1 = new GridLayout(); + FlowLayout flowLayout1 = new FlowLayout(); + JButton button1 = new JButton(); + BorderLayout borderLayout2 = new BorderLayout(); + BorderLayout borderLayout1 = new BorderLayout(); + String product = "Molecular Structure Viewer/Editor"; + String version = "1.0"; + JLabel jLabel1 = new JLabel(); + + public SubmitGaussianFrame_AboutBox() { + this(null); + } + + public SubmitGaussianFrame_AboutBox(Frame parent) { + super(parent); + + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + /** + * Component initialization. + * + * @throws Exception + */ + private void jbInit() throws Exception { + image1 = new ImageIcon(SubmitGaussianFrame.class.getResource("about.png")); + imageLabel.setIcon(image1); + setTitle("About"); + panel1.setLayout(borderLayout1); + panel2.setLayout(borderLayout2); + insetsPanel1.setLayout(flowLayout1); + insetsPanel2.setLayout(flowLayout1); + insetsPanel2.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + gridLayout1.setRows(5); + gridLayout1.setColumns(1); + label1.setToolTipText(""); + label1.setText("Gaussian Job Submitter"); + label2.setToolTipText(""); + label2.setText("Version 1.0 beta"); + label3.setText("Copyright (c) ANU 2006"); + label4.setToolTipText(""); + label4.setText("Written by Dr. V. Vasilyev"); + insetsPanel3.setLayout(gridLayout1); + insetsPanel3.setBorder(BorderFactory.createEmptyBorder(10, 60, 10, 10)); + button1.setText("OK"); + button1.addActionListener(this); + jLabel1.setToolTipText(""); + jLabel1.setText("e-mail:vvv900@gmail.com"); + insetsPanel2.add(imageLabel, null); + panel2.add(insetsPanel2, BorderLayout.WEST); + getContentPane().add(panel1, null); + insetsPanel3.add(label1, null); + insetsPanel3.add(label2, null); + insetsPanel3.add(label3, null); + insetsPanel3.add(label4, null); + insetsPanel3.add(jLabel1); + panel2.add(insetsPanel3, BorderLayout.CENTER); + insetsPanel1.add(button1, null); + panel1.add(insetsPanel1, BorderLayout.SOUTH); + panel1.add(panel2, BorderLayout.NORTH); + setResizable(true); + } + + /** + * Close the dialog on a button event. + * + * @param actionEvent ActionEvent + */ + @Override + public void actionPerformed(ActionEvent actionEvent) { + if (actionEvent.getSource() == button1) { + dispose(); + } + } +} + + +//~ Formatted by Jindent --- http://www.jindent.com diff --git a/src/main/java/cct/grid/ui/gaussian/SubmitGaussianPanel.java b/src/main/java/cct/grid/ui/gaussian/SubmitGaussianPanel.java new file mode 100644 index 0000000..8dcd6d2 --- /dev/null +++ b/src/main/java/cct/grid/ui/gaussian/SubmitGaussianPanel.java @@ -0,0 +1,1023 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.grid.ui.gaussian; + +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FileDialog; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.io.File; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.prefs.Preferences; + +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.SwingConstants; + +import cct.gaussian.Gaussian; +import cct.grid.CheckPoint; +import cct.grid.ClientProgramInterface; +import cct.grid.GridProviderInterface; +import cct.grid.JobDescription; +import cct.grid.OperationalSystems; +import cct.grid.ResourcesProviderInterface; +import cct.interfaces.FileChooserInterface; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class SubmitGaussianPanel + extends JPanel implements ClientProgramInterface { + + final static String gaussianOutputFileTag = "gaussianOutput"; + final static String softwareName = "Gaussian"; + + static final String localDirKey = "localDir"; + static final String remoteDirKey = "remoteDir"; + static final String executableKey = "executableName"; + static final String scriptContentKey = "scriptContent"; + static final String execPattern = "%exec%"; + static final String inputFilePattern = "%input%"; + static final String outputFilePattern = "%output%"; + private String gaussianExecutable = "g09"; + static final java.util.List PreprocessDirectives = new ArrayList (); + static String defaultScriptContent = "#!/bin/csh \n" + + "module load gaussian\n" + + "dos2unix " + inputFilePattern + "\n" + + execPattern + " <" + inputFilePattern + " > " + outputFilePattern + "\n"; + + static String scriptContent = defaultScriptContent; + + static { + PreprocessDirectives.add("module load dos2unix"); + PreprocessDirectives.add("dos2unix " + inputFilePattern); + PreprocessDirectives.add("module load gaussian"); + } + + private Gaussian gaussianInputParser = null; + private FileChooserInterface remoteFileChooser = null; + private String remoteDirectory = ""; + private Preferences prefs = Preferences.userNodeForPackage(getClass()); + private ScriptEditorFrame scriptEditorFrame = null; + private ResourcesProviderInterface Resources = null; + private GridProviderInterface Provider = null; + + JLabel ScriptLabel = new JLabel(); + JTextField ScriptTextField = new JTextField(); + JCheckBox InputCheckBox = new JCheckBox(); + JButton inputButton = new JButton(); + JButton remoteDirButton = new JButton(); + JButton executableButton = new JButton("Browse"); + JButton localDirButton = new JButton(); + JButton editScriptButton = new JButton(); + JLabel RemoteDirLabel = new JLabel(); + JTextField RemoteDirTextField = new JTextField(); + JLabel LocalDirLabel = new JLabel(); + JTextField LocalDirTextField = new JTextField(); + JLabel StderrLabel = new JLabel(); + JLabel executableLabel = new JLabel("Executable: "); + JTextField StderrTextField = new JTextField(); + JTextField executableTextField = new JTextField(); + JLabel StdoutLabel = new JLabel(); + JTextField StdoutTextField = new JTextField(); + JCheckBox StderrCheckBox = new JCheckBox(); + JCheckBox StdoutCheckBox = new JCheckBox(); + JButton StdoutButton = new JButton(); + JButton StderrButton = new JButton(); + JTextField OutputFileTextField = new JTextField(); + JLabel OutputFileLabel = new JLabel(); + JLabel jobNameLabel = new JLabel(); + JTextField jobNameTextField = new JTextField(); + JLabel inputFileLabel = new JLabel(); + JTextField inputFileTextField = new JTextField(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + + public SubmitGaussianPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public String getSoftwareName() { + return softwareName; + } + + public java.util.List getPreprocessDirectives() { + java.util.List dirs = new ArrayList (); + + String input_file = this.getInputFile(); + String output_file = this.getOutputFile(); + gaussianExecutable = this.getExecutable(); + + for (int i = 0; i < PreprocessDirectives.size(); i++) { + String line = PreprocessDirectives.get(i); + try { + line = line.replaceAll(inputFilePattern, input_file); + line = line.replaceAll(outputFilePattern, output_file); + line = line.replaceAll(execPattern, gaussianExecutable); + dirs.add(line); + } + catch (Exception ex) { + System.err.println("Cannot do substitution in line: " + line + " : " + ex.getMessage()); + } + } + return dirs; + } + + public void setRemoteFileChooser(FileChooserInterface rFC) { + remoteFileChooser = rFC; + + if (remoteFileChooser == null) { + if (InputCheckBox.isSelected()) { + inputButton.setEnabled(true); + } + else { + inputButton.setEnabled(false); + } + remoteDirButton.setEnabled(false); + executableButton.setEnabled(false); + } + + else { + inputButton.setEnabled(true); + remoteDirButton.setEnabled(true); + executableButton.setEnabled(true); + } + + } + + public void setResourcesInterface(ResourcesProviderInterface resources) { + Resources = resources; + } + + public void setTaskProviderInterface(GridProviderInterface provider) { + Provider = provider; + + setRemoteFileChooser(provider.getRemoteFileChooser()); + + this.RemoteDirTextField.setEnabled(provider.isRemoteDirectorySelectable()); + this.remoteDirButton.setEnabled(provider.isRemoteDirectorySelectable()); + } + + public String getCommandsAsString() throws Exception { + StringWriter sWriter = new StringWriter(); + + // --- Error check + + if (this.getExecutable().length() < 1) { + throw new Exception("Gaussian executable is not set"); + } + + boolean windowsOS = false; + if (Provider != null && Provider.getOS() == OperationalSystems.WindowsOS) { + windowsOS = true; + } + + String input_file = this.getInputFile(); + String output_file = this.getOutputFile(); + gaussianExecutable = this.getExecutable(); + + if (!windowsOS) { + sWriter.write("\n"); + for (int i = 0; i < PreprocessDirectives.size(); i++) { + String line = PreprocessDirectives.get(i); + try { + line = line.replaceAll(inputFilePattern, input_file); + line = line.replaceAll(outputFilePattern, output_file); + line = line.replaceAll(execPattern, gaussianExecutable); + } + catch (Exception ex) { + throw new Exception("Cannot do substitution in line: " + line + " : " + ex.getMessage()); + } + sWriter.write(line + "\n"); + } + sWriter.write("\n"); + } + + // --- gaussian executable & its arguments + + //sWriter.write(getExecutable() + "<" + input_file + " >" + output_file + "\n\n"); + + try { + sWriter.close(); + } + catch (Exception ex) {} + return sWriter.toString(); + } + + private void jbInit() throws Exception { + + this.setLayout(gridBagLayout1); + ScriptLabel.setToolTipText(""); + ScriptLabel.setHorizontalAlignment(SwingConstants.RIGHT); + ScriptLabel.setText("Run Script: "); + ScriptTextField.setSelectionStart(11); + ScriptTextField.setText(" "); + ScriptTextField.setColumns(15); + InputCheckBox.setSelected(true); + InputCheckBox.setText("Local File"); + InputCheckBox.addItemListener(new + SubmitGaussianPanel_InputCheckBox_itemAdapter(this)); + inputButton.setToolTipText("Select input file"); + inputButton.setText("Browse"); + inputButton.addActionListener(new + SubmitGaussianPanel_ScriptButton_actionAdapter(this)); + editScriptButton.setEnabled(false); + editScriptButton.setToolTipText("Edit script file"); + editScriptButton.setText("Edit"); + editScriptButton.addActionListener(new + SubmitGaussianPanel_editScriptButton_actionAdapter(this)); + RemoteDirLabel.setToolTipText(""); + RemoteDirLabel.setHorizontalAlignment(SwingConstants.RIGHT); + RemoteDirLabel.setText("Remote Directory: "); + RemoteDirTextField.setColumns(15); + RemoteDirTextField.addActionListener(new + SubmitGaussianPanel_RemoteDirTextField_actionAdapter(this)); + LocalDirLabel.setToolTipText(""); + LocalDirLabel.setHorizontalAlignment(SwingConstants.RIGHT); + LocalDirLabel.setText("Local Directory: "); + LocalDirTextField.setText(" "); + LocalDirTextField.setColumns(15); + StderrLabel.setToolTipText(""); + StderrLabel.setHorizontalAlignment(SwingConstants.RIGHT); + StderrLabel.setText("Errors Log: "); + StderrTextField.setEnabled(true); + StderrTextField.setToolTipText("Standard error output"); + StderrTextField.setText(""); + StderrTextField.setColumns(15); + + StdoutLabel.setToolTipText(""); + StdoutLabel.setHorizontalAlignment(SwingConstants.RIGHT); + StdoutLabel.setText("Output Log: "); + StdoutTextField.setEnabled(true); + StdoutTextField.setToolTipText(""); + StdoutTextField.setText(""); + StdoutTextField.setColumns(15); + StderrCheckBox.setEnabled(false); + StderrCheckBox.setSelected(true); + StderrCheckBox.setText("Local File"); + StdoutCheckBox.setEnabled(false); + StdoutCheckBox.setSelected(true); + StdoutCheckBox.setText("Local File"); + StdoutCheckBox.addItemListener(new + SubmitGaussianPanel_StdoutCheckBox_itemAdapter(this)); + StdoutButton.setEnabled(false); + StdoutButton.setToolTipText(""); + StdoutButton.setText("Browse"); + StderrButton.setEnabled(false); + StderrButton.setToolTipText(""); + StderrButton.setText("Browse"); + OutputFileTextField.setEnabled(true); + OutputFileTextField.setEditable(false); + OutputFileTextField.setText(" "); + OutputFileTextField.setColumns(15); + OutputFileLabel.setToolTipText(""); + OutputFileLabel.setHorizontalAlignment(SwingConstants.RIGHT); + OutputFileLabel.setText("Output File: "); + jobNameLabel.setToolTipText(""); + jobNameLabel.setHorizontalAlignment(SwingConstants.RIGHT); + jobNameLabel.setHorizontalTextPosition(SwingConstants.RIGHT); + jobNameLabel.setText("Job Name: "); + jobNameTextField.setToolTipText(""); + jobNameTextField.setText(" "); + jobNameTextField.setColumns(15); + inputFileLabel.setToolTipText(""); + inputFileLabel.setHorizontalAlignment(SwingConstants.RIGHT); + inputFileLabel.setText("Input File: "); + inputFileTextField.setText(" "); + inputFileTextField.setColumns(15); + remoteDirButton.setToolTipText("Select Remote Directory"); + remoteDirButton.setText("Browse"); + localDirButton.setToolTipText("Select Local Directory"); + localDirButton.setText("Browse"); + localDirButton.addActionListener(new + SubmitGaussianPanel_localDirButton_actionAdapter(this)); + remoteDirButton.addActionListener(new + SubmitGaussianPanel_remoteDirButton_actionAdapter(this)); + executableButton.addActionListener(new SubmitGaussianPanel_executableButton_actionAdapter(this)); + + this.add(jobNameTextField, new GridBagConstraints(1, 0, 3, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(inputFileTextField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(InputCheckBox, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(OutputFileTextField, new GridBagConstraints(1, 5, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(StdoutTextField, new GridBagConstraints(1, 6, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(StdoutCheckBox, new GridBagConstraints(2, 6, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(StdoutButton, new GridBagConstraints(3, 6, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(StderrCheckBox, new GridBagConstraints(2, 7, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(StderrButton, new GridBagConstraints(3, 7, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(jobNameLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(inputFileLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(inputButton, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 5), 0, 0)); + this.add(ScriptLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + + this.add(ScriptTextField, new GridBagConstraints(1, 2, 2, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(LocalDirLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(OutputFileLabel, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(RemoteDirLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 5, 2, 2), 0, 0)); + this.add(StdoutLabel, + new GridBagConstraints(0, 6, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), + 0, 0)); + this.add(StderrLabel, + new GridBagConstraints(0, 7, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), + 0, 0)); + this.add(StderrTextField, new GridBagConstraints(1, 7, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0)); + this.add(editScriptButton, + new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(RemoteDirTextField, + new GridBagConstraints(1, 4, 2, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + this.add(remoteDirButton, + new GridBagConstraints(3, 4, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(2, 2, 2, 5), + 0, 0)); + this.add(LocalDirTextField, + new GridBagConstraints(1, 3, 2, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + + this.add(localDirButton, + new GridBagConstraints(3, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(2, 2, 2, 5), + 0, 0)); + + add(executableLabel, + new GridBagConstraints(0, 8, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, + 0)); + add(executableTextField, + new GridBagConstraints(1, 8, 2, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), + 0, 0)); + add(executableButton, + new GridBagConstraints(3, 8, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, 2, 2, 5), + 0, + 0)); + + remoteDirectory = prefs.get(remoteDirKey, ""); + RemoteDirTextField.setText(remoteDirectory); + + String executabelName = prefs.get(executableKey, gaussianExecutable); + executableTextField.setText(executabelName); + + String scriptText = prefs.get(scriptContentKey, ""); + if (scriptText.trim().length() == 0) { + prefs.put(scriptContentKey, scriptContent); + } + else { + scriptContent = scriptText; + } + + if (remoteFileChooser == null) { + inputButton.setEnabled(false); + remoteDirButton.setEnabled(false); + executableButton.setEnabled(false); + } + else { + inputButton.setEnabled(true); + remoteDirButton.setEnabled(true); + executableButton.setEnabled(true); + } + + } + + public void saveCurrentSettings() { + prefs.put(remoteDirKey, RemoteDirTextField.getText().trim()); + + } + + public String getLocalDirectory() { + return LocalDirTextField.getText().trim(); + } + + public void ScriptButton_actionPerformed(ActionEvent e) { + if (!inputButton.isEnabled()) { + return; + } + inputButton.setEnabled(false); + String fileName = ""; + if (InputCheckBox.isSelected()) { // -- Local file + FileDialog fd = new FileDialog(new Frame(), "Open Gaussian Input File", + FileDialog.LOAD); + fd.setFile("*.gjf;*.com;*.g03"); + fd.setVisible(true); + if (fd.getFile() != null) { + + if (fd.getFile().lastIndexOf(".") == -1) { + JOptionPane.showMessageDialog(null, + "Gaussian Input file should have an extention", + "Error", + JOptionPane.ERROR_MESSAGE); + inputButton.setEnabled(true); + return; + } + + fileName = fd.getFile(); + + Gaussian gaussianInputParser = new Gaussian(); + gaussianInputParser.parseGJF(fd.getDirectory() + fileName, 0); + if (gaussianInputParser.getErrorMessage() != null) { + int n = + JOptionPane.showConfirmDialog(null, + "Script file might contain error(s)\n" + gaussianInputParser.getErrorMessage() + + "\n" + + "Do you still want to continue?", "DO you want to continue?", + JOptionPane.YES_NO_OPTION); + if (n == JOptionPane.NO_OPTION || n == JOptionPane.CLOSED_OPTION) { + return; + } + } + + if (this.Resources != null) { + Resources.setNCPUs(gaussianInputParser.getNumberOfProcessors()); + int memory = gaussianInputParser.getMemory(); + if (memory < 1024) { + memory = 100; + } + else { + memory /= 1024; + memory += 100; + } + Resources.setMaxMemoryInMb(memory); + } + + setInputFile(fileName); + LocalDirTextField.setText(fd.getDirectory()); + } + } + + else { // Remote file + try { + remoteFileChooser.setFileChooserVisible(true); + if (remoteFileChooser.getFile() != null) { + fileName = remoteFileChooser.getFile(); + setInputFile(fileName); + } + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + } + + inputButton.setEnabled(true); + } + + public void setInputFile(String fileName) { + if (fileName.indexOf(".") == -1) { + fileName += ".gjf"; + } + inputFileTextField.setText(fileName); + jobNameTextField.setText(fileName.substring(0, fileName.lastIndexOf("."))); + ScriptTextField.setText(fileName.substring(0, fileName.lastIndexOf(".")) + + ".sh"); + OutputFileTextField.setText(fileName.substring(0, fileName.lastIndexOf(".")) + + ".log"); + StdoutTextField.setText(fileName.substring(0, fileName.lastIndexOf(".")) + + ".stdout"); + StderrTextField.setText(fileName.substring(0, fileName.lastIndexOf(".")) + + ".stderr"); + + } + + public String getJobName() { + return jobNameTextField.getText().trim(); + } + + public String getOutputFileName() { + return OutputFileTextField.getText().trim(); + } + + public String getStdoutFileName() { + return StdoutTextField.getText().trim(); + } + + public String getStderrFileName() { + return StderrTextField.getText().trim(); + } + + public String getScriptName() { + return ScriptTextField.getText().trim(); + } + + public String getRemoteDirectory() { + return RemoteDirTextField.getText().trim(); + } + + public void RemoteDirTextField_actionPerformed(ActionEvent e) { + remoteDirectory = RemoteDirTextField.getText().trim(); + try { + prefs.put(remoteDirKey, remoteDirectory); + } + catch (Exception ex) { + System.err.println("Warning: unable to save remote directory: " + + ex.getMessage()); + } + } + + public void editScriptButton_actionPerformed(ActionEvent e) { + if (ScriptTextField.getText().trim().length() == 0) { + return; + } + + if (scriptEditorFrame == null) { + ConfirmEditing_ActionAdapter al = new ConfirmEditing_ActionAdapter(); + scriptEditorFrame = new ScriptEditorFrame(al); + } + scriptEditorFrame.setText(scriptContent); + scriptEditorFrame.setVisible(true); + } + + public void validateScript(String text) throws NullPointerException, + IllegalArgumentException { + + if (text.trim().length() == 0) { + throw new NullPointerException(); + } + String lines[] = text.split("\n"); + for (int i = 0; i < lines.length; i++) { + if (lines[i].indexOf(gaussianExecutable) != -1 && + lines[i].indexOf(inputFilePattern) != -1) { + return; + } + + } + throw new IllegalArgumentException(); + } + + public String getScriptContents() { + String contents = scriptContent; + gaussianExecutable = executableTextField.getText().trim(); + contents = contents.replaceAll(execPattern, gaussianExecutable); + return contents.replaceAll(inputFilePattern, getInputFileName()); + } + + public String getInputFileName() { + return inputFileTextField.getText().trim(); + } + + public void StdoutCheckBox_itemStateChanged(ItemEvent e) { + + } + + public void setExecutable(String executable) { + gaussianExecutable = executable.trim(); + executableTextField.setText(gaussianExecutable); + } + + public String getExecutable() { + try { + prefs.put(executableKey, executableTextField.getText().trim()); + } + catch (Exception ex) { + System.err.println("Warning: " + this.getClass().getCanonicalName() + ": cannot store executableKey=" + + executableTextField.getText().trim() + " : " + ex.getMessage()); + } + return executableTextField.getText().trim(); + } + + public void InputCheckBox_itemStateChanged(ItemEvent e) { + if (InputCheckBox.isSelected()) { + inputButton.setEnabled(true); + return; + } + + if (remoteFileChooser == null) { + inputButton.setEnabled(false); + } + else { + inputButton.setEnabled(true); + } + } + + public void remoteDirButton_actionPerformed(ActionEvent e) { + if (!remoteDirButton.isEnabled()) { + return; + } + + if (remoteFileChooser == null) { + return; + } + + remoteDirButton.setEnabled(false); + try { + remoteFileChooser.setFileChooserVisible(true); + if (remoteFileChooser.getDirectory() != null) { + RemoteDirTextField.setText(remoteFileChooser.getDirectory()); + prefs.put(remoteDirKey, remoteFileChooser.getDirectory()); + } + else if (remoteFileChooser.getFile() != null) { + String file = remoteFileChooser.getFile(); + if (file.indexOf("/") != -1) { + file = file.substring(0, file.indexOf("/")); + RemoteDirTextField.setText(file); + prefs.put(remoteDirKey, file); + } + } + else if (remoteFileChooser.pwd() != null) { + String pwd = remoteFileChooser.pwd(); + RemoteDirTextField.setText(pwd); + prefs.put(remoteDirKey, pwd); + } + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + remoteDirButton.setEnabled(true); + } + + public void localDirButton_actionPerformed(ActionEvent e) { + JFileChooser chooser = new JFileChooser(); + String localDir = prefs.get(localDirKey, ""); + if (localDir.length() > 0) { + File dir = new File(localDir); + if (dir.isDirectory() && dir.exists()) { + chooser.setCurrentDirectory(dir); + } + } + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + int option = chooser.showOpenDialog(this); + if (option == JFileChooser.APPROVE_OPTION && chooser.getSelectedFile() != null) { + localDir = chooser.getSelectedFile().getAbsolutePath(); + LocalDirTextField.setText(localDir); + prefs.put(localDirKey, localDir); + } + } + + public void enableInputFile(boolean enable) { + this.inputFileTextField.setEnabled(enable); + } + + public void enableLocalDir(boolean enable) { + this.LocalDirTextField.setEnabled(enable); + } + + public String getInputFile() { + return getInputFileName(); + } + + public String getOutputFile() { + return getOutputFileName(); + } + + public String getScriptFile() { + return this.ScriptTextField.getText().trim(); + } + + public Component getVisualComponent() { + return this; + } + + public void setLocalDirectory(String localDir) { + this.LocalDirTextField.setText(localDir); + } + + public void setRemoteDirectory(String remoteDir) { + this.RemoteDirTextField.setText(remoteDir); + } + + public void setCheckPointFile(CheckPoint chkp) { + + try { + chkp.setOutputFile(gaussianOutputFileTag, this.getOutputFile()); + } + catch (Exception ex) {} /// !!! + } + + public void setJobDescription(JobDescription job) throws Exception { + + // Stdout & stderr + + String stdout = getStdoutFileName(); + + String stderr = getStderrFileName(); + + if (stdout.length() > 0) { + job.setStdout(stdout); + } + if (stderr.length() > 0) { + job.setStderr(stderr); + } + + job.setExecutable(getScriptFile()); + job.setLocalExecutable(true); + job.setRemoteDirectory(this.getRemoteDirectory()); + job.setJobName(this.getJobName()); + job.setLocalDirectory(this.getLocalDirectory()); + + // --- ( File Staging In ) + + job.setFileStageIn(this.getScriptFile(), this.getScriptFile()); // Run script file + job.setFileStageIn(this.getInputFile(), this.getInputFile()); // Data input file + +// --- File staging out.... + + job.setFileStageOut(this.getOutputFile(), this.getOutputFile()); + + } + + private class ConfirmEditing_ActionAdapter + implements ActionListener { + + ConfirmEditing_ActionAdapter() { + } + + public void actionPerformed(ActionEvent actionEvent) { + String text = scriptEditorFrame.getText(); + boolean valid = true; + try { + validateScript(text); + } + catch (NullPointerException ex) { + scriptEditorFrame.setText(defaultScriptContent); + return; + } + catch (IllegalArgumentException ex) { + int n = JOptionPane.showConfirmDialog(null, "Script file does not contain line with " + gaussianExecutable + " and " + + inputFilePattern + "\n" + + "Do you still want to continue?", "Confirm (possibly) non-valid script", + JOptionPane.YES_NO_OPTION); + if (n == JOptionPane.NO_OPTION || n == JOptionPane.CLOSED_OPTION) { + return; + } + valid = false; + } + + scriptEditorFrame.setVisible(false); + scriptContent = scriptEditorFrame.getText(); + if (valid) { + prefs.put(scriptContentKey, scriptContent); + } + } + } + + private class ScriptEditorFrame + extends JFrame { + JPanel contentPane; + JScrollPane jScrollPane1 = new JScrollPane(); + JTextArea jTextArea1 = new JTextArea(); + JMenuBar jMenuBar1 = new JMenuBar(); + JMenu jMenuFile = new JMenu("File"); + public JMenuItem jMenuFileExit = new JMenuItem("Confirm editing & Return"); + + public ScriptEditorFrame(ActionListener al) { + contentPane = (JPanel) getContentPane(); + this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); + setSize(new Dimension(400, 300)); + setTitle("Edit Script File"); + jTextArea1.setToolTipText("Edit script contents"); + jTextArea1.setEditable(true); + contentPane.add(jScrollPane1, java.awt.BorderLayout.CENTER); + jScrollPane1.getViewport().add(jTextArea1); + + jMenuFileExit.addActionListener(al); + jMenuFile.add(jMenuFileExit); + jMenuBar1.add(jMenuFile); + setJMenuBar(jMenuBar1); + } + + public void setText(String text) { + jTextArea1.setText(text); + } + + public String getText() { + return jTextArea1.getText(); + } + + } + + public void executableButton_actionPerformed(ActionEvent e) { + if (!executableButton.isEnabled()) { + return; + } + + if (remoteFileChooser == null) { + return; + } + + executableButton.setEnabled(false); + try { + remoteFileChooser.setFileChooserVisible(true); + if (remoteFileChooser.getDirectory() != null) { + executableButton.setEnabled(true); + return; + } + else if (remoteFileChooser.getFile() != null) { + String file = remoteFileChooser.getFile(); + executableTextField.setText(file); + prefs.put(executableKey, file); + } + else if (remoteFileChooser.pwd() != null) { + executableButton.setEnabled(true); + return; + } + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + executableButton.setEnabled(true); + + } + + private class SubmitGaussianPanel_localDirButton_actionAdapter + implements ActionListener { + private SubmitGaussianPanel adaptee; + SubmitGaussianPanel_localDirButton_actionAdapter(SubmitGaussianPanel adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.localDirButton_actionPerformed(e); + } + } + + private class SubmitGaussianPanel_remoteDirButton_actionAdapter + implements ActionListener { + private SubmitGaussianPanel adaptee; + SubmitGaussianPanel_remoteDirButton_actionAdapter(SubmitGaussianPanel adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.remoteDirButton_actionPerformed(e); + } + } + + private class SubmitGaussianPanel_executableButton_actionAdapter + implements ActionListener { + private SubmitGaussianPanel adaptee; + SubmitGaussianPanel_executableButton_actionAdapter(SubmitGaussianPanel adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.executableButton_actionPerformed(e); + } + } + + private class SubmitGaussianPanel_InputCheckBox_itemAdapter + implements ItemListener { + private SubmitGaussianPanel adaptee; + SubmitGaussianPanel_InputCheckBox_itemAdapter(SubmitGaussianPanel adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.InputCheckBox_itemStateChanged(e); + } + } + + private class SubmitGaussianPanel_StdoutCheckBox_itemAdapter + implements ItemListener { + private SubmitGaussianPanel adaptee; + SubmitGaussianPanel_StdoutCheckBox_itemAdapter(SubmitGaussianPanel adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.StdoutCheckBox_itemStateChanged(e); + } + } + + private class SubmitGaussianPanel_editScriptButton_actionAdapter + implements ActionListener { + private SubmitGaussianPanel adaptee; + SubmitGaussianPanel_editScriptButton_actionAdapter(SubmitGaussianPanel + adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.editScriptButton_actionPerformed(e); + } + } + + private class SubmitGaussianPanel_ScriptButton_actionAdapter + implements ActionListener { + private SubmitGaussianPanel adaptee; + SubmitGaussianPanel_ScriptButton_actionAdapter(SubmitGaussianPanel adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.ScriptButton_actionPerformed(e); + } + } + + private class SubmitGaussianPanel_RemoteDirTextField_actionAdapter + implements ActionListener { + private SubmitGaussianPanel adaptee; + SubmitGaussianPanel_RemoteDirTextField_actionAdapter(SubmitGaussianPanel + adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.RemoteDirTextField_actionPerformed(e); + } + } + +} diff --git a/src/main/java/cct/grid/ui/gaussian/about.png b/src/main/java/cct/grid/ui/gaussian/about.png new file mode 100644 index 0000000..754005c Binary files /dev/null and b/src/main/java/cct/grid/ui/gaussian/about.png differ diff --git a/src/main/java/cct/grid/ui/gaussian/closeFile.png b/src/main/java/cct/grid/ui/gaussian/closeFile.png new file mode 100644 index 0000000..81cc1a6 Binary files /dev/null and b/src/main/java/cct/grid/ui/gaussian/closeFile.png differ diff --git a/src/main/java/cct/grid/ui/gaussian/help.png b/src/main/java/cct/grid/ui/gaussian/help.png new file mode 100644 index 0000000..d7a33f8 Binary files /dev/null and b/src/main/java/cct/grid/ui/gaussian/help.png differ diff --git a/src/main/java/cct/grid/ui/gaussian/openFile.png b/src/main/java/cct/grid/ui/gaussian/openFile.png new file mode 100644 index 0000000..d4f742a Binary files /dev/null and b/src/main/java/cct/grid/ui/gaussian/openFile.png differ diff --git a/src/main/java/cct/gromacs/Gromacs.java b/src/main/java/cct/gromacs/Gromacs.java new file mode 100644 index 0000000..22282c9 --- /dev/null +++ b/src/main/java/cct/gromacs/Gromacs.java @@ -0,0 +1,304 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gromacs; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.InputStream; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.StringTokenizer; + +import cct.modelling.ChemicalElements; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Gromacs { + + static Map GromacsElements = new HashMap(); + static Map GromacsAtomMap = null; + final static String DefaultGromacsAtomMapFile = "GromacsAtomMap.txt"; + + static { + GromacsElements.put("O", "O"); // ; carbonyl oxygen (C=O) + GromacsElements.put("OM", "O"); // ; carboxyl oxygen (CO-) + GromacsElements.put("OA", "O"); // ; hydroxyl oxygen (OH) + GromacsElements.put("OW", "O"); // ; water oxygen + GromacsElements.put("N", "N"); // ; peptide nitrogen (N or NH) + GromacsElements.put("NT", "N"); // ; terminal nitrogen (NH2) + GromacsElements.put("NL", "N"); // ; terminal nitrogen (NH3) + GromacsElements.put("NR5", "N"); // aromatic N (5-ring,2 bonds) + GromacsElements.put("NR5*", "N"); // ; aromatic N (5-ring,3 bonds) + GromacsElements.put("NP", "N"); // ; porphyrin nitrogen + GromacsElements.put("C", "C"); // ; bare carbon (peptide,C=O,C-N) + GromacsElements.put("CH1", "C"); // ; aliphatic CH-group + GromacsElements.put("CH2", "C"); // ; aliphatic CH2-group + GromacsElements.put("CH3", "C"); // ; aliphatic CH3-group + GromacsElements.put("CR51", "C"); // ; aromatic CH-group (5-ring), united + GromacsElements.put("CR61", "C"); // ; aromatic CH-group (6-ring), united + GromacsElements.put("CB", "C"); // ; bare carbon (5-,6-ring) + GromacsElements.put("H", "H"); // ; hydrogen bonded to nitrogen + GromacsElements.put("HO", "H"); // ; hydroxyl hydrogen + GromacsElements.put("HW", "H"); // ; water hydrogen + GromacsElements.put("HS", "H"); // ; hydrogen bonded to sulfur + GromacsElements.put("S", "S"); // ; sulfur + GromacsElements.put("FE", "Fe"); // ; iron + GromacsElements.put("ZN", "Zn"); // ; zinc + GromacsElements.put("NZ", "N"); // ; arg NH (NH2) + GromacsElements.put("NE", "N"); // arg NE (NH) + GromacsElements.put("P", "P"); // ; phosphor + GromacsElements.put("OS", "O"); // ; sugar or ester oxygen + GromacsElements.put("CS1", "C"); // ; sugar CH-group + GromacsElements.put("NR6", "N"); // ; aromatic N (6-ring,2 bonds) + GromacsElements.put("NR6*", "N"); // ; aromatic N (6-ring,3 bonds) + GromacsElements.put("CS2", "C"); // ; sugar CH2-group + GromacsElements.put("SI", "Si"); // ; silicon + GromacsElements.put("NA", "Na"); // ; sodium (1+) + GromacsElements.put("CL", "Cl"); // ; chlorine (1-) + GromacsElements.put("CA", "Ca"); // ; calcium (2+) + GromacsElements.put("MG", "Mg"); // ; magnesium (2+) + GromacsElements.put("F", "F"); // ; fluorine (cov. bound) + GromacsElements.put("HCR", "H"); // ; H attached to aromatic C (5 or 6 ri + GromacsElements.put("OWT3", "O"); // ; + + GromacsElements.put("LP2", "C"); + GromacsElements.put("LP3", "C"); + GromacsElements.put("LH1", "C"); + GromacsElements.put("LH2", "C"); + GromacsElements.put("LC", "C"); + GromacsElements.put("LC2", "C"); + GromacsElements.put("LC3", "C"); + GromacsElements.put("LO", "O"); + GromacsElements.put("LOS", "O"); + GromacsElements.put("LOM", "O"); + GromacsElements.put("LP", "P"); + GromacsElements.put("LNL", "N"); + + } + + private Gromacs() { + } + + public static int getChemicalElement(String residue, String atom_name) { + int element = 0; + String gromacsType = getGromacsAtomType(residue, atom_name); + if (gromacsType != null) { + gromacsType = gromacsType.toUpperCase(); + if (GromacsElements.containsKey(gromacsType)) { + element = ChemicalElements.getAtomicNumber( (String) + GromacsElements.get(gromacsType)); + } + else { + System.err.println("Gromacs atom type " + gromacsType + + " has no map for element"); + element = guessElement(atom_name); + } + } + else { + element = guessElement(atom_name); + } + return element; + } + + public static int guessElement(String atom_name) { + String name = atom_name.trim(); + if (name.length() == 0) { + return 0; + } + if (name.length() == 1) { + return ChemicalElements.getAtomicNumber(name); + } + if (name.length() == 2) { + if (name.matches("[a-zA-Z]{2}")) { + return ChemicalElements.getAtomicNumber(name); + } + else if (name.matches("[a-zA-Z]{1}.")) { + return ChemicalElements.getAtomicNumber(name.substring(0, 1)); + } + else { + System.err.println("Cannot guess atomic element for atom named " + name + " Set to dummy one..."); + return 0; + } + } + + name = name.substring(0, 2); + if (name.matches("[a-zA-Z]{2}")) { + return ChemicalElements.getAtomicNumber(name); + } + else if (name.matches("[a-zA-Z]{1}.")) { + return ChemicalElements.getAtomicNumber(name.substring(0, 1)); + } + else { + System.err.println("Cannot guess atomic element for atom named " + atom_name + " Set to dummy one..."); + return 0; + } + } + + public static String getGromacsAtomType(String residue_name, + String atom_name) { + String atom_type = null; + if (GromacsAtomMap == null) { + URL gromacsMap = null; + InputStream is = null; + try { + ClassLoader cl = Gromacs.class.getClassLoader(); + //logger.info("Class loader: " + cl.toString()); + gromacsMap = cl.getResource("cct/gromacs/" + + DefaultGromacsAtomMapFile); + GromacsAtomMap = readGromacsAtomMap(gromacsMap.getFile()); + } + catch (Exception ex) { + System.err.println(" : " + ex.getMessage()); + return atom_type; + } + } + + if (GromacsAtomMap.containsKey(residue_name)) { + Map residue = (Map) GromacsAtomMap.get(residue_name); + if (residue.containsKey(atom_name)) { + atom_type = (String) residue.get(atom_name); + } + else { + System.err.println(" No atom " + atom_name + " in residue " + + residue_name + " in atom's map"); + } + } + else { + System.err.println(" No residue " + residue_name + " in atom's map"); + } + return atom_type; + } + + /** + * Reads gromacs atom map + * @param filename String + * @return Map contains Maps of residues (map.put(String residue_name, Map residue)) + * where each residue Map contains gromacs atom map residue.put(String atom_name, String gromacs_atom_type) + * @throws Exception + */ + public static Map readGromacsAtomMap(String filename) throws Exception { + Map map = new HashMap(); + String line; + BufferedReader in = null; + int flag = -1; + Map residue = null; + String res_name = ""; + + try { + in = new BufferedReader(new FileReader(filename)); + + // --- Reading residues and atom names + // [ SOL ] + // OW OW -0.820 0 + // HW1 H 0.410 0 + // HW2 H 0.410 0 + + while ( (line = in.readLine()) != null) { + line = line.trim(); + if (line.startsWith(";")) { + continue; // Comment + } + if (line.length() == 0) { + continue; // Empty line + } + + if (line.startsWith("[")) { // Start to read residue + + if (flag == 0) { // End reading previous residue + map.put(res_name, residue); + } + flag = 0; + + int startIndex = line.indexOf("["); + int endIndex = line.indexOf("]"); + if (startIndex == -1 || endIndex == -1) { + in.close(); + throw new Exception( + "readGromacsAtomMap: ERROR while reading residue name: " + + line); + } + res_name = line.substring(startIndex + 1, endIndex).trim(); + residue = new HashMap(); + } + + // --- Read atom + else if (flag == 0) { + StringTokenizer st = new StringTokenizer(line, " \t", false); + if (st.countTokens() < 2) { + in.close(); + throw new Exception( + "readGromacsAtomMap: ERROR while reading atoms: " + line); + } + String aName = st.nextToken(); + String gromacsType = st.nextToken(); + residue.put(aName, gromacsType); + } + + // --- Error + else { + in.close(); + throw new Exception( + "readGromacsAtomMap: ERROR: Unexpected keyword"); + } + + } + + in.close(); + } + catch (Exception ex) { + if (in != null) { + in.close(); + } + throw new Exception("readGromacsAtomMap: ERROR: " + ex.getMessage()); + } + + return map; + } + +} diff --git a/src/main/java/cct/gromacs/GromacsAtomMap.txt b/src/main/java/cct/gromacs/GromacsAtomMap.txt new file mode 100644 index 0000000..bde484b --- /dev/null +++ b/src/main/java/cct/gromacs/GromacsAtomMap.txt @@ -0,0 +1,1707 @@ +; From ffG43b1.rtp + +;[ bondedtypes ] +; Col 1: Type of bond +; Col 2: Type of angles +; Col 3: Type of proper dihedrals +; Col 4: Type of improper dihedrals +; Col 5: Generate all dihedrals if 1, only heavy atoms of 0. +; Col 6: Number of excluded neighbors for nonbonded interactions +; Col 7: Generate 1,4 interactions between pairs of hydrogens if 1 +; Col 8: Remove impropers over the same bond as a proper if it is 1 +; bonds angles dihedrals impropers all_dihedrals nrexcl HH14 RemoveDih +; 2 2 1 2 0 3 0 1 + +[ ACE ] + CA CH3 0.000 0 + C C 0.380 1 + O O -0.380 1 + [ NH2 ] + N NT -0.83 0 + H1 H 0.415 0 + H2 H 0.415 0 +[ ALA ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH3 0.000 1 + C C 0.380 2 + O O -0.380 2 +[ ARG ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG CH2 0.000 1 + CD CH2 0.000 2 + NE NE -0.240 2 + HE H 0.240 2 + CZ C 0.000 2 + NH1 NZ -0.480 2 + HH11 H 0.240 2 + HH12 H 0.240 2 + NH2 NZ -0.480 2 + HH21 H 0.240 2 + HH22 H 0.240 2 + C C 0.380 3 + O O -0.380 3 +[ ARGN ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG CH2 0.000 2 + CD CH2 0.000 2 + NE NE -0.280 3 + HE H 0.280 3 + CZ C 0.150 4 + NH1 NE -0.548 4 + HH1 H 0.398 4 + NH2 NZ -0.830 5 + HH21 H 0.415 5 + HH22 H 0.415 5 + C C 0.380 6 + O O -0.380 6 +[ ASN ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG C 0.380 2 + OD1 O -0.380 2 + ND2 NT -0.830 3 + HD21 H 0.415 3 + HD22 H 0.415 3 + C C 0.380 4 + O O -0.380 4 +[ ASN1 ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG C 0.380 2 + OD1 O -0.380 2 + ND2 NL -0.830 3 + HD21 H 0.415 3 + HD22 H 0.415 3 + C C 0.380 4 + O O -0.380 4 +[ ASP ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG C 0.720 2 + OD1 OM -0.360 2 + OD2 OM -0.360 2 + C C 0.380 3 + O O -0.380 3 +[ ASPH ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG C 0.530 2 + OD1 O -0.380 2 + OD2 OA -0.548 2 + HD2 H 0.398 2 + C C 0.380 3 + O O -0.380 3 +[ CYS ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.200 2 + SG S -0.200 2 + C C 0.380 3 + O O -0.380 3 +[ CYSH ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + SG S -0.064 2 + HG H 0.064 2 + C C 0.380 3 + O O -0.380 3 +[ CYS1 ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + SG S 0.000 1 + C C 0.380 2 + O O -0.380 2 +[ CYS2 ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + SG S 0.000 1 + C C 0.380 2 + O O -0.380 2 +[ GLN ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG CH2 0.000 1 + CD C 0.380 2 + OE1 O -0.380 2 + NE2 NT -0.830 3 + HE21 H 0.415 3 + HE22 H 0.415 3 + C C 0.380 4 + O O -0.380 4 +[ GLU ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG CH2 0.000 1 + CD C 0.720 2 + OE1 OM -0.360 2 + OE2 OM -0.360 2 + C C 0.380 3 + O O -0.380 3 +[ GLUH ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG CH2 0.000 1 + CD C 0.530 2 + OE1 O -0.380 2 + OE2 OA -0.548 2 + HE2 H 0.398 2 + C C 0.380 3 + O O -0.380 3 +[ GLY ] + N N -0.280 0 + H H 0.280 0 + CA CH2 0.000 1 + C C 0.380 2 + O O -0.380 2 +[ HISA ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG C 0.000 2 + ND1 NR 0.000 2 + HD1 H 0.190 2 + CD2 CR1 0.130 2 + CE1 CR1 0.260 2 + NE2 NR -0.580 2 + C C 0.380 3 + O O -0.380 3 +[ HISB ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG C 0.130 2 + ND1 NR -0.580 2 + CD2 CR1 0.000 2 + CE1 CR1 0.260 2 + NE2 NR 0.000 2 + HE2 H 0.190 2 + C C 0.380 3 + O O -0.380 3 +[ HISH ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG C 0.000 2 + ND1 NR -0.300 2 + HD1 H 0.300 2 + CD2 CR1 0.000 2 + CE1 CR1 0.000 2 + NE2 NR -0.300 2 + HE2 H 0.300 2 + C C 0.380 3 + O O -0.380 3 +[ HIS1 ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG C 0.000 2 + ND1 NR 0.000 2 + HD1 H 0.190 2 + CD2 CR1 0.130 2 + CE1 CR1 0.260 2 + NE2 NR -0.580 2 + C C 0.380 3 + O O -0.380 3 +[ HYP ] + N N 0.000 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG CH1 0.150 2 + OD1 OA -0.548 2 + HD1 H 0.398 2 + CD2 CH2 0.000 3 + C C 0.380 4 + O O -0.380 4 +[ ILE ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH1 0.000 2 + CG1 CH2 0.000 2 + CG2 CH3 0.000 2 + CD CH3 0.000 2 + C C 0.380 3 + O O -0.380 3 +[ LEU ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG CH1 0.000 2 + CD1 CH3 0.000 2 + CD2 CH3 0.000 2 + C C 0.380 3 + O O -0.380 3 +[ LYS ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG CH2 0.000 2 + CD CH2 0.000 2 + CE CH2 0.000 3 + NZ NT -0.830 3 + HZ1 H 0.415 3 + HZ2 H 0.415 3 + C C 0.380 4 + O O -0.380 4 +[ LYSH ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG CH2 0.000 2 + CD CH2 0.000 2 + CE CH2 0.000 3 + NZ NL -0.744 3 + HZ1 H 0.248 3 + HZ2 H 0.248 3 + HZ3 H 0.248 3 + C C 0.380 4 + O O -0.380 4 +[ MET ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG CH2 0.000 1 + SD S 0.000 2 + CE CH3 0.000 2 + C C 0.380 3 + O O -0.380 3 +[ PHE ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG C 0.000 1 + CD1 C -0.100 2 + HD1 HC 0.100 2 + CD2 C -0.100 3 + HD2 HC 0.100 3 + CE1 C -0.100 4 + HE1 HC 0.100 4 + CE2 C -0.100 5 + HE2 HC 0.100 5 + CZ C -0.100 6 + HZ HC 0.100 6 + C C 0.380 7 + O O -0.380 7 +[ PRO ] + N N 0.000 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG CH2 0.000 2 + CD CH2 0.000 2 + C C 0.380 3 + O O -0.380 3 +[ SER ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.150 2 + OG OA -0.548 2 + HG H 0.398 2 + C C 0.380 3 + O O -0.380 3 +[ THR ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH1 0.150 2 + OG1 OA -0.548 2 + HG1 H 0.398 2 + CG2 CH3 0.000 3 + C C 0.380 4 + O O -0.380 4 +[ TRP ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG C -0.140 2 + CD1 C -0.100 2 + HD1 HC 0.100 2 + CD2 C 0.000 2 + NE1 NR -0.050 2 + HE1 H 0.190 2 + CE2 C 0.000 2 + CE3 C -0.100 3 + HE3 HC 0.100 3 + CZ2 C -0.100 4 + HZ2 HC 0.100 4 + CZ3 C -0.100 5 + HZ3 HC 0.100 5 + CH2 C -0.100 6 + HH2 HC 0.100 6 + C C 0.380 7 + O O -0.380 7 +[ TYR ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG C 0.000 1 + CD1 C -0.100 2 + HD1 HC 0.100 2 + CD2 C -0.100 3 + HD2 HC 0.100 3 + CE1 C -0.100 4 + HE1 HC 0.100 4 + CE2 C -0.100 5 + HE2 HC 0.100 5 + CZ C 0.150 6 + OH OA -0.548 6 + HH H 0.398 6 + C C 0.380 7 + O O -0.380 7 +[ VAL ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH1 0.000 1 + CG1 CH3 0.000 1 + CG2 CH3 0.000 1 + C C 0.380 2 + O O -0.380 2 +[ DALA ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH3 0.000 1 + C C 0.380 2 + O O -0.380 2 +[ ABU ] + N N -0.280 0 + H H 0.280 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG CH3 0.000 1 + C C 0.380 2 + O O -0.380 2 +[ MEBMT ] + N N 0.000 0 + CN CH3 0.000 0 + CA CH1 0.000 1 + CB CH1 0.150 2 + OG1 OA -0.548 2 + HG1 H 0.398 2 + CG2 CH1 0.000 3 + CD1 CH3 0.000 3 + CD2 CH2 0.000 3 + CE CR1 0.000 4 + CZ CR1 0.000 4 + CH CH3 0.000 4 + C C 0.380 5 + O O -0.380 5 +[ MELEU ] + N N 0.000 0 + CN CH3 0.000 0 + CA CH1 0.000 1 + CB CH2 0.000 1 + CG CH1 0.000 2 + CD1 CH3 0.000 2 + CD2 CH3 0.000 2 + C C 0.380 3 + O O -0.380 3 +[ MEVAL ] + N N 0.000 0 + CN CH3 0.000 0 + CA CH1 0.000 1 + CB CH1 0.000 1 + CG1 CH3 0.000 1 + CG2 CH3 0.000 1 + C C 0.380 2 + O O -0.380 2 +[ SAR ] + N N 0.000 0 + CN CH3 0.000 0 + CA CH2 0.000 1 + C C 0.380 2 + O O -0.380 2 +[ DADE ] + P P 1.440 0 + O1P OM -0.360 0 + O2P OM -0.360 0 + O5* OA -0.360 0 + C5* CH2 0.000 1 + C4* CH1 0.160 2 + O4* OA -0.360 2 + C1* CH1 0.200 2 + N9 NR -0.200 3 + C4 C 0.200 3 + N3 NR -0.360 4 + C2 CR1 0.360 4 + N1 NR -0.360 5 + C6 C 0.360 5 + N6 NT -0.830 6 + H61 H 0.415 6 + H62 H 0.415 6 + C5 C 0.000 7 + N7 NR -0.360 7 + C8 CR1 0.360 7 + C2* CH2 0.000 8 + C3* CH1 0.000 8 + O3* OA -0.360 9 +[ DGUA ] + P P 1.440 0 + O1P OM -0.360 0 + O2P OM -0.360 0 + O5* OA -0.360 0 + C5* CH2 0.000 1 + C4* CH1 0.160 2 + O4* OA -0.360 2 + C1* CH1 0.200 2 + N9 NR -0.200 3 + C4 C 0.200 3 + N3 NR -0.360 4 + C2 C 0.360 4 + N2 NT -0.830 5 + H21 H 0.415 5 + H22 H 0.415 5 + N1 NR -0.280 6 + H1 H 0.280 6 + C6 C 0.380 7 + O6 O -0.380 7 + C5 C 0.000 8 + N7 NR -0.360 8 + C8 CR1 0.360 8 + C2* CH2 0.000 9 + C3* CH1 0.000 9 + O3* OA -0.360 10 +[ DCYT ] + P P 1.440 0 + O1P OM -0.360 0 + O2P OM -0.360 0 + O5* OA -0.360 0 + C5* CH2 0.000 1 + C4* CH1 0.160 2 + O4* OA -0.360 2 + C1* CH1 0.200 2 + N1 NR -0.200 3 + C6 CR1 0.200 3 + C2 C 0.380 4 + O2 O -0.380 4 + N3 NR -0.360 5 + C4 C 0.360 5 + N4 NT -0.830 6 + H41 H 0.415 6 + H42 H 0.415 6 + C5 CR1 0.000 7 + C2* CH2 0.000 8 + C3* CH1 0.000 8 + O3* OA -0.360 9 +[ DTHY ] + P P 1.440 0 + O1P OM -0.360 0 + O2P OM -0.360 0 + O5* OA -0.360 0 + C5* CH2 0.000 1 + C4* CH1 0.160 2 + O4* OA -0.360 2 + C1* CH1 0.200 2 + N1 NR -0.200 3 + C6 CR1 0.200 3 + C2 C 0.380 4 + O2 O -0.380 4 + N3 NR -0.280 5 + H3 H 0.280 5 + C4 C 0.380 6 + O4 O -0.380 6 + C5 C 0.000 7 + C5M CH3 0.000 7 + C2* CH2 0.000 8 + C3* CH1 0.000 8 + O3* OA -0.360 9 +[ ADE ] + P P 1.440 0 + O1P OM -0.360 0 + O2P OM -0.360 0 + O5* OA -0.360 0 + C5* CH2 0.000 1 + C4* CH1 0.160 2 + O4* OA -0.360 2 + C1* CH1 0.200 2 + N9 NR -0.200 3 + C4 C 0.200 3 + N3 NR -0.360 4 + C2 CR1 0.360 4 + N1 NR -0.360 5 + C6 C 0.360 5 + N6 NT -0.830 6 + H61 H 0.415 6 + H62 H 0.415 6 + C5 C 0.000 7 + N7 NR -0.360 7 + C8 CR1 0.360 7 + C2* CH1 0.150 8 + O2* OA -0.548 8 + H2* H 0.398 8 + C3* CH1 0.000 9 + O3* OA -0.360 10 +[ GUA ] + P P 1.440 0 + O1P OM -0.360 0 + O2P OM -0.360 0 + O5* OA -0.360 0 + C5* CH2 0.000 1 + C4* CH1 0.160 2 + O4* OA -0.360 2 + C1* CH1 0.200 2 + N9 NR -0.200 3 + C4 C 0.200 3 + N3 NR -0.360 4 + C2 C 0.360 4 + N2 NT -0.830 5 + H21 H 0.415 5 + H22 H 0.415 5 + N1 NR -0.280 6 + H1 H 0.280 6 + C6 C 0.380 7 + O6 O -0.380 7 + C5 C 0.000 8 + N7 NR -0.360 8 + C8 CR1 0.360 8 + C2* CH1 0.150 9 + O2* OA -0.548 9 + H2* H 0.398 9 + C3* CH1 0.000 10 + O3* OA -0.360 11 +[ CYT ] + P P 1.440 0 + O1P OM -0.360 0 + O2P OM -0.360 0 + O5* OA -0.360 0 + C5* CH2 0.000 1 + C4* CH1 0.160 2 + O4* OA -0.360 2 + C1* CH1 0.200 2 + N1 NR -0.200 3 + C6 CR1 0.200 3 + C2 C 0.380 4 + O2 O -0.380 4 + N3 NR -0.360 5 + C4 C 0.360 5 + N4 NT -0.830 6 + H41 H 0.415 6 + H42 H 0.415 6 + C5 CR1 0.000 7 + C2* CH1 0.150 8 + O2* OA -0.548 8 + H2* H 0.398 8 + C3* CH1 0.000 9 + O3* OA -0.360 10 +[ URA ] + P P 1.440 0 + O1P OM -0.360 0 + O2P OM -0.360 0 + O5* OA -0.360 0 + C5* CH2 0.000 1 + C4* CH1 0.160 2 + O4* OA -0.360 2 + C1* CH1 0.200 2 + N1 NR -0.200 3 + C6 CR1 0.200 3 + C2 C 0.380 4 + O2 O -0.380 4 + N3 NR -0.280 5 + H3 H 0.280 5 + C4 C 0.380 6 + O4 O -0.380 6 + C5 CR1 0.000 7 + C2* CH1 0.150 8 + O2* OA -0.548 8 + H2* H 0.398 8 + C3* CH1 0.000 9 + O3* OA -0.360 10 +[ FMNO ] + FC9A C 0.200 0 + FN10 NR -0.200 0 +FC10A C 0.360 1 + FN1 NR -0.360 1 + FC2 C 0.380 2 + FO2 O -0.380 2 + FN3 NR -0.280 3 + FH3 H 0.280 3 + FC4 C 0.380 4 + FO4 O -0.380 4 + FC4A C 0.180 5 + FN5 NR -0.280 5 + FC5A C 0.100 5 + FC6 CR1 0.000 6 + FC7 C 0.000 7 + FCM7 CH3 0.000 7 + FC8 C 0.000 8 + FCM8 CH3 0.000 8 + FC9 CR1 0.000 9 + FCA CH2 0.000 10 + FCB CH1 0.150 11 + FOB OA -0.548 11 + FHB H 0.398 11 + FCG CH1 0.150 12 + FOG OA -0.548 12 + FHG H 0.398 12 + FCD CH1 0.150 13 + FOD OA -0.548 13 + FHD H 0.398 13 + FCE CH2 0.150 14 + FOZ OA -0.360 14 + FPH P 1.080 14 + FOH OA -0.548 14 + FHH H 0.398 14 + FOT1 OM -0.360 14 + FOT2 OM -0.360 14 +[ FMNS ] + FC9A C 0.200 0 + FN10 NR -0.200 0 +FC10A C 0.360 1 + FN1 NR -0.360 1 + FC2 C 0.380 2 + FO2 O -0.380 2 + FN3 NR -0.280 3 + FH3 H 0.280 3 + FC4 C 0.380 4 + FO4 O -0.380 4 + FC4A C 0.000 5 + FN5 NR -0.280 6 + FH5 H 0.280 6 + FC5A C 0.000 7 + FC6 CR1 0.000 8 + FC7 C 0.000 9 + FCM7 CH3 0.000 9 + FC8 C 0.000 10 + FCM8 CH3 0.000 10 + FC9 CR1 0.000 11 + FCA CH2 0.000 12 + FCB CH1 0.150 13 + FOB OA -0.548 13 + FHB H 0.398 13 + FCG CH1 0.150 14 + FOG OA -0.548 14 + FHG H 0.398 14 + FCD CH1 0.150 15 + FOD OA -0.548 15 + FHD H 0.398 15 + FCE CH2 0.150 16 + FOZ OA -0.360 16 + FPH P 1.080 16 + FOH OA -0.548 16 + FHH H 0.398 16 + FOT1 OM -0.360 16 + FOT2 OM -0.360 16 +[ FMNR ] + FC9A C 0.100 0 + FN10 NR -0.200 0 +FC10A C 0.100 0 + FN1 NR -0.280 1 + FH1 H 0.280 1 + FC2 C 0.380 2 + FO2 O -0.380 2 + FN3 NR -0.280 3 + FH3 H 0.280 3 + FC4 C 0.380 4 + FO4 O -0.380 4 + FC4A C 0.000 5 + FN5 NR -0.280 6 + FH5 H 0.280 6 + FC5A C 0.000 7 + FC6 CR1 0.000 8 + FC7 C 0.000 9 + FCM7 CH3 0.000 9 + FC8 C 0.000 10 + FCM8 CH3 0.000 10 + FC9 CR1 0.000 11 + FCA CH2 0.000 12 + FCB CH1 0.150 13 + FOB OA -0.548 13 + FHB H 0.398 13 + FCG CH1 0.150 14 + FOG OA -0.548 14 + FHG H 0.398 14 + FCD CH1 0.150 15 + FOD OA -0.548 15 + FHD H 0.398 15 + FCE CH2 0.150 16 + FOZ OA -0.360 16 + FPH P 1.080 16 + FOH OA -0.548 16 + FHH H 0.398 16 + FOT1 OM -0.360 16 + FOT2 OM -0.360 16 +[ PFN ] + FC9A C 0.000 0 + FC10 CR1 0.000 0 +FC10A C 0.000 0 + FC1 CR1 0.000 1 + FC2 CR1 0.000 1 + FC3 C 0.000 2 + FN3 NT -0.830 3 + FH31 H 0.415 3 + FH32 H 0.415 3 + FC4 CR1 0.000 4 + FC4A C 0.000 5 + FN5 NR -0.360 5 + FH5 H 0.360 5 + FC5A C 0.000 5 + FC6 CR1 0.000 6 + FC7 C 0.000 7 + FN7 NT -0.830 8 + FH71 H 0.415 8 + FH72 H 0.415 8 + FC8 CR1 0.000 9 + FC9 CR1 0.000 9 +[ NADP ] + AP P 1.210 0 + AO1P OM -0.360 0 + AO2P OM -0.360 0 + AO5* OA -0.360 0 + O3P OA -0.260 1 + NP P 1.210 1 + NO1P OM -0.360 1 + NO2P OM -0.360 1 + NO5* OA -0.360 1 + AC5* CH2 0.000 2 + AC4* CH1 0.160 3 + AO4* OA -0.360 3 + AC1* CH1 0.200 3 + AN9 NR -0.200 4 + AC4 C 0.200 4 + AN3 NR -0.360 5 + AC2 CR1 0.360 5 + AN1 NR -0.360 6 + AC6 C 0.360 6 + AN6 NT -0.830 7 + AH61 H 0.415 7 + AH62 H 0.415 7 + AC5 C 0.000 8 + AN7 NR -0.360 8 + AC8 CR1 0.360 8 + AC2* CH1 0.150 9 + AO2* OA -0.548 9 + AH2* H 0.398 9 + AC3* CH1 0.150 10 + AO3* OA -0.548 10 + AH3* H 0.398 10 + NC5* CH2 0.000 11 + NC4* CH1 0.160 12 + NO4* OA -0.360 12 + NC1* CH1 0.200 12 + NN1 NR -0.100 13 + NC6 CR1 0.100 13 + NC2 CR1 0.050 13 + NC3 C 0.000 13 + NC4 CR1 0.050 13 + NC5 CR1 -0.100 13 + NC7 C 0.380 14 + NO7 O -0.380 14 + NN7 NT -0.830 15 + NH71 H 0.415 15 + NH72 H 0.415 15 + NC2* CH1 0.150 16 + NO2* OA -0.548 16 + NH2* H 0.398 16 + NC3* CH1 0.150 17 + NO3* OA -0.548 17 + NH3* H 0.398 17 +[ NADH ] + AP P 1.210 0 + AO1P OM -0.360 0 + AO2P OM -0.360 0 + AO5* OA -0.360 0 + O3P OA -0.260 1 + NP P 1.210 1 + NO1P OM -0.360 1 + NO2P OM -0.360 1 + NO5* OA -0.360 1 + AC5* CH2 0.000 2 + AC4* CH1 0.160 3 + AO4* OA -0.360 3 + AC1* CH1 0.200 3 + AN9 NR -0.200 4 + AC4 C 0.200 4 + AN3 NR -0.360 5 + AC2 CR1 0.360 5 + AN1 NR -0.360 6 + AC6 C 0.360 6 + AN6 NT -0.830 7 + AH61 H 0.415 7 + AH62 H 0.415 7 + AC5 C 0.000 8 + AN7 NR -0.360 8 + AC8 CR1 0.360 8 + AC2* CH1 0.150 9 + AO2* OA -0.548 9 + AH2* H 0.398 9 + AC3* CH1 0.150 10 + AO3* OA -0.548 10 + AH3* H 0.398 10 + NC5* CH2 0.000 11 + NC4* CH1 0.160 12 + NO4* OA -0.360 12 + NC1* CH1 0.200 12 + NN1 NR -0.200 13 + NC6 CR1 0.200 13 + NC2 CR1 0.000 13 + NC3 C 0.000 13 + NC4 CH2 0.000 13 + NC5 CR1 0.000 13 + NC7 C 0.380 14 + NO7 O -0.380 14 + NN7 NT -0.830 15 + NH71 H 0.415 15 + NH72 H 0.415 15 + NC2* CH1 0.150 16 + NO2* OA -0.548 16 + NH2* H 0.398 16 + NC3* CH1 0.150 17 + NO3* OA -0.548 17 + NH3* H 0.398 17 +[ NDPH ] + AP P 1.210 0 + AO1P OM -0.360 0 + AO2P OM -0.360 0 + AO5* OA -0.360 0 + O3P OA -0.260 1 + NP P 1.210 1 + NO1P OM -0.360 1 + NO2P OM -0.360 1 + NO5* OA -0.360 1 + AC5* CH2 0.000 2 + AC4* CH1 0.160 3 + AO4* OA -0.360 3 + AC1* CH1 0.200 3 + AN9 NR -0.200 4 + AC4 C 0.200 4 + AN3 NR -0.360 5 + AC2 CR1 0.360 5 + AN1 NR -0.360 6 + AC6 C 0.360 6 + AN6 NT -0.830 7 + AH61 H 0.415 7 + AH62 H 0.415 7 + AC5 C 0.000 8 + AN7 NR -0.360 8 + AC8 CR1 0.360 8 + AC2* CH1 0.150 9 + AO2* OA -0.360 9 + AP2* P 1.080 9 + AO6* OM -0.360 9 + AO7* OM -0.360 9 + AO8* OA -0.548 9 + AH8* H 0.398 9 + AC3* CH1 0.150 10 + AO3* OA -0.548 10 + AH3* H 0.398 10 + NC5* CH2 0.000 11 + NC4* CH1 0.160 12 + NO4* OA -0.360 12 + NC1* CH1 0.200 12 + NN1 NR -0.200 13 + NC6 CR1 0.200 13 + NC2 CR1 0.000 13 + NC3 C 0.000 13 + NC4 CH2 0.000 13 + NC5 CR1 0.000 13 + NC7 C 0.380 14 + NO7 O -0.380 14 + NN7 NT -0.830 15 + NH71 H 0.415 15 + NH72 H 0.415 15 + NC2* CH1 0.150 16 + NO2* OA -0.548 16 + NH2* H 0.398 16 + NC3* CH1 0.150 17 + NO3* OA -0.548 17 + NH3* H 0.398 17 +[ NDPP ] + AP P 1.210 0 + AO1P OM -0.360 0 + AO2P OM -0.360 0 + AO5* OA -0.360 0 + O3P OA -0.260 1 + NP P 1.210 1 + NO1P OM -0.360 1 + NO2P OM -0.360 1 + NO5* OA -0.360 1 + AC5* CH2 0.000 2 + AC4* CH1 0.160 3 + AO4* OA -0.360 3 + AC1* CH1 0.200 3 + AN9 NR -0.200 4 + AC4 C 0.200 4 + AN3 NR -0.360 5 + AC2 CR1 0.360 5 + AN1 NR -0.360 6 + AC6 C 0.360 6 + AN6 NT -0.830 7 + AH61 H 0.415 7 + AH62 H 0.415 7 + AC5 C 0.000 8 + AN7 NR -0.360 8 + AC8 CR1 0.360 8 + AC2* CH1 0.150 9 + AO2* OA -0.360 9 + AP2* P 1.080 9 + AO6* OM -0.360 9 + AO7* OM -0.360 9 + AO8* OA -0.548 9 + AH8* H 0.398 9 + AC3* CH1 0.150 10 + AO3* OA -0.548 10 + AH3* H 0.398 10 + NC5* CH2 0.000 11 + NC4* CH1 0.160 12 + NO4* OA -0.360 12 + NC1* CH1 0.200 12 + NN1 NR -0.100 13 + NC6 CR1 0.100 13 + NC2 CR1 0.050 13 + NC3 C 0.000 13 + NC4 CR1 0.050 13 + NC5 CR1 -0.100 13 + NC7 C 0.380 14 + NO7 O -0.380 14 + NN7 NT -0.830 15 + NH71 H 0.415 15 + NH72 H 0.415 15 + NC2* CH1 0.150 16 + NO2* OA -0.548 16 + NH2* H 0.398 16 + NC3* CH1 0.150 17 + NO3* OA -0.548 17 + NH3* H 0.398 17 +[ NDPHN ] + AP P 1.020 0 + AO1P OA -0.548 0 + AH1P H 0.398 0 + AO2P O -0.380 0 + AO5* OA -0.360 0 + O3P OA -0.260 1 + NP P 1.020 1 + NO1P OA -0.548 1 + NH1P H 0.398 1 + NO2P O -0.380 1 + NO5* OA -0.360 1 + AC5* CH2 0.000 2 + AC4* CH1 0.160 3 + AO4* OA -0.360 3 + AC1* CH1 0.200 3 + AN9 NR -0.200 4 + AC4 C 0.200 4 + AN3 NR -0.360 5 + AC2 CR1 0.360 5 + AN1 NR -0.360 6 + AC6 C 0.360 6 + AN6 NT -0.830 7 + AH61 H 0.415 7 + AH62 H 0.415 7 + AC5 C 0.000 8 + AN7 NR -0.360 8 + AC8 CR1 0.360 8 + AC2* CH1 0.150 9 + AO2* OA -0.360 9 + AP2* P 0.890 9 + AO6* O -0.380 9 + AO7* OA -0.548 9 + AH7* H 0.398 9 + AO8* OA -0.548 9 + AH8* H 0.398 9 + AC3* CH1 0.150 10 + AO3* OA -0.548 10 + AH3* H 0.398 10 + NC5* CH2 0.000 11 + NC4* CH1 0.160 12 + NO4* OA -0.360 12 + NC1* CH1 0.200 12 + NN1 NR -0.200 13 + NC6 CR1 0.200 13 + NC2 CR1 0.000 13 + NC3 C 0.000 13 + NC4 CH2 0.000 13 + NC5 CR1 0.000 13 + NC7 C 0.380 14 + NO7 O -0.380 14 + NN7 NT -0.830 15 + NH71 H 0.415 15 + NH72 H 0.415 15 + NC2* CH1 0.150 16 + NO2* OA -0.548 16 + NH2* H 0.398 16 + NC3* CH1 0.150 17 + NO3* OA -0.548 17 + NH3* H 0.398 17 +[ GLCA ] + C1 CH1 0.400 0 + O5 OA -0.360 0 + C5 CH1 0.160 0 + C6 CH2 0.150 1 + O6 OA -0.548 1 + H6 H 0.398 1 + C2 CH1 0.150 2 + O2 OA -0.548 2 + H2 H 0.398 2 + C3 CH1 0.150 3 + O3 OA -0.548 3 + H3 H 0.398 3 + C4 CH1 0.160 4 + O4 OA -0.360 4 +[ GLCB ] + C1 CH1 0.400 0 + O5 OA -0.360 0 + C5 CH1 0.160 0 + C6 CH2 0.150 1 + O6 OA -0.548 1 + H6 H 0.398 1 + C3 CH1 0.150 2 + O3 OA -0.548 2 + H3 H 0.398 2 + C4 CH1 0.150 3 + O4 OA -0.548 3 + H4 H 0.398 3 + C2 CH1 0.160 4 + O2 OA -0.360 4 +[ GALB ] + C1 CH1 0.400 0 + O5 OA -0.360 0 + C5 CH1 0.160 0 + C6 CH2 0.150 1 + O6 OA -0.548 1 + H6 H 0.398 1 + C2 CH1 0.150 2 + O2 OA -0.548 2 + H2 H 0.398 2 + C4 CH1 0.150 3 + O4 OA -0.548 3 + H4 H 0.398 3 + C3 CH1 0.160 4 + O3 OA -0.360 4 +[ HEME ] + FE FE 0.400 0 + NA NR -0.100 0 + NB NR -0.100 0 + NC NR -0.100 0 + ND NR -0.100 0 + CHA C -0.100 1 + HHA HC 0.100 1 + C1A C 0.000 2 + C2A C 0.000 2 + C3A C 0.000 2 + C4A C 0.000 2 + CMA CH3 0.000 3 + CAA CH2 0.000 4 + CBA CH2 0.000 4 + CGA C 0.720 5 + O1A OM -0.360 5 + O2A OM -0.360 5 + CHB C -0.100 6 + HHB HC 0.100 6 + C1B C 0.000 7 + C2B C 0.000 7 + C3B C 0.000 7 + C4B C 0.000 7 + CMB CH3 0.000 8 + CAB CR1 0.000 9 + CBB CH2 0.000 9 + CHC C -0.100 10 + HHC HC 0.100 10 + C1C C 0.000 11 + C2C C 0.000 11 + C3C C 0.000 11 + C4C C 0.000 11 + CMC CH3 0.000 12 + CAC CR1 0.000 13 + CBC CH2 0.000 13 + CHD C -0.100 14 + HHD HC 0.100 14 + C1D C 0.000 15 + C2D C 0.000 15 + C3D C 0.000 15 + C4D C 0.000 15 + CMD CH3 0.000 16 + CAD CH2 0.000 17 + CBD CH2 0.000 17 + CGD C 0.720 18 + O1D OM -0.360 18 + O2D OM -0.360 18 +[ CYT* ] + C4* CH1 0.160 0 + O4* OA -0.360 0 + C1* CH1 0.200 0 + N1 NR -0.200 1 + C6 CR1 0.200 1 + C2 C 0.380 2 + O2 O -0.380 2 + N3 NR -0.360 3 + C4 C 0.360 3 + N4 NT -0.830 4 + H41 H 0.415 4 + H42 H 0.415 4 + C5 CR1 0.000 5 + C2* CH1 0.150 6 + O2* OA -0.548 6 + H2* H 0.398 6 + C3* CH1 0.000 7 + O3* OA -0.360 8 + SI1 P 0.540 8 + OSI OA -0.360 8 + SI2 P 0.540 8 + O5* OA -0.360 8 + C5* CH2 0.000 9 + C11 CH1 0.000 10 + C111 CH3 0.000 10 + C112 CH3 0.000 10 + C12 CH1 0.000 11 + C121 CH3 0.000 11 + C122 CH3 0.000 11 + C21 CH1 0.000 12 + C211 CH3 0.000 12 + C212 CH3 0.000 12 + C22 CH1 0.000 13 + C221 CH3 0.000 13 + C222 CH3 0.000 13 +[ MTXH ] + N1 NR -0.280 0 + HA1 H 0.280 0 + C2 C 0.000 0 + NA2 NT -0.830 1 + HA21 H 0.415 1 + HA22 H 0.415 1 + N3 NR -0.360 2 + C4 C 0.360 2 + NA4 NT -0.830 3 + HA41 H 0.415 3 + HA42 H 0.415 3 + C4A C 0.000 4 + N5 NR -0.360 4 + C6 C 0.360 4 + C7 CR1 0.360 5 + N8 NR -0.360 5 + C8A C 0.000 5 + C9 CH2 0.000 6 + N10 NE 0.000 6 + CM10 CH3 0.000 6 + C14 C 0.000 7 + C13 CR1 0.000 7 + C15 CR1 0.000 7 + C12 CR1 0.000 8 + C16 CR1 0.000 8 + C11 C 0.000 8 + C C 0.380 9 + O O -0.380 9 + N N -0.280 10 + H H 0.280 10 + CA CH1 0.000 11 + CB CH2 0.000 11 + CG CH2 0.000 11 + CD C 0.720 12 + OE1 OM -0.360 12 + OE2 OM -0.360 12 + CT C 0.720 13 + O1 OM -0.360 13 + O2 OM -0.360 13 +[ FOL ] + N1 NR -0.360 0 + C2 C 0.360 0 + NA2 NT -0.830 1 + HA21 H 0.415 1 + HA22 H 0.415 1 + N3 NR -0.280 2 + HA3 H 0.280 2 + C4 C 0.380 3 + OA4 O -0.380 3 + C4A C 0.000 4 + N5 NR -0.360 4 + C6 C 0.360 4 + C7 CR1 0.360 5 + N8 NR -0.360 5 + C8A C 0.000 5 + C9 CH2 0.000 6 + N10 NE -0.280 6 + H10 H 0.280 6 + C14 C 0.000 7 + C13 CR1 0.000 7 + C15 CR1 0.000 7 + C12 CR1 0.000 8 + C16 CR1 0.000 8 + C11 C 0.000 8 + C C 0.380 9 + O O -0.380 9 + N N -0.280 10 + H H 0.280 10 + CA CH1 0.000 11 + CB CH2 0.000 11 + CG CH2 0.000 11 + CD C 0.720 12 + OE1 OM -0.360 12 + OE2 OM -0.360 12 + CT C 0.720 13 + O1 OM -0.360 13 + O2 OM -0.360 13 +[ DHF ] + N1 NR -0.360 0 + C2 C 0.360 0 + NA2 NT -0.830 1 + HA21 H 0.415 1 + HA22 H 0.415 1 + N3 NR -0.280 2 + HA3 H 0.280 2 + C4 C 0.380 3 + OA4 O -0.380 3 + C4A C 0.000 4 + N5 NR -0.360 4 + C6 C 0.360 4 + C7 CH2 0.000 5 + N8 NR -0.280 5 + HA8 H 0.280 5 + C8A C 0.000 5 + C9 CH2 0.000 6 + N10 NE -0.280 6 + H10 H 0.280 6 + C14 C 0.000 7 + C13 CR1 0.000 7 + C15 CR1 0.000 7 + C12 CR1 0.000 8 + C16 CR1 0.000 8 + C11 C 0.000 8 + C C 0.380 9 + O O -0.380 9 + N N -0.280 10 + H H 0.280 10 + CA CH1 0.000 11 + CB CH2 0.000 11 + CG CH2 0.000 11 + CD C 0.720 12 + OE1 OM -0.360 12 + OE2 OM -0.360 12 + CT C 0.720 13 + O1 OM -0.360 13 + O2 OM -0.360 13 +[ THF ] + N1 NR -0.360 0 + C2 C 0.360 0 + NA2 NT -0.830 1 + HA21 H 0.415 1 + HA22 H 0.415 1 + N3 NR -0.280 2 + HA3 H 0.280 2 + C4 C 0.380 3 + OA4 O -0.380 3 + C4A C 0.000 4 + N5 NR -0.280 4 + HA5 H 0.280 4 + C6 CH1 0.000 4 + C7 CH2 0.000 5 + N8 NR -0.280 5 + HA8 H 0.280 5 + C8A C 0.000 5 + C9 CH2 0.000 6 + N10 NE -0.280 6 + H10 H 0.280 6 + C14 C 0.000 7 + C13 CR1 0.000 7 + C15 CR1 0.000 7 + C12 CR1 0.000 8 + C16 CR1 0.000 8 + C11 C 0.000 8 + C C 0.380 9 + O O -0.380 9 + N N -0.280 10 + H H 0.280 10 + CA CH1 0.000 11 + CB CH2 0.000 11 + CG CH2 0.000 11 + CD C 0.720 12 + OE1 OM -0.360 12 + OE2 OM -0.360 12 + CT C 0.720 13 + O1 OM -0.360 13 + O2 OM -0.360 13 +[ TMP ] + N1 NR -0.360 0 + C2 C 0.360 0 + NA2 NT -0.830 1 + HA21 H 0.415 1 + HA22 H 0.415 1 + N3 NR -0.360 2 + C4 C 0.360 2 + NA4 NT -0.830 3 + HA41 H 0.415 3 + HA42 H 0.415 3 + C5 C 0.000 4 + C6 CR1 0.000 4 + C7 CH2 0.000 4 + C11 C 0.000 5 + C12 CR1 0.000 5 + C16 CR1 0.000 5 + C13 C 0.180 6 + O13 OA -0.360 6 + CM13 CH3 0.180 6 + C15 C 0.180 7 + O15 OA -0.360 7 + CM15 CH3 0.180 7 + C14 C 0.180 8 + O14 OA -0.360 8 + CM14 CH3 0.180 8 +[ TMPH ] + N1 NR -0.280 0 + HA1 H 0.280 0 + C2 C 0.000 0 + NA2 NT -0.830 1 + HA21 H 0.415 1 + HA22 H 0.415 1 + N3 NR -0.360 2 + C4 C 0.360 2 + NA4 NT -0.830 3 + HA41 H 0.415 3 + HA42 H 0.415 3 + C5 C 0.000 4 + C6 CR1 0.000 4 + C7 CH2 0.000 4 + C11 C 0.000 5 + C12 CR1 0.000 5 + C16 CR1 0.000 5 + C13 C 0.180 6 + O13 OA -0.360 6 + CM13 CH3 0.180 6 + C15 C 0.180 7 + O15 OA -0.360 7 + CM15 CH3 0.180 7 + C14 C 0.180 8 + O14 OA -0.360 8 + CM14 CH3 0.180 8 +[ TMPHP ] + N1 NR -0.360 0 + HA1 H 0.360 0 + C2 C 0.000 0 + NA2 NT -0.830 1 + HA21 H 0.415 1 + HA22 H 0.415 1 + N3 NR -0.360 2 + C4 C 0.360 2 + NA4 NT -0.830 3 + HA41 H 0.415 3 + HA42 H 0.415 3 + C5 C 0.000 4 + C6 CR1 0.000 4 + C7 CH2 0.000 4 + C11 C 0.000 5 + C12 CR1 0.000 5 + C16 CR1 0.000 5 + C13 C 0.180 6 + O13 OA -0.360 6 + CM13 CH3 0.180 6 + C15 C 0.180 7 + O15 OA -0.360 7 + CM15 CH3 0.180 7 + C14 C 0.180 8 + O14 OA -0.360 8 + CM14 CH3 0.180 8 +[ PDG ] + P P 1.080 0 + O1P OM -0.360 0 + O2P OM -0.360 0 + O3P OA -0.548 0 + H3P H 0.398 0 + O4P OA -0.360 0 + C1 CH2 0.150 0 + C2 CH1 0.150 1 + O2 OA -0.548 1 + H2 H 0.398 1 + C3 C 0.720 2 + OT1 OM -0.360 2 + OT2 OM -0.360 2 +[ ATP ] + AN9 NR -0.200 0 + AC4 C 0.200 0 + AN3 NR -0.360 1 + AC2 CR1 0.360 1 + AN1 NR -0.360 2 + AC6 C 0.360 2 + AN6 NT -0.830 3 + AH61 H 0.415 3 + AH62 H 0.415 3 + AC5 C 0.000 4 + AN7 NR -0.360 4 + AC8 CR1 0.360 4 + AC1* CH1 0.200 5 + AO4* OA -0.360 5 + AC4* CH1 0.160 5 + AC2* CH1 0.150 6 + AO2* OA -0.548 6 + AH2* H 0.398 6 + AC3* CH1 0.150 7 + AO3* OA -0.548 7 + AH3* H 0.398 7 + AC5* CH2 0.000 8 + AO5* OA -0.360 9 + APA P 1.155 9 +AO1PA OM -0.360 9 +AO2PA OM -0.360 9 +AO3PA OA -0.360 10 + APB P 1.155 10 +AO1PB OM -0.360 10 +AO2PB OM -0.360 10 +AO3PB OA -0.360 11 + APG P 1.080 11 +AO1PG OM -0.360 11 +AO2PG OM -0.360 11 +AO3PG OA -0.548 11 +AH3PG H 0.398 11 +[ PMB ] + PC8 CH3 0.000 0 + PC5 C 0.000 0 + PC4 CR1 0.000 0 + PC6 CR1 0.000 0 + PC3 CR1 0.000 1 + PC7 CR1 0.000 1 + PC2 C 0.000 1 + PC1 C 0.500 2 + PO OM -0.300 2 + PHC1 HC -0.100 2 + PHC2 HC -0.100 2 +[ PMBH ] + PC8 CH3 0.000 0 + PC5 C 0.000 0 + PC4 CR1 0.000 0 + PC6 CR1 0.000 0 + PC3 CR1 0.000 1 + PC7 CR1 0.000 1 + PC2 C 0.000 1 + PC1 C -0.050 2 + PO OA -0.548 2 + PH H 0.398 2 + PHC1 HC 0.100 2 + PHC2 HC 0.100 2 +[ BA ] + C3 C -0.100 0 + H3 HC 0.100 0 + C2 C -0.100 1 + H2 HC 0.100 1 + C4 C -0.100 2 + H4 HC 0.100 2 + C1 C -0.100 3 + H1 HC 0.100 3 + C5 C -0.100 4 + H5 HC 0.100 4 + C6 C 0.000 5 + C7 C 0.530 6 + O8 O -0.380 6 + O9 OA -0.548 6 + H9 H 0.398 6 +[ RTOL ] + C18 CH3 0.000 0 + C17 CH3 0.000 0 + C1 C 0.000 0 + C2 CH2 0.000 1 + C3 CH2 0.000 1 + C4 CH2 0.000 1 + C5 C 0.000 2 + C16 CH3 0.000 2 + C6 C 0.000 2 + C7 CR1 0.000 3 + C8 CR1 0.000 3 + C9 C 0.000 4 + C19 CH3 0.000 4 + C10 CR1 0.000 4 + C11 CR1 0.000 5 + C12 CR1 0.000 5 + C13 C 0.000 6 + C20 CH3 0.000 6 + C14 CR1 0.000 6 + C15 CH2 0.150 7 + O21 OA -0.548 7 + H21 H 0.398 7 +[ TEMP ] + O1 O -0.200 0 + N1 NR -0.036 0 + C1 C 0.118 0 + C4 C 0.118 0 + CA C 0.000 1 + C3 CR1 0.000 1 + C6 CH3 0.000 2 + C7 CH3 0.000 3 + C8 CH3 0.000 4 + C9 CH3 0.000 5 + C5 C 0.380 6 + O5 O -0.380 6 +[ ETH ] + EO OM -0.360 0 + EC1 CH2 0.360 0 + EC2 CH3 0.000 0 +[ ETHH ] + EH H 0.398 0 + EO OA -0.548 0 + EC1 CH2 0.150 0 + EC2 CH3 0.000 1 +[ CH4 ] + CM CH4 0.000 0 +[ AR ] + AR AR 0.000 0 +[ SO42- ] + S S 1.440 0 + O1 OM -0.360 0 + O2 OM -0.360 0 + O3 OM -0.360 0 + O4 OM -0.360 0 +[ ZN2+ ] + ZN ZN2+ 2.000 0 +[ NA+ ] + NA NA+ 1.000 0 +[ CL- ] + CL CL- -1.000 0 +[ CA2+ ] + CA CA2+ 2.000 0 +[ MG2+ ] + MG MG2+ 2.000 0 +[ CU1+ ] + CU CU1+ 1.000 0 +[ CU2+ ] + CU CU2+ 2.000 0 +[ H2O ] + OW OW -0.820 0 + HW1 H 0.410 0 + HW2 H 0.410 0 +[ SOL ] + OW OW -0.820 0 + HW1 H 0.410 0 + HW2 H 0.410 0 +[ HOH ] + OW OW -0.820 0 + HW1 H 0.410 0 + HW2 H 0.410 0 +[ HO4 ] + OW OWT4 0.0 0 + HW1 H 0.52 0 + HW2 H 0.52 0 + HW3 IW -1.04 0 +[ H2OE ] + OW OW -0.848 0 + HW1 H 0.424 0 + HW2 H 0.424 0 +[ CHCL3 ] + CChl CCHL 0.179 0 + HChl HCHL 0.082 0 +CLCh1 CLCHL -0.087 0 +CLCh2 CLCHL -0.087 0 +CLCh3 CLCHL -0.087 0 +[ DMSO ] +SD S 0.139 0 +OD O -0.459 0 +CD1 CH3 0.160 0 +CD2 CH3 0.160 0 +[UREA] +C1 C 2.064 2.162 +O2 O 2.163 2.120 +N3 NT 2.055 2.285 +H4 H 1.965 2.301 +H5 H 2.136 2.342 +N6 NT 1.951 2.093 +H7 H 1.866 2.125 +H8 H 1.958 0 +;[ DMSO ] +;SDmso SDMSO 0.139 0 +;ODmso ODMSO -0.459 0 +;CDms1 CDMSO 0.160 0 +;CDms2 CDMSO 0.160 0 +[ CH3OH ] + Omet OMET -0.574 0 + HMet H 0.398 0 + CMet CMET 0.176 0 +[ CCL4 ] + CCl4 CCL4 0.000 0 +CLCl1 CLCL4 0.000 0 +CLCl2 CLCL4 0.000 0 +CLCl3 CLCL4 0.000 0 +CLCl4 CLCL4 0.000 0 + +; Lipid parameters +[ DOPC ] + C52 LP3 + C51 LP2 + C31 LP2 + C30 LP2 + C29 LP2 + C28 LP2 + C27 LP2 + C26 LP2 + C25 LH1 + C24 LH1 + C23 LP2 + C22 LP2 + C21 LP2 + C20 LP2 + C19 LP2 + C18 LP2 + C17 LP2 + C15 LC + O16 LO + O14 LOS + C13 LH1 + C12 LC2 + O11 LOS + P8 LP + O9 LOM + O10 LOM + O7 LOS + C6 LC2 + C5 LH2 + N4 LNL + C2 LC3 + C3 LC3 + C1 LC3 + C32 LC2 + O33 LOS + C34 LC + O35 LO + C36 LP2 + C37 LP2 + C38 LP2 + C39 LP2 + C40 LP2 + C41 LH1 + C42 LH1 + C43 LP2 + C44 LP2 + C45 LP2 + C46 LP2 + C47 LP2 + C48 LP2 + C49 LP2 + C50 LP2 + C53 LP2 + C54 LP3 + + diff --git a/src/main/java/cct/gromacs/GromacsParserFactory.java b/src/main/java/cct/gromacs/GromacsParserFactory.java new file mode 100644 index 0000000..cc4d6be --- /dev/null +++ b/src/main/java/cct/gromacs/GromacsParserFactory.java @@ -0,0 +1,259 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gromacs; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.util.StringTokenizer; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class GromacsParserFactory { + private GromacsParserFactory() { + } + + public static MoleculeInterface parseGromacsCoordFile(String filename, + MoleculeInterface mol) throws Exception { + return parseGromacsCoordFile(filename, mol, null); + } + + public static MoleculeInterface parseGromacsCoordFile(String filename, + MoleculeInterface mol, Object dictionary) throws + Exception { + String line; + BufferedReader in = null; + int residuenr = -1, previousRes = -1; + + try { + in = new BufferedReader(new FileReader(filename)); + + // --- Reading molecular title + // "%s\n", Title + if ( (line = in.readLine()) == null) { + in.close(); + throw new Exception( + "parseGromacsCoordFile: ERROR: Unxpected End of file while reading molecule title"); + } + + mol.setName(line); + + // --- Reading number of atoms + //"%5d\n", natoms + + if ( (line = in.readLine()) == null) { + in.close(); + throw new Exception( + "parseGromacsCoordFile: ERROR: Unxpected End of file while reading number of atoms"); + } + + int natoms = 0; + try { + natoms = Integer.parseInt(line.trim()); + } + catch (Exception e) { + in.close(); + throw new Exception( + "parseGromacsCoordFile: ERROR: Error while parsing number of atoms: " + + e.getMessage()); + } + + // --- Reading atoms + //"%5d%5s%5s%5d%8.3f%8.3f%8.3f%8.4f%8.4f%8.4f\n", + //residuenr,residuename,atomname,atomnr,x,y,z,vx,vy,vz + + for (int i = 0; i < natoms; i++) { + + AtomInterface atom = mol.getNewAtomInstance(); + + if ( (line = in.readLine()) == null) { + in.close(); + throw new Exception( + "parseGromacsCoordFile: ERROR: Unxpected End of file while reading atom " + + (i + 1)); + } + + // --- Residue number + + try { + residuenr = Integer.parseInt(line.substring(0, 5).trim()); + } + catch (Exception ex) { + in.close(); + throw new Exception( + "parseGromacsCoordFile: ERROR: Error while parsing atom: " + + (i + 1) + + " Cannot parse atom's residue number: " + line); + } + + // --- Residue name + + String residuename = ""; + try { + residuename = line.substring(5, 10).trim(); + } + catch (IndexOutOfBoundsException ex) { + throw new Exception( + "parseGromacsCoordFile: ERROR: Error while parsing atom: " + + (i + 1) + + " Cannot parse atom's residue name: " + ex.getMessage() + + " : " + line); + } + + // --- Atom name + + String atomname = ""; + try { + atomname = line.substring(10, 15).trim(); + } + catch (IndexOutOfBoundsException ex) { + throw new Exception( + "parseGromacsCoordFile: ERROR: Error while parsing atom: " + + (i + 1) + + " Cannot parse atom's name: " + ex.getMessage() + " : " + + line); + } + + atom.setName(atomname); + + // --- Skipping atom number... + + // --- Getting x,y,z + + float xyz; + try { + xyz = Float.parseFloat(line.substring(20, 28).trim()); + atom.setX(xyz * 10); + xyz = Float.parseFloat(line.substring(28, 36).trim()); + atom.setY(xyz * 10); + xyz = Float.parseFloat(line.substring(36, 44).trim()); + atom.setZ(xyz * 10); + } + catch (Exception ex) { + in.close(); + throw new Exception( + "parseGromacsCoordFile: ERROR: Error while parsing atom: " + + (i + 1) + + " Cannot parse atom's coordinate(s): " + line); + } + + // --- Getting element, etc + + int element = 0; // Dummy by default + if (dictionary == null) { + try { + element = Gromacs.getChemicalElement(residuename, atomname); + } + catch (Exception ex) { + System.err.println("Resolving chemical element: " + + ex.getMessage()); + } + } + + atom.setAtomicNumber(element); + + if (residuenr != previousRes) { + mol.addMonomer(residuename); + int n = mol.getNumberOfMonomers(); + mol.addAtom(atom, n - 1); + previousRes = residuenr; + } + else { + mol.addAtom(atom); + } + + } + + // --- Read periodic box vectors + // Box vectors (free format, space separated reals), values: v1(x) v2(y) v3(z) v1(y) v1(z) v2(x) v2(z) v3(x) v3(y), + // the last 6 values may be omitted (they will be set to zero). Gromacs only supports boxes with v1(y)=v1(z)=v2(z)=0. + + // --- Program uses only the first three number + + if ( (line = in.readLine()) != null) { + Float xyz[] = new Float[3]; + StringTokenizer st = new StringTokenizer(line, " \t", false); + if (st.countTokens() < 3) { + System.err.println("Warning: Reading Box vectors: expect at least 3 numbers... Ignored..."); + } + else { + try { + xyz[0] = Float.parseFloat(st.nextToken()) * 10; + xyz[1] = Float.parseFloat(st.nextToken()) * 10; + xyz[2] = Float.parseFloat(st.nextToken()) * 10; + mol.addProperty(MoleculeInterface.PeriodicBox, xyz); + } + catch (Exception ex) { + System.err.println("parseGromacsCoordFile: Warning: Error while parsing Box vectors: " + line + " Ignored..."); + } + } + } + + in.close(); + + for (int i = 0; i < mol.getNumberOfMonomers(); i++) { + mol.guessCovalentBondsInMonomer(i); + if (i > 0) { + mol.guessCovalentBondsBetweenMonomers(i - 1, i); + } + } + + } + catch (Exception ex) { + if (in != null) { + in.close(); + } + throw new Exception("parseGromacsCoordFile: ERROR: " + ex.getMessage()); + } + + return mol; + } + +} diff --git a/src/main/java/cct/gulp/GULPAtom.java b/src/main/java/cct/gulp/GULPAtom.java new file mode 100644 index 0000000..ffa2d69 --- /dev/null +++ b/src/main/java/cct/gulp/GULPAtom.java @@ -0,0 +1,91 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gulp; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class GULPAtom { + String Label; + private String speciesType = "CORE"; + int Element; + double[] Cartesians = null; + double[] Fractional = null; + double[] Xyz = new double[3]; + + public GULPAtom(String label, int elem) { + Element = elem; + Label = label; + } + + public void setSpeciesType(String type) { + speciesType = type; + } + + public String getSpeciesType() { + return speciesType; + } + + public void setCartesians(double[] xyz) { + if (Cartesians == null) { + Cartesians = new double[3]; + } + Cartesians[0] = xyz[0]; + Cartesians[1] = xyz[1]; + Cartesians[2] = xyz[2]; + } + + public void setFractionalCoord(double[] xyz) { + if (Fractional == null) { + Fractional = new double[3]; + } + Fractional[0] = xyz[0]; + Fractional[1] = xyz[1]; + Fractional[2] = xyz[2]; + } + +} diff --git a/src/main/java/cct/gulp/Gulp.java b/src/main/java/cct/gulp/Gulp.java new file mode 100644 index 0000000..833a4a4 --- /dev/null +++ b/src/main/java/cct/gulp/Gulp.java @@ -0,0 +1,576 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gulp; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.ChemicalElements; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ + +enum GULP_KEY_WORDS { + CELL, FRACTIONAL, TITLE, VECTORS, CARTESIAN +} + +public class Gulp { + + static final double ONE_BOHR = 0.529177249; // In Angstrom + static final double DEGREES_TO_RADIANS = Math.PI / 180.0; + static final String GULP_SPECIES_TYPE_SPECIFIER = "Gulp-species-type-specifier"; + + static Map keyWords = new HashMap (); + + static { + keyWords.put("CELL", GULP_KEY_WORDS.CELL); + keyWords.put("CART", GULP_KEY_WORDS.CARTESIAN); + keyWords.put("FRAC", GULP_KEY_WORDS.FRACTIONAL); + keyWords.put("TITL", GULP_KEY_WORDS.TITLE); + keyWords.put("VECT", GULP_KEY_WORDS.VECTORS); + } + + private boolean fractional = true; + private String Title = "No title"; + private double Vectors[][] = null; + private List Atoms = null; + + public Gulp() { + } + + public void getMolecularInterface(MoleculeInterface molec) throws + Exception { + if (molec == null) { + throw new Exception(this.getClass().getCanonicalName() + " : molec == null"); + } + if (Atoms.size() < 1) { + throw new Exception(this.getClass().getCanonicalName() + " : no GULP atoms"); + } + + molec.addMonomer("GULP"); + + calcAbsoluteCoordinates(Atoms, Vectors); + + for (int i = 0; i < Atoms.size(); i++) { + GULPAtom ga = Atoms.get(i); + AtomInterface atom = molec.getNewAtomInstance(); + atom.setName(ga.Label); + atom.setProperty(GULP_SPECIES_TYPE_SPECIFIER, ga.getSpeciesType()); + atom.setAtomicNumber(ga.Element); + + atom.setXYZ( (float) ga.Xyz[0], (float) ga.Xyz[1], (float) ga.Xyz[2]); + + molec.addAtom(atom); + } + + } + + public void parseInput(String file_name, int fileType) throws Exception { + String line, token; + BufferedReader in = null; + + if (fileType == 0) { // Read from file + try { + in = new BufferedReader(new FileReader(file_name)); + } + catch (Exception ex) { + throw ex; + } + } + else if (fileType == 1) { // Read from String + in = new BufferedReader(new StringReader(file_name)); + } + else { + throw new Exception( + "parsing ADF Input: INTERNAL ERROR: Unknown file type"); + } + + try { + + while ( (line = in.readLine()) != null) { + line = line.trim(); + + if (line.length() < 1) { // Blank line + continue; + } + + if (line.startsWith("#")) { // comment + continue; + } + + //StringTokenizer st = new StringTokenizer(line.toUpperCase(), " "); + if (line.length() > 3) { + token = line.substring(0, 4).toUpperCase(); + } + else { + token = line.substring(0, line.length()).toUpperCase(); + } + + if (!keyWords.containsKey(token)) { + continue; + } + + GULP_KEY_WORDS keyWord = keyWords.get(token); + + switch (keyWord) { + case TITLE: + Title = parseTITLE(line, in); + break; + case VECTORS: + Vectors = parseVECTORS(line, in); + break; + case CELL: + Vectors = parseCELL(line, in); + break; + + case CARTESIAN: + case FRACTIONAL: + Atoms = this.parseCoordinates(line, in); + break; + default: + break; + } + + } + + in.close(); + } + catch (Exception ex) { + throw new Exception("Error while reading GULP input file: " + ex.getMessage()); + } + + if (Atoms.size() < 1) { + throw new Exception("No atoms found in GULP input file"); + } + + } + + public String parseTITLE(String title, BufferedReader in) throws Exception { + StringTokenizer st = new StringTokenizer(title, " "); + String line; + String gulp_title = ""; + if (st.countTokens() == 1) { // Read until end + + while ( (line = in.readLine()) != null) { + line = line.trim(); + if (line.toUpperCase().startsWith("END")) { + return gulp_title; + } + if (gulp_title.length() > 0) { + gulp_title += "\n"; + } + gulp_title += line; + } + } + + else if (st.countTokens() > 1) { // Read n lines + st.nextToken(); + String token = st.nextToken(); + try { + int n = Integer.parseInt(token); + if (n < 0) { + throw new Exception("Number of title lines should be positive number: " + title); + } + for (int i = 0; i < n; i++) { + if ( (line = in.readLine()) == null) { + return gulp_title; + } + if (gulp_title.length() > 0) { + gulp_title += "\n"; + } + gulp_title += line; + } + } + catch (Exception ex) { + throw new Exception("Cannot parse number of title lines: " + title + " : " + ex.getMessage()); + } + } + return gulp_title; + } + + public double[][] parseVECTORS(String line, BufferedReader in) throws Exception { + /* + vectors x y z for vector 1 x y z for vector 2 x y z for vector 3 <6 x optimisation flags> + Units: Angstrom (default) or au + Use: Specifies the cartesian components of the lattice vectors. + Either "vectors" or "cell" must be included. Strain optimsation flags appear on last line. + */ + double vectors[][] = new double[3][3]; + StringTokenizer st = new StringTokenizer(line, " "); + String token; + double factor = 1.0; + if (st.countTokens() > 1) { + st.nextToken(); + token = st.nextToken().toUpperCase(); + if (token.startsWith("ANGS")) { + factor = 1.0; + } + else if (token.startsWith("AU")) { + factor = ONE_BOHR; + } + else { + throw new Exception("Unknown units for vectors: " + token); + } + } + + for (int i = 0; i < 3; i++) { + if ( (line = in.readLine()) == null) { + throw new Exception("Unexpected end of file while reading vectors"); + } + st = new StringTokenizer(line, " "); + if (st.countTokens() < 3) { + throw new Exception("Expected at least tokens for vectors, got " + line); + } + for (int j = 0; j < 3; j++) { + token = st.nextToken(); + try { + vectors[i][j] = Double.parseDouble(token) * factor; + } + catch (Exception ex) { + throw new Exception("Cannot parse vectors data " + line + " : " + ex.getMessage()); + } + } + } + return vectors; + } + + public List parseCoordinates(String line, BufferedReader in) throws Exception { + List atoms = new ArrayList (); + + String token, speciesType = "CORE"; + double factor = 1.0; + double xyz[] = new double[3]; + StringTokenizer st = new StringTokenizer(line, " "); + token = st.nextToken().toUpperCase(); + if (token.startsWith("FRAC")) { + fractional = true; + } + else if (token.startsWith("CART")) { + fractional = false; + } + else { + throw new Exception("Unknown coordinate input type: " + line); + } + + while ( (line = in.readLine()) != null) { + line = line.trim(); + if (line.startsWith("#")) { + continue; + } + if (line.length() < 1) { + break; + } + st = new StringTokenizer(line, " "); + String label = st.nextToken(); + + if (label.length() > 2) { + break; // End of input + } + + int element = parseAtomLabel(label); + + token = st.nextToken(); + + // Parse cartesians + + boolean already_read = true; + try { + xyz[0] = Double.parseDouble(token) * factor; + } + catch (Exception ex) { + already_read = false; + speciesType = token; + } + + if (!already_read) { + if (!st.hasMoreTokens()) { + throw new Exception("Unexpected end of line while reading coordinates: " + line); + } + token = st.nextToken(); + + try { + xyz[0] = Double.parseDouble(token) * factor; + } + catch (Exception ex) { + throw new Exception("Cannot parse coordinate: " + line + " : " + ex.getMessage()); + } + } + + for (int i = 1; i < 3; i++) { + if (!st.hasMoreTokens()) { + throw new Exception("Unexpected end of line while reading coordinates: " + line); + } + token = st.nextToken(); + try { + xyz[i] = Double.parseDouble(token) * factor; + } + catch (Exception ex) { + throw new Exception("Cannot parse coordinate: " + line + " : " + ex.getMessage()); + } + } + + GULPAtom atom = new GULPAtom(label, element); + atom.setSpeciesType(speciesType); + if (fractional) { + atom.setFractionalCoord(xyz); + } + else { + atom.setCartesians(xyz); + } + atoms.add(atom); + + } + return atoms; + } + + public int parseAtomLabel(String label) throws Exception { + int element = 0; + + try { + element = Integer.parseInt(label); + if (element < 0 || element > ChemicalElements.getNumberOfElements()) { + throw new Exception("Wrong element number " + label); + } + return element; + } + catch (Exception ex) { + // Label is not a number + } + + if (label.length() == 1 || label.length() == 2) { + element = ChemicalElements.getAtomicNumber(label); + return element; + } + throw new Exception("Cannot parse atomic label " + label); + } + + public void calcAbsoluteCoordinates(List atoms, double vectors[][]) throws Exception { + + double norm_vectors[][] = new double[3][3]; + if (vectors != null) { + for (int i = 0; i < 3; i++) { + double sum = Math.sqrt(vectors[i][0] * vectors[i][0] + vectors[i][1] * vectors[i][1] + vectors[i][2] * vectors[i][2]); + norm_vectors[i][0] = vectors[i][0] / sum; + norm_vectors[i][1] = vectors[i][1] / sum; + norm_vectors[i][2] = vectors[i][2] / sum; + } + } + else { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + norm_vectors[i][j] = 0.0; + } + norm_vectors[i][i] = 1.0; + } + } + + for (int i = 0; i < Atoms.size(); i++) { + GULPAtom ga = Atoms.get(i); + if (ga.Cartesians != null) { + ga.Xyz[0] = ga.Cartesians[0] * norm_vectors[0][0] + ga.Cartesians[1] * norm_vectors[0][1] + + ga.Cartesians[2] * norm_vectors[0][2]; + ga.Xyz[1] = ga.Cartesians[0] * norm_vectors[1][0] + ga.Cartesians[1] * norm_vectors[1][1] + + ga.Cartesians[2] * norm_vectors[1][2]; + ga.Xyz[2] = ga.Cartesians[0] * norm_vectors[2][0] + ga.Cartesians[1] * norm_vectors[2][1] + + ga.Cartesians[2] * norm_vectors[2][2]; + } + else if (ga.Fractional != null) { + ga.Xyz[0] = ga.Fractional[0] * vectors[0][0] + ga.Fractional[1] * vectors[0][1] + + ga.Fractional[2] * vectors[0][2]; + ga.Xyz[1] = ga.Fractional[0] * vectors[1][0] + ga.Fractional[1] * vectors[1][1] + + ga.Fractional[2] * vectors[1][2]; + ga.Xyz[2] = ga.Fractional[0] * vectors[2][0] + ga.Fractional[1] * vectors[2][1] + + ga.Fractional[2] * vectors[2][2]; + } + else { + throw new Exception("Neither cartesian nor fractional coordinates are set for " + (i + 1) + " atoms"); + } + } + } + + public double[][] parseCELL(String line, BufferedReader in) throws Exception { + /* + cell a b c alpha beta gamma <6 x optimisation flags> + Units: Angstrom (default) or au for a, b, c and degrees for angles + Use: Crystallographic unit cell. Either "vectors" or "cell" must be given. + For optimisations or fitting, flags must be set unless cellonly, conp or conv are specified. + */ + double a, b, c, alpha, beta, gamma; + StringTokenizer st = new StringTokenizer(line, " "); + String token; + double factor = 1.0; + if (st.countTokens() > 1) { + st.nextToken(); + token = st.nextToken().toUpperCase(); + if (token.startsWith("ANGS")) { + factor = 1.0; + token = st.nextToken(); + } + else if (token.startsWith("AU")) { + factor = ONE_BOHR; + token = st.nextToken(); + } + else { + throw new Exception("Expected cell parameters, got " + line); + } + } + + // --- Read next line with cell parameters + + while ( (line = in.readLine()) != null) { + line = line.trim(); + if (line.startsWith("#")) { + continue; + } + else { + break; + } + } + + st = new StringTokenizer(line, " "); + token = st.nextToken(); + + // --- Get a + + try { + a = Double.parseDouble(token) * factor; + } + catch (Exception ex) { + throw new Exception("Cannot parse a in cell: " + line + " : " + ex.getMessage()); + } + + // --- Get b + + token = st.nextToken(); + try { + b = Double.parseDouble(token) * factor; + } + catch (Exception ex) { + throw new Exception("Cannot parse b in cell: " + line + " : " + ex.getMessage()); + } + + // --- Get c + + token = st.nextToken(); + try { + c = Double.parseDouble(token) * factor; + } + catch (Exception ex) { + throw new Exception("Cannot parse c in cell: " + line + " : " + ex.getMessage()); + } + + // --- Get alpha + + token = st.nextToken(); + try { + alpha = Double.parseDouble(token) * DEGREES_TO_RADIANS; + } + catch (Exception ex) { + throw new Exception("Cannot parse alpha in cell: " + line + " : " + ex.getMessage()); + } + + // --- Get beta + + token = st.nextToken(); + try { + beta = Double.parseDouble(token) * DEGREES_TO_RADIANS; + } + catch (Exception ex) { + throw new Exception("Cannot parse beta in cell: " + line + " : " + ex.getMessage()); + } + + // --- Get gamma + + token = st.nextToken(); + try { + gamma = Double.parseDouble(token) * DEGREES_TO_RADIANS; + } + catch (Exception ex) { + throw new Exception("Cannot parse gamma in cell: " + line + " : " + ex.getMessage()); + } + + // --- Get crystal to Cartesian transformation matrix + + double[][] transform = getCrystalToCartesianMatrix(a, b, c, alpha, beta, gamma); + + return transform; + } + + public double[][] getCrystalToCartesianMatrix(double a, double b, double c, double alpha, double beta, double gamma) { + double[][] matrix = new double[3][3]; + + double factor = Math.sqrt(1.0 - Math.cos(alpha) * Math.cos(alpha) - Math.cos(beta) * Math.cos(beta) - + Math.cos(gamma) * Math.cos(gamma) + 2.0 * Math.cos(alpha) * Math.cos(beta) * Math.cos(gamma)); + + matrix[0][0] = a; + matrix[0][1] = b * Math.cos(gamma); + matrix[0][2] = c * Math.cos(beta); + + matrix[1][0] = 0; + matrix[1][1] = b * Math.sin(gamma); + matrix[1][2] = c * (Math.cos(alpha) - Math.cos(beta) * Math.cos(gamma)) / Math.sin(gamma); + + matrix[2][0] = 0; + matrix[2][1] = 0; + matrix[2][2] = c * factor / Math.sin(gamma); + + return matrix; + } + + public static void main(String[] args) { + Gulp gulp = new Gulp(); + } +} diff --git a/src/main/java/cct/gulp/GulpMDTrajectory.java b/src/main/java/cct/gulp/GulpMDTrajectory.java new file mode 100644 index 0000000..d0b2426 --- /dev/null +++ b/src/main/java/cct/gulp/GulpMDTrajectory.java @@ -0,0 +1,55 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.gulp; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class GulpMDTrajectory { + public GulpMDTrajectory() { + } +} diff --git a/src/main/java/cct/help/HelpPanel.java b/src/main/java/cct/help/HelpPanel.java new file mode 100644 index 0000000..8caf94d --- /dev/null +++ b/src/main/java/cct/help/HelpPanel.java @@ -0,0 +1,118 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.help; + +import java.io.IOException; +import java.net.URL; + +import javax.swing.JEditorPane; +import javax.swing.JScrollPane; +import javax.swing.event.HyperlinkEvent; +import javax.swing.event.HyperlinkListener; +import javax.swing.text.html.HTMLDocument; +import javax.swing.text.html.HTMLFrameHyperlinkEvent; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class HelpPanel + extends JScrollPane implements HyperlinkListener { + + JEditorPane editorPane = new JEditorPane(); + + public HelpPanel() { + try { + jbInit(); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + + private void jbInit() throws Exception { + editorPane.setEditable(false); + editorPane.addHyperlinkListener(this); + editorPane.setText("jEditorPane1"); + this.getViewport().add(editorPane); + } + + public void setText(URL helpURL) { + if (helpURL != null) { + try { + editorPane.setPage(helpURL); + } + catch (IOException e) { + System.err.println("Attempted to read a bad URL: " + helpURL); + } + } + else { + System.err.println("Couldn't find file: TextSamplerDemoHelp.html"); + } + + } + + @Override + public void hyperlinkUpdate(HyperlinkEvent e) { + if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { + JEditorPane pane = (JEditorPane) e.getSource(); + if (e instanceof HTMLFrameHyperlinkEvent) { + HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent) e; + HTMLDocument doc = (HTMLDocument) pane.getDocument(); + doc.processHTMLFrameHyperlinkEvent(evt); + } + else { + try { + pane.setPage(e.getURL()); + } + catch (Throwable t) { + t.printStackTrace(); + } + } + } + } + +} diff --git a/src/main/java/cct/help/JavaHelp.java b/src/main/java/cct/help/JavaHelp.java new file mode 100644 index 0000000..df15bdb --- /dev/null +++ b/src/main/java/cct/help/JavaHelp.java @@ -0,0 +1,196 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.help; + +import java.net.URL; +import java.util.logging.Logger; + +import javax.help.CSH; +import javax.help.HelpBroker; +import javax.help.HelpSet; + +import cct.interfaces.HelperInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class JavaHelp + implements HelperInterface { + HelpSet helpSet = null; + HelpBroker helpBroker = null; + static final Logger logger = Logger.getLogger(JavaHelp.class.getCanonicalName()); + + boolean ok = false; + + public JavaHelp(String helpsetName) throws Exception { + + try { + Class javaH = this.getClass().getClassLoader().loadClass( + "javax.help.HelpSet"); + } + catch (Exception ex) { + System.err.println(ex.getMessage()); + throw ex; + } + + + try { + ClassLoader cl = JavaHelp.class.getClassLoader(); + URL url = HelpSet.findHelpSet(cl, helpsetName); + helpSet = new HelpSet(cl, url); + } + catch (Exception ee) { + logger.info("Help Set " + helpsetName + " not found"); + throw ee; + //return; + } + catch (ExceptionInInitializerError ex) { + System.err.println("initialization error:"); + ex.getException().printStackTrace(); + throw ex; + //return; + } + helpBroker = helpSet.createHelpBroker(); + ok = true; + } + + /* + public JavaHelp() { + // Find the HelpSet file and create the HelpSet object: + + ClassLoader cl = JavaHelp.class.getClassLoader(); + //String path = "file:" + IOUtils.getRootDirectory(this) + + //"cct/resources/JavaHelp/jmoleditor/" + helpHS; + //logger.info("Help Set Path: " + path); + try { + URL hsURL = HelpSet.findHelpSet(cl, helpHS); + //URL hsURL = new URL(path); + hs = new HelpSet(null, hsURL); + } + catch (Exception ee) { +// Say what the exception really is + logger.info("HelpSet " + ee.getMessage()); + logger.info("HelpSet " + helpHS + " not found"); + return; + } +// Create a HelpBroker object: + hb = hs.createHelpBroker(); + + } + + public void showHelp() { + + try { + hb.setCurrentID("toplevelfolder"); + hb.setDisplayed(true); + } + catch (Exception ee) { + System.err.println("trouble with visiting id; " + ee); + } + + + try { + Popup popup = (Popup) Popup.getPresentation(hs, null); + popup.setInvoker(null); + popup.setCurrentID("toplevelfolder"); + popup.setDisplayed(true); + } + catch (Exception ee) { + System.err.println("trouble with visiting id; " + ee); + } + + } + */ + + public static void main(String[] args) { + String helpHS = "JMolEditorHelpSet.hs"; + try { + JavaHelp javahelp = new JavaHelp(helpHS); + } + catch (Exception ex) {} + } + + @Override + public void setHelpIDString(java.awt.Component comp, String helpID) { + if (!ok) { + return; + } + CSH.setHelpIDString(comp, helpID); + } + + @Override + public void enableHelpKey(java.awt.Component comp, String id) { + if (!ok) { + return; + } + helpBroker.enableHelpKey(comp, id, helpSet); + } + + @Override + public void enableHelpKey(java.awt.Component comp, String id, String presentation, String presentationName) { + if (!ok) { + return; + } + helpBroker.enableHelpKey(comp, id, helpSet, presentation, presentationName); + } + + @Override + public void addActionListenerForTracking(javax.swing.AbstractButton comp) { + if (!ok) { + return; + } + comp.addActionListener(new CSH.DisplayHelpAfterTracking(helpBroker)); + } + + @Override + public void displayHelpFromSourceActionListener(javax.swing.AbstractButton comp) { + if (!ok) { + return; + } + comp.addActionListener(new CSH.DisplayHelpFromSource(helpBroker)); + } +} diff --git a/src/main/java/cct/interfaces/AtomInterface.java b/src/main/java/cct/interfaces/AtomInterface.java new file mode 100644 index 0000000..ecd8181 --- /dev/null +++ b/src/main/java/cct/interfaces/AtomInterface.java @@ -0,0 +1,150 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.interfaces; + +import java.util.List; +import java.util.Map; + +/** + * + *

Title: Computational Chemsitry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public interface AtomInterface + extends Point3fInterface, Cloneable { + + float COVALENT_TO_GRADIUS_FACTOR = 0.5f; + + int RENDER_SPHERE = 0; + int RENDER_POINT = 1; + int RENDER_SMART_POINT = 2; + + String NAME = "Name"; + String SYBYL_TYPE = "Sybyl_Type"; + String CCT_ATOM_TYPE = "CCTAtomType"; + String AMBER_NAME = "AmberName"; + String AMBER_TYPE_INDEX = "AmberTypeIndex"; + String ATOMIC_CHARGE = "AtomicCharge"; + String GR_RADIUS = "GRadius"; + String RGB_COLOR = "RGBColor"; + String AMBIENT_RGB_COLOR = "_AmbientRGBColor"; + String DIFFUSE_RGB_COLOR = "_DiffuseRGBColor"; + String SPECULAR_RGB_COLOR = "_SpecularRGBColor"; + String PICKABILITY = "Pickability"; + String VISIBLE = "Visible"; + String RENDERING_STYLE = "RenderingStyle"; + + float getAtomicMass(); + + int getAtomicNumber(); + + List getBondedToAtoms(); // !!! to delete !!! + + List getBondIndex(); + + int getNumberOfBondedAtoms(); + + Map getProperties(); + + Object getProperty(String key); + + void setAtomicNumber(int anumber); + + BondInterface getBondToAtom(AtomInterface a); + + String getName(); + + int getSubstructureNumber(); + + boolean isBondedTo(AtomInterface a); + + boolean isSelected(); + + boolean isDynamic(); + + boolean removeBond(BondInterface bond); + + void setAtomicMass(float mass); + + void setBondedTo(AtomInterface a, boolean set_bond); + + void setBondIndex(BondInterface a); + + void setProperty(Object prop, Object value); + + void setName(String aName); + + void setSubstructureNumber(int n); + + void setSelected(boolean select); + + AtomInterface getNewAtomInstance(); + + AtomInterface getNewAtomInstance(AtomInterface a); + + String toString(); + + // -- related to internal coordinates + + int getNA(); + int getNB(); + int getNC(); + int[] getNX(); + int[] getIJK(); + void setNA(int na); + void setNB(int nb); + void setNC(int nc); + void setNX(int[] nx); + void setIJK(int[] nx); + double getBond(); + double getAngle(); + double getDihedralAngle(); + double[] getZmatrix(); + void setBond(double bond); + void setAngle(double angle); + void setDihedralAngle(double dihedral); + void setZmatrix(double[] z); +} diff --git a/src/main/java/cct/interfaces/BondInterface.java b/src/main/java/cct/interfaces/BondInterface.java new file mode 100644 index 0000000..fb25112 --- /dev/null +++ b/src/main/java/cct/interfaces/BondInterface.java @@ -0,0 +1,93 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.interfaces; + +import java.util.Map; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface BondInterface { + + float DEFAULT_BONDS_AND_STICKS_RADIUS = 0.2f; + float DEFAULT_STICKS_RADIUS = 0.15f; + + String CYLINDER_RADIUS = "BondRadius"; + String RGB_COLOR = "RGBColor"; + String COLOR_SCHEME = "ColorScheme"; + String RENDERING_STYLE = "RenderingStyle"; + String VISIBLE = "Visible"; + + int RENDER_CYLINDER = 0; + int RENDER_LINE = 1; + + int MONOCOLOR = 0; + int BICOLOR = 1; + + int CYLINDER_MONOCOLOR = 0; + int CYLINDER_BICOLOR = 1; + int LINE_MONOCOLOR = 2; + int LINE_BICOLOR = 3; + + float bondLength(); + + AtomInterface getIAtomInterface(); + + AtomInterface getJAtomInterface(); + + BondInterface getNewBondInstance(); + + BondInterface getNewBondInstance(BondInterface bond); + + BondInterface getNewBondInstance(AtomInterface a_i, AtomInterface a_j); + + Map getProperties(); + + Object getProperty(String key); + + void setProperty(String prop, Object value); +} diff --git a/src/main/java/cct/interfaces/CellViewManagerInterface.java b/src/main/java/cct/interfaces/CellViewManagerInterface.java new file mode 100644 index 0000000..1f8f0ae --- /dev/null +++ b/src/main/java/cct/interfaces/CellViewManagerInterface.java @@ -0,0 +1,57 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.interfaces; + +import cct.modelling.CELL_PARAMETER; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public interface CellViewManagerInterface { + + void replicateCell(CELL_PARAMETER direction, int repetition_factor) throws Exception; +} diff --git a/src/main/java/cct/interfaces/ChartDataProvider.java b/src/main/java/cct/interfaces/ChartDataProvider.java new file mode 100644 index 0000000..9565f22 --- /dev/null +++ b/src/main/java/cct/interfaces/ChartDataProvider.java @@ -0,0 +1,40 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.interfaces; + +import java.util.List; +import java.util.Set; + +/** + * + * @author Vlad + */ +public interface ChartDataProvider { + + double[] cdpGetDataAsDouble(String descriptor); + + float[] cdpGetDataAsFloat(String descriptor); + + int[] cdpGetDataAsInteger(String descriptor); + + String[] cdpGetDataAsString(String descriptor); + + Object[] cdpGetDataAsObject(String descriptor); + + String cdpGetDescription(); + + Set cdpGetDescriptors(); + + void cdpParseData(String filename) throws Exception; + + /** + * Checks format and returns score (0 to 1 range) + * @param filename + * @return 0 - wrong format, 1 - for sure it's this format + * @throws Exception + */ + float cdpIsThisFormat(String filename) throws Exception; +} diff --git a/src/main/java/cct/interfaces/ColorChangerInterface.java b/src/main/java/cct/interfaces/ColorChangerInterface.java new file mode 100644 index 0000000..f03d1f5 --- /dev/null +++ b/src/main/java/cct/interfaces/ColorChangerInterface.java @@ -0,0 +1,21 @@ +package cct.interfaces; + +import java.awt.Color; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public interface ColorChangerInterface { + void setColor(Color newColor); + void reset(); + void stop(); +} diff --git a/src/main/java/cct/interfaces/ContractorInterface.java b/src/main/java/cct/interfaces/ContractorInterface.java new file mode 100644 index 0000000..8ac9c6f --- /dev/null +++ b/src/main/java/cct/interfaces/ContractorInterface.java @@ -0,0 +1,25 @@ +package cct.interfaces; + +import java.awt.Component; + +/** + *

Title: Jamberoo + MSMS interface

+ * + *

Description: Interfacing MSMS in Jamberoo

+ * + *

Copyright: Copyright (c) 2010

+ * + *

Company:

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface ContractorInterface { + int SUCCESS = 0, FAILURE = 1; + + void setMolecule(MoleculeInterface molecule); + + int execute() throws Exception; + + void setParentComponent(Component parent); +} diff --git a/src/main/java/cct/interfaces/CoordinateBuilderInterface.java b/src/main/java/cct/interfaces/CoordinateBuilderInterface.java new file mode 100644 index 0000000..6cbe271 --- /dev/null +++ b/src/main/java/cct/interfaces/CoordinateBuilderInterface.java @@ -0,0 +1,22 @@ +package cct.interfaces; + +import java.io.Writer; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public interface CoordinateBuilderInterface { + + void getCoordinates(MoleculeInterface mol, boolean inAngstroms, Writer writer) throws Exception; + + String getCoordinatesAsString(MoleculeInterface molec, boolean inAngstroms) throws Exception; +} diff --git a/src/main/java/cct/interfaces/CoordinateParserInterface.java b/src/main/java/cct/interfaces/CoordinateParserInterface.java new file mode 100644 index 0000000..f24ddbe --- /dev/null +++ b/src/main/java/cct/interfaces/CoordinateParserInterface.java @@ -0,0 +1,21 @@ +package cct.interfaces; + +import java.io.BufferedReader; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public interface CoordinateParserInterface { + void parseCoordinates(BufferedReader in, MoleculeInterface molecule) throws Exception; + + double evaluateCompliance(BufferedReader in) throws Exception; +} diff --git a/src/main/java/cct/interfaces/FTPManagerInterface.java b/src/main/java/cct/interfaces/FTPManagerInterface.java new file mode 100644 index 0000000..c59b005 --- /dev/null +++ b/src/main/java/cct/interfaces/FTPManagerInterface.java @@ -0,0 +1,56 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.interfaces; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface FTPManagerInterface { + String[] getAvailableFTPProtocols(); + + FileBrowserInterface getFTPBrowser(String protocol); +} diff --git a/src/main/java/cct/interfaces/FileBrowserGUIInterface.java b/src/main/java/cct/interfaces/FileBrowserGUIInterface.java new file mode 100644 index 0000000..473d285 --- /dev/null +++ b/src/main/java/cct/interfaces/FileBrowserGUIInterface.java @@ -0,0 +1,60 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.interfaces; + +import java.awt.Component; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface FileBrowserGUIInterface { + void setBusy(boolean busy); + + void updateCWD(String cwd); + + void updateFieView(Component fileView); +} diff --git a/src/main/java/cct/interfaces/FileBrowserInterface.java b/src/main/java/cct/interfaces/FileBrowserInterface.java new file mode 100644 index 0000000..91bcd1a --- /dev/null +++ b/src/main/java/cct/interfaces/FileBrowserInterface.java @@ -0,0 +1,108 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.interfaces; + +import cct.tools.FileFilterImpl; +import cct.tools.filebrowser.SelectionInfoInterface; +import com.sshtools.j2ssh.FileTransferProgress; + +import java.awt.*; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface FileBrowserInterface { + void cd(String dir); + + void connect(String hostname) throws Exception; + + void connect(String hostname, String username, char[] password, int port) throws Exception; + + void disconnect(); + + void downloadSelected(); + + void get(String remote, String local) throws Exception; + + void get(String remote, String local, FileTransferProgress progress) throws Exception; + + Component getComponent(); + + int getFileCount(); + + String [] getFileNames(); + + String[] getSelectedFiles(); + + String[] getSelectedFolders(); + + boolean isAuthenticated(); + + void mkdir(); + + void mkdir(String dir); + + String pwd(); + + void refresh(); + + void removeSelectedPaths(); + + void rm(String path); + + void setFileFilter(FileFilterImpl filter); + + void listUsingFilePattern(String pattern) throws Exception; + + void setSelectionInfoInterface(SelectionInfoInterface selectionInfo); + + void setTopGUI(FileBrowserGUIInterface guiInterface); + + void upDirectory(); + + void setSelectionMode(int mode) throws Exception; +} diff --git a/src/main/java/cct/interfaces/FileChooserInterface.java b/src/main/java/cct/interfaces/FileChooserInterface.java new file mode 100644 index 0000000..482b0da --- /dev/null +++ b/src/main/java/cct/interfaces/FileChooserInterface.java @@ -0,0 +1,64 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.interfaces; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface FileChooserInterface { + String getDirectory(); + + String[] getDirectories(); + + String getFile(); + + String[] getFiles(); + + String pwd(); + + void setFileChooserVisible(boolean enable) throws Exception ; +} diff --git a/src/main/java/cct/interfaces/ForceFieldInterface.java b/src/main/java/cct/interfaces/ForceFieldInterface.java new file mode 100644 index 0000000..98ae2de --- /dev/null +++ b/src/main/java/cct/interfaces/ForceFieldInterface.java @@ -0,0 +1,98 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.interfaces; + +import cct.modelling.AngleBendsArray; +import cct.modelling.MolecularPlane; +import cct.sff.BondParam; +import java.util.List; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface ForceFieldInterface { + + int CONSTANT_DIELECTRIC_FUNCTION = 0; + int DISTANCE_DIELECTRIC_FUNCTION = 1; + + void enableCalculateElectrostatics(boolean enable); + + void enableUseNBCutoff(boolean enable); + + float get14ElsScale(); + + float get14NBScale(); + + float getDielectricConstant(); + + void getAngleBendParams(MoleculeInterface molec, AngleBendsArray angles); + + BondParam getBondStretchParam(String a1, String a2) throws Exception; + + void getSurfaceParam(MolecularPlane mPlane) throws Exception; + + List getTorsionParams(MoleculeInterface molec, List torsions); + + int getDielectricFunction(); + + String getName(); + + float getNBCutoff(); + + boolean isCalculateElectrostatics(); + + boolean isUseNBCutoff(); + + void set14ElsScale(float scne); + + void set14NBScale(float scnb); + + void setDielectricConstant(float diel); + + void setDielectricFunction(int func); + + void setNBCutoff(float cutoff); +} diff --git a/src/main/java/cct/interfaces/GraphicsObjectInterface.java b/src/main/java/cct/interfaces/GraphicsObjectInterface.java new file mode 100644 index 0000000..1e4d9d0 --- /dev/null +++ b/src/main/java/cct/interfaces/GraphicsObjectInterface.java @@ -0,0 +1,85 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.interfaces; + +import java.awt.Component; + +import org.scijava.java3d.Shape3D; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface GraphicsObjectInterface { + + void addGraphics(GraphicsObjectInterface graphis); + + void addGraphics(String name, Shape3D graphis); + + String getName(); + + int getNGraphicsElements(); + + Object getGraphicsElement(int n); + + java.util.List getShape3DElements(); + + Component getVisualComponent(); + + Component getVisualComponent(int n); + + boolean isVisible(); + + void removeAllGraphics(); + + void removeGraphics(Object graphics); + + void setName(String name); + + void setVisible(boolean visible); + + void setVisible(Object graphics, boolean visible); +} diff --git a/src/main/java/cct/interfaces/GraphicsRendererInterface.java b/src/main/java/cct/interfaces/GraphicsRendererInterface.java new file mode 100644 index 0000000..05a6d9e --- /dev/null +++ b/src/main/java/cct/interfaces/GraphicsRendererInterface.java @@ -0,0 +1,68 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.interfaces; + +import java.awt.Color; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface GraphicsRendererInterface { + MoleculeInterface getMoleculeInterface(); + + void renderMolecule(MoleculeInterface m); + + void setElementForSelectedAtoms(int new_element); + + void setColorForSelectedAtoms(Color new_color); + + void setLabelForSelectedAtoms(String new_label); + + void setRadiusForSelectedAtoms(float radius); + + void setAtomTypeForSelectedAtoms(String new_atomType); +} diff --git a/src/main/java/cct/interfaces/HelperInterface.java b/src/main/java/cct/interfaces/HelperInterface.java new file mode 100644 index 0000000..2ab5b0c --- /dev/null +++ b/src/main/java/cct/interfaces/HelperInterface.java @@ -0,0 +1,74 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.interfaces; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface HelperInterface { + + String JMD_ADD_ATOM_ID = "editing.adding.atom"; + String JMD_ADD_MOLECULE_ID = "editing.adding.molec"; + String JMD_ADD_FRAGMENT_ID = "editing.adding.frag"; + String JMD_MODIFY_ANGLE_ID = "editing.modifying.angle"; + String JMD_MODIFY_BOND_ID = "editing.modifying.bond"; + String JMD_MODIFY_TORSION_ID = "editing.modifying.torsion"; + String JMD_SELECT_ATOMS_ID = "generics.select_atoms"; + String JMD_MANAGE_GAUSSIAN_CUBES_ID = "managing.gaussian.cubes"; + String JMD_MANAGE_GRAPHICS_OBJECTS_ID = "managing.graphics.objects"; + + void setHelpIDString(java.awt.Component comp, String helpID); + + void enableHelpKey(java.awt.Component comp, String id); + + void enableHelpKey(java.awt.Component comp, String id, String presentation, String presentationName); + + void addActionListenerForTracking(javax.swing.AbstractButton comp); + + void displayHelpFromSourceActionListener(javax.swing.AbstractButton comp); + +} diff --git a/src/main/java/cct/interfaces/ImplicitFunctionInterface.java b/src/main/java/cct/interfaces/ImplicitFunctionInterface.java new file mode 100644 index 0000000..5403904 --- /dev/null +++ b/src/main/java/cct/interfaces/ImplicitFunctionInterface.java @@ -0,0 +1,54 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.interfaces; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface ImplicitFunctionInterface { + double eval(float x, float y, float z); +} diff --git a/src/main/java/cct/interfaces/JamberooCoreInterface.java b/src/main/java/cct/interfaces/JamberooCoreInterface.java new file mode 100644 index 0000000..d72a5f7 --- /dev/null +++ b/src/main/java/cct/interfaces/JamberooCoreInterface.java @@ -0,0 +1,33 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.interfaces; + +import javax.swing.JComponent; +import javax.swing.JDialog; + +import cct.j3d.Java3dUniverse; +import cct.tools.filebrowser.ShadowSFTPManager; + +/** + * + * @author vvv900 + */ +public interface JamberooCoreInterface { + + HelperInterface getHelper(); + + void setHelper(HelperInterface helper); + + Java3dUniverse getJamberooRenderer(); + ShadowSFTPManager getShadowSFTPManager(); + + void openAtomSelectionDialog(Java3dUniverse j3d, int jobType, int mode, boolean select_and_process); + void openAtomSelectionDialog(Java3dUniverse j3d, int jobType, int mode, boolean select_and_process, JComponent component); + void openAtomSelectionDialog(Java3dUniverse j3d, int jobType, int mode, boolean select_and_process, JDialog nextDialog); + + void showGraphicsObjectsDialog(boolean visible); + + void updateGraphicsObjectsDialog(); +} diff --git a/src/main/java/cct/interfaces/MinimizeProgressInterface.java b/src/main/java/cct/interfaces/MinimizeProgressInterface.java new file mode 100644 index 0000000..d1e7232 --- /dev/null +++ b/src/main/java/cct/interfaces/MinimizeProgressInterface.java @@ -0,0 +1,71 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.interfaces; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface MinimizeProgressInterface { + + void minimizationStarted(String _started); + + boolean isMinimizationCancelled(); + + void minimizationProgressed(String _progress); + + void minimizationCompleted(); + + /** + * Frequency for updating optimized variables + * @return int + */ + int getVariablesFrequencyUpdate(); + + void setVariablesFrequencyUpdate(int n); + + void updateVariables(int n, float x[]); +} diff --git a/src/main/java/cct/interfaces/MoleculeChangeListener.java b/src/main/java/cct/interfaces/MoleculeChangeListener.java new file mode 100644 index 0000000..3d79b82 --- /dev/null +++ b/src/main/java/cct/interfaces/MoleculeChangeListener.java @@ -0,0 +1,49 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.interfaces; + +import java.util.EventListener; + +/** + * + * @author vvv900 + */ +public interface MoleculeChangeListener extends EventListener { + + void moleculeChanged(MoleculeEventObject event); +} diff --git a/src/main/java/cct/interfaces/MoleculeEventObject.java b/src/main/java/cct/interfaces/MoleculeEventObject.java new file mode 100644 index 0000000..196d20d --- /dev/null +++ b/src/main/java/cct/interfaces/MoleculeEventObject.java @@ -0,0 +1,87 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.interfaces; + +import java.util.EventObject; + +/** + * MoleculeEventObject is used to notify interested parties that molecule has changed in the event source. + * + * @author vvv900 + */ +public class MoleculeEventObject extends EventObject { + + public enum MOLECULE_EVENT { + + MOLECULE_DELETED, MOLECULE_LOADED, MOLECULE_MODIFIED + } + + private MOLECULE_EVENT moleculeEvent = MOLECULE_EVENT.MOLECULE_DELETED; + private String urlString = ""; + + public MoleculeEventObject(Object source) { + super(source); + } + + public MoleculeEventObject(Object source, MOLECULE_EVENT moleculeEvent) { + super(source); + setMoleculeEvent(moleculeEvent); + } + + public MoleculeEventObject(Object source, MOLECULE_EVENT moleculeEvent, String url) { + super(source); + setMoleculeEvent(moleculeEvent); + setUrlString(url); + } + + public void setMoleculeEvent(MOLECULE_EVENT moleculeEvent) { + this.moleculeEvent = moleculeEvent; + } + + public MOLECULE_EVENT getMoleculeEvent() { + return moleculeEvent; + } + + public String getUrlString() { + return urlString; + } + + public void setUrlString(String urlString) { + this.urlString = urlString; + } + +} diff --git a/src/main/java/cct/interfaces/MoleculeInterface.java b/src/main/java/cct/interfaces/MoleculeInterface.java new file mode 100644 index 0000000..f9eb9af --- /dev/null +++ b/src/main/java/cct/interfaces/MoleculeInterface.java @@ -0,0 +1,175 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.interfaces; + +import java.util.List; +import java.util.Map; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface MoleculeInterface { + + Integer WIREFRAME = 0; + Integer STICKS = 1; + Integer BALL_AND_STICKS = 2; + Integer SPACEFILL = 3; + String OUTPUT_RESULTS = "_OutputResults"; + String VIBRATION_RENDERER = "_VibrationRenderer"; + String RenderingStyle = "RenderingStyle"; + String AtomicSets = "AtomicSets"; + String ChargeProperty = "Charge"; + String MultiplicityProperty = "Multiplicity"; + String SCFEnergyProperty = "SCF Energy"; + String MP2EnergyProperty = "MP2 Energy"; + String MP3EnergyProperty = "MP3 Energy"; + String MP4DEnergyProperty = "MP4D Energy"; + String MP4DQEnergyProperty = "MP4DQ Energy"; + String MP4SDQEnergyProperty = "MP4SDQ Energy"; + String CCSDEnergyProperty = "CCSD Energy"; + String CCSDTEnergyProperty = "CCSDT Energy"; + String DipoleMomentProperty = "Dipole"; + String PolarizabilityProperty = "Polarizability"; + String MullikenChargesProperty = "Mulliken charges"; + String ESPChargesProperty = "ESP charges"; + String FrameGroupProperty = "FrameGroup"; + String S_SquaredProperty = "S**2"; + String ZeroPointCorrProperty = "ZPCorr"; + String EnergyThermCorrProperty = "EnergyTC"; + String EnthalpyThermCorrProperty = "EnthalpyTC"; + String GibbsThermCorrProperty = "GibbsTC"; + String ImaginaryFreqsProperty = "ImaginaryFreqs"; + String SurfacesProperty = "Surfaces"; + String NotesProperty = "Notes"; + String ProgramProperty = "Program"; + String VersionProperty = "Version"; + String PeriodicBox = "PeriodicBox"; + String LATTICE_VECTORS = "LatticeVectors"; + String LATTICE_PARAMETERS = "LatticeParamaters"; + + void addAtom(AtomInterface a); + + void addAtom(AtomInterface a, int monomer_number); + + void addAtom(AtomInterface a, int n, String name); + + void addBond(BondInterface b); + + void addMonomer(String monomer_name); + + void addProperty(String propName, Object value); + + /** + * Adds atoms from molecule "mol" (not their copies) + * + * @param mol MoleculeInterface + */ + void mergeMolecule(MoleculeInterface mol); + + /** + * Adds COPIES of atoms from molecule "mol" + * + * @param mol MoleculeInterface + */ + void appendMolecule(MoleculeInterface mol); + + void centerMolecule(float x, float y, float z); + + AtomInterface deleteAtom(int n); + + BondInterface deleteBond(BondInterface bond_to_delete); + + int getAtomIndex(AtomInterface a); + + AtomInterface getAtomInterface(int i); + + int getBondIndex(BondInterface b); + + BondInterface getBondInterface(int i); + + MonomerInterface getMonomerInterface(int n); + + String getName(); + + AtomInterface getNewAtomInstance() throws NullPointerException; + + BondInterface getNewBondInstance() throws NullPointerException; + + BondInterface getNewBondInstance(AtomInterface a, AtomInterface b) throws + NullPointerException; + + int getNumberOfAtoms(); + + int getNumberOfBonds(); + + int getNumberOfMonomers(); + + List getMolecularSubstructure(); + + Map getProperties(); + + Object getProperty(String key); + + float getXmax(); + + float getXmin(); + + float getYmax(); + + float getYmin(); + + float getZmax(); + + float getZmin(); + + MoleculeInterface getInstance(); + + void guessCovalentBondsBetweenMonomers(int n, int m); + + void guessCovalentBondsInMonomer(int n); + + void setName(String name); +} diff --git a/src/main/java/cct/interfaces/MoleculeRendererInterface.java b/src/main/java/cct/interfaces/MoleculeRendererInterface.java new file mode 100644 index 0000000..f8490dd --- /dev/null +++ b/src/main/java/cct/interfaces/MoleculeRendererInterface.java @@ -0,0 +1,21 @@ +package cct.interfaces; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public interface MoleculeRendererInterface { + int LOAD_CANCELED = 0, OVERWRITE_MOLECULE = 1, MERGE_MOLECULE = 2, NEW_MOLECULE = 3; + + void addMolecule(MoleculeInterface molecule); + + void addMolecule(MoleculeInterface molecule, int how_to_load_molecule); +} diff --git a/src/main/java/cct/interfaces/MoleculeSelectorInterface.java b/src/main/java/cct/interfaces/MoleculeSelectorInterface.java new file mode 100644 index 0000000..269d581 --- /dev/null +++ b/src/main/java/cct/interfaces/MoleculeSelectorInterface.java @@ -0,0 +1,21 @@ +package cct.interfaces; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2009 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public interface MoleculeSelectorInterface { + int countMolecules(); + + MoleculeInterface getMolecule(int n) throws Exception; + + String getMoleculeDescription(int n) throws Exception; +} diff --git a/src/main/java/cct/interfaces/MonomerInterface.java b/src/main/java/cct/interfaces/MonomerInterface.java new file mode 100644 index 0000000..c35cce3 --- /dev/null +++ b/src/main/java/cct/interfaces/MonomerInterface.java @@ -0,0 +1,62 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.interfaces; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface MonomerInterface { + AtomInterface getAtom(int n); + + int getAtomIndex(AtomInterface atom); + + String getName(); + + int getNumberOfAtoms(); + + void setName(String name); +} diff --git a/src/main/java/cct/interfaces/OutputResultsInterface.java b/src/main/java/cct/interfaces/OutputResultsInterface.java new file mode 100644 index 0000000..9392086 --- /dev/null +++ b/src/main/java/cct/interfaces/OutputResultsInterface.java @@ -0,0 +1,95 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.interfaces; + +import cct.modelling.VIBRATIONAL_SPECTRUM; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public interface OutputResultsInterface { + + VIBRATIONAL_SPECTRUM[] availableVibrationalSpectra(); + + int countFrequencies(); + + int countSpectra(); + + boolean hasJobSummary(); + + boolean hasDisplacementVectors(); + + boolean hasInteractiveChart(); + + boolean hasVCDSpectrum(); + + boolean hasUDepolSpectrum(); + + boolean hasPDepolSpectrum(); + + boolean hasRamanSpectrum(); + + boolean hasInfraredSpectrum(); + + float[][] getDisplacementVectors(int n); + + double getFrequency(int n); + + double getSpectrumValue(int n, VIBRATIONAL_SPECTRUM spectrum); + + void getSpectrum(double[] x, double[] y, int dim, VIBRATIONAL_SPECTRUM type) throws Exception; + + String[] getAvailPropToChart(); + + String getOutputResume(); + + void setNormalTermination(boolean yes); + + boolean isNormalTermination(); + + double[] getAllTerms(String term); +} diff --git a/src/main/java/cct/interfaces/ParentInterface.java b/src/main/java/cct/interfaces/ParentInterface.java new file mode 100644 index 0000000..f211fe0 --- /dev/null +++ b/src/main/java/cct/interfaces/ParentInterface.java @@ -0,0 +1,69 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.interfaces; + +import java.awt.Component; +import java.awt.Frame; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface ParentInterface { + /** + * To inform parent that its child process finished its execution + * @param child Object - Some ID of a child given by parent + */ + void childFinished(Object child); + + /** + * Gets parent component (if any) + * @return Component + */ + Component getComponent(); + + Frame getParentFrame(); +} diff --git a/src/main/java/cct/interfaces/Point3fInterface.java b/src/main/java/cct/interfaces/Point3fInterface.java new file mode 100644 index 0000000..6f8716d --- /dev/null +++ b/src/main/java/cct/interfaces/Point3fInterface.java @@ -0,0 +1,79 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.interfaces; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface Point3fInterface { + + double distanceTo(Point3fInterface point); + + float getX(); + + float getY(); + + float getZ(); + + void setX(double x); + + void setY(double y); + + void setZ(double z); + + void setXYZ(double xx, double yy, double zz); + + void setXYZ(Point3fInterface xyz); + + void subtract(Point3fInterface a1, Point3fInterface a2); + + Point3fInterface getInstance(); + + Point3fInterface getInstance(Point3fInterface a); + + Point3fInterface getInstance(float xx, float yy, float zz); +} diff --git a/src/main/java/cct/interfaces/TreeSelectorInterface.java b/src/main/java/cct/interfaces/TreeSelectorInterface.java new file mode 100644 index 0000000..ceb0d88 --- /dev/null +++ b/src/main/java/cct/interfaces/TreeSelectorInterface.java @@ -0,0 +1,56 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.interfaces; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface TreeSelectorInterface { + void getSelectedBranch(String value); + + void cancelTreeSelection(); +} diff --git a/src/main/java/cct/interfaces/VibrationsRendererProvider.java b/src/main/java/cct/interfaces/VibrationsRendererProvider.java new file mode 100644 index 0000000..9ed957e --- /dev/null +++ b/src/main/java/cct/interfaces/VibrationsRendererProvider.java @@ -0,0 +1,30 @@ +package cct.interfaces; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public interface VibrationsRendererProvider { + + int getMinimumDuration(); + + int getMaximumDuration(); + + int getDuration(); + + void setDuration(int duration); + + void animateVibrations(int frequency, boolean show); + + void showDisplacementVectors(int frequency, boolean show); + + void saveScene(int frequency, String format) throws Exception; +} diff --git a/src/main/java/cct/interfaces/VolumetricDataInterface.java b/src/main/java/cct/interfaces/VolumetricDataInterface.java new file mode 100644 index 0000000..fd3d1d7 --- /dev/null +++ b/src/main/java/cct/interfaces/VolumetricDataInterface.java @@ -0,0 +1,125 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.interfaces; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public interface VolumetricDataInterface { + + /** + * Parses file with volumetric data + * @param filename String - file name + * @throws Exception - if any error occurs + */ + void parseVolumetricData(String filename) throws Exception; + + /** + * Returns description of the whole volumetric data + * @return String + */ + String getCubeDescription(); + + /** + * Returns description of nth cube + * @param n int - cube number + * @return String + */ + String getCubeLabel(int n); + + /** + * Returns minimum function value + * @return double + */ + double getMinFunValue(); + + /** + * Returns maximum function value + * @return double + */ + double getMaxFunValue(); + + /** + * Returns number of volumetric cubes + * @return int + */ + int countCubes(); + + /** + * Returns 3d array of volumetric data + * @return float[][][] + */ + float[][][] getVolumetricData(); + + /** + * Returns 3d array of volumetric data for n-th cube + * @param n int - cube number + * @return float[][][] + */ + float[][][] getVolumetricData(int n); + + /** + * Data origin of a cube, i.e. minimal x, y and z + * @return double[] + */ + double[] getDataOrigin(); + + /** + * Number of voxels along every axis (x,y,z) + * @return int[] + */ + int[] getNumberOfVoxels(); + + // Lengths (in A) of a cube along all axes - + float[][] getAxisVectors(); + + /** + * Returns molecular goemetry (if any). null is no molecular geometry in the cube file + * @param molecule MoleculeInterface + */ + void getMolecule(MoleculeInterface molecule); +} diff --git a/src/main/java/cct/j3d/.DS_Store b/src/main/java/cct/j3d/.DS_Store new file mode 100644 index 0000000..b034208 Binary files /dev/null and b/src/main/java/cct/j3d/.DS_Store differ diff --git a/src/main/java/cct/j3d/._.DS_Store b/src/main/java/cct/j3d/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/cct/j3d/._.DS_Store differ diff --git a/src/main/java/cct/j3d/AppearanceSetup.java b/src/main/java/cct/j3d/AppearanceSetup.java new file mode 100644 index 0000000..5cf61ac --- /dev/null +++ b/src/main/java/cct/j3d/AppearanceSetup.java @@ -0,0 +1,381 @@ +/* + * $RCSfile: SphereMotion.java,v $ + * + * Copyright (c) 2006 Sun Microsystems, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL + * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF + * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR + * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, + * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND + * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR + * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed, licensed or + * intended for use in the design, construction, operation or + * maintenance of any nuclear facility. + * + * $Revision: 1.2 $ + * $Date: 2006/03/01 07:07:38 $ + * $State: Exp $ + */ + +package cct.j3d; + +import org.scijava.java3d.utils.behaviors.mouse.MouseRotate; +import org.scijava.java3d.utils.geometry.Primitive; +import org.scijava.java3d.utils.geometry.Sphere; +import org.scijava.java3d.utils.universe.SimpleUniverse; + +import org.scijava.java3d.*; +import org.scijava.vecmath.*; +import java.awt.*; +import java.util.logging.Logger; + + +public class AppearanceSetup + extends javax.swing.JFrame { + + private SimpleUniverse univ = null; + private BranchGroup scene = null; + + // Constants for type of light to use + private static final int DIRECTIONAL_LIGHT = 0; + private static final int POINT_LIGHT = 1; + private static final int SPOT_LIGHT = 2; + + // Flag indicates type of lights: directional, point, or spot + // lights. This flag is set based on command line argument + private static int lightType = POINT_LIGHT; + static final Logger logger = Logger.getLogger(AppearanceSetup.class.getCanonicalName()); + + public BranchGroup createSceneGraph() { + Color3f eColor = new Color3f(0.0f, 0.0f, 0.0f); + Color3f sColor = new Color3f(1.0f, 1.0f, 1.0f); + Color3f objColor = new Color3f(0.6f, 0.6f, 0.6f); + Color3f lColor1 = new Color3f(1.0f, 0.0f, 0.0f); + Color3f lColor2 = new Color3f(0.0f, 1.0f, 0.0f); + Color3f alColor = new Color3f(0.2f, 0.2f, 0.2f); + Color3f bgColor = new Color3f(0.05f, 0.05f, 0.2f); + + Transform3D t; + + // Create the root of the branch graph + BranchGroup objRoot = new BranchGroup(); + + TransformGroup sceneOffset = new TransformGroup(); + + Transform3D offset = new Transform3D(); + offset.set(new Vector3f(0.0f, 0.0f, -3.0f)); + sceneOffset.setTransform(offset); + + // Create a Transformgroup to scale all objects so they + // appear in the scene. + /* + TransformGroup objScale = new TransformGroup(); + Transform3D t3d = new Transform3D(); + t3d.setScale(0.4); + objScale.setTransform(t3d); + objRoot.addChild(objScale); + */ + // Create a bounds for the background and lights + BoundingSphere bounds = + new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); + + // Set up the background + Background bg = new Background(bgColor); + bg.setApplicationBounds(bounds); + //objScale.addChild(bg); + sceneOffset.addChild(bg); + + // Create a Sphere object, generate one copy of the sphere, + // and add it into the scene graph. + Material m = new Material(objColor, eColor, objColor, sColor, 100.0f); + Appearance a = new Appearance(); + m.setLightingEnable(true); + a.setMaterial(m); + Sphere sph = new Sphere(1.0f, Primitive.GENERATE_NORMALS, 80, a); + //objScale.addChild(sph); + sceneOffset.addChild(sph); + + // Create the transform group node for the each light and initialize + // it to the identity. Enable the TRANSFORM_WRITE capability so that + // our behavior code can modify it at runtime. Add them to the root + // of the subgraph. + + TransformGroup l1RotTrans = new TransformGroup(); + l1RotTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + //objScale.addChild(l1RotTrans); + sceneOffset.addChild(l1RotTrans); + + TransformGroup l2RotTrans = new TransformGroup(); + l2RotTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + //objScale.addChild(l2RotTrans); + sceneOffset.addChild(l2RotTrans); + + // Create transformations for the positional lights + t = new Transform3D(); + Vector3d lPos1 = new Vector3d(0.0, 0.0, 2.0); + t.set(lPos1); + TransformGroup l1Trans = new TransformGroup(t); + l1Trans.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); + l1Trans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + l1RotTrans.addChild(l1Trans); + + t = new Transform3D(); + Vector3d lPos2 = new Vector3d(0.5, 0.8, 2.0); + t.set(lPos2); + TransformGroup l2Trans = new TransformGroup(t); + l2RotTrans.addChild(l2Trans); + + // Create Geometry for point lights + ColoringAttributes caL1 = new ColoringAttributes(); + ColoringAttributes caL2 = new ColoringAttributes(); + caL1.setColor(lColor1); + caL2.setColor(lColor2); + Appearance appL1 = new Appearance(); + Appearance appL2 = new Appearance(); + appL1.setColoringAttributes(caL1); + appL2.setColoringAttributes(caL2); + + MouseRotate mouseRotate = new MouseRotate(); + mouseRotate.setTransformGroup(l1RotTrans); + mouseRotate.setSchedulingBounds(bounds); + sceneOffset.addChild(mouseRotate); + sceneOffset.setCapability(Group.ALLOW_CHILDREN_WRITE); + sceneOffset.setCapability(Group.ALLOW_CHILDREN_READ); + + l1Trans.addChild(new Sphere(0.05f, appL1)); + l2Trans.addChild(new Sphere(0.05f, appL2)); + + // Create lights + AmbientLight aLgt = new AmbientLight(alColor); + + Light lgt1 = null; + Light lgt2 = null; + + Point3f lPoint = new Point3f(0.0f, 0.0f, 0.0f); + Point3f atten = new Point3f(1.0f, 0.0f, 0.0f); + Vector3f lDirect1 = new Vector3f(lPos1); + Vector3f lDirect2 = new Vector3f(lPos2); + lDirect1.negate(); + lDirect2.negate(); + + switch (lightType) { + case DIRECTIONAL_LIGHT: + lgt1 = new DirectionalLight(lColor1, lDirect1); + lgt2 = new DirectionalLight(lColor2, lDirect2); + break; + case POINT_LIGHT: + lgt1 = new PointLight(lColor1, lPoint, atten); + lgt2 = new PointLight(lColor2, lPoint, atten); + break; + case SPOT_LIGHT: + lgt1 = new SpotLight(lColor1, lPoint, atten, lDirect1, + 25.0f * (float) Math.PI / 180.0f, 10.0f); + lgt2 = new SpotLight(lColor2, lPoint, atten, lDirect2, + 25.0f * (float) Math.PI / 180.0f, 10.0f); + break; + } + + // Set the influencing bounds + aLgt.setInfluencingBounds(bounds); + lgt1.setInfluencingBounds(bounds); + lgt2.setInfluencingBounds(bounds); + + // Add the lights into the scene graph + //objScale.addChild(aLgt); + sceneOffset.addChild(aLgt); + l1Trans.addChild(lgt1); + l2Trans.addChild(lgt2); + + // Create a new Behavior object that will perform the desired + // operation on the specified transform object and add it into the + // scene graph. + /* + Transform3D yAxis = new Transform3D(); + Alpha rotor1Alpha = new Alpha(-1, Alpha.INCREASING_ENABLE, + 0, 0, + 4000, 0, 0, + 0, 0, 0); + RotationInterpolator rotator1 = + new RotationInterpolator(rotor1Alpha, + l1RotTrans, + yAxis, + 0.0f, (float) Math.PI*2.0f); + rotator1.setSchedulingBounds(bounds); + l1RotTrans.addChild(rotator1); + */ + // Create a new Behavior object that will perform the desired + // operation on the specified transform object and add it into the + // scene graph. + /* + Alpha rotor2Alpha = new Alpha(-1, Alpha.INCREASING_ENABLE, + 0, 0, + 1000, 0, 0, + 0, 0, 0); + RotationInterpolator rotator2 = + new RotationInterpolator(rotor2Alpha, + l2RotTrans, + yAxis, + 0.0f, 0.0f); + bounds = new BoundingSphere(new Point3d(0.0,0.0,0.0), 100.0); + rotator2.setSchedulingBounds(bounds); + l2RotTrans.addChild(rotator2); + */ + + // Create a position interpolator and attach it to the view + // platform + + /* + TransformGroup vpTrans = + univ.getViewingPlatform().getViewPlatformTransform(); + Transform3D axisOfTranslation = new Transform3D(); + Alpha transAlpha = new Alpha(-1, + Alpha.INCREASING_ENABLE | + Alpha.DECREASING_ENABLE, + 0, 0, + 5000, 0, 0, + 5000, 0, 0); + axisOfTranslation.rotY(-Math.PI/2.0); + PositionInterpolator translator = + new PositionInterpolator(transAlpha, + vpTrans, + axisOfTranslation, + 2.0f, 3.5f); + translator.setSchedulingBounds(bounds); + objScale.addChild(translator); + */ + // Let Java 3D perform optimizations on this scene graph. + objRoot.addChild(sceneOffset); + objRoot.compile(); + + return objRoot; + } + + private Canvas3D createUniverse() { + // Get the preferred graphics configuration for the default screen + GraphicsConfiguration config = + SimpleUniverse.getPreferredConfiguration(); + + // Create a Canvas3D using the preferred configuration + Canvas3D c = new Canvas3D(config); + + // Create simple universe with view branch + univ = new SimpleUniverse(c); + + // This will move the ViewPlatform back a bit so the + // objects in the scene can be viewed. + univ.getViewingPlatform().setNominalViewingTransform(); + + // Ensure at least 5 msec per frame (i.e., < 200Hz) + univ.getViewer().getView().setMinimumFrameCycleTime(5); + + return c; + } + + /** + * Creates new form SphereMotion + */ + public AppearanceSetup(final String[] args) { + + // Parse the Input Arguments + String usage = "Usage: java SphereMotion [-point | -spot | -dir]"; + for (int i = 0; i < args.length; i++) { + if (args[i].startsWith("-")) { + if (args[i].equals("-point")) { + logger.info("Using point lights"); + lightType = POINT_LIGHT; + } + else if (args[i].equals("-spot")) { + logger.info("Using spot lights"); + lightType = SPOT_LIGHT; + } + else if (args[i].equals("-dir")) { + logger.info("Using directional lights"); + lightType = DIRECTIONAL_LIGHT; + } + else { + logger.info(usage); + System.exit(0); + } + } + else { + logger.info(usage); + System.exit(0); + } + } + + // Initialize the GUI components + initComponents(); + + // Create Canvas3D and SimpleUniverse; add canvas to drawing panel + Canvas3D c = createUniverse(); + drawingPanel.add(c, BorderLayout.CENTER); + + // Create the content branch and add it to the universe + scene = createSceneGraph(); + univ.addBranchGraph(scene); + } + + // ---------------------------------------------------------------- + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // //GEN-BEGIN:initComponents + private void initComponents() { + drawingPanel = new javax.swing.JPanel(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + setTitle("SphereMotion"); + drawingPanel.setLayout(new BorderLayout()); + + drawingPanel.setPreferredSize(new Dimension(700, 700)); + getContentPane().add(drawingPanel, BorderLayout.CENTER); + + pack(); + } // //GEN-END:initComponents + + /** + * @param args the command line arguments + */ + public static void main(final String args[]) { + EventQueue.invokeLater(new Runnable() { + @Override + public void run() { + AppearanceSetup sphereMotion = new AppearanceSetup(args); + sphereMotion.setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JPanel drawingPanel; + // End of variables declaration//GEN-END:variables + +} diff --git a/src/main/java/cct/j3d/ArrowNode.java b/src/main/java/cct/j3d/ArrowNode.java new file mode 100644 index 0000000..3467e9d --- /dev/null +++ b/src/main/java/cct/j3d/ArrowNode.java @@ -0,0 +1,299 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import org.scijava.java3d.Appearance; +import org.scijava.java3d.BranchGroup; +import org.scijava.java3d.ColoringAttributes; +import org.scijava.java3d.Group; +import org.scijava.java3d.Material; +import org.scijava.java3d.Node; +import org.scijava.java3d.PolygonAttributes; +import org.scijava.java3d.Shape3D; +import org.scijava.java3d.Transform3D; +import org.scijava.java3d.TransformGroup; +import org.scijava.vecmath.AxisAngle4f; +import org.scijava.vecmath.Color3f; +import org.scijava.vecmath.Vector3d; +import org.scijava.vecmath.Vector3f; + +import org.scijava.java3d.utils.geometry.Cone; +import org.scijava.java3d.utils.geometry.Cylinder; +import org.scijava.java3d.utils.geometry.Primitive; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class ArrowNode + extends BranchGroup { + + private Color3f arrowColor = new Color3f(1.0f, 0.5f, 0.7f); + private Color3f arrowHeadColor = new Color3f(1.0f, 0.5f, 0.7f); + private float arrowRadius = 0.2f; + private float arrowHeadRadius = 0.2f; + private float arrowHeadLength = 2.0f * arrowHeadRadius; + private BranchGroup rootBranch = new BranchGroup(); + private Cylinder cylinder = null; + private Cone arrowHead = null; + private float arrowLength = 1.0f; + + private float vX, vY, vZ; + private float originX = 0, originY = 0, originZ = 0; + private float angle; + private AxisAngle4f rot = new AxisAngle4f(); + + public ArrowNode() { + super(); + init(); + } + + public ArrowNode(float[] origin, float[] direction) { + super(); + init(); + + getOrientation(direction); + arrowLength = (float) Math.sqrt(direction[0] * direction[0] + direction[1] * direction[1] + direction[2] * direction[2]); + + originX = origin[0]; + originY = origin[1]; + originZ = origin[2]; + + } + + private void init() { + setCapability(Group.ALLOW_CHILDREN_READ); + setCapability(Group.ALLOW_CHILDREN_WRITE); + setCapability(Group.ALLOW_CHILDREN_EXTEND); + setCapability(BranchGroup.ALLOW_DETACH); + + rootBranch.setCapability(Group.ALLOW_CHILDREN_READ); + rootBranch.setCapability(Group.ALLOW_CHILDREN_WRITE); + rootBranch.setCapability(Group.ALLOW_CHILDREN_EXTEND); + rootBranch.setCapability(BranchGroup.ALLOW_DETACH); + + } + + public void setArrowLength(float new_length) { + arrowLength = new_length; + } + + public void setArrowHeadLength(float new_length) { + arrowHeadLength = new_length; + } + + public void setArrowRadius(float new_radius) { + arrowRadius = new_radius; + } + + public void setArrowHeadRadius(float new_radius) { + arrowHeadRadius = new_radius; + } + + public void createArrow() { + Transform3D move = new Transform3D(); + move.setScale(new Vector3d(arrowRadius, arrowLength, arrowRadius)); + move.setRotation(rot); + move.setTranslation(new Vector3f( (originX + 0.5f * arrowLength * vX), + (originY + 0.5f * arrowLength * vY), + (originZ + 0.5f * arrowLength * vZ))); + + TransformGroup atg = new TransformGroup(move); + atg.setCapability(Group.ALLOW_CHILDREN_READ); + atg.setCapability(Group.ALLOW_CHILDREN_WRITE); + atg.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); + atg.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + + Appearance aAppear = getAppearance(arrowColor); + + cylinder = createCylinder(1, 1, aAppear); + cylinder.setCapability(Primitive.ENABLE_APPEARANCE_MODIFY); + cylinder.setCapability(Group.ALLOW_CHILDREN_READ); + cylinder.setCapability(Group.ALLOW_CHILDREN_WRITE); + UserData.setUserData(cylinder, UserData.NODE_NAME, "Arrow"); + + atg.addChild(cylinder); + + rootBranch.addChild(atg); + + // --- Arrow head + + TransformGroup tg = new TransformGroup(); + tg.setCapability(Group.ALLOW_CHILDREN_READ); + tg.setCapability(Group.ALLOW_CHILDREN_WRITE); + tg.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); + tg.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + + Transform3D transform = new Transform3D(); + transform.setScale(new Vector3d(arrowHeadRadius, arrowHeadLength / 2.0f, arrowHeadRadius)); + // Constructs a default Cone of radius of 1.0 and height of 2.0. + arrowHead = new Cone(); + arrowHead.setCapability(Primitive.ENABLE_APPEARANCE_MODIFY); + arrowHead.setCapability(Group.ALLOW_CHILDREN_READ); + arrowHead.setCapability(Node.ALLOW_BOUNDS_WRITE); + UserData.setUserData(arrowHead, UserData.NODE_NAME, "Arrow_Head"); + aAppear = getAppearance(arrowHeadColor); + arrowHead.setAppearance(aAppear); + + transform.setRotation(rot); + transform.setTranslation(new Vector3f( (float) (originX + (arrowHeadLength / 2.0 + arrowLength) * vX), + (float) (originY + (arrowHeadLength / 2.0 + arrowLength) * vY), + (float) (originZ + (arrowHeadLength / 2.0 + arrowLength) * vZ))); + + tg.setTransform(transform); + tg.addChild(arrowHead); + rootBranch.addChild(tg); + + addChild(rootBranch); + } + + public void setNodeName(String name) { + if (cylinder == null) { + return; + } + UserData.setUserData(cylinder, UserData.NODE_NAME, name); + UserData.setUserData(arrowHead, UserData.NODE_NAME, name); + } + + private Cylinder createCylinder(float radius, float height, Appearance ap) { + Cylinder cyl = new Cylinder(radius, height, ap); + cyl.setCapability(Primitive.ENABLE_APPEARANCE_MODIFY); + cyl.setCapability(Primitive.ENABLE_APPEARANCE_MODIFY); + Shape3D shape = cyl.getShape(Cylinder.BODY); + shape.setCapability(Shape3D.ALLOW_APPEARANCE_READ); + shape.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); + shape = cyl.getShape(Cylinder.BOTTOM); + shape.setCapability(Shape3D.ALLOW_APPEARANCE_READ); + shape.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); + shape = cyl.getShape(Cylinder.TOP); + shape.setCapability(Shape3D.ALLOW_APPEARANCE_READ); + shape.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); + + return cyl; + } + + public void setColor(Color3f color) { + try { + Appearance aAppear = getAppearance(color); + cylinder.setAppearance(aAppear); + aAppear = getAppearance(color); + arrowHead.setAppearance(aAppear); + } + catch (Exception ex) { + System.err.println(this.getClass().getCanonicalName() + ": setColor: " + ex.getMessage()); + } + } + + private Appearance getAppearance(Color3f color) { + ColoringAttributes ca = new ColoringAttributes(); + ca.setCapability(ColoringAttributes.ALLOW_COLOR_READ); + ca.setCapability(ColoringAttributes.ALLOW_COLOR_WRITE); + + ca.setColor(color); + Appearance aAppear = new Appearance(); + aAppear.setCapability(Appearance.ALLOW_COLORING_ATTRIBUTES_READ); + aAppear.setCapability(Appearance.ALLOW_COLORING_ATTRIBUTES_WRITE); + aAppear.setCapability(Appearance.ALLOW_MATERIAL_READ); + aAppear.setCapability(Appearance.ALLOW_MATERIAL_WRITE); + aAppear.setColoringAttributes(ca); + + Material material = createMaterial(color); + aAppear.setMaterial(material); + + PolygonAttributes polyAppear = new PolygonAttributes(); + polyAppear.setCullFace(PolygonAttributes.CULL_BACK); + + aAppear.setPolygonAttributes(polyAppear); + return aAppear; + } + + private Material createMaterial(Color3f color) { + Material material = new Material(); + // --- Diffuse Color + material.setDiffuseColor(color); + + // --- Ambient Color + material.setAmbientColor(0.2f * color.x, 0.2f * color.y, 0.2f * color.z); + + // --- Emissive Color + material.setEmissiveColor(0.0f, 0.0f, 0.0f); + + // --- Specular Color + material.setSpecularColor(1.0f, 1.0f, 1.0f); + + // --- Set Shininess + material.setShininess(15.0f); + + material.setCapability(Material.ALLOW_COMPONENT_READ); + material.setCapability(Material.ALLOW_COMPONENT_WRITE); + return material; + } + + private void getOrientation(float[] direction) { + + // Get orientation + vX = direction[0]; + vY = direction[1]; + vZ = direction[2]; + float norm = (float) Math.sqrt(vX * vX + vY * vY + vZ * vZ); + vX /= norm; + vY /= norm; + vZ /= norm; + + angle = (float) Math.acos(vY); + if (vY + 1.0 < 0.001) { + rot.set(1.0f, 0.0f, 0.0f, angle); + } + else { + rot.set(vZ, 0.0f, -vX, angle); + } + } + + public static void main(String[] args) { + ArrowNode arrownode = new ArrowNode(); + } + +} diff --git a/src/main/java/cct/j3d/AtomNode.java b/src/main/java/cct/j3d/AtomNode.java new file mode 100644 index 0000000..6f81b7a --- /dev/null +++ b/src/main/java/cct/j3d/AtomNode.java @@ -0,0 +1,772 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.j3d; + +import java.awt.Color; +import java.util.Iterator; +import java.util.List; + +import org.scijava.java3d.Appearance; +import org.scijava.java3d.BranchGroup; +import org.scijava.java3d.ColoringAttributes; +import org.scijava.java3d.GeometryArray; +import org.scijava.java3d.Group; +import org.scijava.java3d.Material; +import org.scijava.java3d.Node; +import org.scijava.java3d.PointArray; +import org.scijava.java3d.PointAttributes; +import org.scijava.java3d.PolygonAttributes; +import org.scijava.java3d.Shape3D; +import org.scijava.java3d.Transform3D; +import org.scijava.java3d.TransformGroup; +import org.scijava.vecmath.Color3f; +import org.scijava.vecmath.Point3f; +import org.scijava.vecmath.Vector3f; + +import cct.interfaces.AtomInterface; +import cct.modelling.ChemicalElements; + +import org.scijava.java3d.utils.geometry.Primitive; +import org.scijava.java3d.utils.geometry.Sphere; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Logger; +import org.scijava.java3d.*; + +/** + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2006

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class AtomNode + extends BranchGroup implements Cloneable { + + static int defaultNumberDivisions = 100; + static final Logger logger = Logger.getLogger(AtomNode.class.getCanonicalName()); + BranchGroup rootBranch = null; + AtomInterface atom = null; + TransformGroup objTransform = null; + Transform3D t3d = null; + ColoringAttributes ca = new ColoringAttributes(); + Appearance aAppear = new Appearance(); + PolygonAttributes polyAppear = new PolygonAttributes(); + Sphere atomicSphere = null; + Color3f atomColor = null; + float sphereRadius = 1; + int numberDivisions = defaultNumberDivisions; + int renderingStyle = AtomInterface.RENDER_SPHERE; + Material atomMaterial = null; + float[] xyz = new float[3]; + PointArray atomPoint = null; + PointAttributes pointAttributes = null; + float pointSize = 4; + static float highlightPointSize = 8; + boolean pointAntialiasing = true; + Shape3D atomShape = null; + boolean visible = true; + boolean highlighted = false; + boolean useSwitch = true; + private Switch showSwitch = new Switch(); + private Map switchShapes = new HashMap(); + private Map switchIndex = new HashMap(); + + public AtomNode(AtomInterface atom) { + this(atom, defaultNumberDivisions); + + setCapability(Group.ALLOW_CHILDREN_READ); + setCapability(Group.ALLOW_CHILDREN_WRITE); + setCapability(Group.ALLOW_CHILDREN_EXTEND); + setCapability(Group.ALLOW_CHILDREN_WRITE); + setCapability(Node.ALLOW_PICKABLE_READ); + setCapability(Node.ALLOW_PICKABLE_WRITE); + setCapability(Node.ALLOW_LOCAL_TO_VWORLD_READ); + setCapability(Node.ENABLE_PICK_REPORTING); + setCapability(BranchGroup.ALLOW_DETACH); + setPickable(true); + + } + + @Override + public void detach() { + System.err.println("DO not use detach in AtomNode!!!"); + Object obj = this.getRootBranch(); + if (obj instanceof MoleculeNode) { + ((MoleculeNode) obj).removeChild(this); + return; + } + super.detach(); + } + + public AtomNode(AtomInterface _atom, int divisions) { + + atom = _atom; + UserData.setUserData(this, UserData.NODE_NAME, "Atom_" + ChemicalElements.getElementSymbol(atom.getAtomicNumber())); + //setName("Atom_" + atom.getName()); // --- >1.4 java3d feature + + xyz[0] = atom.getX(); + xyz[1] = atom.getY(); + xyz[2] = atom.getZ(); + + numberDivisions = divisions; + + // --- Setup RGB color of atomic sphere + atomColor = getAtomColor(atom); + + // --- Getting rendering style + renderingStyle = getRenderingStyle(atom); + + // --- Getting visibility + Object obj = atom.getProperty(AtomInterface.VISIBLE); + if (obj != null && obj instanceof Boolean) { + visible = (Boolean) obj; + } + + //Transform3D move = new Transform3D(); + //move.set(new Vector3f(x, y, z)); + //TransformGroup objMove = new TransformGroup(move); + t3d = new Transform3D(); + t3d.set(new Vector3f(xyz[0], xyz[1], xyz[2])); + + // --- Setup radius of atomic sphere + sphereRadius = getAtomicSphereRadius(atom); + if (renderingStyle == AtomInterface.RENDER_POINT || renderingStyle == AtomInterface.RENDER_SMART_POINT) { + t3d.setScale(1.0); + } else { + t3d.setScale(sphereRadius); + } + objTransform = this.getTransformGroup(t3d); + + rootBranch = this.getRootBranch(); + rootBranch.addChild(objTransform); + if (this.useSwitch) { + objTransform.addChild(showSwitch); + showSwitch.setCapability(Switch.ALLOW_SWITCH_READ); + showSwitch.setCapability(Switch.ALLOW_SWITCH_WRITE); + showSwitch.setCapability(Switch.ALLOW_CHILDREN_EXTEND); + showSwitch.setCapability(Switch.ALLOW_CHILDREN_READ); + showSwitch.setCapability(Switch.ALLOW_CHILDREN_WRITE); + } + + addChild(rootBranch); + + // --- Render atom + if (renderingStyle == AtomInterface.RENDER_POINT) { + Node point = null; + if (useSwitch) { + BranchGroup bg = switchShapes.get(J3D_ATOM_PROPERTY.POINT_3D); + if (bg == null) { + bg = new BranchGroup(); + point = createAtomicPoint(pointSize, atomColor); + bg.addChild(point); + switchShapes.put(J3D_ATOM_PROPERTY.POINT_3D, bg); + showSwitch.addChild(bg); + switchIndex.put(bg, showSwitch.numChildren() - 1); + } + showSwitch.setWhichChild(switchIndex.get(bg)); + } else { + point = createAtomicPoint(pointSize, atomColor); + objTransform.addChild(point); + } + //************************************************************* + } else if (renderingStyle == AtomInterface.RENDER_SMART_POINT) { + Node point; + if (useSwitch) { + if (isRenderPoint()) { + BranchGroup bg = switchShapes.get(J3D_ATOM_PROPERTY.POINT_3D); + if (bg == null) { + bg = new BranchGroup(); + point = createAtomicPoint(pointSize, atomColor); + bg.addChild(point); + switchShapes.put(J3D_ATOM_PROPERTY.POINT_3D, bg); + showSwitch.addChild(bg); + switchIndex.put(bg, showSwitch.numChildren() - 1); + } + showSwitch.setWhichChild(switchIndex.get(bg)); + } else { + showSwitch.setWhichChild(Switch.CHILD_NONE); + } + + } else { + point = renderPointIfNecessary(); + if (point != null) { + objTransform.addChild(point); + } + } + + } else if (renderingStyle == AtomInterface.RENDER_SPHERE) { + // --- Set material of atomic sphere + + //Node sphere; + if (this.useSwitch) { + BranchGroup bg = switchShapes.get(J3D_ATOM_PROPERTY.SPHERE_3D); + if (bg == null) { + bg = new BranchGroup(); + atomicSphere = createAtomicSphere(atom); + bg.addChild(atomicSphere); + switchShapes.put(J3D_ATOM_PROPERTY.SPHERE_3D, bg); + showSwitch.addChild(bg); + switchIndex.put(bg, showSwitch.numChildren() - 1); + } + showSwitch.setWhichChild(switchIndex.get(bg)); + } else { + atomicSphere = createAtomicSphere(atom); + objTransform.addChild(atomicSphere); + } + } + } + + Sphere createAtomicSphere(AtomInterface atom) { + atomMaterial = ChemicalElementsColors.createMaterial(atomColor); + + Color3f color = new Color3f(); + atomMaterial.getAmbientColor(color); + atom.setProperty(AtomInterface.AMBIENT_RGB_COLOR, new float[]{color.x, color.y, color.z}); + + atomMaterial.getDiffuseColor(color); + atom.setProperty(AtomInterface.DIFFUSE_RGB_COLOR, new float[]{color.x, color.y, color.z}); + + atomMaterial.getSpecularColor(color); + atom.setProperty(AtomInterface.SPECULAR_RGB_COLOR, new float[]{color.x, color.y, color.z}); + + return createAtomicSphere(numberDivisions, atomColor, atomMaterial); + } + + public boolean isVisible() { + return visible; + } + + public AtomNode(float radius, float x, float y, float z, int divisions, Color3f color, Material material) { + super(); + + sphereRadius = radius; + atomColor = color; + numberDivisions = divisions; + atomMaterial = material; + xyz[0] = x; + xyz[1] = y; + xyz[2] = z; + + t3d = new Transform3D(); + t3d.set(new Vector3f(xyz[0], xyz[1], xyz[2])); + t3d.setScale(sphereRadius); + + atomicSphere = createAtomicSphere(divisions, color, material); + if (useSwitch) { + BranchGroup bg = new BranchGroup(); + bg.addChild(atomicSphere); + switchShapes.put(J3D_ATOM_PROPERTY.SPHERE_3D, bg); + showSwitch.addChild(bg); + switchIndex.put(bg, showSwitch.numChildren() - 1); + showSwitch.setWhichChild(switchIndex.get(bg)); + } else { + objTransform.addChild(atomicSphere); + } + } + + private Node createAtomicPoint(float point_size, Color3f color) { + + atomPoint = new PointArray(1, GeometryArray.COORDINATES | GeometryArray.COLOR_3); + + atomPoint.setCapability(GeometryArray.ALLOW_COLOR_READ); + atomPoint.setCapability(GeometryArray.ALLOW_COLOR_WRITE); + atomPoint.setCapability(GeometryArray.ALLOW_COORDINATE_READ); + atomPoint.setCapability(GeometryArray.ALLOW_COORDINATE_WRITE); + + //atomPoint.setCoordinate(0, new Point3f(atom.getX(), atom.getY(), atom.getZ())); + atomPoint.setCoordinate(0, new Point3f(0, 0, 0)); // --- Location is already in transform3d + atomPoint.setColor(0, color); + + Shape3D atomShape = new Shape3D(atomPoint); + atomShape.setCapability(Shape3D.ALLOW_GEOMETRY_READ); + atomShape.setCapability(Shape3D.ALLOW_GEOMETRY_WRITE); + + pointAttributes = new PointAttributes(point_size, pointAntialiasing); + aAppear.setPointAttributes(pointAttributes); + + atomShape.setAppearance(aAppear); + + //addChild(atomShape); + return atomShape; + } + + boolean isRenderPoint() { + List bondedAtoms = atom.getBondedToAtoms(); + if (bondedAtoms == null || bondedAtoms.size() < 1) { + return true; + } + Iterator iter = bondedAtoms.iterator(); + while (iter.hasNext()) { + AtomInterface a = (AtomInterface) iter.next(); + Object obj = a.getProperty(AtomInterface.VISIBLE); + if (obj == null) { // So, it's visible + return false; + } + if (obj != null && obj instanceof Boolean) { + boolean vis = (Boolean) obj; + if (vis) { + return false; + } + } + } + return true; + } + + Node renderPointIfNecessary() { + if (isRenderPoint()) { + return createAtomicPoint(pointSize, atomColor); + } else { + return null; + } + } + + private Sphere createAtomicSphere(int divisions, Color3f color, Material material) { + + ca.setColor(color); + + aAppear.setColoringAttributes(ca); + + aAppear.setMaterial(material); + + polyAppear.setCullFace(PolygonAttributes.CULL_BACK); + + aAppear.setPolygonAttributes(polyAppear); + aAppear.setCapability(Appearance.ALLOW_COLORING_ATTRIBUTES_READ); + aAppear.setCapability(Appearance.ALLOW_COLORING_ATTRIBUTES_WRITE); + aAppear.setCapability(Appearance.ALLOW_LINE_ATTRIBUTES_READ); + aAppear.setCapability(Appearance.ALLOW_LINE_ATTRIBUTES_WRITE); + aAppear.setCapability(Appearance.ALLOW_MATERIAL_READ); + aAppear.setCapability(Appearance.ALLOW_MATERIAL_WRITE); + aAppear.setCapability(Appearance.ALLOW_POINT_ATTRIBUTES_READ); + aAppear.setCapability(Appearance.ALLOW_POINT_ATTRIBUTES_WRITE); + aAppear.setCapability(Appearance.ALLOW_POLYGON_ATTRIBUTES_READ); + aAppear.setCapability(Appearance.ALLOW_POLYGON_ATTRIBUTES_WRITE); + aAppear.setCapability(Appearance.ALLOW_RENDERING_ATTRIBUTES_READ); + aAppear.setCapability(Appearance.ALLOW_RENDERING_ATTRIBUTES_WRITE); + aAppear.setCapability(Appearance.ALLOW_TEXGEN_READ); + aAppear.setCapability(Appearance.ALLOW_TEXGEN_WRITE); + aAppear.setCapability(Appearance.ALLOW_TEXTURE_ATTRIBUTES_READ); + aAppear.setCapability(Appearance.ALLOW_TEXTURE_READ); + aAppear.setCapability(Appearance.ALLOW_TEXTURE_UNIT_STATE_READ); + aAppear.setCapability(Appearance.ALLOW_TRANSPARENCY_ATTRIBUTES_READ); + + // Setup atoms + Sphere atomicSphere = new Sphere(1, Primitive.GENERATE_NORMALS, divisions, aAppear); + //objTransform.addChild(atomicSphere); + + Shape3D shape = atomicSphere.getShape(); + + shape.setCapability(Shape3D.ALLOW_APPEARANCE_READ); + shape.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_READ); + shape.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); + shape.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_WRITE); + atomicSphere.setCapability(Group.ALLOW_CHILDREN_READ); + atomicSphere.setCapability(Group.ALLOW_CHILDREN_WRITE); + atomicSphere.setCapability(Group.ALLOW_CHILDREN_EXTEND); + atomicSphere.setCapability(Node.ALLOW_PICKABLE_READ); + atomicSphere.setCapability(Primitive.ENABLE_APPEARANCE_MODIFY); + + shape.setAppearanceOverrideEnable(true); + + return atomicSphere; + } + + public Sphere getAtomicSphere() { + return atomicSphere; + } + + /** + * returns sphere radius for drawing an atom + * + * @param atom AtomInterface + * @return float + */ + public static float getAtomicSphereRadius(AtomInterface atom) { + + float radius = ChemicalElements.getCovalentRadius(atom.getAtomicNumber()); + radius *= AtomInterface.COVALENT_TO_GRADIUS_FACTOR; + Float R = (Float) atom.getProperty(AtomInterface.GR_RADIUS); + if (R != null) { + radius = R; + } + + if (radius < 0.001f) { + radius = 0.2f; + } + atom.setProperty(AtomInterface.GR_RADIUS, new Float(radius)); // GR_RADIUS "gradius" is a "graphics radius" + + return radius; + } + + public AtomInterface getAtomInterface() { + return atom; + } + + public float getAtomicSphereRadius() { + return sphereRadius; + } + + public Material getMaterial() { + return atomMaterial; + } + + public void setAtomicSphereRadius(float radius) { + try { + int style = getRenderingStyle(atom); + + if (style == AtomInterface.RENDER_SPHERE && style == this.renderingStyle) { + sphereRadius = radius; + //t3d = new Transform3D(); + objTransform.getTransform(t3d); + t3d.setScale(sphereRadius); + objTransform.setTransform(t3d); + //******************************************************************** + } else if (style == AtomInterface.RENDER_SPHERE) { + renderingStyle = style; + sphereRadius = radius; + + objTransform.getTransform(t3d); + t3d.setScale(sphereRadius); + objTransform.setTransform(t3d); + + if (useSwitch) { + BranchGroup bg = switchShapes.get(J3D_ATOM_PROPERTY.SPHERE_3D); + if (bg == null) { + bg = new BranchGroup(); + atomicSphere = createAtomicSphere(atom); + bg.addChild(atomicSphere); + switchShapes.put(J3D_ATOM_PROPERTY.SPHERE_3D, bg); + showSwitch.addChild(bg); + switchIndex.put(bg, showSwitch.numChildren() - 1); + } + showSwitch.setWhichChild(switchIndex.get(bg)); + } else { + removeAllChildren(); + + atomicSphere = createAtomicSphere(atom); + rootBranch = this.getRootBranch(); + rootBranch.addChild(objTransform); + + addChild(rootBranch); + } + //***************************************************************************** + } else if (style == AtomInterface.RENDER_SMART_POINT && style == this.renderingStyle) { + //********************************************************************************* + } else if (style == AtomInterface.RENDER_SMART_POINT && renderingStyle == AtomInterface.RENDER_SPHERE) { + renderingStyle = style; + + if (!useSwitch) { + removeAllChildren(); + + objTransform = this.getTransformGroup(t3d); + rootBranch = this.getRootBranch(); + rootBranch.addChild(objTransform); + + addChild(rootBranch); + } + + Node point; + if (useSwitch) { + if (isRenderPoint()) { + BranchGroup bg = switchShapes.get(J3D_ATOM_PROPERTY.POINT_3D); + if (bg == null) { + bg = new BranchGroup(); + point = createAtomicPoint(pointSize, atomColor); + bg.addChild(point); + switchShapes.put(J3D_ATOM_PROPERTY.POINT_3D, bg); + showSwitch.addChild(bg); + switchIndex.put(bg, showSwitch.numChildren() - 1); + } else { + } + showSwitch.setWhichChild(switchIndex.get(bg)); + } else { + //point = switchShapes.get(J3D_ATOM_PROPERTY.NOTHING); + //if (point == null) { + // point = new Group(); + // switchShapes.put(J3D_ATOM_PROPERTY.NOTHING, point); + // showSwitch.addChild(point); + // switchIndex.put(point, showSwitch.numChildren() - 1); + //} + showSwitch.setWhichChild(Switch.CHILD_NONE); + } + } else { + point = renderPointIfNecessary(); + if (point != null) { + objTransform.addChild(point); + } + } + } + + /* + * TransformGroup scale = getAtomicSphereScale(atom_node); Transform3D value = new Transform3D(); value.setScale(radius); + * scale.setTransform(value); + */ + } catch (Exception ex) { + logger.warning("Exception: " + ex.getMessage()); + } + } + + public void setAtomColor(Color3f new_color, Material new_material) { + + aAppear.setMaterial(new_material); + + atomColor = new Color3f(new_color); + + atom.setProperty(AtomInterface.RGB_COLOR, new Integer[]{new_color.get().getRed(), new_color.get().getGreen(), + new_color.get().getBlue()}); + } + + public void setAtomColor(Color new_color) { + Color3f color3f = new Color3f(new_color); + setAtomColor(color3f); + } + + public void setAtomColor(Color3f new_color) { + if (atomColor == null) { + atomColor = new Color3f(new_color); + } else { + atomColor.set(new_color.x, new_color.y, new_color.z); + } + + atom.setProperty(AtomInterface.RGB_COLOR, new Integer[]{new_color.get().getRed(), new_color.get().getGreen(), + new_color.get().getBlue()}); + + atomMaterial = ChemicalElementsColors.createMaterial(atomColor); + atomMaterial.setCapability(Material.ALLOW_COMPONENT_READ); + atomMaterial.setCapability(Material.ALLOW_COMPONENT_WRITE); + + if (!aAppear.getCapability(Appearance.ALLOW_MATERIAL_WRITE)) { + aAppear.setCapability(Appearance.ALLOW_MATERIAL_WRITE); + } + if (!aAppear.getCapability(Appearance.ALLOW_COLORING_ATTRIBUTES_WRITE)) { + aAppear.setCapability(Appearance.ALLOW_COLORING_ATTRIBUTES_WRITE); + } + if (atomMaterial.getCapability(Material.ALLOW_COMPONENT_WRITE)) { + atomMaterial.setCapability(Material.ALLOW_COMPONENT_WRITE); + } + + aAppear.setMaterial(atomMaterial); + } + + public Color3f getColor3f() { + return atomColor; + } + + public void setAtomicCoordinates(AtomInterface atom) { + + xyz[0] = atom.getX(); + xyz[1] = atom.getY(); + xyz[2] = atom.getZ(); + + if (renderingStyle == AtomInterface.RENDER_SPHERE) { + + objTransform.getTransform(t3d); + t3d.set(new Vector3f(xyz)); + t3d.setScale(sphereRadius); + + //t3d.set(xyz); + objTransform.setTransform(t3d); + } else if (renderingStyle == AtomInterface.RENDER_SMART_POINT && atomPoint != null) { + atomPoint.setCoordinate(0, + new Point3f(atom.getX(), atom.getY(), + atom.getZ())); + } + } + + public void setAtomicCoordinates(float[] coord) { + + xyz[0] = coord[0]; + xyz[1] = coord[1]; + xyz[2] = coord[2]; + + objTransform.getTransform(t3d); + t3d.set(new Vector3f(xyz)); + t3d.setScale(sphereRadius); + objTransform.setTransform(t3d); + } + + static public int getRenderingStyle(AtomInterface a) { + int rendering_style = AtomInterface.RENDER_SPHERE; + Object obj = a.getProperty(AtomInterface.RENDERING_STYLE); + if (obj != null && obj instanceof Integer) { + rendering_style = (Integer) obj; + } + return rendering_style; + } + + static public Color3f getAtomColor(AtomInterface a) { + Object obj = a.getProperty(AtomInterface.RGB_COLOR); + Color3f color; + if (obj != null && obj instanceof Integer[]) { + Integer[] rgbColor = (Integer[]) obj; + color = new Color3f(rgbColor[0].floatValue() / 255.0f, + rgbColor[1].floatValue() / 255.0f, + rgbColor[2].floatValue() / 255.0f); + } else { + color = ChemicalElementsColors.getElementColor(a.getAtomicNumber()); + Integer[] rgbColor = new Integer[3]; + rgbColor[0] = (int) (color.x * 255.0f); + rgbColor[1] = (int) (color.y * 255.0f); + rgbColor[2] = (int) (color.z * 255.0f); + a.setProperty(AtomInterface.RGB_COLOR, rgbColor); + } + return color; + } + + public boolean isHighlighted() { + return highlighted; + } + + public void highlightAtom(boolean highlight) { + + if (highlighted && highlight) { + return; + } + if ((!highlighted) && (!highlight)) { + return; + } + + highlighted = highlight; + + int rendering_style = getRenderingStyle(atom); + if (rendering_style != this.renderingStyle) { + this.renderingStyle = rendering_style; + } + + if (highlight && renderingStyle == AtomInterface.RENDER_SPHERE) { + aAppear.setMaterial(ChemicalElementsColors.getHighlightMaterial()); + atomicSphere.setAppearance(aAppear); + } else if (highlight && renderingStyle == AtomInterface.RENDER_SMART_POINT) { + + if (atomShape != null) { + pointAttributes.setPointSize(highlightPointSize); + aAppear.setPointAttributes(pointAttributes); + atomShape.removeAllGeometries(); + atomPoint = new PointArray(1, GeometryArray.COORDINATES | GeometryArray.COLOR_3); + + atomPoint.setCapability(GeometryArray.ALLOW_COLOR_READ); + atomPoint.setCapability(GeometryArray.ALLOW_COLOR_WRITE); + atomPoint.setCapability(GeometryArray.ALLOW_COORDINATE_READ); + atomPoint.setCapability(GeometryArray.ALLOW_COORDINATE_WRITE); + + //atomPoint.setCoordinate(0, new Point3f(atom.getX(), atom.getY(), atom.getZ())); + atomPoint.setCoordinate(0, new Point3f(0, 0, 0)); // --- Location is already in transform3d + + atomPoint.setColor(0, ChemicalElementsColors.getHighlightColor3f()); + atomShape.setGeometry(atomPoint); + atomShape.setAppearance(aAppear); + + } else { + Node point; + if (this.useSwitch) { + BranchGroup bg = switchShapes.get(J3D_ATOM_PROPERTY.POINT_3D); + if (bg == null) { + point = createAtomicPoint(pointSize, atomColor); + bg = new BranchGroup(); + bg.addChild(point); + switchShapes.put(J3D_ATOM_PROPERTY.POINT_3D, bg); + showSwitch.addChild(bg); + switchIndex.put(bg, showSwitch.numChildren() - 1); + } + showSwitch.setWhichChild(switchIndex.get(bg)); + } else { + point = createAtomicPoint(highlightPointSize, ChemicalElementsColors.getHighlightColor3f()); + objTransform.addChild(point); + } + + } + } else if ((!highlight) && renderingStyle == AtomInterface.RENDER_SMART_POINT) { + objTransform.removeAllChildren(); + renderPointIfNecessary(); + } else if ((!highlight) && renderingStyle == AtomInterface.RENDER_SPHERE) { + aAppear.setMaterial(atomMaterial); + atomicSphere.setAppearance(aAppear); + } + + } + + @Override + public Object clone() throws CloneNotSupportedException { + super.clone(); + AtomNode atom_node = null; + if (atom == null) { + atom_node = new AtomNode(sphereRadius, xyz[0], xyz[1], xyz[2], numberDivisions, atomColor, atomMaterial); + } else { + atom_node = new AtomNode(atom, numberDivisions); + } + return atom_node; + } + + private BranchGroup getRootBranch() { + BranchGroup root = new BranchGroup(); + root.setCapability(Group.ALLOW_CHILDREN_READ); + root.setCapability(Group.ALLOW_CHILDREN_WRITE); + root.setCapability(Group.ALLOW_CHILDREN_EXTEND); + root.setCapability(BranchGroup.ALLOW_DETACH); + return root; + } + + private TransformGroup getTransformGroup() { + TransformGroup tg = new TransformGroup(); + tg.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); + tg.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + tg.setCapability(Group.ALLOW_CHILDREN_READ); + tg.setCapability(Group.ALLOW_CHILDREN_WRITE); + //tg.setName("Atom"); // --- >1.4 java3d feature + return tg; + } + + private TransformGroup getTransformGroup(Transform3D t3d) { + TransformGroup tg = new TransformGroup(t3d); + tg.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); + tg.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + tg.setCapability(Group.ALLOW_CHILDREN_READ); + tg.setCapability(Group.ALLOW_CHILDREN_WRITE); + //tg.setName("Atom"); // --- >1.4 java3d feature + return tg; + } +} diff --git a/src/main/java/cct/j3d/BondNode.java b/src/main/java/cct/j3d/BondNode.java new file mode 100644 index 0000000..03992cf --- /dev/null +++ b/src/main/java/cct/j3d/BondNode.java @@ -0,0 +1,924 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import org.scijava.java3d.Appearance; +import org.scijava.java3d.BranchGroup; +import org.scijava.java3d.ColoringAttributes; +import org.scijava.java3d.GeometryArray; +import org.scijava.java3d.Group; +import org.scijava.java3d.LineArray; +import org.scijava.java3d.Material; +import org.scijava.java3d.Node; +import org.scijava.java3d.PolygonAttributes; +import org.scijava.java3d.Shape3D; +import org.scijava.java3d.Transform3D; +import org.scijava.java3d.TransformGroup; +import org.scijava.vecmath.AxisAngle4f; +import org.scijava.vecmath.Color3f; +import org.scijava.vecmath.Point3f; +import org.scijava.vecmath.Vector3d; +import org.scijava.vecmath.Vector3f; + +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; +import cct.modelling.ChemicalElements; + +import org.scijava.java3d.utils.geometry.Cylinder; +import org.scijava.java3d.utils.geometry.Primitive; +import java.util.HashMap; +import java.util.Map; +import org.scijava.java3d.*; + +/** + * + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class BondNode + extends BranchGroup implements Cloneable { + + enum BOND_TYPE { LINE, CYLINDER } + + protected boolean delete = false; + //int bondColoring = MONOCOLOR; + int bondColoring = BondInterface.BICOLOR; + int renderingStyle; + int colorScheme; + float cylinderRadius = BondInterface.DEFAULT_BONDS_AND_STICKS_RADIUS; + + BranchGroup rootBranch = null; + Color3f defaultMonoColor = new Color3f(1.0f, 0.5f, 0.7f); + Point3f coord = new Point3f(); + Point3f[] coordinates = null; + LineArray lineBond; + Shape3D line_shape = null; + Shape3D shape; + private float vX, vY, vZ; + private float angle; + private AxisAngle4f rot = new AxisAngle4f(); + private BondInterface bond = null; + + boolean useSwitch = true; + private Switch showSwitch = new Switch(); + private Map switchShapes = new HashMap(); + private Map switchIndex = new HashMap(); + + BondNode() { + super(); + //setName("Bond"); // --- >1.4 java3d feature + } + + BondNode(BondInterface b) { + this(b, BondInterface.BICOLOR); + } + + BondNode(BondInterface b, int bondFormat) { + super(); + //setName("Bond "); // --- >1.4 java3d feature + + if (bondFormat == BondInterface.CYLINDER_BICOLOR) { + bondColoring = BondInterface.BICOLOR; + renderingStyle = BondInterface.CYLINDER_BICOLOR; + colorScheme = BondInterface.BICOLOR; + } + else if (bondFormat == BondInterface.CYLINDER_MONOCOLOR) { + bondColoring = BondInterface.MONOCOLOR; + renderingStyle = BondInterface.CYLINDER_MONOCOLOR; + colorScheme = BondInterface.MONOCOLOR; + } + else if (bondFormat == BondInterface.LINE_MONOCOLOR) { + bondColoring = BondInterface.MONOCOLOR; + renderingStyle = BondInterface.LINE_MONOCOLOR; + colorScheme = BondInterface.MONOCOLOR; + } + else if (bondFormat == BondInterface.LINE_BICOLOR) { + bondColoring = BondInterface.BICOLOR; + renderingStyle = BondInterface.LINE_BICOLOR; + colorScheme = BondInterface.BICOLOR; + } + + b.setProperty(BondInterface.RENDERING_STYLE, new Integer(bondFormat)); + + bond = b; + setCapability(Group.ALLOW_CHILDREN_READ); + setCapability(Group.ALLOW_CHILDREN_WRITE); + setCapability(Group.ALLOW_CHILDREN_EXTEND); + setCapability(BranchGroup.ALLOW_DETACH); + setPickable(false); + + rootBranch = getRootBranch(); + + //gAtom a1 = (gAtom) b.getI(); + //gAtom a2 = (gAtom) b.getJ(); + AtomInterface a1 = b.getIAtomInterface(); + AtomInterface a2 = b.getJAtomInterface(); + + // Adjust bond radius. Should be <= then the smalest atomic radius + + Float R = (Float) b.getProperty(BondInterface.CYLINDER_RADIUS); + if (R != null) { + cylinderRadius = R; + } + + float r1 = ChemicalElements.getCovalentRadius(a1.getAtomicNumber()); + r1 *= AtomInterface.COVALENT_TO_GRADIUS_FACTOR; + R = (Float) a1.getProperty(AtomInterface.GR_RADIUS); + if (R != null) { + r1 = R; + } + + cylinderRadius = Math.min(r1, cylinderRadius); + + r1 = ChemicalElements.getCovalentRadius(a2.getAtomicNumber()); + r1 *= AtomInterface.COVALENT_TO_GRADIUS_FACTOR; + R = (Float) a1.getProperty(AtomInterface.GR_RADIUS); + if (R != null) { + r1 = R; + } + + cylinderRadius = Math.min(r1, cylinderRadius); + + b.setProperty(BondInterface.CYLINDER_RADIUS, new Float(cylinderRadius)); + + if (bondFormat == BondInterface.CYLINDER_MONOCOLOR) { + renderingStyle = BondInterface.CYLINDER_MONOCOLOR; + colorScheme = BondInterface.MONOCOLOR; + + TransformGroup atg = createMonoCylinder(bond); + rootBranch.addChild(atg); + addChild(rootBranch); + } + else if (bondFormat == BondInterface.LINE_MONOCOLOR) { + renderingStyle = BondInterface.LINE_MONOCOLOR; + colorScheme = BondInterface.MONOCOLOR; + + // Setup bonds + + shape = getMonocolorLine(bond); + rootBranch.addChild(shape); + addChild(rootBranch); + + //addChild(shape); + } + + else if (bondFormat == BondInterface.LINE_BICOLOR) { + renderingStyle = BondInterface.LINE_BICOLOR; + colorScheme = BondInterface.BICOLOR; + + // Setup bonds + + shape = getBicolorLine(bond); + rootBranch.addChild(shape); + addChild(rootBranch); + } + + // --- Bicolor scheme + else if (bondFormat == BondInterface.CYLINDER_BICOLOR) { + renderingStyle = BondInterface.CYLINDER_BICOLOR; + colorScheme = BondInterface.BICOLOR; + + getOrientation(a1, a2); + + // --- First cylinder + + TransformGroup atg = getFirstCylinder(bond); + rootBranch.addChild(atg); + + // --- Second cylinder + + atg = getSecondCylinder(bond); + rootBranch.addChild(atg); + + addChild(rootBranch); + } + + setNodeName("Bond_" + ChemicalElements.getElementSymbol(a1.getAtomicNumber()) + "_" + + ChemicalElements.getElementSymbol(a2.getAtomicNumber())); + } + + public BondInterface getBond() { + return bond; + } + + public void setNodeName(String name) { + if (rootBranch.numChildren() < 1) { + return; + } + for (int i = 0; i < rootBranch.numChildren(); i++) { + Node child = rootBranch.getChild(i); + UserData.setUserData(child, UserData.NODE_NAME, name); + } + } + + Shape3D getMonocolorLine(BondInterface b) { + AtomInterface a1 = b.getIAtomInterface(); + AtomInterface a2 = b.getJAtomInterface(); + + lineBond = new LineArray(2, GeometryArray.COORDINATES | GeometryArray.COLOR_3); + + lineBond.setCapability(GeometryArray.ALLOW_COLOR_READ); + lineBond.setCapability(GeometryArray.ALLOW_COLOR_WRITE); + lineBond.setCapability(GeometryArray.ALLOW_COORDINATE_READ); + lineBond.setCapability(GeometryArray.ALLOW_COORDINATE_WRITE); + lineBond.setCapability(GeometryArray.ALLOW_COUNT_READ); + lineBond.setCapability(GeometryArray.ALLOW_COUNT_WRITE); + lineBond.setCapability(GeometryArray.ALLOW_VERTEX_ATTR_READ); + lineBond.setCapability(GeometryArray.ALLOW_VERTEX_ATTR_WRITE); + + coordinates = new Point3f[2]; + coordinates[0] = new Point3f(a1.getX(), a1.getY(), a1.getZ()); + coordinates[1] = new Point3f(a2.getX(), a2.getY(), a2.getZ()); + lineBond.setCoordinates(0, coordinates); + lineBond.setColor(0, defaultMonoColor); + lineBond.setColor(1, defaultMonoColor); + + line_shape = new Shape3D(); + line_shape.setGeometry(lineBond); + line_shape.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_READ); + line_shape.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_WRITE); + line_shape.setCapability(Shape3D.ALLOW_APPEARANCE_READ); + line_shape.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); + line_shape.setCapability(Shape3D.ALLOW_GEOMETRY_READ); + line_shape.setCapability(Shape3D.ALLOW_GEOMETRY_WRITE); + + int rgb_color[] = { + defaultMonoColor.get().getRed(), defaultMonoColor.get().getGreen(), defaultMonoColor.get().getBlue()}; + b.setProperty(BondInterface.RGB_COLOR, rgb_color); + + return line_shape; + } + + Shape3D getBicolorLine(BondInterface b) { + AtomInterface a1 = b.getIAtomInterface(); + AtomInterface a2 = b.getJAtomInterface(); + + lineBond = new LineArray(4, GeometryArray.COORDINATES | GeometryArray.COLOR_3); + + lineBond.setCapability(GeometryArray.ALLOW_COLOR_READ); + lineBond.setCapability(GeometryArray.ALLOW_COLOR_WRITE); + lineBond.setCapability(GeometryArray.ALLOW_COORDINATE_READ); + lineBond.setCapability(GeometryArray.ALLOW_COORDINATE_WRITE); + lineBond.setCapability(GeometryArray.ALLOW_COUNT_READ); + lineBond.setCapability(GeometryArray.ALLOW_COUNT_WRITE); + lineBond.setCapability(GeometryArray.ALLOW_VERTEX_ATTR_READ); + lineBond.setCapability(GeometryArray.ALLOW_VERTEX_ATTR_WRITE); + + coordinates = new Point3f[4]; + coordinates[0] = new Point3f(a1.getX(), a1.getY(), a1.getZ()); + coordinates[1] = new Point3f(a1.getX() + + (a2.getX() - a1.getX()) / 2.0f, + a1.getY() + + (a2.getY() - a1.getY()) / 2.0f, + a1.getZ() + + (a2.getZ() - a1.getZ()) / 2.0f); + coordinates[2] = new Point3f(a1.getX() + + (a2.getX() - a1.getX()) / 2.0f, + a1.getY() + + (a2.getY() - a1.getY()) / 2.0f, + a1.getZ() + + (a2.getZ() - a1.getZ()) / 2.0f + ); + + coordinates[3] = new Point3f(a2.getX(), a2.getY(), a2.getZ()); + lineBond.setCoordinates(0, coordinates); + + Color3f color = this.getColor3f(a1); + lineBond.setColor(0, color); + lineBond.setColor(1, color); + color = this.getColor3f(a2); + lineBond.setColor(2, color); + lineBond.setColor(3, color); + + Shape3D line_shape = new Shape3D(); + line_shape.setGeometry(lineBond); + return line_shape; + } + + TransformGroup getSecondCylinder(BondInterface b) { + // --- Second cylinder + AtomInterface a1 = b.getIAtomInterface(); + AtomInterface a2 = b.getJAtomInterface(); + + Transform3D move = new Transform3D(); + move.setScale(new Vector3d(cylinderRadius, b.bondLength() / 2, + cylinderRadius)); + move.setRotation(rot); + move.setTranslation(new Vector3f( (a1.getX() + + 0.75f * b.bondLength() * vX), + (a1.getY() + + 0.75f * b.bondLength() * vY), + (a1.getZ() + + 0.75f * b.bondLength() * vZ))); + + TransformGroup atg = new TransformGroup(move); + atg.setCapability(Group.ALLOW_CHILDREN_READ); + atg.setCapability(Group.ALLOW_CHILDREN_WRITE); + atg.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); + atg.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + //atg.setName("Bond"); // --- >1.4 java3d feature + + Appearance aAppear = getAppearance(a2); + + // Setup bonds + + //Cylinder cyl = new Cylinder(0.15f, b.bondLength(), aAppear); + Cylinder cyl = createCylinder(1, 1, aAppear); + + atg.addChild(cyl); + return atg; + } + + TransformGroup getFirstCylinder(BondInterface b) { + // --- First cylinder + AtomInterface a1 = b.getIAtomInterface(); + + Transform3D move = new Transform3D(); + move.setScale(new Vector3d(cylinderRadius, 0.5 * b.bondLength(), + cylinderRadius)); + move.setRotation(rot); + move.setTranslation(new Vector3f( (a1.getX() + + 0.25f * b.bondLength() * vX), + (a1.getY() + + 0.25f * b.bondLength() * vY), + (a1.getZ() + + 0.25f * b.bondLength() * vZ))); + + TransformGroup atg = new TransformGroup(move); + atg.setCapability(Group.ALLOW_CHILDREN_READ); + atg.setCapability(Group.ALLOW_CHILDREN_WRITE); + atg.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); + atg.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + //atg.setName("Bond"); // --- >1.4 java3d feature + + Appearance aAppear = getAppearance(a1); + + // Setup bonds + + //Cylinder cyl = new Cylinder(0.15f, b.bondLength(), aAppear); + Cylinder cyl = createCylinder(1, 1, aAppear); + + atg.addChild(cyl); + return atg; + } + + /** + * Creates TransformGroup with a cylinder for monocolored bond + * @param b BondInterface + * @return TransformGroup + */ + TransformGroup createMonoCylinder(BondInterface b) { + AtomInterface a1 = b.getIAtomInterface(); + AtomInterface a2 = b.getJAtomInterface(); + + getOrientation(a1, a2); + + Transform3D move = new Transform3D(); + move.setScale(new Vector3d(cylinderRadius, b.bondLength(), + cylinderRadius)); + move.setRotation(rot); + move.setTranslation(new Vector3f( (a1.getX() + + 0.5f * b.bondLength() * vX), + (a1.getY() + + 0.5f * b.bondLength() * vY), + (a1.getZ() + + 0.5f * b.bondLength() * vZ))); + + TransformGroup atg = new TransformGroup(move); + atg.setCapability(Group.ALLOW_CHILDREN_READ); + atg.setCapability(Group.ALLOW_CHILDREN_WRITE); + atg.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); + atg.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + //atg.setName("Bond"); // --- >1.4 java3d feature + + ColoringAttributes ca = new ColoringAttributes(); + ca.setColor(defaultMonoColor); + + int rgb_color[] = { + defaultMonoColor.get().getRed(), defaultMonoColor.get().getGreen(), defaultMonoColor.get().getBlue()}; + b.setProperty(BondInterface.RGB_COLOR, rgb_color); + + Appearance aAppear = new Appearance(); + aAppear.setColoringAttributes(ca); + + Material material = ChemicalElementsColors.getElementMaterial(0); + aAppear.setMaterial(material); + + PolygonAttributes polyAppear = new PolygonAttributes(); + polyAppear.setCullFace(PolygonAttributes.CULL_BACK); + + aAppear.setPolygonAttributes(polyAppear); + + // Setup bonds + + Cylinder cyl = createCylinder(1, 1, aAppear); + + atg.addChild(cyl); + return atg; + } + + LineArray createLine() { + LineArray line = new LineArray(2, + GeometryArray.COORDINATES | GeometryArray.COLOR_3); + line.setCapability(GeometryArray.ALLOW_COLOR_READ); + line.setCapability(GeometryArray.ALLOW_COLOR_WRITE); + line.setCapability(GeometryArray.ALLOW_COORDINATE_READ); + line.setCapability(GeometryArray.ALLOW_COORDINATE_WRITE); + return line; + } + + Cylinder createCylinder(float radius, float height, Appearance ap) { + Cylinder cyl = new Cylinder(radius, height, ap); + cyl.setCapability(Primitive.ENABLE_APPEARANCE_MODIFY); + cyl.setCapability(Primitive.ENABLE_APPEARANCE_MODIFY); + Shape3D shape = cyl.getShape(Cylinder.BODY); + shape.setCapability(Shape3D.ALLOW_APPEARANCE_READ); + shape.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); + shape = cyl.getShape(Cylinder.BOTTOM); + shape.setCapability(Shape3D.ALLOW_APPEARANCE_READ); + shape.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); + shape = cyl.getShape(Cylinder.TOP); + shape.setCapability(Shape3D.ALLOW_APPEARANCE_READ); + shape.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); + + return cyl; + } + + Appearance getAppearance(AtomInterface atom) { + ColoringAttributes ca = new ColoringAttributes(); + ca.setCapability(ColoringAttributes.ALLOW_COLOR_READ); + ca.setCapability(ColoringAttributes.ALLOW_COLOR_WRITE); + + Color3f a1_color = null; + Object obj = atom.getProperty(AtomInterface.RGB_COLOR); + if (obj != null && obj instanceof Integer[]) { + Integer[] rgbColor = (Integer[]) obj; + a1_color = new Color3f(rgbColor[0].floatValue() / 255.0f, + rgbColor[1].floatValue() / 255.0f, + rgbColor[2].floatValue() / 255.0f); + } + else { + a1_color = ChemicalElementsColors.getElementColor(atom. + getAtomicNumber()); + } + + ca.setColor(a1_color); + Appearance aAppear = new Appearance(); + aAppear.setCapability(Appearance.ALLOW_COLORING_ATTRIBUTES_READ); + aAppear.setCapability(Appearance.ALLOW_COLORING_ATTRIBUTES_WRITE); + aAppear.setCapability(Appearance.ALLOW_MATERIAL_READ); + aAppear.setCapability(Appearance.ALLOW_MATERIAL_WRITE); + aAppear.setColoringAttributes(ca); + + Material material = ChemicalElementsColors.createMaterial(a1_color); + aAppear.setMaterial(material); + + PolygonAttributes polyAppear = new PolygonAttributes(); + polyAppear.setCullFace(PolygonAttributes.CULL_BACK); + + aAppear.setPolygonAttributes(polyAppear); + return aAppear; + } + + Color3f getColor3f(AtomInterface atom) { + Color3f a1_color = null; + Object obj = atom.getProperty(AtomInterface.RGB_COLOR); + if (obj != null && obj instanceof Integer[]) { + Integer[] rgbColor = (Integer[]) obj; + a1_color = new Color3f(rgbColor[0].floatValue() / 255.0f, + rgbColor[1].floatValue() / 255.0f, + rgbColor[2].floatValue() / 255.0f); + } + else { + a1_color = ChemicalElementsColors.getElementColor(atom. + getAtomicNumber()); + } + + return a1_color; + } + + private void getOrientation(AtomInterface a1, AtomInterface a2) { + + // Get orientation + vX = a2.getX() - a1.getX(); + vY = a2.getY() - a1.getY(); + vZ = a2.getZ() - a1.getZ(); + float norm = (float) Math.sqrt(vX * vX + vY * vY + vZ * vZ); + vX /= norm; + vY /= norm; + vZ /= norm; + + angle = (float) Math.acos(vY); + rot.set(vZ, 0.0f, -vX, angle); + } + + private void getOrientation(float[] a1, float[] a2) { + + // Get orientation + vX = a2[0] - a1[0]; + vY = a2[1] - a1[1]; + vZ = a2[2] - a1[2]; + float norm = (float) Math.sqrt(vX * vX + vY * vY + vZ * vZ); + vX /= norm; + vY /= norm; + vZ /= norm; + + angle = (float) Math.acos(vY); + rot.set(vZ, 0.0f, -vX, angle); + } + + public boolean isToDelete() { + return delete; + } + + public void markForDeletion(boolean flag) { + delete = flag; + } + + public void updateBond() { + AtomInterface a1 = bond.getIAtomInterface(); + AtomInterface a2 = bond.getJAtomInterface(); + + float[] v1 = { + a1.getX(), a1.getY(), a1.getZ()}; + float[] v2 = { + a2.getX(), a2.getY(), a2.getZ()}; + updateTransform3D(v1, v2); + } + + public void updateBond(float[] a1, float[] a2) { + updateTransform3D(a1, a2); + } + + Cylinder getCylinder(int i) { + if (i < 0) { + return null; + } + TransformGroup atg = (TransformGroup) rootBranch.getChild(i); + Object obj = atg.getChild(0); + if (obj == null) { + return null; + } + if (! (obj instanceof Cylinder)) { + return null; + } + return (Cylinder) obj; + } + + /* + void updateBondLength(float height) { + + if (numChildren() < 1) { + return; + } + + if (renderingStyle == BondInterface.RENDER_CYLINDER && + bondColoring == BondInterface.MONOCOLOR) { + + TransformGroup atg = (TransformGroup) rootBranch.getChild(0); // !!1 Only 1 child now + Cylinder cyl = (Cylinder) atg.getChild(0); // !!! Only 1 child now + float radius = cyl.getRadius(); + + atg.removeChild(cyl); + + Appearance aAppear = cyl.getAppearance(); + cyl = new Cylinder(radius, height, aAppear); + cyl.setCapability(Cylinder.ENABLE_APPEARANCE_MODIFY); + cyl.setCapability(Primitive.ENABLE_APPEARANCE_MODIFY); + + atg.addChild(cyl); + + } + + } + */ + void updateBondColor() { + if (bondColoring == BondInterface.MONOCOLOR) { + return; + } + AtomInterface a1 = bond.getIAtomInterface(); + AtomInterface a2 = bond.getJAtomInterface(); + + if (renderingStyle == BondInterface.CYLINDER_BICOLOR || renderingStyle == BondInterface.CYLINDER_MONOCOLOR) { + + Cylinder cylinder = getCylinder(0); + Appearance atomAppear = getAppearance(a1); + ColoringAttributes ca = atomAppear.getColoringAttributes(); + Color3f color = new Color3f(); + ca.getColor(color); + Material material = atomAppear.getMaterial(); + + Appearance cylAppear = cylinder.getAppearance(); + ColoringAttributes cylCA = cylAppear.getColoringAttributes(); + cylCA.setColor(color); + cylAppear.setMaterial(material); + + cylinder = getCylinder(1); + atomAppear = this.getAppearance(a2); + ca = atomAppear.getColoringAttributes(); + color = new Color3f(); + ca.getColor(color); + material = atomAppear.getMaterial(); + + cylAppear = cylinder.getAppearance(); + cylCA = cylAppear.getColoringAttributes(); + cylCA.setColor(color); + cylAppear.setMaterial(material); + } + else if (renderingStyle == BondInterface.LINE_BICOLOR || renderingStyle == BondInterface.LINE_MONOCOLOR) { + + Color3f color = this.getColor3f(a1); + lineBond.setColor(0, color); + lineBond.setColor(1, color); + color = this.getColor3f(a2); + lineBond.setColor(2, color); + lineBond.setColor(3, color); + + } + } + + void updateBondRadius() { + Object obj; + + obj = bond.getProperty(BondInterface.VISIBLE); + if (obj != null && obj instanceof Boolean && ! ( (Boolean) obj).booleanValue()) { + this.removeAllChildren(); + return; + } + + obj = bond.getProperty(BondInterface.RENDERING_STYLE); + int rendering_style = renderingStyle; + if (obj != null && obj instanceof Integer) { + rendering_style = (Integer) obj; + } + + obj = bond.getProperty(BondInterface.COLOR_SCHEME); + if (obj != null && obj instanceof Integer) { + colorScheme = (Integer) obj; + } + + if ( (rendering_style == BondInterface.CYLINDER_BICOLOR || rendering_style == BondInterface.CYLINDER_MONOCOLOR) && + this.numChildren() > 0 && + rootBranch.getChild(0) instanceof TransformGroup) { + + renderingStyle = rendering_style; + + obj = bond.getProperty(BondInterface.CYLINDER_RADIUS); + if (obj != null) { + Float R = (Float) obj; + cylinderRadius = R; + } + + if (bondColoring == BondInterface.MONOCOLOR) { + Transform3D move = new Transform3D(); + TransformGroup atg = (TransformGroup) rootBranch.getChild(0); + atg.getTransform(move); + move.setScale(new Vector3d(cylinderRadius, bond.bondLength(), cylinderRadius)); + atg.setTransform(move); + } + else if (bondColoring == BondInterface.BICOLOR) { + Transform3D move = new Transform3D(); + TransformGroup atg = (TransformGroup) rootBranch.getChild(0); + atg.getTransform(move); + move.setScale(new Vector3d(cylinderRadius, bond.bondLength() / 2, cylinderRadius)); + atg.setTransform(move); + move = new Transform3D(); + atg = (TransformGroup) rootBranch.getChild(1); + atg.getTransform(move); + move.setScale(new Vector3d(cylinderRadius, bond.bondLength() / 2, cylinderRadius)); + atg.setTransform(move); + } + } + + else if (rendering_style == BondInterface.CYLINDER_BICOLOR || rendering_style == BondInterface.CYLINDER_MONOCOLOR) { //&& + //! (rootBranch.getChild(0) instanceof TransformGroup)) { + //rendering_style != renderingStyle) { + renderingStyle = rendering_style; + + obj = bond.getProperty(BondInterface.CYLINDER_RADIUS); + if (obj != null) { + Float R = (Float) obj; + cylinderRadius = R; + } + + if (colorScheme == BondInterface.BICOLOR) { + removeAllChildren(); + AtomInterface a1 = bond.getIAtomInterface(); + AtomInterface a2 = bond.getJAtomInterface(); + + getOrientation(a1, a2); + + rootBranch = null; + rootBranch = this.getRootBranch(); + + // --- First cylinder + + TransformGroup atg = getFirstCylinder(bond); + rootBranch.addChild(atg); + + // --- Second cylinder + + atg = getSecondCylinder(bond); + rootBranch.addChild(atg); + + addChild(rootBranch); + } + else if (colorScheme == BondInterface.MONOCOLOR) { + TransformGroup atg = createMonoCylinder(bond); + removeAllChildren(); + rootBranch = this.getRootBranch(); + rootBranch.addChild(atg); + addChild(rootBranch); + } + } + + /* + else if (rendering_style == BondInterface.RENDER_LINE && + rendering_style == renderingStyle) { + + if (colorScheme == BondInterface.BICOLOR) { + + } + else if (colorScheme == BondInterface.MONOCOLOR) { + + } + + } + */ + + // Not elegant but simple + else if (rendering_style == BondInterface.LINE_BICOLOR || rendering_style == BondInterface.LINE_MONOCOLOR) { //&& + //rendering_style != renderingStyle) { + + renderingStyle = rendering_style; + + if (colorScheme == BondInterface.BICOLOR) { + removeAllChildren(); + rootBranch = this.getRootBranch(); + shape = getBicolorLine(bond); + rootBranch.addChild(shape); + addChild(rootBranch); + } + else if (colorScheme == BondInterface.MONOCOLOR) { + removeAllChildren(); + shape = getMonocolorLine(bond); + rootBranch = this.getRootBranch(); + rootBranch.addChild(shape); + addChild(rootBranch); + } + + } + } + + void updateTransform3D(float[] origin_1, float[] origin_2) { + + if (numChildren() < 1) { + return; + } + + float dX = origin_2[0] - origin_1[0]; + float dY = origin_2[1] - origin_1[1]; + float dZ = origin_2[2] - origin_1[2]; + + float bondLength = (float) Math.sqrt(dX * dX + dY * dY + dZ * dZ); + + if (renderingStyle == BondInterface.CYLINDER_MONOCOLOR) { + // Get orientation + getOrientation(origin_1, origin_2); + + Transform3D move = new Transform3D(); + move.setScale(new Vector3d(cylinderRadius, bondLength, cylinderRadius)); + move.setRotation(rot); + move.setTranslation(new Vector3f( (origin_1[0] + 0.5f * bondLength * vX), + (origin_1[1] + 0.5f * bondLength * vY), + (origin_1[2] + 0.5f * bondLength * vZ))); + + TransformGroup atg = (TransformGroup) rootBranch.getChild(0); // !!1 Only 1 child now + atg.setTransform(move); + } + + else if (renderingStyle == BondInterface.CYLINDER_BICOLOR) { + // Get orientation + getOrientation(origin_1, origin_2); + + Transform3D move = new Transform3D(); + move.setScale(new Vector3d(cylinderRadius, bondLength / 2, cylinderRadius)); + move.setRotation(rot); + move.setTranslation(new Vector3f( (origin_1[0] + 0.25f * bondLength * vX), + (origin_1[1] + 0.25f * bondLength * vY), + (origin_1[2] + 0.25f * bondLength * vZ))); + + TransformGroup atg = (TransformGroup) rootBranch.getChild(0); + atg.setTransform(move); + + move = new Transform3D(); + move.setScale(new Vector3d(cylinderRadius, bondLength / 2, cylinderRadius)); + move.setRotation(rot); + move.setTranslation(new Vector3f( (origin_1[0] + 0.75f * bondLength * vX), + (origin_1[1] + 0.75f * bondLength * vY), + (origin_1[2] + 0.75f * bondLength * vZ))); + + atg = (TransformGroup) rootBranch.getChild(1); + atg.setTransform(move); + } + + else if (renderingStyle == BondInterface.LINE_MONOCOLOR) { + System.err.println("BondInterface.LINE_MONOCOLOR is not implemented yet..."); + } + + else if (renderingStyle == BondInterface.LINE_BICOLOR) { + coordinates[0].set(origin_1[0], origin_1[1], origin_1[2]); + coordinates[1].set(origin_1[0] + (origin_2[0] - origin_1[0]) / 2.0f, + origin_1[1] + (origin_2[1] - origin_1[1]) / 2.0f, + origin_1[2] + (origin_2[2] - origin_1[2]) / 2.0f); + coordinates[2].set(origin_1[0] + (origin_2[0] - origin_1[0]) / 2.0f, + origin_1[1] + (origin_2[1] - origin_1[1]) / 2.0f, + origin_1[2] + (origin_2[2] - origin_1[2]) / 2.0f); + coordinates[3].set(origin_2[0], origin_2[1], origin_2[2]); + + if (lineBond.getCapability(GeometryArray.ALLOW_COORDINATE_WRITE)) { + lineBond.setCoordinates(0, coordinates); + } + else { + System.err.println("updateTransform3D: no capability to set coordinates"); + } + } + + } + + public void setBondColoring(int coloring) throws Exception { + if (coloring != BondInterface.MONOCOLOR && + coloring != BondInterface.BICOLOR) { + throw new Exception("Wrong bond coloring scheme"); + } + bondColoring = coloring; + } + + public float getCylinderRadius() { + return cylinderRadius; + } + + public void setCylinderRadius(float radius) { + cylinderRadius = radius; + } + + BranchGroup getRootBranch() { + BranchGroup root = new BranchGroup(); + root.setCapability(Group.ALLOW_CHILDREN_READ); + root.setCapability(Group.ALLOW_CHILDREN_WRITE); + root.setCapability(Group.ALLOW_CHILDREN_EXTEND); + root.setCapability(BranchGroup.ALLOW_DETACH); + return root; + } + + @Override + public Object clone() throws CloneNotSupportedException { + if (bond != null) { + return new BondNode(bond); + } + return null; + } +} diff --git a/src/main/java/cct/j3d/CellViewManager.java b/src/main/java/cct/j3d/CellViewManager.java new file mode 100644 index 0000000..e14d5ec --- /dev/null +++ b/src/main/java/cct/j3d/CellViewManager.java @@ -0,0 +1,68 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import cct.interfaces.CellViewManagerInterface; +import cct.modelling.CELL_PARAMETER; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class CellViewManager + implements CellViewManagerInterface { + + private Java3dUniverse java3dUniverse = null; + + public CellViewManager(Java3dUniverse j3d) { + java3dUniverse = j3d; + } + + @Override + public void replicateCell(CELL_PARAMETER direction, int repetition_factor) { + + } +} diff --git a/src/main/java/cct/j3d/ChangeAtomColors.java b/src/main/java/cct/j3d/ChangeAtomColors.java new file mode 100644 index 0000000..ee66b12 --- /dev/null +++ b/src/main/java/cct/j3d/ChangeAtomColors.java @@ -0,0 +1,97 @@ +package cct.j3d; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.scijava.vecmath.Color3f; + +import cct.interfaces.AtomInterface; +import cct.interfaces.ColorChangerInterface; +import cct.interfaces.MoleculeInterface; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class ChangeAtomColors + implements ColorChangerInterface { + + private Java3dUniverse j3d; + private List selectedAtoms = null; + private Map colorStore = null; + + public ChangeAtomColors(Java3dUniverse j3d) { + this.j3d = j3d; + } + + public void getSelectedAtoms() { + if (selectedAtoms == null) { + selectedAtoms = new ArrayList (j3d.getMoleculeInterface().getNumberOfAtoms()); + colorStore = new HashMap (j3d.getMoleculeInterface().getNumberOfAtoms()); + } + else { + selectedAtoms.clear(); + colorStore.clear(); + } + + MoleculeInterface molec = j3d.getMoleculeInterface(); + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface atom = molec.getAtomInterface(i); + if (atom.isSelected()) { + selectedAtoms.add(atom); + Object obj = atom.getProperty(Java3dUniverse.ATOM_NODE); + if (obj == null) { + System.err.println(this.getClass().getCanonicalName() + ": getSelectedAtoms: atom does not contain AtomNode. Ignored..."); + continue; + } + Color3f color3f = AtomNode.getAtomColor(atom); + colorStore.put(atom, color3f); + } + } + } + + @Override + public void setColor(Color newColor) { + if (selectedAtoms == null) { + getSelectedAtoms(); + } + if (selectedAtoms.size() < 1) { + return; + } + for (int i = 0; i < selectedAtoms.size(); i++) { + AtomInterface atom = selectedAtoms.get(i); + j3d.setAtomColor(atom, newColor); + } + } + + @Override + public void reset() { + Iterator iter = colorStore.keySet().iterator(); + while (iter.hasNext()) { + AtomInterface atom = (AtomInterface) iter.next(); + Color3f color3f = colorStore.get(atom); + j3d.setAtomColor(atom, color3f); + } + } + + @Override + public void stop() { + j3d.endProcessingSelectedAtoms(); + } + + public static void main(String[] args) { + //ChangeAtomColors changeatomcolors = new ChangeAtomColors(); + } +} diff --git a/src/main/java/cct/j3d/ChemicalElementsColors.java b/src/main/java/cct/j3d/ChemicalElementsColors.java new file mode 100644 index 0000000..90a274b --- /dev/null +++ b/src/main/java/cct/j3d/ChemicalElementsColors.java @@ -0,0 +1,724 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.logging.Logger; +import java.util.prefs.Preferences; + +import org.scijava.java3d.Material; +import org.scijava.vecmath.Color3f; + +import cct.modelling.ChemicalElements; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class ChemicalElementsColors + extends ChemicalElements { + + static final String DEFAULT_ATOM_COLOR_SCHEME = "Sybyl Scheme"; + static final String ATOM_COLOR_SCHEME_2 = "GaussView Scheme"; + static final String ATOM_COLOR_SCHEME_JMOL = "Jmol Scheme"; + static final String ATOM_COLOR_SCHEME_RASMOL = "Rasmol Scheme"; + static final String ATOM_COLOR_SCHEME_RASMOL_NEW = "Rasmol CPKnew Scheme"; + + private static String currentColorSchemeName = DEFAULT_ATOM_COLOR_SCHEME; + private static List currentColorScheme; + private static String atomColorSchemeKey = "atomColorScheme"; + private static Preferences prefs; // = Preferences.userNodeForPackage(getClass()); + static final Logger logger = Logger.getLogger(ChemicalElementsColors.class.getCanonicalName()); + + static TreeMap atomColours = new TreeMap(); + static List elementMaterial = new ArrayList(); + static List elementColors = new ArrayList(); + static List gaussianElementColors = new ArrayList(); + static List rasmolElementColors = new ArrayList(); + static List rasmolNewElementColors = new ArrayList(); + static List jmolElementColors = new ArrayList(); + static Map colorScheme = new LinkedHashMap(); + + static Material highlightMaterial = new Material( + new Color3f(0.333f, 0.777f, 0.222f), + new Color3f(0.777f, 0.222f, 0.555f), new Color3f(0.777f, 0.222f, 0.555f), + new Color3f(1.0f, 1.0f, 1.0f), 15.0f); + + static Color3f highlightColor = new Color3f(Color.MAGENTA); + + static { + elementColors.add(new Color3f(Color.DARK_GRAY)); // 0 - Dummy + elementColors.add(new Color3f(Color.CYAN)); // 1 - H + elementColors.add(new Color3f(Color.MAGENTA)); // 2 - He + elementColors.add(new Color3f(Color.MAGENTA)); // 3 - Li + elementColors.add(new Color3f(Color.MAGENTA)); // 4 - Be + elementColors.add(new Color3f(Color.MAGENTA)); // 5 - B + elementColors.add(new Color3f(Color.WHITE)); // 6 - C + elementColors.add(new Color3f(Color.BLUE)); // 7 - N + elementColors.add(new Color3f(Color.RED)); // 8 - O + elementColors.add(new Color3f(Color.GREEN)); // 9 - F + elementColors.add(new Color3f(Color.MAGENTA)); // 10 - Ne + elementColors.add(new Color3f(Color.MAGENTA)); // 11 - Na + elementColors.add(new Color3f(Color.MAGENTA)); // 12 - Mg + elementColors.add(new Color3f(Color.CYAN)); // 13 - Al + elementColors.add(new Color3f(Color.YELLOW)); // 14 - Si + elementColors.add(new Color3f(Color.ORANGE)); // 15 - P + elementColors.add(new Color3f(Color.YELLOW)); // 16 - S + elementColors.add(new Color3f(Color.GREEN)); // 17 - Cl + elementColors.add(new Color3f(Color.MAGENTA)); // 18 - Ar + elementColors.add(new Color3f(Color.MAGENTA)); // 19 - K + elementColors.add(new Color3f(Color.MAGENTA)); // 20 - Ca + elementColors.add(new Color3f(Color.MAGENTA)); // 21 - Sc + elementColors.add(new Color3f(Color.MAGENTA)); // 22 - Ti + elementColors.add(new Color3f(Color.MAGENTA)); // 23 - V + elementColors.add(new Color3f(Color.MAGENTA)); // 24 - Cr + elementColors.add(new Color3f(Color.MAGENTA)); // 25 - Mn + elementColors.add(new Color3f(Color.MAGENTA)); // 26 - Fe + elementColors.add(new Color3f(Color.MAGENTA)); // 27 - Co + elementColors.add(new Color3f(Color.MAGENTA)); // 28 - Ni + elementColors.add(new Color3f(Color.MAGENTA)); // 29 - Cu + elementColors.add(new Color3f(Color.MAGENTA)); // 30 - Zn + elementColors.add(new Color3f(Color.MAGENTA)); // 31 - Ga + elementColors.add(new Color3f(Color.MAGENTA)); // 32 - Ge + elementColors.add(new Color3f(Color.MAGENTA)); // 33 - As + elementColors.add(new Color3f(Color.MAGENTA)); // 34 - Se + elementColors.add(new Color3f(Color.GREEN)); // 35 - Br + elementColors.add(new Color3f(Color.MAGENTA)); // 36 - Kr + elementColors.add(new Color3f(Color.MAGENTA)); // 37 - Rb + elementColors.add(new Color3f(Color.MAGENTA)); // 38 - Sr + elementColors.add(new Color3f(Color.MAGENTA)); // 39 - Y + elementColors.add(new Color3f(Color.MAGENTA)); // 40 - Zr + elementColors.add(new Color3f(Color.MAGENTA)); // 41 - Nb + elementColors.add(new Color3f(Color.MAGENTA)); // 42 - Mo + elementColors.add(new Color3f(Color.MAGENTA)); // 43 - Tc + elementColors.add(new Color3f(Color.MAGENTA)); // 44 - Ru + elementColors.add(new Color3f(Color.MAGENTA)); // 45 - Rh + elementColors.add(new Color3f(Color.MAGENTA)); // 46 - Pd + elementColors.add(new Color3f(Color.MAGENTA)); // 47 - Ag + elementColors.add(new Color3f(Color.MAGENTA)); // 48 - Cd + elementColors.add(new Color3f(Color.MAGENTA)); // 49 - In + elementColors.add(new Color3f(Color.MAGENTA)); // 50 - Sn + elementColors.add(new Color3f(Color.MAGENTA)); // 51 - Sb + elementColors.add(new Color3f(Color.MAGENTA)); // 52 - Te + elementColors.add(new Color3f(Color.PINK)); // 53 - I + elementColors.add(new Color3f(Color.MAGENTA)); // 54 - Xe + elementColors.add(new Color3f(Color.MAGENTA)); // 55 - Cs + elementColors.add(new Color3f(Color.MAGENTA)); // 56 - Ba + elementColors.add(new Color3f(Color.MAGENTA)); // 57 - La + elementColors.add(new Color3f(Color.MAGENTA)); // 58 - Ce + elementColors.add(new Color3f(Color.MAGENTA)); // 59 - Pr + elementColors.add(new Color3f(Color.MAGENTA)); // 60 - Nd + elementColors.add(new Color3f(Color.MAGENTA)); // 61 - Pm + elementColors.add(new Color3f(Color.MAGENTA)); // 62 - Sm + elementColors.add(new Color3f(Color.MAGENTA)); // 63 - Eu + elementColors.add(new Color3f(Color.MAGENTA)); // 64 - Gd + elementColors.add(new Color3f(Color.MAGENTA)); // 65 - Tb + elementColors.add(new Color3f(Color.MAGENTA)); // 66 - Dy + elementColors.add(new Color3f(Color.MAGENTA)); // 67 - Ho + elementColors.add(new Color3f(Color.MAGENTA)); // 68 - Er + elementColors.add(new Color3f(Color.MAGENTA)); // 69 - Tm + elementColors.add(new Color3f(Color.MAGENTA)); // 70 - Yb + elementColors.add(new Color3f(Color.MAGENTA)); // 71 - Lu + elementColors.add(new Color3f(Color.MAGENTA)); // 72 - Hf + elementColors.add(new Color3f(Color.MAGENTA)); // 73 - Ta + elementColors.add(new Color3f(Color.MAGENTA)); // 74 - W + elementColors.add(new Color3f(Color.MAGENTA)); // 75 - Re + elementColors.add(new Color3f(Color.MAGENTA)); // 76 - Os + elementColors.add(new Color3f(Color.MAGENTA)); // 77 - Ir + elementColors.add(new Color3f(Color.MAGENTA)); // 78 - Pt + elementColors.add(new Color3f(Color.MAGENTA)); // 79 - Au + elementColors.add(new Color3f(Color.MAGENTA)); // 80 - Hg + elementColors.add(new Color3f(Color.MAGENTA)); // 81 - Tl + elementColors.add(new Color3f(Color.MAGENTA)); // 82 - Pb + elementColors.add(new Color3f(Color.MAGENTA)); // 83 - Bi + elementColors.add(new Color3f(Color.MAGENTA)); // 84 - Po + elementColors.add(new Color3f(Color.MAGENTA)); // 85 - At + elementColors.add(new Color3f(Color.MAGENTA)); // 86 - Rn + elementColors.add(new Color3f(Color.MAGENTA)); // 87 - Fr + elementColors.add(new Color3f(Color.MAGENTA)); // 88 - Ra + elementColors.add(new Color3f(Color.MAGENTA)); // 89 - Ac + elementColors.add(new Color3f(Color.MAGENTA)); // 90 - Th + elementColors.add(new Color3f(Color.MAGENTA)); // 91 - Pa + elementColors.add(new Color3f(Color.MAGENTA)); // 92 - U + elementColors.add(new Color3f(Color.MAGENTA)); // 93 - Np + elementColors.add(new Color3f(Color.MAGENTA)); // 94 - Pu + elementColors.add(new Color3f(Color.MAGENTA)); // 95 - Am + elementColors.add(new Color3f(Color.MAGENTA)); // 96 - Cm + elementColors.add(new Color3f(Color.MAGENTA)); // 97 - Bk + elementColors.add(new Color3f(Color.MAGENTA)); // 98 - Cf + elementColors.add(new Color3f(Color.MAGENTA)); // 99 - Es + elementColors.add(new Color3f(Color.MAGENTA)); // 100 - Fm + elementColors.add(new Color3f(Color.MAGENTA)); // 101 - Md + elementColors.add(new Color3f(Color.MAGENTA)); // 102 - No + elementColors.add(new Color3f(Color.MAGENTA)); // 103 - Lr + elementColors.add(new Color3f(Color.MAGENTA)); // 104 - Db + elementColors.add(new Color3f(Color.MAGENTA)); // 105 - Jl + elementColors.add(new Color3f(Color.MAGENTA)); // 106 - Rf + elementColors.add(new Color3f(Color.MAGENTA)); // 107 - Bh + elementColors.add(new Color3f(Color.MAGENTA)); // 108 - Hn + elementColors.add(new Color3f(Color.MAGENTA)); // 109 - Mt + + gaussianElementColors.add(new Color3f(Color.DARK_GRAY)); // 0 - Dummy + gaussianElementColors.add(new Color3f(0.80f, 0.80f, 0.80f)); // 1 - H + gaussianElementColors.add(new Color3f(0.85f, 1.00f, 1.00f)); // 2 - He + gaussianElementColors.add(new Color3f(0.80f, 0.49f, 1.00f)); // 3 - Li + gaussianElementColors.add(new Color3f(0.80f, 1.00f, 0.00f)); // 4 - Be + gaussianElementColors.add(new Color3f(1.00f, 0.71f, 0.71f)); // 5 - B + gaussianElementColors.add(new Color3f(0.56f, 0.56f, 0.56f)); // 6 - C + gaussianElementColors.add(new Color3f(0.10f, 0.10f, 0.90f)); // 7 - N + gaussianElementColors.add(new Color3f(0.90f, 0.00f, 0.00f)); // 8 - O + gaussianElementColors.add(new Color3f(0.70f, 1.00f, 1.00f)); // 9 - F + gaussianElementColors.add(new Color3f(0.69f, 0.89f, 0.96f)); // 10 - Ne + gaussianElementColors.add(new Color3f(0.67f, 0.36f, 0.95f)); // 11 - Na + gaussianElementColors.add(new Color3f(0.70f, 0.80f, 0.00f)); // 12 - Mg + gaussianElementColors.add(new Color3f(0.82f, 0.65f, 0.65f)); // 13 - Al + gaussianElementColors.add(new Color3f(0.50f, 0.60f, 0.60f)); // 14 - Si + gaussianElementColors.add(new Color3f(1.00f, 0.50f, 0.00f)); // 15 - P + gaussianElementColors.add(new Color3f(1.00f, 0.78f, 0.16f)); // 16 - S + gaussianElementColors.add(new Color3f(0.10f, 0.94f, 0.10f)); // 17 - Cl + gaussianElementColors.add(new Color3f(0.50f, 0.82f, 0.89f)); // 18 - Ar + gaussianElementColors.add(new Color3f(0.56f, 0.25f, 0.83f)); // 19 - K + gaussianElementColors.add(new Color3f(0.60f, 0.60f, 0.00f)); // 20 - Ca + gaussianElementColors.add(new Color3f(0.90f, 0.90f, 0.89f)); // 21 - Sc + gaussianElementColors.add(new Color3f(0.75f, 0.76f, 0.78f)); // 22 - Ti + gaussianElementColors.add(new Color3f(0.65f, 0.65f, 0.67f)); // 23 - V + gaussianElementColors.add(new Color3f(0.54f, 0.60f, 0.78f)); // 24 - Cr + gaussianElementColors.add(new Color3f(0.61f, 0.48f, 0.78f)); // 25 - Mn + gaussianElementColors.add(new Color3f(0.50f, 0.48f, 0.78f)); // 26 - Fe + gaussianElementColors.add(new Color3f(0.36f, 0.43f, 1.00f)); // 27 - Co + gaussianElementColors.add(new Color3f(0.36f, 0.48f, 0.76f)); // 28 - Ni + gaussianElementColors.add(new Color3f(1.00f, 0.48f, 0.38f)); // 29 - Cu + gaussianElementColors.add(new Color3f(0.49f, 0.50f, 0.69f)); // 30 - Zn + gaussianElementColors.add(new Color3f(0.76f, 0.56f, 0.56f)); // 31 - Ga + gaussianElementColors.add(new Color3f(0.40f, 0.56f, 0.56f)); // 32 - Ge + gaussianElementColors.add(new Color3f(0.74f, 0.50f, 0.89f)); // 33 - As + gaussianElementColors.add(new Color3f(1.00f, 0.63f, 0.00f)); // 34 - Se + gaussianElementColors.add(new Color3f(0.65f, 0.13f, 0.13f)); // 35 - Br + gaussianElementColors.add(new Color3f(0.36f, 0.73f, 0.82f)); // 36 - Kr + gaussianElementColors.add(new Color3f(0.44f, 0.18f, 0.69f)); // 37 - Rb + gaussianElementColors.add(new Color3f(0.50f, 0.40f, 0.00f)); // 38 - Sr + gaussianElementColors.add(new Color3f(0.58f, 0.99f, 1.00f)); // 39 - Y + gaussianElementColors.add(new Color3f(0.58f, 0.88f, 0.88f)); // 40 - Zr + gaussianElementColors.add(new Color3f(0.45f, 0.76f, 0.79f)); // 41 - Nb + gaussianElementColors.add(new Color3f(0.33f, 0.71f, 0.71f)); // 42 - Mo + gaussianElementColors.add(new Color3f(0.23f, 0.62f, 0.66f)); // 43 - Tc + gaussianElementColors.add(new Color3f(0.14f, 0.56f, 0.59f)); // 44 - Ru + gaussianElementColors.add(new Color3f(0.04f, 0.49f, 0.55f)); // 45 - Rh + gaussianElementColors.add(new Color3f(0.00f, 0.41f, 0.52f)); // 46 - Pd + gaussianElementColors.add(new Color3f(0.60f, 0.78f, 1.00f)); // 47 - Ag + gaussianElementColors.add(new Color3f(1.00f, 0.85f, 0.56f)); // 48 - Cd + gaussianElementColors.add(new Color3f(0.65f, 0.46f, 0.45f)); // 49 - In + gaussianElementColors.add(new Color3f(0.40f, 0.50f, 0.50f)); // 50 - Sn + gaussianElementColors.add(new Color3f(0.62f, 0.39f, 0.71f)); // 51 - Sb + gaussianElementColors.add(new Color3f(0.83f, 0.48f, 0.00f)); // 52 - Te + gaussianElementColors.add(new Color3f(0.58f, 0.00f, 0.58f)); // 53 - I + gaussianElementColors.add(new Color3f(0.26f, 0.62f, 0.69f)); // 54 - Xe + gaussianElementColors.add(new Color3f(0.34f, 0.09f, 0.56f)); // 55 - Cs + gaussianElementColors.add(new Color3f(0.40f, 0.20f, 0.00f)); // 56 - Ba + gaussianElementColors.add(new Color3f(0.44f, 0.87f, 1.00f)); // 57 - La + gaussianElementColors.add(new Color3f(1.00f, 1.00f, 0.78f)); // 58 - Ce + gaussianElementColors.add(new Color3f(0.85f, 1.00f, 0.78f)); // 59 - Pr + gaussianElementColors.add(new Color3f(0.78f, 1.00f, 0.78f)); // 60 - Nd + gaussianElementColors.add(new Color3f(0.64f, 1.00f, 0.78f)); // 61 - Pm + gaussianElementColors.add(new Color3f(0.56f, 1.00f, 0.78f)); // 62 - Sm + gaussianElementColors.add(new Color3f(0.38f, 1.00f, 0.78f)); // 63 - Eu + gaussianElementColors.add(new Color3f(0.27f, 1.00f, 0.78f)); // 64 - Gd + gaussianElementColors.add(new Color3f(0.19f, 1.00f, 0.78f)); // 65 - Tb + gaussianElementColors.add(new Color3f(0.12f, 1.00f, 0.71f)); // 66 - Dy + gaussianElementColors.add(new Color3f(0.00f, 1.00f, 0.71f)); // 67 - Ho + gaussianElementColors.add(new Color3f(0.00f, 0.90f, 0.46f)); // 68 - Er + gaussianElementColors.add(new Color3f(0.00f, 0.83f, 0.32f)); // 69 - Tm + gaussianElementColors.add(new Color3f(0.00f, 0.75f, 0.22f)); // 70 - Yb + gaussianElementColors.add(new Color3f(0.00f, 0.67f, 0.14f)); // 71 - Lu + gaussianElementColors.add(new Color3f(0.30f, 0.76f, 1.00f)); // 72 - Hf + gaussianElementColors.add(new Color3f(0.30f, 0.65f, 1.00f)); // 73 - Ta + gaussianElementColors.add(new Color3f(0.15f, 0.58f, 0.84f)); // 74 - W + gaussianElementColors.add(new Color3f(0.15f, 0.49f, 0.67f)); // 75 - Re + gaussianElementColors.add(new Color3f(0.15f, 0.40f, 0.59f)); // 76 - Os + gaussianElementColors.add(new Color3f(0.09f, 0.33f, 0.53f)); // 77 - Ir + gaussianElementColors.add(new Color3f(0.09f, 0.36f, 0.56f)); // 78 - Pt + gaussianElementColors.add(new Color3f(1.00f, 0.82f, 0.14f)); // 79 - Au + gaussianElementColors.add(new Color3f(0.71f, 0.71f, 0.76f)); // 80 - Hg + gaussianElementColors.add(new Color3f(0.65f, 0.33f, 0.30f)); // 81 - Tl + gaussianElementColors.add(new Color3f(0.34f, 0.35f, 0.38f)); // 82 - Pb + gaussianElementColors.add(new Color3f(0.62f, 0.31f, 0.71f)); // 83 - Bi + gaussianElementColors.add(new Color3f(0.67f, 0.36f, 0.00f)); // 84 - Po + gaussianElementColors.add(new Color3f(0.46f, 0.31f, 0.27f)); // 85 - At + gaussianElementColors.add(new Color3f(0.26f, 0.51f, 0.59f)); // 86 - Rn + gaussianElementColors.add(new Color3f(0.26f, 0.00f, 0.40f)); // 87 - Fr + gaussianElementColors.add(new Color3f(0.30f, 0.10f, 0.00f)); // 88 - Ra + gaussianElementColors.add(new Color3f(0.44f, 0.67f, 0.98f)); // 89 - Ac + gaussianElementColors.add(new Color3f(0.00f, 0.73f, 1.00f)); // 90 - Th + gaussianElementColors.add(new Color3f(0.00f, 0.63f, 1.00f)); // 91 - Pa + gaussianElementColors.add(new Color3f(0.00f, 0.56f, 1.00f)); // 92 - U + gaussianElementColors.add(new Color3f(0.00f, 0.50f, 0.95f)); // 93 - Np + gaussianElementColors.add(new Color3f(0.00f, 0.42f, 0.95f)); // 94 - Pu + gaussianElementColors.add(new Color3f(0.33f, 0.36f, 0.95f)); // 95 - Am + gaussianElementColors.add(new Color3f(0.47f, 0.36f, 0.89f)); // 96 - Cm + gaussianElementColors.add(new Color3f(0.54f, 0.37f, 0.89f)); // 97 - Bk + gaussianElementColors.add(new Color3f(0.63f, 0.21f, 0.83f)); // 98 - Cf + gaussianElementColors.add(new Color3f(0.66f, 0.17f, 0.78f)); // 99 - Es + gaussianElementColors.add(new Color3f(0.70f, 0.12f, 0.73f)); // 100 - Fm + gaussianElementColors.add(new Color3f(0.70f, 0.05f, 0.65f)); // 101 - Md + gaussianElementColors.add(new Color3f(0.74f, 0.05f, 0.53f)); // 102 - No + gaussianElementColors.add(new Color3f(0.78f, 0.00f, 0.40f)); // 103 - Lr + gaussianElementColors.add(new Color3f(1.00f, 0.50f, 0.50f)); // 104 - Db + gaussianElementColors.add(new Color3f(0.90f, 0.40f, 0.40f)); // 105 - Jl + gaussianElementColors.add(new Color3f(0.80f, 0.30f, 0.30f)); // 106 - Rf + gaussianElementColors.add(new Color3f(0.70f, 0.20f, 0.20f)); // 107 - Bh + gaussianElementColors.add(new Color3f(0.60f, 0.10f, 0.10f)); // 108 - Hn + gaussianElementColors.add(new Color3f(0.50f, 0.00f, 0.00f)); // 109 - Mt + + jmolElementColors.add(new Color3f(new Color(0xFA1691))); // 0 - Dummy + jmolElementColors.add(new Color3f(new Color(255, 255, 255))); // 1 - H + jmolElementColors.add(new Color3f(new Color(217, 255, 255))); // 2 - He + jmolElementColors.add(new Color3f(new Color(204, 128, 255))); // 3 - Li + jmolElementColors.add(new Color3f(new Color(194, 255, 0))); // 4 - Be + jmolElementColors.add(new Color3f(new Color(255, 181, 181))); // 5 - B + jmolElementColors.add(new Color3f(new Color(144, 144, 144))); // 6 - C + jmolElementColors.add(new Color3f(new Color(48, 80, 248))); // 7 - N + jmolElementColors.add(new Color3f(new Color(255, 13, 13))); // 8 - O + jmolElementColors.add(new Color3f(new Color(144, 224, 80))); // 9 - F + jmolElementColors.add(new Color3f(new Color(179, 227, 245))); // 10 - Ne + jmolElementColors.add(new Color3f(new Color(171, 92, 242))); // 11 - Na + jmolElementColors.add(new Color3f(new Color(138, 255, 0))); // 12 - Mg + jmolElementColors.add(new Color3f(new Color(191, 166, 166))); // 13 - Al + jmolElementColors.add(new Color3f(new Color(240, 200, 160))); // 14 - Si + jmolElementColors.add(new Color3f(new Color(255, 128, 0))); // 15 - P + jmolElementColors.add(new Color3f(new Color(255, 255, 48))); // 16 - S + jmolElementColors.add(new Color3f(new Color(31, 240, 31))); // 17 - Cl + jmolElementColors.add(new Color3f(new Color(128, 209, 227))); // 18 - Ar + jmolElementColors.add(new Color3f(new Color(143, 64, 212))); // 19 - K + jmolElementColors.add(new Color3f(new Color(61, 255, 0))); // 20 - Ca + jmolElementColors.add(new Color3f(new Color(230, 230, 230))); // 21 - Sc + jmolElementColors.add(new Color3f(new Color(191, 194, 199))); // 22 - Ti + jmolElementColors.add(new Color3f(new Color(166, 166, 171))); // 23 - V + jmolElementColors.add(new Color3f(new Color(138, 153, 199))); // 24 - Cr + jmolElementColors.add(new Color3f(new Color(156, 122, 199))); // 25 - Mn + jmolElementColors.add(new Color3f(new Color(224, 102, 51))); // 26 - Fe + jmolElementColors.add(new Color3f(new Color(240, 144, 160))); // 27 - Co + jmolElementColors.add(new Color3f(new Color(80, 208, 80))); // 28 - Ni + jmolElementColors.add(new Color3f(new Color(200, 128, 51))); // 29 - Cu + jmolElementColors.add(new Color3f(new Color(125, 128, 176))); // 30 - Zn + jmolElementColors.add(new Color3f(new Color(194, 143, 143))); // 31 - Ga + jmolElementColors.add(new Color3f(new Color(102, 143, 143))); // 32 - Ge + jmolElementColors.add(new Color3f(new Color(189, 128, 227))); // 33 - As + jmolElementColors.add(new Color3f(new Color(255, 161, 0))); // 34 - Se + jmolElementColors.add(new Color3f(new Color(166, 41, 41))); // 35 - Br + jmolElementColors.add(new Color3f(new Color(92, 184, 209))); // 36 - Kr + jmolElementColors.add(new Color3f(new Color(112, 46, 176))); // 37 - Rb + jmolElementColors.add(new Color3f(new Color(0, 255, 0))); // 38 - Sr + jmolElementColors.add(new Color3f(new Color(148, 255, 255))); // 39 - Y + jmolElementColors.add(new Color3f(new Color(148, 224, 224))); // 40 - Zr + jmolElementColors.add(new Color3f(new Color(115, 194, 201))); // 41 - Nb + jmolElementColors.add(new Color3f(new Color(84, 181, 181))); // 42 - Mo + jmolElementColors.add(new Color3f(new Color(59, 158, 158))); // 43 - Tc + jmolElementColors.add(new Color3f(new Color(36, 143, 143))); // 44 - Ru + jmolElementColors.add(new Color3f(new Color(10, 125, 140))); // 45 - Rh + jmolElementColors.add(new Color3f(new Color(0, 105, 133))); // 46 - Pd + jmolElementColors.add(new Color3f(new Color(192, 192, 192))); // 47 - Ag + jmolElementColors.add(new Color3f(new Color(255, 217, 143))); // 48 - Cd + jmolElementColors.add(new Color3f(new Color(166, 117, 115))); // 49 - In + jmolElementColors.add(new Color3f(new Color(102, 128, 128))); // 50 - Sn + jmolElementColors.add(new Color3f(new Color(158, 99, 181))); // 51 - Sb + jmolElementColors.add(new Color3f(new Color(212, 122, 0))); // 52 - Te + jmolElementColors.add(new Color3f(new Color(148, 0, 148))); // 53 - I + jmolElementColors.add(new Color3f(new Color(66, 158, 176))); // 54 - Xe + jmolElementColors.add(new Color3f(new Color(87, 23, 143))); // 55 - Cs + jmolElementColors.add(new Color3f(new Color(0, 201, 0))); // 56 - Ba + jmolElementColors.add(new Color3f(new Color(112, 212, 255))); // 57 - La + jmolElementColors.add(new Color3f(new Color(255, 255, 199))); // 58 - Ce + jmolElementColors.add(new Color3f(new Color(217, 255, 199))); // 59 - Pr + jmolElementColors.add(new Color3f(new Color(199, 255, 199))); // 60 - Nd + jmolElementColors.add(new Color3f(new Color(163, 255, 199))); // 61 - Pm + jmolElementColors.add(new Color3f(new Color(143, 255, 199))); // 62 - Sm + jmolElementColors.add(new Color3f(new Color(97, 255, 199))); // 63 - Eu + jmolElementColors.add(new Color3f(new Color(69, 255, 199))); // 64 - Gd + jmolElementColors.add(new Color3f(new Color(48, 255, 199))); // 65 - Tb + jmolElementColors.add(new Color3f(new Color(31, 255, 199))); // 66 - Dy + jmolElementColors.add(new Color3f(new Color(0, 255, 156))); // 67 - Ho + jmolElementColors.add(new Color3f(new Color(0, 230, 117))); // 68 - Er + jmolElementColors.add(new Color3f(new Color(0, 212, 82))); // 69 - Tm + jmolElementColors.add(new Color3f(new Color(0, 191, 56))); // 70 - Yb + jmolElementColors.add(new Color3f(new Color(0, 171, 36))); // 71 - Lu + jmolElementColors.add(new Color3f(new Color(77, 194, 255))); // 72 - Hf + jmolElementColors.add(new Color3f(new Color(77, 166, 255))); // 73 - Ta + jmolElementColors.add(new Color3f(new Color(33, 148, 214))); // 74 - W + jmolElementColors.add(new Color3f(new Color(38, 125, 171))); // 75 - Re + jmolElementColors.add(new Color3f(new Color(38, 102, 150))); // 76 - Os + jmolElementColors.add(new Color3f(new Color(23, 84, 135))); // 77 - Ir + jmolElementColors.add(new Color3f(new Color(208, 208, 224))); // 78 - Pt + jmolElementColors.add(new Color3f(new Color(255, 209, 35))); // 79 - Au + jmolElementColors.add(new Color3f(new Color(184, 184, 208))); // 80 - Hg + jmolElementColors.add(new Color3f(new Color(166, 84, 77))); // 81 - Tl + jmolElementColors.add(new Color3f(new Color(87, 89, 97))); // 82 - Pb + jmolElementColors.add(new Color3f(new Color(158, 79, 181))); // 83 - Bi + jmolElementColors.add(new Color3f(new Color(171, 92, 0))); // 84 - Po + jmolElementColors.add(new Color3f(new Color(117, 79, 69))); // 85 - At + jmolElementColors.add(new Color3f(new Color(66, 130, 150))); // 86 - Rn + jmolElementColors.add(new Color3f(new Color(66, 0, 102))); // 87 - Fr + jmolElementColors.add(new Color3f(new Color(0, 125, 0))); // 88 - Ra + jmolElementColors.add(new Color3f(new Color(112, 171, 250))); // 89 - Ac + jmolElementColors.add(new Color3f(new Color(0, 186, 255))); // 90 - Th + jmolElementColors.add(new Color3f(new Color(0, 161, 255))); // 91 - Pa + jmolElementColors.add(new Color3f(new Color(0, 143, 255))); // 92 - U + jmolElementColors.add(new Color3f(new Color(0, 128, 255))); // 93 - Np + jmolElementColors.add(new Color3f(new Color(0, 107, 255))); // 94 - Pu + jmolElementColors.add(new Color3f(new Color(84, 92, 242))); // 95 - Am + jmolElementColors.add(new Color3f(new Color(120, 92, 227))); // 96 - Cm + jmolElementColors.add(new Color3f(new Color(138, 79, 227))); // 97 - Bk + jmolElementColors.add(new Color3f(new Color(161, 54, 212))); // 98 - Cf + jmolElementColors.add(new Color3f(new Color(179, 31, 212))); // 99 - Es + jmolElementColors.add(new Color3f(new Color(179, 31, 186))); // 100 - Fm + jmolElementColors.add(new Color3f(new Color(179, 13, 166))); // 101 - Md + jmolElementColors.add(new Color3f(new Color(189, 13, 135))); // 102 - No + jmolElementColors.add(new Color3f(new Color(199, 0, 102))); // 103 - Lr + jmolElementColors.add(new Color3f(new Color(204, 0, 89))); // 104 - Db + jmolElementColors.add(new Color3f(new Color(209, 0, 79))); // 105 - Jl + jmolElementColors.add(new Color3f(new Color(217, 0, 69))); // 106 - Rf + jmolElementColors.add(new Color3f(new Color(224, 0, 56))); // 107 - Bh + jmolElementColors.add(new Color3f(new Color(230, 0, 46))); // 108 - Hn + jmolElementColors.add(new Color3f(new Color(235, 0, 38))); // 109 - Mt + + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 0 - Dummy + rasmolElementColors.add(new Color3f(new Color(0xFFFFFF))); // 1 - H + rasmolElementColors.add(new Color3f(new Color(0xFFC0CB))); // 2 - He + rasmolElementColors.add(new Color3f(new Color(0xB22222))); // 3 - Li + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 4 - Be + rasmolElementColors.add(new Color3f(new Color(0x00FF00))); // 5 - B + rasmolElementColors.add(new Color3f(new Color(0xC8C8C8))); // 6 - C + rasmolElementColors.add(new Color3f(new Color(0x8F8FFF))); // 7 - N + rasmolElementColors.add(new Color3f(new Color(0xF00000))); // 8 - O + rasmolElementColors.add(new Color3f(new Color(0xDAA520))); // 9 - F + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 10 - Ne + rasmolElementColors.add(new Color3f(new Color(0x0000FF))); // 11 - Na + rasmolElementColors.add(new Color3f(new Color(0x228B22))); // 12 - Mg + rasmolElementColors.add(new Color3f(new Color(0x808090))); // 13 - Al + rasmolElementColors.add(new Color3f(new Color(0xDAA520))); // 14 - Si + rasmolElementColors.add(new Color3f(new Color(0xFFA500))); // 15 - P + rasmolElementColors.add(new Color3f(new Color(0xFFC832))); // 16 - S + rasmolElementColors.add(new Color3f(new Color(0x00FF00))); // 17 - Cl + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 18 - Ar + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 19 - K + rasmolElementColors.add(new Color3f(new Color(0x808090))); // 20 - Ca + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 21 - Sc + rasmolElementColors.add(new Color3f(new Color(0x808090))); // 22 - Ti + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 23 - V + rasmolElementColors.add(new Color3f(new Color(0x808090))); // 24 - Cr + rasmolElementColors.add(new Color3f(new Color(0x808090))); // 25 - Mn + rasmolElementColors.add(new Color3f(new Color(0xFFA500))); // 26 - Fe + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 27 - Co + rasmolElementColors.add(new Color3f(new Color(0xA52A2A))); // 28 - Ni + rasmolElementColors.add(new Color3f(new Color(0xA52A2A))); // 29 - Cu + rasmolElementColors.add(new Color3f(new Color(0xA52A2A))); // 30 - Zn + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 31 - Ga + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 32 - Ge + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 33 - As + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 34 - Se + rasmolElementColors.add(new Color3f(new Color(0xA52A2A))); // 35 - Br + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 36 - Kr + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 37 - Rb + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 38 - Sr + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 39 - Y + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 40 - Zr + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 41 - Nb + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 42 - Mo + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 43 - Tc + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 44 - Ru + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 45 - Rh + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 46 - Pd + rasmolElementColors.add(new Color3f(new Color(0x808090))); // 47 - Ag + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 48 - Cd + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 49 - In + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 50 - Sn + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 51 - Sb + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 52 - Te + rasmolElementColors.add(new Color3f(new Color(0xA020F0))); // 53 - I + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 54 - Xe + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 55 - Cs + rasmolElementColors.add(new Color3f(new Color(0xFFA500))); // 56 - Ba + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 57 - La + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 58 - Ce + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 59 - Pr + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 60 - Nd + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 61 - Pm + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 62 - Sm + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 63 - Eu + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 64 - Gd + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 65 - Tb + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 66 - Dy + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 67 - Ho + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 68 - Er + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 69 - Tm + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 70 - Yb + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 71 - Lu + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 72 - Hf + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 73 - Ta + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 74 - W + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 75 - Re + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 76 - Os + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 77 - Ir + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 78 - Pt + rasmolElementColors.add(new Color3f(new Color(0xDAA520))); // 79 - Au + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 80 - Hg + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 81 - Tl + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 82 - Pb + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 83 - Bi + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 84 - Po + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 85 - At + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 86 - Rn + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 87 - Fr + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 88 - Ra + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 89 - Ac + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 90 - Th + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 91 - Pa + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 92 - U + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 93 - Np + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 94 - Pu + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 95 - Am + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 96 - Cm + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 97 - Bk + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 98 - Cf + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 99 - Es + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 100 - Fm + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 101 - Md + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 102 - No + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 103 - Lr + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 104 - Db + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 105 - Jl + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 106 - Rf + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 107 - Bh + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 108 - Hn + rasmolElementColors.add(new Color3f(new Color(0xFF1493))); // 109 - Mt + + rasmolNewElementColors.addAll(rasmolElementColors); + rasmolNewElementColors.set(0, new Color3f(new Color(0xFA1691))); // 0 - Unknown + rasmolNewElementColors.set(3, new Color3f(new Color(0xB22121))); // 3 - Li + rasmolNewElementColors.set(6, new Color3f(new Color(0xD3D3D3))); // 6 - C + rasmolNewElementColors.set(7, new Color3f(new Color(0x87CEE6))); // 7 - N + rasmolNewElementColors.set(8, new Color3f(new Color(0xFF0000))); // 8 - O + rasmolNewElementColors.set(13, new Color3f(new Color(0x696969))); // 13 - Al + rasmolNewElementColors.set(15, new Color3f(new Color(0xFFAA00))); // 15 - P + rasmolNewElementColors.set(16, new Color3f(new Color(0xFFFF00))); // 16 - S + rasmolNewElementColors.set(20, new Color3f(new Color(0x696969))); // 20 - Ca + rasmolNewElementColors.set(22, new Color3f(new Color(0x696969))); // 22 - Ti + rasmolNewElementColors.set(24, new Color3f(new Color(0x696969))); // 24 - Cr + rasmolNewElementColors.set(25, new Color3f(new Color(0x696969))); // 25 - Mn + rasmolNewElementColors.set(26, new Color3f(new Color(0xFFAA00))); // 26 - Fe + rasmolNewElementColors.set(28, new Color3f(new Color(0x802828))); // 28 - Ni + rasmolNewElementColors.set(29, new Color3f(new Color(0x802828))); // 29 - Cu + rasmolNewElementColors.set(30, new Color3f(new Color(0x802828))); // 30 - Zn + rasmolNewElementColors.set(35, new Color3f(new Color(0x802828))); // 35 - Br + rasmolNewElementColors.set(47, new Color3f(new Color(0x696969))); // 47 - Ag + rasmolNewElementColors.set(56, new Color3f(new Color(0xFFAA00))); // 56 - Ba + + colorScheme.put(DEFAULT_ATOM_COLOR_SCHEME, elementColors); + colorScheme.put(ATOM_COLOR_SCHEME_2, gaussianElementColors); + colorScheme.put(ATOM_COLOR_SCHEME_JMOL, jmolElementColors); + colorScheme.put(ATOM_COLOR_SCHEME_RASMOL, rasmolElementColors); + colorScheme.put(ATOM_COLOR_SCHEME_RASMOL_NEW, rasmolNewElementColors); + + currentColorScheme = elementColors; + + } + + public static Color3f getElementColor(int atomNumber) { + Color3f color = new Color3f(Color.LIGHT_GRAY); + if (atomNumber < 0 || atomNumber >= elementColors.size()) { + return color; + } + try { + //color.set( (Color3f) elementColors.get(atomNumber)); + color.set( (Color3f) currentColorScheme.get(atomNumber)); + } + catch (IndexOutOfBoundsException e) { + // + } + return color; + } + + public static Material createMaterial(Color3f color) { + if (color == null) { + return null; + } + Material material = new Material(); + // --- Diffuse Color + material.setDiffuseColor(color); + + // --- Ambient Color + material.setAmbientColor(0.2f * color.x, 0.2f * color.y, 0.2f * color.z); + + // --- Emissive Color + material.setEmissiveColor(0.0f, 0.0f, 0.0f); + + // --- Specular Color + material.setSpecularColor(1.0f, 1.0f, 1.0f); + + // --- Set Shininess + material.setShininess(15.0f); + + material.setCapability(Material.ALLOW_COMPONENT_READ); + material.setCapability(Material.ALLOW_COMPONENT_WRITE); + return material; + + } + + public static Material getElementMaterial(int atomNumber) { + Material material = new Material(); + if (atomNumber < 0 || atomNumber >= elementColors.size()) { + return material; + } + + Color3f color = new Color3f(); + try { + color.set( (Color3f) currentColorScheme.get(atomNumber)); + //color.set( (Color3f) elementColors.get(atomNumber)); + } + catch (IndexOutOfBoundsException e) { + // + } + + return createMaterial(color); + } + + /** + * Returns number of available atom color schemes + * @return int + */ + public static int getAtomColorSchemeNumber() { + return colorScheme.size(); + } + + public static String getCurrentAtomColorScheme() { + return currentColorSchemeName; + } + + public static void setCurrentAtomColorScheme(String scheme) { + if (colorScheme.containsKey(scheme)) { + currentColorSchemeName = scheme; + currentColorScheme = (List) colorScheme.get(scheme); + return; + } + System.err.println("No such atom color scheme: " + scheme + " Ignored..."); + } + + public static String[] getAtomColorSchemeNames() { + + if (colorScheme == null || colorScheme.size() < 1) { + return null; + } + + String[] schemes = new String[colorScheme.size()]; + Set set = colorScheme.entrySet(); + Iterator iter = set.iterator(); + int count = 0; + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + schemes[count] = me.getKey().toString(); + ++count; + } + return schemes; + } + + public static void retrieveAtomColorSchemePrefs(Class c) { + try { + prefs = Preferences.userNodeForPackage(c); + } + catch (Exception ex) { + System.err.println("Error retrieving Atom Color Scheme Preferences: " + + ex.getMessage() + " Ignored..."); + return; + } + + String scheme = prefs.get(atomColorSchemeKey, currentColorSchemeName); + if (colorScheme.containsKey(scheme)) { + currentColorSchemeName = scheme; + currentColorScheme = (List) colorScheme.get(scheme); + return; + } + else { + logger.info("Retrieving Preferences: There is no such Atom Color Scheme: " + scheme); + currentColorSchemeName = ATOM_COLOR_SCHEME_2; + currentColorScheme = (List) colorScheme.get(currentColorSchemeName); + } + } + + public static void saveAtomColorSchemePrefs(Class c) { + try { + prefs = Preferences.userNodeForPackage(c); + } + catch (Exception ex) { + System.err.println("Error saving Atom Color Scheme Preferences: " + + ex.getMessage()); + return; + } + + try { + prefs.put(atomColorSchemeKey, currentColorSchemeName); + } + catch (Exception ex) { + System.err.println("Cannot save Atom Color Scheme Preferences: " + + ex.getMessage()); + } + + } + + public static Material getHighlightMaterial() { + return highlightMaterial; + } + + public static Color3f getHighlightColor3f() { + return highlightColor; + } + +} diff --git a/src/main/java/cct/j3d/ColorRangeScheme.java b/src/main/java/cct/j3d/ColorRangeScheme.java new file mode 100644 index 0000000..5deea58 --- /dev/null +++ b/src/main/java/cct/j3d/ColorRangeScheme.java @@ -0,0 +1,278 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import java.util.ArrayList; +import java.util.List; + +import org.scijava.vecmath.Color3f; +import org.scijava.vecmath.Color4f; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class ColorRangeScheme { + float fMin, fMax; + private float funAbsMax; + private float minClipValue, maxClipValue; + boolean useAbsMax = false; + + color3fPalette defaultPalette = new color3fPalette(); + + /** + * + * @param min float - min function value on vertices + * @param max float - max function value on vertices + */ + public ColorRangeScheme(float min, float max) { + fMin = min; + fMax = max; + + if (useAbsMax) { + if (fMin < 0 && fMax > 0) { + funAbsMax = Math.max(Math.abs(fMin), fMax); + minClipValue = -funAbsMax; + maxClipValue = funAbsMax; + } else if (fMin >= 0) { + funAbsMax = fMax; + minClipValue = fMin; + maxClipValue = fMax; + } else if (fMax <= 0) { + funAbsMax = -fMin; + minClipValue = fMin; + maxClipValue = fMax; + } + } else { + if (fMin < 0 && fMax > 0) { + funAbsMax = Math.min(Math.abs(fMin), fMax); + minClipValue = -funAbsMax; + maxClipValue = funAbsMax; + } else if (fMin >= 0) { + funAbsMax = fMax; + minClipValue = fMin; + maxClipValue = fMax; + } else if (fMax <= 0) { + funAbsMax = -fMin; + minClipValue = fMin; + maxClipValue = fMax; + } + + } + + defaultPalette.addColor(new Color3f(0, 0, 1)); // Blue + defaultPalette.addColor(new Color3f(0, 0.5f, 1)); // + defaultPalette.addColor(new Color3f(0, 1, 0)); // Green + defaultPalette.addColor(new Color3f(0.5f, 1, 0)); // greenyellow(SVG) rgb(173, 255, 47) + defaultPalette.addColor(new Color3f(1, 0, 0)); // Red + } + + public float getAbsRange() { + return funAbsMax; + } + + public float getClipMin() { + return minClipValue; + } + + public float getClipMax() { + return maxClipValue; + } + + public void setClipMin(float value) { + minClipValue = value; + } + + public void setClipMax(float value) { + maxClipValue = value; + } + + public float getMinFunValue() { + return fMin; + } + + public float getMaxFunValue() { + return fMax; + } + + public void getColor3f(float fValue, Color3f color) { + + //float range = (fValue + funAbsMax) / (2.0f * funAbsMax); + float range = (fValue - minClipValue) / (maxClipValue - minClipValue); + Color3f intepolated = defaultPalette.getColor3fInRange(range); + + color.x = intepolated.x; + color.y = intepolated.y; + color.z = intepolated.z; + } + + public int getColorRRGGBB(float fValue) { + + //float range = (fValue + funAbsMax) / (2.0f * funAbsMax); + float range = (fValue - minClipValue) / (maxClipValue - minClipValue); + Color3f intepolated = defaultPalette.getColor3fInRange(range); + + int color = intepolated.get().getRed(); + color <<= 8; + color |= intepolated.get().getGreen(); + color <<= 8; + color |= intepolated.get().getBlue(); + return color; + } + + public int getColorAARRGGBB(float fValue) { + float factor = 75.0f; + int color = 0; + float absMax = Math.min(Math.abs(fMin), Math.abs(fMax)); + + if (fMin < 0 && fMax > 0) { + if (fValue >= 0) { + color = (int) (fValue / absMax * 255.0f / factor); + if (color > 255) { + color = 255; + } + color <<= 8; + color |= 255; + color <<= 16; + } else { + color = (int) ( -fValue / absMax * 255.0f / factor); + if (color > 255) { + color = 255; + } + color <<= 24; + color |= 255; + } + } + + else if (fMin < 0) { + color = (int) (fValue / absMax * 255.0f / factor); + if (color > 255) { + color = 255; + } + color <<= 24; + color |= 255; + } else { + color = (int) (fValue / absMax * 255.0f / factor); + if (color > 255) { + color = 255; + } + color <<= 8; + color |= 255; + color <<= 16; + } + + if (true) { + return color; + } + + float range = (fValue - minClipValue) / (maxClipValue - minClipValue); + Color3f intepolated = defaultPalette.getColor3fInRange(range); + + color = intepolated.get().getRed(); + color <<= 8; + color |= intepolated.get().getGreen(); + color <<= 8; + color |= intepolated.get().getBlue(); + return color; + } + + + public void getColor4f(float fValue, Color4f color) { + + //float range = (fValue + funAbsMax) / (2.0f * funAbsMax); + float range = (fValue - minClipValue) / (maxClipValue - minClipValue); + Color3f intepolated = defaultPalette.getColor3fInRange(range); + + color.x = intepolated.x; + color.y = intepolated.y; + color.z = intepolated.z; + } + + public List getColor3fPalette() { + return defaultPalette.getColor3fPalette(); + } + +} + + +class color3fPalette { + List Colors = new ArrayList(); + + public void addColor(Color3f color) { + Colors.add(color); + } + + public Color3f getColor3fInRange(float range) { + if (range < 0) { + range = 0; + } else if (range > 1) { + range = 1; + } + + float step = 1.0f / (Colors.size() - 1); + int start_index = (int) (range / step); + int end_index = start_index; + if (end_index < Colors.size() - 2) { + ++end_index; + } + + Color3f start_color = Colors.get(start_index); + Color3f end_color = Colors.get(end_index); + + Color3f interpolatedColor = new Color3f(); + + float delta = range - start_index * step; + interpolatedColor.x = start_color.x + delta / step * (end_color.x - start_color.x); + interpolatedColor.y = start_color.y + delta / step * (end_color.y - start_color.y); + interpolatedColor.z = start_color.z + delta / step * (end_color.z - start_color.z); + + return interpolatedColor; + } + + public List getColor3fPalette() { + return Colors; + } +} diff --git a/src/main/java/cct/j3d/GroupToVRML.java b/src/main/java/cct/j3d/GroupToVRML.java new file mode 100644 index 0000000..d5a03bc --- /dev/null +++ b/src/main/java/cct/j3d/GroupToVRML.java @@ -0,0 +1,1568 @@ +package cct.j3d; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.Enumeration; +import java.util.logging.Logger; +import java.util.prefs.Preferences; + +import org.scijava.java3d.Alpha; +import org.scijava.java3d.AmbientLight; +import org.scijava.java3d.Appearance; +import org.scijava.java3d.Background; +import org.scijava.java3d.Behavior; +import org.scijava.java3d.BoundingLeaf; +import org.scijava.java3d.BranchGroup; +import org.scijava.java3d.Canvas3D; +import org.scijava.java3d.DirectionalLight; +import org.scijava.java3d.ExponentialFog; +import org.scijava.java3d.Fog; +import org.scijava.java3d.Geometry; +import org.scijava.java3d.GeometryArray; +import org.scijava.java3d.GeometryStripArray; +import org.scijava.java3d.Group; +import org.scijava.java3d.Leaf; +import org.scijava.java3d.Light; +import org.scijava.java3d.LinearFog; +import org.scijava.java3d.Locale; +import org.scijava.java3d.Material; +import org.scijava.java3d.Node; +import org.scijava.java3d.PointLight; +import org.scijava.java3d.PolygonAttributes; +import org.scijava.java3d.SceneGraphObject; +import org.scijava.java3d.Shape3D; +import org.scijava.java3d.Switch; +import org.scijava.java3d.SwitchValueInterpolator; +import org.scijava.java3d.Transform3D; +import org.scijava.java3d.TransformGroup; +import org.scijava.java3d.TransparencyAttributes; +import org.scijava.java3d.TriangleArray; +import org.scijava.java3d.TriangleFanArray; +import org.scijava.java3d.TriangleStripArray; +import org.scijava.java3d.View; +import org.scijava.java3d.ViewPlatform; +import javax.swing.JFileChooser; +import org.scijava.vecmath.AxisAngle4d; +import org.scijava.vecmath.Color3f; +import org.scijava.vecmath.Color4f; +import org.scijava.vecmath.Matrix3d; +import org.scijava.vecmath.Point3d; +import org.scijava.vecmath.Vector3d; +import org.scijava.vecmath.Vector3f; + +import cct.GlobalConstants; +import cct.tools.FileFilterImpl; + +import org.scijava.java3d.utils.geometry.Cone; +import org.scijava.java3d.utils.geometry.Cylinder; +import org.scijava.java3d.utils.geometry.Primitive; +import org.scijava.java3d.utils.geometry.Sphere; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class GroupToVRML + implements GlobalConstants { + + public enum DUMP_SWITCH { + ALL, ACTIVE_CHILD_ONLY} + + DUMP_SWITCH dumpSwitch = DUMP_SWITCH.ALL; + + private static String lastPWDKey = "lastPWD"; + + private boolean skipLight = true; + + private boolean writeColorsPerVertex = true; + private Preferences prefs = Preferences.userNodeForPackage(getClass()); + private File currentWorkingDirectory = null; + private JFileChooser chooser = null; + private FileFilterImpl filter = null; + + private Node node = null; + private Locale locale = null; + private Canvas3D canvas3D = null; + private String prefix = ""; + static final Logger logger = Logger.getLogger(GroupToVRML.class.getCanonicalName()); + + public GroupToVRML(Node nd) { + node = nd; + } + + public GroupToVRML(Locale loc) { + locale = loc; + } + + public void setCanvas3D(Canvas3D c3d) { + canvas3D = c3d; + } + + public void setPrefix(String pref) { + prefix = pref; + } + + public void enableColorsPerVertex(boolean enable) { + writeColorsPerVertex = enable; + } + + public static void main(String[] args) { + //BranchGroupToVRML java3dtovrml = new BranchGroupToVRML(); + } + + public void getNode(Node node, OutputStream vrml) { + try { + if (node instanceof Group) { + vrml.write("\n".getBytes()); + getGroup( (Group) node, vrml); + vrml.write("\n".getBytes()); + } + else if (node instanceof Leaf) { + vrml.write("\n".getBytes()); + getLeaf( (Leaf) node, vrml); + vrml.write("\n".getBytes()); + } + else { + System.err.println("getNode: don't know how to handle class: " + node.getClass().getCanonicalName()); + return; + } + } + catch (Exception ex) { + System.err.println("getNode: I/O Error: " + ex.getMessage()); + } + } + + /** + * Writes Locale into OutputStream + * @param locale Locale + * @param vrml OutputStream + */ + public void getLocale(Locale locale, OutputStream vrml) throws Exception { + int n = locale.numBranchGraphs(); + if (n < 1) { + return; + } + + Enumeration branchGraphs = null; + try { + branchGraphs = locale.getAllBranchGraphs(); + } + catch (Exception ex) { + System.err.println("getLocale: " + ex.getMessage()); + return; + } + + while (branchGraphs.hasMoreElements()) { + BranchGroup bg = (BranchGroup) branchGraphs.nextElement(); + getBranchGroup(bg, vrml); + } + } + + /** + * Converts Group into VRML String + * @param group Group + * @return String + */ + public void getGroup(Group group, OutputStream vrml) throws Exception { + Enumeration children = group.getAllChildren(); + if (!children.hasMoreElements()) { + return; + } + + while (children.hasMoreElements()) { + Object obj = children.nextElement(); + + if (obj instanceof BranchGroup) { + vrml.write("\n".getBytes()); + getBranchGroup( (BranchGroup) obj, vrml); + vrml.write("\n".getBytes()); + } + else if (obj instanceof Primitive) { + vrml.write("\n".getBytes()); + getPrimitive( (Primitive) obj, vrml); + vrml.write("\n".getBytes()); + } + else if (obj instanceof TransformGroup) { + vrml.write("\n".getBytes()); + getTransformGroup( (TransformGroup) obj, vrml); + vrml.write("\n".getBytes()); + } + else if (obj instanceof Switch) { + vrml.write("\n".getBytes()); + getSwitch( (Switch) obj, vrml); + vrml.write("\n".getBytes()); + } + else if (obj instanceof Leaf) { + vrml.write("\n".getBytes()); + getLeaf( (Leaf) obj, vrml); + vrml.write("\n".getBytes()); + } + else { + System.err.println("getGroup: don't know how to handle class: " + obj.getClass().getCanonicalName()); + } + } + } + + public void getPrimitive(Primitive prim, OutputStream vrml) throws Exception { + + if (prim instanceof Sphere) { + getSphere( (Sphere) prim, vrml); + } + else if (prim instanceof Cylinder) { + getCylinder( (Cylinder) prim, vrml); + } + else if (prim instanceof Cone) { + getCone( (Cone) prim, vrml); + } + else { + System.err.println("getPrimitiveAsVRMLString: do not know how to handle class " + prim.getClass().getCanonicalName()); + } + } + + public void getSphere(Sphere sphere, OutputStream vrml) throws Exception { + + vrml.write("\n Shape { # ".getBytes()); + vrml.write(createDEF(sphere, UserData.NODE_NAME).getBytes()); + vrml.write("\n".getBytes()); + try { + Appearance app = sphere.getAppearance(); + getAppearance(app, vrml); + } + catch (Exception ex) { + System.err.println("getSphereGroupAsVRMLString: " + ex.getMessage()); + } + + vrml.write( (" geometry Sphere { radius " + sphere.getRadius() + " }\n").getBytes()); + + vrml.write(" }\n".getBytes()); + } + + public void getCylinder(Cylinder cylinder, OutputStream vrml) throws Exception { + + vrml.write( ("\n " + createDEF(cylinder, UserData.NODE_NAME) + " Shape { # " + + UserData.getUserDataAsString(cylinder, UserData.NODE_NAME) + "\n").getBytes()); + try { + Appearance app = cylinder.getAppearance(); + getAppearance(app, vrml); + } + catch (Exception ex) { + System.err.println("getCylinderGroupAsVRMLString: " + ex.getMessage()); + } + + vrml.write( (" geometry Cylinder { radius " + cylinder.getRadius() + " height " + cylinder.getHeight() + " }\n").getBytes()); + + vrml.write(" }\n".getBytes()); + } + + public void getCone(Cone cone, OutputStream vrml) throws Exception { + + vrml.write( ("\n " + createDEF(cone, UserData.NODE_NAME) + " Shape { # " + + UserData.getUserDataAsString(cone, UserData.NODE_NAME) + "\n").getBytes()); + try { + Appearance app = cone.getAppearance(); + getAppearance(app, vrml); + } + catch (Exception ex) { + System.err.println("getConeGroupAsVRMLString: " + ex.getMessage()); + } + + vrml.write( (" geometry Cone { bottomRadius " + cone.getRadius() + " height " + cone.getHeight() + " }\n").getBytes()); + + vrml.write(" }\n".getBytes()); + } + + /* + public String getVRMLAsString(Group gr) throws Exception { + StringWriter vrml = new StringWriter(1024); + Enumeration children = gr.getAllChildren(); + if (!children.hasMoreElements()) { + return ""; + } + + if (gr instanceof BranchGroup) { + vrml.write("\n" + getBranchGroupAsVRMLString( (BranchGroup) gr) + "\n"); + } + else if (gr instanceof TransformGroup) { + vrml.write("\n" + getTransformGroupAsVRMLString( (TransformGroup) gr) + "\n"); + } + else if (gr instanceof Switch) { + vrml.write("\n" + getSwitchAsVRMLString( (Switch) gr) + "\n"); + } + + else { + System.err.println("getVRMLAsString: don't know how to handle class: " + gr.getClass().getCanonicalName()); + } + + return vrml.toString(); + } + */ + + public void getBranchGroup(BranchGroup bg, OutputStream vrml) throws Exception { + Enumeration children = bg.getAllChildren(); + if (!children.hasMoreElements()) { + return; + } + + vrml.write( ("\n" + createDEF(bg, UserData.NODE_NAME) + " Group { children [\n").getBytes()); + + while (children.hasMoreElements()) { + Object obj = children.nextElement(); + if (obj instanceof Group) { + //vrml.write("\n" + getGroupAsVRMLString( (Group) obj) + "\n"); + vrml.write("\n".getBytes()); + getGroup( (Group) obj, vrml); + vrml.write("\n".getBytes()); + } + else if (obj instanceof Leaf) { + vrml.write("\n".getBytes()); + getLeaf( (Leaf) obj, vrml); + vrml.write("\n".getBytes()); + } + else { + System.err.println("getBranchGroupAsVRMLString: don't know how to handle class: " + obj.getClass().getCanonicalName()); + } + } + vrml.write("\n ] }\n".getBytes()); + } + + public void getTransformGroup(TransformGroup tg, OutputStream vrml) throws Exception { + Enumeration children = tg.getAllChildren(); + if (!children.hasMoreElements()) { + return; + } + + vrml.write( ("\n" + createDEF(tg, UserData.NODE_NAME) + " Transform {\n").getBytes()); + + Transform3D t3d = new Transform3D(); + tg.getTransform(t3d); + + vrml.write("\n".getBytes()); + getTransform3D(t3d, vrml); + vrml.write("\n".getBytes()); + + vrml.write("\n children [\n".getBytes()); + while (children.hasMoreElements()) { + Object obj = children.nextElement(); + if (obj instanceof Primitive) { // This is a special case + vrml.write("\n ".getBytes()); + getPrimitive( (Primitive) obj, vrml); + vrml.write(" \n".getBytes()); + } + else if (obj instanceof Group) { + try { + vrml.write("\n ".getBytes()); + getGroup( (Group) obj, vrml); + vrml.write(" \n".getBytes()); + } + catch (Exception ex) { + System.err.println("getTransformGroup: " + ex.getMessage()); + } + } + else if (obj instanceof Leaf) { + vrml.write("\n ".getBytes()); + getLeaf( (Leaf) obj, vrml); + vrml.write(" \n".getBytes()); + } + + else { + System.err.println("getTransformGroup: don't know how to handle class: " + obj.getClass().getCanonicalName()); + } + } + vrml.write("\n ]\n".getBytes()); + + vrml.write("\n}\n".getBytes()); + } + + private void getTransform3D(Transform3D t3d, OutputStream vrml) throws Exception { + + Vector3f v3f = new Vector3f(); + t3d.get(v3f); + vrml.write( ("\n translation " + v3f.x + " " + v3f.y + " " + v3f.z + "\n").getBytes()); + + Matrix3d m = new Matrix3d(); + t3d.get(m); + AxisAngle4d axisAngle4d = new AxisAngle4d(); + Java3dUtils.toAxisAngle(m, axisAngle4d); + vrml.write( (" rotation " + axisAngle4d.x + " " + axisAngle4d.y + " " + axisAngle4d.z + " " + axisAngle4d.angle + "\n"). + getBytes()); + + Vector3d v3d = new Vector3d(); + t3d.getScale(v3d); + vrml.write( (" scale " + v3d.x + " " + v3d.y + " " + v3d.z + "\n").getBytes()); + } + + public void getAppearance(Appearance app, OutputStream vrml) throws Exception { + + vrml.write(" appearance Appearance { # --- Start of Appearance\n".getBytes()); + try { + Material material = app.getMaterial(); + vrml.write(" material Material {\n".getBytes()); + Color3f color = new Color3f(); + material.getAmbientColor(color); + vrml.write( (" ambientIntensity " + Math.sqrt(color.x * color.x + color.y * color.y + color.z * color.z) + "\n"). + getBytes()); + material.getDiffuseColor(color); + vrml.write( (" diffuseColor " + color.x + " " + color.y + " " + color.z + "\n").getBytes()); + material.getEmissiveColor(color); + vrml.write( (" emissiveColor " + color.x + " " + color.y + " " + color.z + "\n").getBytes()); + material.getSpecularColor(color); + vrml.write( (" specularColor " + color.x + " " + color.y + " " + color.z + "\n").getBytes()); + vrml.write( (" shininess " + material.getShininess() + "\n").getBytes()); + TransparencyAttributes ta = app.getTransparencyAttributes(); + float transp = 0; + if (ta != null) { + transp = ta.getTransparency(); + } + vrml.write( (" transparency " + transp + "\n").getBytes()); + + vrml.write( (" }\n").getBytes()); + } + catch (Exception ex) { + System.err.println("getAppearanceAsVRMLString: " + ex.getMessage()); + } + + vrml.write(" } # --- End of Appearance\n".getBytes()); + } + + private void getSwitch(Switch sw, OutputStream vrml) throws Exception { + int which_child = 0; + try { + which_child = sw.getWhichChild(); + } + catch (Exception ex) { + System.err.println(ex.getMessage() + " : ignored..."); + return; + } + + Object obj = null; + + switch (which_child) { + case Switch.CHILD_NONE: + return; + + case Switch.CHILD_ALL: + Enumeration children = sw.getAllChildren(); + if (!children.hasMoreElements()) { + return; + } + while (children.hasMoreElements()) { + obj = children.nextElement(); + if (obj instanceof Group) { + try { + getGroup( (Group) obj, vrml); + } + catch (Exception ex) { + System.err.println(ex.getMessage()); + } + } + else if (obj instanceof Leaf) { + vrml.write("\n".getBytes()); + getLeaf( (Leaf) obj, vrml); + vrml.write("\n".getBytes()); + } + } + return; + + case Switch.CHILD_MASK: + System.err.println("getSwitchAsVRMLString: handling CHILD_MASK is not implemented yet"); + break; + + default: + obj = sw.getChild(which_child); + if (obj instanceof Group) { + try { + getGroup( (Group) obj, vrml); + return; + } + catch (Exception ex) {} + } + else { + System.err.println("getSwitchAsVRMLString: don't know how to handle class: " + obj.getClass().getCanonicalName()); + } + + } + return; + } + + public void getLeaf(Leaf leaf, OutputStream vrml) throws Exception { + // Leaf could be AlternateAppearance, Background, Behavior, BoundingLeaf, Clip, Fog, Light, Link, ModelClip, Morph, Shape3D, Sound, Soundscape, ViewPlatform + + Object obj = leaf; + if (obj instanceof Shape3D) { + getShape3D( (Shape3D) leaf, vrml); + return; + } + else if (obj instanceof Fog) { + getFog( (Fog) leaf, vrml); + return; + } + else if (obj instanceof Light) { + getLight( (Light) leaf, vrml); + return; + } + else if (obj instanceof Background) { + getBackground( (Background) leaf, vrml); + return; + } + + else if (obj instanceof ViewPlatform) { + getViewPlatform(vrml); + return; + } + + else if (obj instanceof SwitchValueInterpolator) { + getSwitchValueInterpolator( (SwitchValueInterpolator) obj, vrml); + return; + } + + else if (obj instanceof BoundingLeaf) { + logger.info("getLeafAsVRMLString: skipping " + obj.getClass().getCanonicalName()); + } + else if (obj instanceof Behavior) { + logger.info("getLeafAsVRMLString: skipping " + obj.getClass().getCanonicalName()); + } + + else { + System.err.println("getLeafAsVRMLString: don't know how to handle class: " + obj.getClass().getCanonicalName()); + } + } + + public void getSwitchValueInterpolator(SwitchValueInterpolator svi, OutputStream vrml) throws Exception { + if (canvas3D == null) { + return; + } + Switch sw = svi.getTarget(); + Alpha alpha = svi.getAlpha(); + vrml.write("\n# --- Start of SwitchValueInterpolator\n".getBytes()); + + int which_child = 0; + try { + which_child = sw.getWhichChild(); + } + catch (Exception ex) { + System.err.println(ex.getMessage() + " : ignored..."); + return; + } + + //if ( which_child != Switch.CHILD_ALL ) sw.setWhichChild(Switch.CHILD_ALL); + + switch (dumpSwitch) { + case ACTIVE_CHILD_ONLY: + this.getSwitch(sw, vrml); + break; + + case ALL: + //String store = prefix; + for (int i = 0; i < sw.numChildren(); i++) { + //prefix = String.format("%03d_STR_", (i + 1)) + store; + sw.setWhichChild(i); + this.getSwitch(sw, vrml); + } + //prefix = store; + sw.setWhichChild(which_child); + break; + } + vrml.write("# --- End of SwitchValueInterpolator\n".getBytes()); + } + + public void getViewPlatform(OutputStream vrml) throws Exception { + if (canvas3D == null) { + return; + } + if (false) { // --- Skip + + vrml.write("\n Viewpoint { # --- Start of Viewpoint\n".getBytes()); + + vrml.write(" description \"Default Viewpoint\"\n".getBytes()); + vrml.write(" jump TRUE\n".getBytes()); + vrml.write(" set_bind TRUE\n".getBytes()); + + View view = canvas3D.getView(); + int pPolicy = view.getProjectionPolicy(); + + vrml.write( (" fieldOfView " + view.getFieldOfView() + " # In degrees: " + + (view.getFieldOfView() * RADIANS_TO_DEGREES) + "\n").getBytes()); + + Point3d position = new Point3d(); + canvas3D.getCenterEyeInImagePlate(position); + Transform3D motion = new Transform3D(); + canvas3D.getImagePlateToVworld(motion); + motion.transform(position); + + vrml.write( (" position " + position.x + " " + position.y + " " + position.z + "\n").getBytes()); + + vrml.write(" } # --- End of Viewpoint\n".getBytes()); + + vrml.write("\n NavigationInfo { # --- Start of NavigationInfo\n".getBytes()); + vrml.write(" type \"EXAMINE\"\n".getBytes()); + vrml.write(" speed 10.0\n".getBytes()); + vrml.write(" avatarSize [0.5, 0.5, 0.5]\n".getBytes()); + vrml.write(" headlight FALSE\n".getBytes()); + vrml.write(" set_bind TRUE\n".getBytes()); + vrml.write(" } # --- End of NavigationInfo\n".getBytes()); + } + } + + public void getFog(Fog fog, OutputStream vrml) throws Exception { + if (fog instanceof ExponentialFog) { + System.err.println("getFogAsVRMLString: ExponentialFog is not implemented yet"); + return; + } + else if (fog instanceof LinearFog) { + getLinearFog( (LinearFog) fog, vrml); + return; + } + System.err.println("getFogAsVRMLString: don't know how to handle class: " + fog.getClass().getCanonicalName()); + return; + } + + public void getLight(Light light, OutputStream vrml) throws Exception { + if (skipLight) { + return; + } + if (light instanceof AmbientLight) { + logger.info("getLightAsVRMLString: AmbientLight is not implemented yet"); + return; + } + else if (light instanceof DirectionalLight) { + getDirectionalLight( (DirectionalLight) light, vrml); + return; + } + else if (light instanceof PointLight) { + System.err.println("getLightAsVRMLString: PointLight is not implemented yet"); + return; + } + + System.err.println("getLightAsVRMLString: don't know how to handle class: " + light.getClass().getCanonicalName()); + } + + public void getLinearFog(LinearFog fog, OutputStream vrml) throws Exception { + + Color3f color = new Color3f(); + double backDist = 0; + + vrml.write("\n Fog { # --- Start of Linear Fog\n".getBytes()); + vrml.write(" fogType \"LINEAR\"\n".getBytes()); + try { + fog.getColor(color); + vrml.write( (" color " + color.x + " " + color.y + " " + color.z + "\n").getBytes()); + } + catch (Exception ex) { + System.err.println("getLinearFogAsVRMLString: " + ex.getMessage()); + } + try { + backDist = fog.getBackDistance(); + } + catch (Exception ex) { + System.err.println("getLinearFogAsVRMLString: " + ex.getMessage()); + } + vrml.write( (" visibilityRange " + String.format("%8.3f", backDist) + "\n").getBytes()); + + vrml.write(" } # --- End of Linear Fog\n".getBytes()); + } + + public void getBackground(Background bg, OutputStream vrml) throws Exception { + Color3f color = new Color3f(0, 0, 0); + double backDist = 0; + + vrml.write("\n Background { # --- Start of Background\n".getBytes()); + try { + bg.getColor(color); + } + catch (Exception ex) { + System.err.println("getBackgroundAsVRMLString: " + ex.getMessage()); + } + vrml.write( (" skyColor " + color.x + " " + color.y + " " + color.z + "\n").getBytes()); + + vrml.write(" } # --- End of Background\n".getBytes()); + } + + public void getDirectionalLight(DirectionalLight light, OutputStream vrml) throws Exception { + + boolean lightOn = true; // default + Color3f color = new Color3f(1, 1, 1); // default + Vector3f direction = new Vector3f(0, 0, -1); // default + + vrml.write("\n DirectionalLight { # --- Start of DirectionalLight\n".getBytes()); + try { + lightOn = light.getEnable(); + } + catch (Exception ex) { + System.err.println("getDirectionalLightAsVRMLString: " + ex.getMessage()); + } + vrml.write(" on ".getBytes()); + if (lightOn) { + vrml.write("TRUE\n".getBytes()); + } + else { + vrml.write("FALSE\n".getBytes()); + } + + try { + light.getColor(color); + } + catch (Exception ex) { + System.err.println("getDirectionalLightAsVRMLString: " + ex.getMessage()); + } + vrml.write( (" color " + color.x + " " + color.y + " " + color.z + "\n").getBytes()); + + try { + light.getDirection(direction); + } + catch (Exception ex) { + System.err.println("getDirectionalLightAsVRMLString: " + ex.getMessage()); + } + vrml.write( (" direction " + direction.x + " " + direction.y + " " + direction.z + "\n").getBytes()); + + vrml.write(" intensity 1.0\n".getBytes()); // Default + vrml.write(" ambientIntensity 0.0\n".getBytes()); // Default + + vrml.write(" } # --- End of DirectionalLight\n".getBytes()); + } + + /** + * The Shape3D leaf node specifies all geometric objects. It contains a list of one or more + * Geometry component objects and a single Appearance component object. + * @param shape3d Shape3D + * @return String + */ + public void getShape3D(Shape3D shape3d, OutputStream vrml) throws Exception { + + int n_shapes = 0; + try { + n_shapes = shape3d.numGeometries(); + } + catch (Exception ex) { + System.err.println("getShape3DAsVRMLString: " + ex.getMessage()); + return; + } + + if (n_shapes < 1) { + return; + } + + //if (shape3d.getCapability(Shape3D.ALLOW_GEOMETRY_READ)) { + // System.err.println("getShape3DAsVRMLString: ALLOW_GEOMETRY_READ is not set"); + // return ""; + //} + + vrml.write( ("\n" + createDEF(shape3d, UserData.NODE_NAME) + " Shape { # --- Start of Shape " + + createDEF(shape3d, UserData.NODE_NAME) + "\n"). + getBytes()); + + // Write down Appearance + try { + Appearance app = shape3d.getAppearance(); + vrml.write("\n".getBytes()); + getAppearance(app, vrml); + vrml.write("\n".getBytes()); + //RenderingAttributes ra = app.getRenderingAttributes(); + } + catch (Exception ex) { + System.err.println("getShape3DAsVRMLString: " + ex.getMessage()); + } + + // --- Get polygon attributes + int rasterizationMode = PolygonAttributes.POLYGON_FILL; // Default for java3d + try { + Appearance app = shape3d.getAppearance(); + PolygonAttributes pa = app.getPolygonAttributes(); + if (pa != null) { + rasterizationMode = pa.getPolygonMode(); + } + } + catch (Exception ex) { + System.err.println("getShape3DAsVRMLString: " + ex.getMessage()); + } + + // Write down geometries + + for (int i = 0; i < n_shapes; i++) { + Geometry geometry = shape3d.getGeometry(i); + vrml.write("\n".getBytes()); + getGeometry(geometry, rasterizationMode, vrml); + vrml.write("\n".getBytes()); + } + + vrml.write("\n} # --- End of Shape\n".getBytes()); + } + + /** + * Geometry is an abstract class that specifies the geometry component information required by a Shape3D node. + * Geometry objects describe both the geometry and topology of the Shape3D nodes that reference them. + * Geometry objects consist of four generic geometric types: + * Compressed Geometry + * GeometryArray + * Raster + * Text3D + * @param geometry Geometry + * @return String + */ + public void getGeometry(Geometry geometry, int rasterizationMode, OutputStream vrml) throws Exception { + if (geometry instanceof GeometryArray) { + vrml.write("\n".getBytes()); + getGeometryArray( (GeometryArray) geometry, rasterizationMode, vrml); + vrml.write("\n".getBytes()); + } + else { + System.err.println("getGeometryAsVRMLString: don't know how to handle class: " + geometry.getClass().getCanonicalName()); + return; + } + } + + /** + * The GeometryArray object contains separate arrays of positional coordinates, colors, + * normals, texture coordinates, and vertex attributes that describe point, line, or polygon geometry. + * This class is extended to create the various primitive types (such as lines, triangle strips, etc.). + * Vertex data may be passed to this geometry array in one of two ways: + * by copying the data into the array using the existing methods, or by passing a reference to the data. + * @param ga GeometryArray + * @return String + */ + public void getGeometryArray(GeometryArray ga, int rasterizationMode, OutputStream vrml) throws Exception { + + if (ga instanceof TriangleArray) { + getTriangleArray( (TriangleArray) ga, rasterizationMode, vrml); + } + else if (ga instanceof GeometryStripArray) { + getGeometryStripArray( (GeometryStripArray) ga, vrml); + } + + else { + System.err.println("getGeometryArrayAsVRMLString: don't know how to handle class: " + ga.getClass().getCanonicalName()); + return; + } + } + + public void getGeometryStripArray(GeometryStripArray gsa, OutputStream vrml) throws Exception { + + if (gsa instanceof TriangleFanArray) { + getTriangleFanArray( (TriangleFanArray) gsa, vrml); + } + else if (gsa instanceof TriangleStripArray) { + getTriangleStripArray( (TriangleStripArray) gsa, vrml); + } + + else { + System.err.println("getGeometryStripArrayAsVRMLString: don't know how to handle class: " + gsa.getClass().getCanonicalName()); + return; + } + } + + /** + * Note that only one additional vertex is needed to draw the second triangle. + * In OpenGL, the order in which the vertices are specified is important so that surface normals are consistent. + * Quoted directly from the OpenGL redbook: + * GL_TRIANGLE_STRIP Draws a series of triangles (three-sided polygons) using vertices v0, v1, v2, then v2, v1, v3 (note the order), then v2, v3, v4, and so on. The ordering is to ensure that the triangles are all drawn with the same orientation so that the strip can correctly form part of a surface. + * + * @param tsa TriangleStripArray + * @return String + */ + public void getTriangleStripArray(TriangleStripArray tsa, OutputStream vrml) throws Exception { + + int format = 0; + try { + format = tsa.getVertexFormat(); + } + catch (Exception ex) { + System.err.println("getTriangleStripArrayAsVRMLString: " + ex.getMessage()); + format |= GeometryArray.COORDINATES; + } + + // --- Get number of vertices + + int n_vertices = 0; + try { + n_vertices = tsa.getVertexCount(); + } + catch (Exception ex) { + System.err.println("getTriangleStripArrayAsVRMLString: " + ex.getMessage()); + return; + } + + if (n_vertices < 1) { + System.err.println("getTriangleStripArrayAsVRMLString: number of vertices < 1"); + return; + } + + // --- Get coordinates, colors, and normals, if any + + double[] coordinates = this.getCoordinates(tsa); + Color3f[] colors3f = this.getColors3f(tsa); + Color4f[] colors4f = this.getColors4f(tsa); + Vector3f[] normals = this.getNormals(tsa); + + // --- Create VRML + + vrml.write("\n geometry IndexedFaceSet { # --- Start of TriangleStripArray\n".getBytes()); + vrml.write(" ccw TRUE\n".getBytes()); + vrml.write(" solid FALSE\n".getBytes()); + vrml.write(" coord Coordinate { # --- Start of Coordinates\n".getBytes()); + + vrml.write(" point [\n".getBytes()); + for (int i = 0; i < n_vertices; i++) { + if (i != 0) { + vrml.write(",\n".getBytes()); + } + vrml.write( (" " + + String.format("%10.4f %10.4f %10.4f", coordinates[3 * i], coordinates[3 * i + 1], coordinates[3 * i + 2])). + getBytes()); + } + vrml.write("\n ]\n".getBytes()); + + vrml.write(" } # --- End of Coordinates\n".getBytes()); + + // --- Write triangle indices + + vrml.write(" coordIndex [ # --- Start of Triangles indices\n".getBytes()); + for (int i = 0; i < n_vertices - 2; i++) { + if (i != 0) { + vrml.write(",\n".getBytes()); + } + if (i % 2 == 0) { + vrml.write( (" " + i + ", " + (i + 1) + ", " + (i + 2) + ", -1").getBytes()); + } + else { + vrml.write( (" " + (i + 1) + ", " + i + ", " + (i + 2) + ", -1").getBytes()); + } + } + vrml.write("\n ] # --- End of Triangles indices\n".getBytes()); + + // --- write colors, if any + + if (writeColorsPerVertex && (colors3f != null || colors4f != null)) { + vrml.write(" colorPerVertex TRUE\n".getBytes()); + vrml.write(" color Color {\n".getBytes()); + vrml.write(" color [\n".getBytes()); + for (int i = 0; i < n_vertices; i++) { + if (i != 0) { + vrml.write(",\n".getBytes()); + } + if (colors3f != null) { + vrml.write( (" " + String.format("%7.4f %7.4f %7.4f", colors3f[i].x, colors3f[i].y, colors3f[i].z)). + getBytes()); + } + else if (colors4f != null) { + vrml.write( (" " + String.format("%7.4f %7.4f %7.4f", colors4f[i].x, colors4f[i].y, colors4f[i].z)). + getBytes()); + } + } + + vrml.write("\n ]\n".getBytes()); + vrml.write(" }\n".getBytes()); + + vrml.write(" colorIndex [\n".getBytes()); + for (int i = 0; i < n_vertices - 2; i++) { + if (i != 0) { + vrml.write(",\n".getBytes()); + } + if (i % 2 == 0) { + vrml.write( (" " + i + ", " + (i + 1) + ", " + (i + 2) + ", -1").getBytes()); + } + else { + vrml.write( (" " + (i + 1) + ", " + i + ", " + (i + 2) + ", -1").getBytes()); + } + + } + vrml.write("\n ]\n".getBytes()); + } + else { + vrml.write(" colorPerVertex FALSE\n".getBytes()); + } + + // --- write normals, if any + + if (normals != null) { + vrml.write(" normalPerVertex TRUE\n".getBytes()); + vrml.write(" normal Normal {\n".getBytes()); + vrml.write(" vector [\n".getBytes()); + for (int i = 0; i < n_vertices; i++) { + if (i != 0) { + vrml.write(",\n".getBytes()); + } + vrml.write( (" " + String.format("%7.4f %7.4f %7.4f", normals[i].x, normals[i].y, normals[i].z)).getBytes()); + } + + vrml.write("\n ]\n".getBytes()); + vrml.write(" }\n".getBytes()); + + vrml.write(" normalIndex [\n".getBytes()); + for (int i = 0; i < n_vertices - 2; i++) { + if (i != 0) { + vrml.write(",\n".getBytes()); + } + if (i % 2 == 0) { + vrml.write( (" " + i + ", " + (i + 1) + ", " + (i + 2) + ", -1").getBytes()); + } + else { + vrml.write( (" " + (i + 1) + ", " + i + ", " + (i + 2) + ", -1").getBytes()); + } + + } + vrml.write( ("\n ]\n").getBytes()); + + } + else { + vrml.write(" normalPerVertex FALSE\n".getBytes()); + } + + vrml.write("\n } # --- End of TriangleStripArray\n".getBytes()); + } + + /** + * A triangle fan is a primitive in 3D computer graphics that saves on storage and processing time. + * It describes a set of connected triangles that share one central vertex. + * If N is the number of triangles in the fan, the number of vertices describing it is N+2. + * This is a considerable improvement over the 3N vertices that are necessary to describe the triangles separately. + * @param tfa TriangleFanArray + * @return String + */ + private void getTriangleFanArray(TriangleFanArray tfa, OutputStream vrml) throws Exception { + int format = 0; + try { + format = tfa.getVertexFormat(); + } + catch (Exception ex) { + System.err.println("getTriangleFanArrayAsVRMLString: " + ex.getMessage()); + format |= GeometryArray.COORDINATES; + } + + // --- Get number of vertices + + int n_vertices = 0; + try { + n_vertices = tfa.getVertexCount(); + } + catch (Exception ex) { + System.err.println("getTriangleFanArrayAsVRMLString: " + ex.getMessage()); + return; + } + + if (n_vertices < 1) { + System.err.println("getTriangleFanArrayAsVRMLString: number of vertices < 1"); + return; + } + + // --- Get coordinates, colors, and normals, if any + + double[] coordinates = this.getCoordinates(tfa); + Color3f[] colors3f = this.getColors3f(tfa); + Color4f[] colors4f = this.getColors4f(tfa); + Vector3f[] normals = this.getNormals(tfa); + + // --- Create VRML + + vrml.write("\n geometry IndexedFaceSet { # --- Start of TriangleFanArray\n".getBytes()); + vrml.write(" ccw TRUE\n".getBytes()); + vrml.write(" solid FALSE\n".getBytes()); + vrml.write(" coord Coordinate { # --- Start of Coordinates\n".getBytes()); + + vrml.write(" point [\n".getBytes()); + for (int i = 0; i < n_vertices; i++) { + if (i != 0) { + vrml.write(",\n".getBytes()); + } + vrml.write( (" " + + String.format("%10.4f %10.4f %10.4f", coordinates[3 * i], coordinates[3 * i + 1], coordinates[3 * i + 2])). + getBytes()); + } + vrml.write("\n ]\n".getBytes()); + + vrml.write(" } # --- End of Coordinates\n".getBytes()); + + // --- Write triangle indices + + vrml.write(" coordIndex [ # --- Start of Triangles indices\n".getBytes()); + for (int i = 0; i < n_vertices - 2; i++) { + if (i != 0) { + vrml.write(",\n".getBytes()); + } + vrml.write( (" " + 0 + ", " + (i + 1) + ", " + (i + 2) + ", -1").getBytes()); + } + vrml.write("\n ] # --- End of Triangles indices\n".getBytes()); + +// --- write colors, if any + + if (writeColorsPerVertex && (colors3f != null || colors4f != null)) { + vrml.write(" colorPerVertex TRUE\n".getBytes()); + vrml.write(" color Color {\n".getBytes()); + vrml.write(" color [\n".getBytes()); + for (int i = 0; i < n_vertices; i++) { + if (i != 0) { + vrml.write(",\n".getBytes()); + } + if (colors3f != null) { + vrml.write( (" " + String.format("%7.4f %7.4f %7.4f", colors3f[i].x, colors3f[i].y, colors3f[i].z)). + getBytes()); + } + else if (colors4f != null) { + vrml.write( (" " + String.format("%7.4f %7.4f %7.4f", colors4f[i].x, colors4f[i].y, colors4f[i].z)). + getBytes()); + } + } + + vrml.write("\n ]\n".getBytes()); + vrml.write(" }\n".getBytes()); + + vrml.write(" colorIndex [\n".getBytes()); + for (int i = 0; i < n_vertices - 2; i++) { + if (i != 0) { + vrml.write(",\n".getBytes()); + } + vrml.write( (" " + 0 + ", " + (i + 1) + ", " + (i + 2) + ", -1").getBytes()); + } + vrml.write("\n ]\n".getBytes()); + } + else { + vrml.write(" colorPerVertex FALSE\n".getBytes()); + } + +// --- write normals, if any + + if (normals != null) { + vrml.write(" normalPerVertex TRUE\n".getBytes()); + vrml.write(" normal Normal {\n".getBytes()); + vrml.write(" vector [\n".getBytes()); + for (int i = 0; i < n_vertices; i++) { + if (i != 0) { + vrml.write(",\n".getBytes()); + } + vrml.write( (" " + String.format("%7.4f %7.4f %7.4f", normals[i].x, normals[i].y, normals[i].z)).getBytes()); + } + + vrml.write("\n ]\n".getBytes()); + vrml.write(" }\n".getBytes()); + + vrml.write(" normalIndex [\n".getBytes()); + for (int i = 0; i < n_vertices - 2; i++) { + if (i != 0) { + vrml.write(",\n".getBytes()); + } + vrml.write( (" " + 0 + ", " + (i + 1) + ", " + (i + 2) + ", -1").getBytes()); + } + vrml.write("\n ]\n".getBytes()); + + } + else { + vrml.write(" normalPerVertex FALSE\n".getBytes()); + } + + vrml.write("\n } # --- End of TriangleFanArray\n".getBytes()); + } + + /** + * The TriangleArray object draws the array of vertices as individual triangles. Each group of three vertices defines a triangle to be drawn. + * @param ta TriangleArray + * @return String + */ + public void getTriangleArray(TriangleArray ta, int rasterizationMode, OutputStream vrml) throws Exception { + + int format = 0; + try { + format = ta.getVertexFormat(); + } + catch (Exception ex) { + System.err.println("getTriangleArrayAsVRMLString: " + ex.getMessage()); + format |= GeometryArray.COORDINATES; + } + + // --- Get number of vertices + + int n_vertices = 0; + try { + n_vertices = ta.getVertexCount(); + } + catch (Exception ex) { + System.err.println("getTriangleArrayAsVRMLString: " + ex.getMessage()); + return; + } + + if (n_vertices < 1) { + System.err.println("getTriangleArrayAsVRMLString: number of vertices < 1"); + return; + } + + // --- Get coordinates, colors, and normals, if any + + double[] coordinates = this.getCoordinates(ta); + Color3f[] colors3f = this.getColors3f(ta); + Color4f[] colors4f = this.getColors4f(ta); + Vector3f[] normals = this.getNormals(ta); + + if (rasterizationMode != PolygonAttributes.POLYGON_LINE && rasterizationMode != PolygonAttributes.POLYGON_POINT) { + rasterizationMode = PolygonAttributes.POLYGON_FILL; // Set to the default value + } + + // --- Create VRML + + if (rasterizationMode == PolygonAttributes.POLYGON_FILL) { + vrml.write("\n geometry IndexedFaceSet { # --- Start of geometry\n".getBytes()); + vrml.write(" ccw TRUE\n".getBytes()); + vrml.write(" solid FALSE\n".getBytes()); + } + else if (rasterizationMode == PolygonAttributes.POLYGON_LINE) { + vrml.write("\n geometry IndexedLineSet { # --- Start of geometry\n".getBytes()); + } + else if (rasterizationMode == PolygonAttributes.POLYGON_POINT) { + vrml.write("\n geometry PointSet { # --- Start of geometry\n".getBytes()); + } + + vrml.write(" coord Coordinate { # --- Start of Coordinates\n".getBytes()); + + vrml.write(" point [\n".getBytes()); + for (int i = 0; i < n_vertices; i++) { + if (i != 0) { + vrml.write(",\n".getBytes()); + } + vrml.write( (" " + + String.format("%10.4f %10.4f %10.4f", coordinates[3 * i], coordinates[3 * i + 1], coordinates[3 * i + 2])). + getBytes()); + } + vrml.write("\n ]\n".getBytes()); + + vrml.write(" } # --- End of Coordinates\n".getBytes()); + + // --- Write triangle indices + + if (rasterizationMode != PolygonAttributes.POLYGON_POINT) { + vrml.write(" coordIndex [ # --- Start of Triangles indices\n".getBytes()); + for (int i = 0; i < n_vertices / 3; i++) { + if (i != 0) { + vrml.write(",\n".getBytes()); + } + vrml.write( (" " + (3 * i) + ", " + (3 * i + 1) + ", " + (3 * i + 2) + ", -1").getBytes()); + } + vrml.write("\n ] # --- End of Triangles indices\n".getBytes()); + } + + // --- write colors, if any + + if (writeColorsPerVertex && (colors3f != null || colors4f != null)) { + vrml.write(" colorPerVertex TRUE\n".getBytes()); + vrml.write(" color Color {\n".getBytes()); + vrml.write(" color [\n".getBytes()); + for (int i = 0; i < n_vertices; i++) { + if (i != 0) { + vrml.write(",\n".getBytes()); + } + if (colors3f != null) { + vrml.write( (" " + String.format("%7.4f %7.4f %7.4f", colors3f[i].x, colors3f[i].y, colors3f[i].z)). + getBytes()); + } + else if (colors4f != null) { + vrml.write( (" " + String.format("%7.4f %7.4f %7.4f", colors4f[i].x, colors4f[i].y, colors4f[i].z)). + getBytes()); + } + } + + vrml.write("\n ]\n".getBytes()); + vrml.write(" }\n".getBytes()); + + if (rasterizationMode != PolygonAttributes.POLYGON_POINT) { + vrml.write(" colorIndex [\n".getBytes()); + for (int i = 0; i < n_vertices / 3; i++) { + if (i != 0) { + vrml.write(",\n".getBytes()); + } + vrml.write( (" " + (3 * i) + ", " + (3 * i + 1) + ", " + (3 * i + 2) + ", -1").getBytes()); + } + vrml.write("\n ]\n".getBytes()); + } + else { + vrml.write(" colorPerVertex FALSE\n".getBytes()); + } + } + + // --- write normals, if any + + if (rasterizationMode == PolygonAttributes.POLYGON_FILL) { + if (normals != null) { + vrml.write(" normalPerVertex TRUE\n".getBytes()); + vrml.write(" normal Normal {\n".getBytes()); + vrml.write(" vector [\n".getBytes()); + for (int i = 0; i < n_vertices; i++) { + if (i != 0) { + vrml.write(",\n".getBytes()); + } + vrml.write( (" " + String.format("%7.4f %7.4f %7.4f", normals[i].x, normals[i].y, normals[i].z)). + getBytes()); + } + + vrml.write("\n ]\n".getBytes()); + vrml.write(" }\n".getBytes()); + + vrml.write(" normalIndex [\n".getBytes()); + for (int i = 0; i < n_vertices / 3; i++) { + if (i != 0) { + vrml.write(",\n".getBytes()); + } + vrml.write( (" " + (3 * i) + ", " + (3 * i + 1) + ", " + (3 * i + 2) + ", -1").getBytes()); + } + vrml.write("\n ]\n".getBytes()); + + } + else { + vrml.write(" normalPerVertex FALSE\n".getBytes()); + } + } + + vrml.write("\n } # --- End of geometry\n".getBytes()); + } + + private double[] getCoordinates(GeometryArray ga) { + int format = 0; + try { + format = ga.getVertexFormat(); + } + catch (Exception ex) { + System.err.println("getCoordinates: " + ex.getMessage()); + format |= GeometryArray.COORDINATES; + } + + int n_vertices = 0; + try { + n_vertices = ga.getVertexCount(); + } + catch (Exception ex) { + System.err.println("getCoordinates: " + ex.getMessage()); + return null; + } + +// --- Get coordinates + + double[] coordinates = new double[3 * n_vertices]; + + try { + ga.getCoordinates(0, coordinates); + } + catch (Exception ex) { + System.err.println("getCoordinates: " + ex.getMessage()); + return null; + } + return coordinates; + } + + private Color3f[] getColors3f(GeometryArray ga) { + int format = 0; + try { + format = ga.getVertexFormat(); + } + catch (Exception ex) { + System.err.println("getColors3f: " + ex.getMessage()); + return null; + } + + int n_vertices = 0; + try { + n_vertices = ga.getVertexCount(); + } + catch (Exception ex) { + System.err.println("getColors3f: " + ex.getMessage()); + return null; + } + Color3f[] colors3f = null; + if ( (format & TriangleArray.COLOR_3) == TriangleArray.COLOR_3) { + colors3f = new Color3f[n_vertices]; + for (int i = 0; i < n_vertices; i++) { + colors3f[i] = new Color3f(); + } + try { + ga.getColors(0, colors3f); + } + catch (Exception ex) { + System.err.println("getColors3f: " + ex.getMessage()); + colors3f = null; + } + } + return colors3f; + } + + private Color4f[] getColors4f(GeometryArray ga) { + int format = 0; + try { + format = ga.getVertexFormat(); + } + catch (Exception ex) { + System.err.println("getColors4f: " + ex.getMessage()); + return null; + } + + int n_vertices = 0; + try { + n_vertices = ga.getVertexCount(); + } + catch (Exception ex) { + System.err.println("getColors4f: " + ex.getMessage()); + return null; + } + Color4f[] colors4f = null; + if ( (format & TriangleArray.COLOR_4) == TriangleArray.COLOR_4) { + colors4f = new Color4f[n_vertices]; + for (int i = 0; i < n_vertices; i++) { + colors4f[i] = new Color4f(); + } + + try { + ga.getColors(0, colors4f); + } + catch (Exception ex) { + System.err.println("getColors4f: " + ex.getMessage()); + colors4f = null; + } + } + return colors4f; + } + + private Vector3f[] getNormals(GeometryArray ga) { + int format = 0; + try { + format = ga.getVertexFormat(); + } + catch (Exception ex) { + System.err.println("getNormals: " + ex.getMessage()); + return null; + } + + int n_vertices = 0; + try { + n_vertices = ga.getVertexCount(); + } + catch (Exception ex) { + System.err.println("getNormals: " + ex.getMessage()); + return null; + } + + // --- Get normals, if any + Vector3f[] normals = null; + if ( (format & TriangleArray.NORMALS) == TriangleArray.NORMALS) { + normals = new Vector3f[n_vertices]; + for (int i = 0; i < n_vertices; i++) { + normals[i] = new Vector3f(); + } + + try { + ga.getNormals(0, normals); + } + catch (Exception ex) { + System.err.println("getNormals: " + ex.getMessage()); + normals = null; + } + } + return normals; + } + + public void saveVRMLFile() throws Exception { + if (chooser == null) { + chooser = new JFileChooser(); + filter = new FileFilterImpl(); + + String temp[] = { + "wrl", "WRL"}; // extensions.split(";"); + for (int i = 0; i < temp.length; i++) { + filter.addExtension(temp[i]); + } + filter.setDescription("VRML Files (*.wrl)"); + chooser.setFileFilter(filter); + } + + chooser.setDialogTitle("Save as VRML File"); + chooser.setDialogType(JFileChooser.SAVE_DIALOG); + + if (currentWorkingDirectory != null) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } + else { + String lastPWD = prefs.get(lastPWDKey, ""); + if (lastPWD.length() > 0) { + currentWorkingDirectory = new File(lastPWD); + if (currentWorkingDirectory.isDirectory() && + currentWorkingDirectory.exists()) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } + } + } + + int returnVal = JFileChooser.CANCEL_OPTION; + + returnVal = chooser.showSaveDialog(null); + + if (returnVal == JFileChooser.CANCEL_OPTION) { + return; + } + + if (returnVal == JFileChooser.APPROVE_OPTION) { + String fileName = chooser.getSelectedFile().getPath(); + if (fileName.endsWith(".")) { + fileName += "wrl"; + } + else if (!fileName.endsWith(".wrl") && !fileName.endsWith(".WRL")) { + fileName += ".wrl"; + } + currentWorkingDirectory = chooser.getCurrentDirectory(); + try { + prefs.put(lastPWDKey, currentWorkingDirectory.getAbsolutePath()); + } + catch (Exception ex) { + System.err.println("Cannot save cwd: " + ex.getMessage() + + " Ignored..."); + } + //logger.info("You chose to open this file: " + + // fileName); + + saveVRMLFile(fileName); + } + } + + public void saveVRMLFile(String filename) throws Exception { + FileOutputStream out; + try { + out = new FileOutputStream(filename); + + out.write("#VRML V2.0 utf8\n".getBytes()); + out.write("# --- File is generated by Jamberoo\n".getBytes()); + out.write("\n".getBytes()); + + if (locale != null) { + getLocale(locale, out); + //out.write(this.getLocaleAsVRMLString(locale).getBytes()); + } + else if (node != null) { + getNode(node, out); + } + else { + throw new Exception("Neither Locale nor Node is set"); + } + + out.close(); + Runtime.getRuntime().gc(); + } + + catch (IOException e) { + throw e; + } + + } + + String createDEF(SceneGraphObject sgo, String key) { + String pref = ""; + if (prefix != null && prefix.length() > 0) { + pref = prefix + "_"; + } + String def = pref + UserData.getUserDataAsString(sgo, key); + if (def.length() > 0) { + def = "DEF " + def + " "; + } + return def; + } + + } diff --git a/src/main/java/cct/j3d/ImageSequenceManager.java b/src/main/java/cct/j3d/ImageSequenceManager.java new file mode 100644 index 0000000..1a66d56 --- /dev/null +++ b/src/main/java/cct/j3d/ImageSequenceManager.java @@ -0,0 +1,196 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.j3d; + +import cct.GlobalSettings; +import cct.j3d.Java3dUniverse; +import cct.povray.Povray; +import cct.tools.IOUtils; +import cct.tools.ImageTools; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Dirty class at the moment... + * + * @author vvv900 + */ +public class ImageSequenceManager { + + public static final String DEFAULT_FILE_PREFIX = "md-"; + public static final String DEFAULT_FILE_NUMBER_FORMAT = "%06d"; + private String filePrefix = DEFAULT_FILE_PREFIX; + private String fileNumberFormat = DEFAULT_FILE_NUMBER_FORMAT; + private Map availableFormats = new HashMap(); + private Java3dUniverse java3dUniverse = null; + private int counter = 0; + private int imageSequenceNumber = 0; + private boolean useImageSeqNumber = false; + + private String outputFormat; + private boolean sequenceInitialized = false; + static final Logger logger = Logger.getLogger(ImageSequenceManager.class.getCanonicalName()); + + public ImageSequenceManager(Java3dUniverse java3d) { + java3dUniverse = java3d; + outputFormat = "jpg"; + // --- get Image formats + String formats[] = ImageTools.getSaveImageFormatNames(); + for (String f : formats) { + availableFormats.put(f, null); + } + availableFormats.put("pov", null); + } + + public Object[] getAvailableFormats() { + return availableFormats.keySet().toArray(); + } + + public void initializeImageSequence() { + sequenceInitialized = true; + counter = 0; + } + + public void finalizeImageSequence() { + + sequenceInitialized = false; + if (this.outputFormat.equalsIgnoreCase("pov")) { + +// --- Generate povray image sequence control file + String povTemplate = GlobalSettings.getProperty( + Povray.IMAGE_SEQ_POV_TEMPLATE_KEY, + Povray.DEFAULT_IMAGE_SEQ_POV_TEMPLATE); + System.out.println("Povray Pov template:\n" + povTemplate); + povTemplate = povTemplate.replaceAll(Povray.FILE_PREFIX_TEMPLATE, this.getFilePrefix()); + try { + IOUtils.saveStringIntoFile(povTemplate, getFilePrefix() + Povray.DEFAULT_IMAGE_SEQ_POV_FILENAME); + } catch (Exception ex) { + Logger.getLogger(ImageSequenceManager.class.getName()).log(Level.SEVERE, null, ex); + } + + // --- Generate Povray initemplate + String iniTemplate = GlobalSettings.getProperty( + Povray.IMAGE_SEQ_INI_TEMPLATE_KEY, + Povray.DEFAULT_IMAGE_SEQ_INI_TEMPLATE); + System.out.println("Povray INI template:\n" + iniTemplate); + iniTemplate = iniTemplate.replaceAll(Povray.NUMBER_OF_FRAMES_TEMPLATE, String.valueOf(counter)). + replaceAll(Povray.POVRAY_CONTROL_FILE_NAME_TEMPLATE, getFilePrefix() + Povray.DEFAULT_IMAGE_SEQ_POV_FILENAME); + + try { + IOUtils.saveStringIntoFile(iniTemplate, getFilePrefix() + Povray.DEFAULT_IMAGE_SEQ_INI_FILENAME); + } catch (Exception ex) { + Logger.getLogger(ImageSequenceManager.class.getName()).log(Level.SEVERE, null, ex); + } + } + counter = 0; + } + + public void generateImage(Java3dUniverse java3d, int seqNumber) { + imageSequenceNumber = seqNumber; + generateImage(java3d); + } + + public void generateImage(Java3dUniverse java3d) { + if (!sequenceInitialized) { + return; + } + if (filePrefix == null) { + filePrefix = ""; + } + ++counter; + int imageSequence = counter; + if (useImageSeqNumber) { + imageSequence = imageSequenceNumber; + } + String fileName = String.format(filePrefix + fileNumberFormat, imageSequence); + + // --- Save image + if (this.outputFormat.equalsIgnoreCase("pov")) { + PovrayJava3d povray = new PovrayJava3d(java3d); + try { + povray.savePovrayFile(fileName + ".pov"); + } catch (Exception ex) { + logger.severe(ex.getLocalizedMessage()); + return; + } + } else if (this.outputFormat.equalsIgnoreCase("bmp") || outputFormat.equalsIgnoreCase("jpg") + || outputFormat.equalsIgnoreCase("png")) { + ImageToolsJ3D it3d = new ImageToolsJ3D(java3d); + it3d.setImageType(outputFormat); + try { + it3d.saveImage(fileName); + } catch (Exception ex) { + logger.severe(ex.getLocalizedMessage()); + return; + } + } + } + + public String getFilePrefix() { + return filePrefix; + } + + public void setFilePrefix(String filePrefix) { + this.filePrefix = filePrefix; + } + + public String getOutputFormat() { + return outputFormat; + } + + public void setOutputFormat(String outputFormat) { + this.outputFormat = outputFormat; + } + + public String getFileNumberFormat() { + return fileNumberFormat; + } + + public void setFileNumberFormat(String fileNumberFormat) { + this.fileNumberFormat = fileNumberFormat; + } + + public boolean isUseImageSeqNumber() { + return useImageSeqNumber; + } + + public void setUseImageSeqNumber(boolean useImageSeqNumber) { + this.useImageSeqNumber = useImageSeqNumber; + } +} diff --git a/src/main/java/cct/j3d/ImageToolsJ3D.java b/src/main/java/cct/j3d/ImageToolsJ3D.java new file mode 100644 index 0000000..4728479 --- /dev/null +++ b/src/main/java/cct/j3d/ImageToolsJ3D.java @@ -0,0 +1,91 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.j3d; + +import cct.tools.ImageTools; +import java.awt.Frame; +import java.awt.MediaTracker; +import java.awt.image.BufferedImage; +import javax.swing.JOptionPane; + +/** + * + * @author vvv900 + */ +public class ImageToolsJ3D { + + Java3dUniverse java3d; + String imageType = "jpg"; + + public ImageToolsJ3D(Java3dUniverse java3d) { + this.java3d = java3d; + } + + public Java3dUniverse getJava3d() { + return java3d; + } + + public void setJava3d(Java3dUniverse java3d) { + this.java3d = java3d; + } + + public String getImageType() { + return imageType; + } + + public void setImageType(String imageType) { + this.imageType = imageType.toLowerCase(); + } + + public void saveImage(String fileName) throws Exception { + if (fileName == null || fileName.trim().length() < 1) { + throw new Exception("File name is not set"); + } + if (java3d == null) { + throw new Exception("Java3dUniverse is not set"); + } + BufferedImage bImage = java3d.getImageCapture(); + MediaTracker mediaTracker = new MediaTracker(new Frame()); + mediaTracker.addImage(bImage, 0); + try { + mediaTracker.waitForID(0); + ImageTools.saveImage(bImage, imageType, fileName); + } catch (Exception ex) { + throw new Exception("Error Saving Image: " + fileName + " : " + ex.getMessage()); + } + } +} diff --git a/src/main/java/cct/j3d/InfoPopup.java b/src/main/java/cct/j3d/InfoPopup.java new file mode 100644 index 0000000..5dc873a --- /dev/null +++ b/src/main/java/cct/j3d/InfoPopup.java @@ -0,0 +1,71 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.Popup; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class InfoPopup + implements ActionListener { + + Popup popup = null; + + public InfoPopup(Popup p) { + popup = p; + } + + @Override + public void actionPerformed(ActionEvent e) { + popup.hide(); + } + +} diff --git a/src/main/java/cct/j3d/J3D_ATOM_PROPERTY.java b/src/main/java/cct/j3d/J3D_ATOM_PROPERTY.java new file mode 100644 index 0000000..6415564 --- /dev/null +++ b/src/main/java/cct/j3d/J3D_ATOM_PROPERTY.java @@ -0,0 +1,13 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.j3d; + +/** + * + * @author Vlad + */ +public enum J3D_ATOM_PROPERTY { + SPHERE_3D, SPHERE_3D_HIGHLIGHTED, POINT_3D, POINT_3D_HIGHLIGHTED, NOTHING +} diff --git a/src/main/java/cct/j3d/J3D_MOLECULAR_PROPERTY.java b/src/main/java/cct/j3d/J3D_MOLECULAR_PROPERTY.java new file mode 100644 index 0000000..0125242 --- /dev/null +++ b/src/main/java/cct/j3d/J3D_MOLECULAR_PROPERTY.java @@ -0,0 +1,13 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.j3d; + +/** + * + * @author Vlad + */ +public enum J3D_MOLECULAR_PROPERTY { + +} diff --git a/src/main/java/cct/j3d/Java3dUniverse.java b/src/main/java/cct/j3d/Java3dUniverse.java new file mode 100644 index 0000000..8b5fb1f --- /dev/null +++ b/src/main/java/cct/j3d/Java3dUniverse.java @@ -0,0 +1,6604 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.j3d; + +import cct.GlobalSettings; +import java.awt.Color; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Frame; +import java.awt.GraphicsConfiguration; +import java.awt.MediaTracker; +import java.awt.MenuItem; +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; + +import org.scijava.java3d.AmbientLight; +import org.scijava.java3d.Appearance; +import org.scijava.java3d.Background; +import org.scijava.java3d.BoundingLeaf; +import org.scijava.java3d.BoundingSphere; +import org.scijava.java3d.Bounds; +import org.scijava.java3d.BranchGroup; +import org.scijava.java3d.Canvas3D; +import org.scijava.java3d.ColoringAttributes; +import org.scijava.java3d.DirectionalLight; +import org.scijava.java3d.Group; +import org.scijava.java3d.LinearFog; +import org.scijava.java3d.Locale; +import org.scijava.java3d.Material; +import org.scijava.java3d.Node; +import org.scijava.java3d.PhysicalBody; +import org.scijava.java3d.PhysicalEnvironment; +import org.scijava.java3d.PolygonAttributes; +import org.scijava.java3d.Screen3D; +import org.scijava.java3d.Shape3D; +import org.scijava.java3d.Switch; +import org.scijava.java3d.Transform3D; +import org.scijava.java3d.TransformGroup; +import org.scijava.java3d.View; +import org.scijava.java3d.ViewPlatform; +import org.scijava.java3d.VirtualUniverse; +import javax.swing.JColorChooser; +import javax.swing.JFrame; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import org.scijava.vecmath.Color3f; +import org.scijava.vecmath.Matrix3d; +import org.scijava.vecmath.Point3d; +import org.scijava.vecmath.Point3f; +import org.scijava.vecmath.Vector3d; +import org.scijava.vecmath.Vector3f; + +import cct.awtdialogs.AddNewMoleculeDialog; +import cct.awtdialogs.AddNewStructureDialog; +import cct.awtdialogs.AtomLabelsDialog; +import cct.awtdialogs.AtomTypeDialog; +import cct.awtdialogs.ConnectSQLServer; +import cct.awtdialogs.GeometrySelectDialog; +import cct.awtdialogs.MessageWindow; +import cct.awtdialogs.TextEntryDialog; +import cct.awtdialogs.YesNoDialog; +import cct.cprocessor.CommandInterface; +import cct.cprocessor.Variable; +import cct.database.ChemistryDatabaseDialog; +import cct.database.SQLChemistryDatabase; +import cct.database.SQLDatabaseAccess; +import cct.database.new_ChemistryDatabaseDialog; +import cct.database.new_SQLChemistryDatabase; +import cct.dialogs.JAddMoleculeDialog; +import cct.dialogs.JAtomTypeDialog; +import cct.dialogs.JChoiceDialog; +import cct.dialogs.JModifyAngleDialog; +import cct.dialogs.JModifyAtomDialog; +import cct.dialogs.JModifyBondDialog; +import cct.dialogs.JModifyTorsionDialog; +import cct.dialogs.JSelectTreeDialog; +import cct.dialogs.JSolvateShellDialog; +import cct.gaussian.Gaussian; +import cct.gaussian.GaussianFragment; +import cct.gaussian.GaussianJob; +import cct.gaussian.GaussianOutput; +import cct.gaussian.ui.GaussianInputEditorFrame; +import cct.gromacs.GromacsParserFactory; +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; +import cct.interfaces.GraphicsObjectInterface; +import cct.interfaces.GraphicsRendererInterface; +import cct.interfaces.HelperInterface; +import cct.interfaces.MoleculeInterface; +import cct.interfaces.MoleculeRendererInterface; +import cct.interfaces.MonomerInterface; +import cct.interfaces.Point3fInterface; +import cct.interfaces.TreeSelectorInterface; +import cct.mdl.MDLMol; +import cct.modelling.*; +import cct.pdb.PDB; +import cct.sff.SimpleForceField; +import cct.tools.CCTParser; +import cct.tools.FragmentDictionaryParser; +import cct.tools.SimpleParserFactory; +import cct.tools.Utils; +import cct.tools.XMolXYZ; +import cct.tools.ui.DoubleSpinnerDialog; +import cct.tools.ui.JShowText; +import cct.tools.ui.JobProgressInterface; +import cct.tripos.TriposParser; +import cct.vecmath.Geometry3d; +import cct.vecmath.Segment3f; + +import org.scijava.java3d.utils.behaviors.mouse.MouseBehavior; +import org.scijava.java3d.utils.behaviors.mouse.MouseTranslate; +import org.scijava.java3d.utils.behaviors.mouse.MouseZoom; +import org.scijava.java3d.utils.geometry.Cylinder; +import org.scijava.java3d.utils.geometry.Primitive; +import org.scijava.java3d.utils.geometry.Sphere; +import org.scijava.java3d.utils.geometry.Text2D; +import org.scijava.java3d.utils.picking.PickResult; +import org.scijava.java3d.utils.universe.SimpleUniverse; +import java.util.List; +import java.util.logging.Level; + +import static cct.vecmath.Point3f.*; + +/** + * + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

Some conventions: Atomic sphere: BranchGroup -> Transform Group (move) -> TransformGroup (scale + * radius) -> Sphere + * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class Java3dUniverse + extends MolecularEditor implements MolecularProperties, + OperationsOnAtoms, GraphicsRendererInterface, TreeSelectorInterface, + ActionListener, MoleculeRendererInterface { + + static double RADS_TO_DEGS = 180.00 / Math.PI; + static final Logger logger = Logger.getLogger(Java3dUniverse.class.getCanonicalName()); + static Map renderStyles = new LinkedHashMap(); + + static { + renderStyles.put("Wireframe", MoleculeInterface.WIREFRAME); + renderStyles.put("Sticks", MoleculeInterface.STICKS); + renderStyles.put("Ball & Sticks", MoleculeInterface.BALL_AND_STICKS); + renderStyles.put("Spacefill", MoleculeInterface.SPACEFILL); + } + public static final String ATOM_NODE = "_AtomNode"; + public static final String BOND_NODE = "_BondNode"; + public static final String ATOM_NODE_MATERIAL_COPY = "_ANMMatCopy"; + public static final String PERSPECTIVE_PROJECTION = "Perspective"; + public static final String PARALLEL_PROJECTION = "Parallel"; + private boolean debug = false; + HelperInterface helper = null; + private List renderingListeners = new ArrayList(); + //SampleFrame parentFrame = null; // TODO to remove lately... + Frame guiFrame = null; // TODO to remove lately... + int renderingStyle = MoleculeInterface.BALL_AND_STICKS; + private VirtualUniverse universe; + private Locale locale; + private View view; + private int projectionPolicy = View.PERSPECTIVE_PROJECTION; + private GraphicsConfiguration config; + private Background bgNode; + Canvas3D canvas3D; + OffScreenCanvas3D offScreenCanvas3D; + BranchGroup scene; + Transform3D rotate; + Transform3D translate; + TransformGroup objRotate; + TransformGroup sceneTrans; + TransformGroup moleculeTrans = new TransformGroup(); + TransformGroup sceneOffset; + Switch sceneSwitch; + private ProcessMouseRotate behavior; + private MouseZoom myMouseZoom; + private Appearance atomAppear; + private BranchGroup fastGroup; + private BranchGroup niceGroup; + private ViewPlatform vp = new ViewPlatform(); + private BranchGroup root = null; + private TransformGroup rootTrans = null; + private BranchGroup localeRoot = null; + private BoundingSphere bounds = null; + private LinearFog fog = null; + Java3dUniverse otherRenderer = null; + // --- Fragments related + String fragContext = null; + URL fragmentDictionary = null; + Map fragmentsReferences = new HashMap(); + String solventContext = null; + URL solventDictionary = null; + boolean HighlightSelectedAtoms = false; + boolean atomInfoPopup = true; + MyMouseMotionListener tracer = new MyMouseMotionListener(this); + //BranchGroup mol = new BranchGroup(); + MoleculeNode mol = new MoleculeNode(); + List bondNodes = new ArrayList(); + public String selectionTypes[] = { + "Atom", "Monomer", "Molecule" + }; + public String selectionRules[] = { + "Union", "Difference", "Intersection" + }; + List graphicsObjects = null; + Color3f atomLabelsColor = new Color3f(Color.PINK); + int atomLabelsFontSize = 75; + int atomLabelsFontStyle = Font.ITALIC; + String atomLabelsFontName = "Helvetica"; + Font atomLabelsFont = null; + List atomLabels = new ArrayList(); + boolean enableLabels = false; + boolean otherLabelMethod = true; // For tesing + AtomLabelsDialog atomLabelsDialog = null; + Text2D referenceText2D = new Text2D("", atomLabelsColor, atomLabelsFontName, + atomLabelsFontSize, atomLabelsFontStyle); + int bondRenderingStyle = BondInterface.CYLINDER_BICOLOR; + public int selectedRule = 0; + public boolean selectionInProgress = false; + MousePicking mouse_picking_behavior = null; + public Object oneAtomSelectionDialog = null; + public GeometrySelectDialog geometrySelectioDialog = null; + JSelectTreeDialog selectDefaultSolvent = null; + public JModifyAtomDialog jModifyAtomDialog = null; + public JModifyBondDialog jModifyBondDialog = null; + public JModifyAngleDialog jModifyAngleDialog = null; + public JAddMoleculeDialog jAddMoleculeDialog = null; + JSolvateShellDialog jSolvateShellDialog = null; + Map defaultSolventList = null; + public Object chooseAtomType = null; + GaussianInputEditorFrame gaussianInputEditorFrame = null; + public int lastSelectedAtom = -1; + private List selectedAtoms = new ArrayList(); + private List trackSelectedAtoms = new ArrayList(); + //private java.util.Set trackSelectedAtoms = new HashSet(); + protected List Geometries = null; + protected int selectedGeometry = 0; +// --- Menu Items + public MenuItem geometrySelection = null; +// --- Working structures + Matrix3d temp_Matrix = null; + Sphere temp_Sphere = null; + List temp_Group_1 = null, temp_Group_2 = null, temp_Group_3 = null; + cct.vecmath.Point3f temp_axis = null; + cct.vecmath.Point3f temp_structure[] = null; // + + //public SampleFrame(String title, String [] args) { + // new SampleFrame(title); + // startBulkDatabaseLoad(args); + //} + + /* + * public Java3dUniverse(SampleFrame parent) { this(); parentFrame = parent; + * + * } + */ + public Java3dUniverse() { + + config = SimpleUniverse.getPreferredConfiguration(); + if (config == null) { + System.err.println(config); + return; + } + canvas3D = new Canvas3D(config); + //logger.info("Java3dUniverse: " + canvas3D); + if (canvas3D == null) { + logger.info(canvas3D.toString()); + return; + } + + if (atomInfoPopup) { + canvas3D.addMouseMotionListener(tracer); + } + + offScreenCanvas3D = new OffScreenCanvas3D(config, true); + + //add("Center", canvas3D); // To be returned + createUniverse(); + + initSceneGraph(); + //initSceneGraph(universe); + + initLighting(); + + moleculeTrans.setCapability(TransformGroup.ALLOW_CHILDREN_EXTEND); + moleculeTrans.setCapability(TransformGroup.ALLOW_CHILDREN_READ); + moleculeTrans.setCapability(TransformGroup.ALLOW_CHILDREN_WRITE); + moleculeTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); + moleculeTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + + niceGroup.addChild(moleculeTrans); + + root.compile(); + localeRoot.addChild(root); + try { + locale.addBranchGraph(localeRoot); + //simpleU.addBranchGraph(localeRoot); + } catch (Exception ex) { + //ex.printStackTrace(); + } + + try { + jbInit(); + } catch (Exception ex) { + ex.printStackTrace(); + } + + //mol.setCapability(BranchGroup.ALLOW_DETACH); + moleculeTrans.addChild(mol); + UserData.setUserData(moleculeTrans, UserData.NODE_NAME, "Molecule"); + //moleculeTrans.setName("Molecule"); // --- >1.4 java3d feature + } + + public View getView() { + return view; + } + + public void enableMousePicking(boolean flag) { + if (mouse_picking_behavior == null) { + return; + } + mouse_picking_behavior.setEnable(flag); + selectionInProgress = flag; + logger.info("Mouse picking: " + Boolean.toString(flag)); + } + + public boolean getMousePickingStatus() { + if (mouse_picking_behavior == null) { + return false; + } + return mouse_picking_behavior.getEnable(); + } + + public void setOtherRenderer(Java3dUniverse otherJ3D) { + otherRenderer = otherJ3D; + } + + public Java3dUniverse getOtherRenderer() { + return otherRenderer; + } + + /** + * Add listener for change rendering style events + * + * @param listener RenderingListener - listener + */ + public void addRenderingListener(RenderingListener listener) { + if (renderingListeners.contains(listener)) { + return; + } + renderingListeners.add(listener); + } + + public void removeRenderingListener(RenderingListener listener) { + if (renderingListeners.contains(listener)) { + renderingListeners.remove(listener); + } + } + + void createUniverse() { + // Establish a virtual universe, with a single hi-res Locale + universe = new VirtualUniverse(); + //simpleU = new SimpleUniverse(canvas3D); + locale = new Locale(universe); + //locale = new Locale(simpleU); + + Screen3D sOn = canvas3D.getScreen3D(); + Screen3D sOff = offScreenCanvas3D.getScreen3D(); + Dimension dim = sOn.getSize(); + dim.width *= 3; + dim.height *= 3; + sOff.setSize(dim); + sOff.setPhysicalScreenWidth(sOn.getPhysicalScreenWidth() * 3); + sOff.setPhysicalScreenHeight(sOn.getPhysicalScreenHeight() * 3); + + // Create a PhysicalBody and Physical Environment object + PhysicalBody body = new PhysicalBody(); + PhysicalEnvironment environment = new PhysicalEnvironment(); + + // Create a View and attach the Canvas3D and the physical + // body and environment to the view. + view = new View(); + //View view = simpleU.getViewer().getView(); + view.addCanvas3D(canvas3D); + view.setPhysicalBody(body); + view.setPhysicalEnvironment(environment); + view.setBackClipDistance(500.0); + setProjection(projectionPolicy); + //view.setProjectionPolicy(projectionPolicy); + + //simpleU.getViewer().getView().setPhysicalBody(body); + //simpleU.getViewer().getView().setPhysicalEnvironment(environment); + //simpleU.getViewer().getView().setBackClipDistance(500.0); + //simpleU.getViewer().getView().addCanvas3D(offScreenCanvas3D); + view.addCanvas3D(offScreenCanvas3D); + + //logger.info("Clip front/back: "+view.getFrontClipDistance()+"/"+ + // view.getBackClipDistance()); + // Create a branch group node for the view platform + root = new BranchGroup(); + root.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE); + root.setCapability(BranchGroup.ALLOW_CHILDREN_READ); + root.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND); + root.setCapability(BranchGroup.ALLOW_DETACH); + root.setCapability(BranchGroup.ALLOW_COLLISION_BOUNDS_READ); + root.setCapability(BranchGroup.ALLOW_COLLISION_BOUNDS_WRITE); + + localeRoot = new BranchGroup(); + localeRoot.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE); + localeRoot.setCapability(BranchGroup.ALLOW_CHILDREN_READ); + localeRoot.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND); + localeRoot.setCapability(BranchGroup.ALLOW_DETACH); + + vp.setCapability(ViewPlatform.ALLOW_POLICY_READ); + vp.setCapability(ViewPlatform.ALLOW_POLICY_WRITE); + vp.setViewAttachPolicy(View.NOMINAL_SCREEN); + vp.setActivationRadius(10); + + rootTrans = new TransformGroup(); + rootTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); + + bounds + = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 1000.0); + + /* + * Does not work Background bg = new Background(new Color3f(Color.BLUE)); bg.setBounds(bounds); rootTrans.addChild(bg); + */ + rootTrans.addChild(vp); + BoundingLeaf boundingLeaf = new BoundingLeaf(bounds); + rootTrans.addChild(boundingLeaf); + localeRoot.addChild(rootTrans); + //simpleU.getViewer().getView().attachViewPlatform(vp); + view.attachViewPlatform(vp); + + // Set up the background + Color3f bgColor = new Color3f(0.0f, 0.0f, 0.0f); + bgNode = new Background(bgColor); + bgNode.setApplicationBounds(bounds); + bgNode.setCapability(Background.ALLOW_COLOR_READ); + bgNode.setCapability(Background.ALLOW_COLOR_WRITE); + root.addChild(bgNode); + + } + + public BoundingSphere getBoundingSphere() { + return bounds; + } + + /** + * Sets projection policy + * + * @param mode int - either View.PERSPECTIVE_PROJECTION or View.PARALLEL_PROJECTION. Do nothing if mode != one of this + * values + */ + public void setProjection(int mode) { + switch (mode) { + case View.PERSPECTIVE_PROJECTION: + view.setProjectionPolicy(View.PERSPECTIVE_PROJECTION); + break; + case View.PARALLEL_PROJECTION: + view.setProjectionPolicy(View.PARALLEL_PROJECTION); + view.setScreenScalePolicy(View.SCALE_EXPLICIT); + view.setScreenScale(0.05); + break; + default: + logger.warning("Projection mode should be equal to either View.PERSPECTIVE_PROJECTION or View.PARALLEL_PROJECTION"); + } + } + + public void setProjection(String mode) { + if (mode.equalsIgnoreCase(PERSPECTIVE_PROJECTION)) { + setProjection(View.PERSPECTIVE_PROJECTION); + } else if (mode.equalsIgnoreCase(PARALLEL_PROJECTION)) { + setProjection(View.PARALLEL_PROJECTION); + } + } + + public int getProjectionMode() { + return view.getProjectionPolicy(); + } + + public String getProjectionModeAsString() { + if (view.getProjectionPolicy() == View.PERSPECTIVE_PROJECTION) { + return PERSPECTIVE_PROJECTION; + } else { + return PARALLEL_PROJECTION; + } + } + + public String[] getProjectionModes() { + return new String[]{ + PERSPECTIVE_PROJECTION, PARALLEL_PROJECTION}; + } + + public void setBackgroundColor(Color3f color) { + if (color == null) { + logger.warning("Background color cannot be null"); + return; + } + if (bgNode.getCapability(Background.ALLOW_COLOR_WRITE)) { + bgNode.setColor(color); + } else { + System.err.println("No capability to set background color"); + } + } + + public void setBackgroundColor(float red, float green, float blue) { + red = red < 0 ? 0 : red > 1 ? 1 : red; + green = green < 0 ? 0 : green > 1 ? 1 : green; + blue = blue < 0 ? 0 : blue > 1 ? 1 : blue; + if (bgNode.getCapability(Background.ALLOW_COLOR_WRITE)) { + bgNode.setColor(red, green, blue); + } else { + logger.severe("No capability to set background color"); + } + } + + public void setBackgroundColor(int red, int green, int blue) { + red = red < 0 ? 0 : red > 1 ? 1 : red; + green = green < 0 ? 0 : green > 1 ? 1 : green; + blue = blue < 0 ? 0 : blue > 1 ? 1 : blue; + if (bgNode.getCapability(Background.ALLOW_COLOR_WRITE)) { + bgNode.setColor((float) red / 255.0f, (float) green / 255.0f, + (float) blue / 255.0f); + } else { + logger.severe("No capability to set background color"); + } + } + + public Color getBackgroundColor() { + if (bgNode.getCapability(Background.ALLOW_COLOR_READ)) { + Color3f bgColor = new Color3f(); + bgNode.getColor(bgColor); + Color color = new Color(bgColor.x, bgColor.y, bgColor.z); + return color; + } else { + logger.severe("No capability to get background color"); + return null; + } + + } + + public Color3f getBackgroundColor3f() { + if (bgNode.getCapability(Background.ALLOW_COLOR_READ)) { + Color3f bgColor = new Color3f(); + bgNode.getColor(bgColor); + return bgColor; + } else { + logger.severe("No capability to get background color"); + return null; + } + + } + + void initSceneGraph() { + Transform3D t = new Transform3D(); + t.set(new Vector3f(0.0f, 0.0f, -100.0f)); + sceneOffset = new TransformGroup(t); + sceneOffset.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); + sceneOffset.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + + sceneTrans = new TransformGroup(); + sceneTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); + sceneTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + sceneTrans.setCapability(TransformGroup.ALLOW_LOCAL_TO_VWORLD_READ); + + sceneSwitch = new Switch(Switch.CHILD_MASK); + sceneSwitch.setCapability(Switch.ALLOW_SWITCH_READ); + sceneSwitch.setCapability(Switch.ALLOW_SWITCH_WRITE); + + fastGroup = new BranchGroup(); + niceGroup = new BranchGroup(); + fastGroup.setCapability(Group.ALLOW_CHILDREN_EXTEND); + fastGroup.setCapability(Group.ALLOW_CHILDREN_READ); + fastGroup.setCapability(Group.ALLOW_CHILDREN_WRITE); + + niceGroup.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND); + niceGroup.setCapability(BranchGroup.ALLOW_CHILDREN_READ); + niceGroup.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE); + niceGroup.setPickable(true); + + sceneSwitch.addChild(niceGroup); + sceneSwitch.addChild(fastGroup); + sceneSwitch.setWhichChild(0); + + // Create the drag behavior node !!! Commented + //MouseFastRotate behavior = new MouseFastRotate(sceneTrans, this ); + //behavior.setSchedulingBounds(bounds); + //sceneTrans.addChild(behavior); + //MouseRotate behavior = new MouseRotate(sceneTrans); + behavior = new ProcessMouseRotate(this, sceneTrans); + behavior.setSchedulingBounds(bounds); + sceneTrans.addChild(behavior); + + //behavior.setParentFrame(this); + // Create the zoom behavior node + //MouseZoom behavior2 = new MouseZoom(sceneTrans); + //behavior2.setSchedulingBounds(bounds); + //sceneTrans.addChild(behavior2); + MyMouseZoom myMouseZoom = new MyMouseZoom(sceneTrans); + myMouseZoom.setSchedulingBounds(bounds); + sceneTrans.addChild(myMouseZoom); + + // Create the zoom behavior node + MouseTranslate behavior3 = new MouseTranslate(sceneTrans); + behavior3.setSchedulingBounds(bounds); + sceneTrans.addChild(behavior3); + + // --- Keyborad behavior (experimental phase) + KeyHandler k_behavior = new KeyHandler(sceneTrans); + //TransformGroup vpTrans = su.getViewingPlatform().getViewPlatformTransform(); + //myKeyNavigatorBehavior k_behavior = new myKeyNavigatorBehavior(sceneTrans); + k_behavior.setSchedulingBounds(bounds); + sceneTrans.addChild(k_behavior); + + // --- Mouse behavior (experimental) + //MousePickingHandler m_behavior = new MousePickingHandler(canvas3D, root, bounds); + //root.addChild( m_behavior ); + //root.setPickable( true ); + sceneTrans.addChild(sceneSwitch); + + sceneOffset.addChild(sceneTrans); + rootTrans.addChild(sceneOffset); + } + + void initLighting() { + + Color3f dlColor = new Color3f(.75f, 0.75f, 0.75f); + + Vector3f lDirect1 = new Vector3f(-1.0f, -1.0f, -1.0f); + //Vector3f lDirect1 = new Vector3f(1.0f, -1.0f, -1.0f); + //Vector3f lDirect2 = new Vector3f( -1.0f, 1.0f, 1.0f); + + DirectionalLight lgt1 = new DirectionalLight(dlColor, lDirect1); + lgt1.setInfluencingBounds(bounds); + //DirectionalLight lgt2 = new DirectionalLight(dlColor, lDirect2); + //lgt2.setInfluencingBounds(bounds); + + Color3f alColor = new Color3f(0.65f, 0.65f, 0.65f); + AmbientLight aLgt = new AmbientLight(alColor); + aLgt.setInfluencingBounds(bounds); + + root.addChild(aLgt); + root.addChild(lgt1); + //root.addChild(lgt2); + + // Try some fog for depth cueing + fog = new LinearFog(); + fog.setCapability(LinearFog.ALLOW_DISTANCE_WRITE); + fog.setColor(new Color3f(0.0f, 0.0f, 0.0f)); + fog.setFrontDistance(10.0); + fog.setBackDistance(500.0); + fog.setInfluencingBounds(bounds); + fog.addScope(sceneTrans); + sceneTrans.addChild(fog); + + } + + public void renderMolecule(MoleculeInterface m) { + addMolecule(m); + } + + public void addMolecule(Molecule m) { + addMolecule((MoleculeInterface) m); + } + + public void appendMolecule(MoleculeInterface referenceMol, + MoleculeInterface m, float coord[][]) { + // --- Add atoms to the real molecule + + int oldNumAtoms = referenceMol.getNumberOfAtoms(); + int oldNumBonds = referenceMol.getNumberOfBonds(); + logger.info("Old # atoms: " + oldNumAtoms + " Old # bonds: " + + oldNumBonds); + referenceMol.appendMolecule(m); + logger.info("New # atoms: " + referenceMol.getNumberOfAtoms() + + " New # bonds: " + referenceMol.getNumberOfBonds()); + + // --- Update their coordinates + logger.info("Updating coords " + oldNumAtoms + " - " + (oldNumAtoms + m.getNumberOfAtoms() - 1)); + for (int i = 0; i < m.getNumberOfAtoms(); i++) { + AtomInterface atom = referenceMol.getAtomInterface(oldNumAtoms + i); + atom.setXYZ(coord[i][0], coord[i][1], coord[i][2]); + } + + // --- create graphics + // --- Add new atoms + for (int i = oldNumAtoms; i < referenceMol.getNumberOfAtoms(); i++) { + AtomInterface atom = referenceMol.getAtomInterface(i); + //BranchGroup at = createAtom(atom); + AtomNode at = new AtomNode(atom); + atom.setProperty(ATOM_NODE, at); + atomLabels.add(i, null); + mol.addChild(at); + //atomNodes.add(at); + Material store = cloneMaterial(at.getMaterial()); + store.setCapability(Material.ALLOW_COMPONENT_READ); + store.setCapability(Material.ALLOW_COMPONENT_WRITE); + atom.setProperty(ATOM_NODE_MATERIAL_COPY, store); + //materialStore.add(store); + } + + // --- Add new bonds + for (int i = oldNumBonds; i < referenceMol.getNumberOfBonds(); i++) { + BondInterface b = referenceMol.getBondInterface(i); + BondNode bond = new BondNode(b); + mol.addChild(bond); + bondNodes.add(bond); + } + + } + + public void addGraphicsToMolecule(Group object, boolean enable) { + if (object == null) { + return; + } + if (enable && object.getParent() == null) { + moleculeTrans.addChild(object); + } else if (!enable) { + //logger.info("Object: allow detach " + object.getCapability(BranchGroup.ALLOW_DETACH)); + //if (!object.getCapability(BranchGroup.ALLOW_DETACH)) { + //object.setCapability(BranchGroup.ALLOW_DETACH); + //} + //object.detach(); + moleculeTrans.removeChild(object); + } + } + + public void appendMolecule(MoleculeInterface m, boolean merge_molecules) { + + if (m == null || m.getNumberOfAtoms() < 1) { + return; + } + + // --- Add atoms to the real molecule + boolean empty = molecule == null || molecule.getNumberOfAtoms() == 0; + if (empty) { + this.setMolecule(m); + return; + } + + int oldNumAtoms = empty ? 0 : molecule.getNumberOfAtoms(); + int oldNumBonds = empty ? 0 : molecule.getNumberOfBonds(); + System.out.println("To be appended # atoms: " + m.getNumberOfAtoms() + " # bonds: " + m.getNumberOfBonds()); + System.out.println("Old # atoms: " + oldNumAtoms + " Old # bonds: " + oldNumBonds); + logger.info("Old # atoms: " + oldNumAtoms + " Old # bonds: " + oldNumBonds); + if (merge_molecules) { + molecule.mergeMolecule(m); + } else { + molecule.appendMolecule(m); + } + logger.info("New # atoms: " + molecule.getNumberOfAtoms() + " New # bonds: " + molecule.getNumberOfBonds()); + + // --- create graphics + // --- Add new atoms + for (int i = oldNumAtoms; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface atom = molecule.getAtomInterface(i); + AtomNode at = new AtomNode(atom); // createAtom(atom); + atom.setProperty(ATOM_NODE, at); + atomLabels.add(i, null); + mol.addChild(at); + //atomNodes.add(at); + Material store = cloneMaterial(at.getMaterial()); + atom.setProperty(ATOM_NODE_MATERIAL_COPY, store); + //materialStore.add(store); + + } + + // --- Add new bonds + for (int i = oldNumBonds; i < molecule.getNumberOfBonds(); i++) { + BondInterface b = molecule.getBondInterface(i); + BondNode bond = new BondNode(b); + mol.addChild(bond); + bondNodes.add(bond); + } + + } + + /** + * Clones material + * + * @param material Material + * @return Material + */ + public static Material cloneMaterial(Material material) { + if (material == null) { + return null; + } + Color3f ambientColor = new Color3f(); + Color3f emissiveColor = new Color3f(); + Color3f diffuseColor = new Color3f(); + Color3f specularColor = new Color3f(); + + material.getAmbientColor(ambientColor); + material.getEmissiveColor(emissiveColor); + material.getDiffuseColor(diffuseColor); + material.getSpecularColor(specularColor); + float shininess = material.getShininess(); + Material store = new Material(ambientColor, emissiveColor, + diffuseColor, specularColor, shininess); + store.setCapability(Material.ALLOW_COMPONENT_READ); + store.setCapability(Material.ALLOW_COMPONENT_WRITE); + return store; + } + + public void appendMolecule(Java3dUniverse otherRenderer) { + } + + /** + * General version. + * + * @param m + * @param read_mode + */ + public void setMolecule(MoleculeInterface m, GlobalSettings.ADD_MOLECULE_MODE read_mode) { + switch (read_mode) { + case SET: + removeMolecule(); + addMolecule(m); + break; + case APPEND: + appendMolecule(m, false); + break; + default: + logger.warning(read_mode.toString() + " is not implemented"); + } + } + + /** + * Default version First deletes molecule and all related graphics, then adds a new molecule + * + * @param m MoleculeInterface + */ + public void setMolecule(MoleculeInterface m) { + setMolecule(m, GlobalSettings.ADD_MOLECULE_MODE.SET); + } + + public void addMolecule(MoleculeInterface molecule, int how_to_load_molecule) { + addMolecule(molecule); + } + + public void setRenderingParameters(int style) { + if (style == MoleculeInterface.WIREFRAME) { + int atomRenderingStyle = AtomInterface.RENDER_SMART_POINT; + bondRenderingStyle = BondInterface.LINE_BICOLOR; + + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface a = molecule.getAtomInterface(i); + a.setProperty(AtomInterface.RENDERING_STYLE, new Integer(atomRenderingStyle)); + a.setProperty(AtomInterface.GR_RADIUS, new Float(0.01f)); // GR_RADIUS "gradius" is a "graphics radius" + } + + for (int i = 0; i < molecule.getNumberOfBonds(); i++) { + BondInterface b = molecule.getBondInterface(i); + b.setProperty(BondInterface.RENDERING_STYLE, new Integer(BondInterface.LINE_BICOLOR)); + b.setProperty(BondInterface.COLOR_SCHEME, new Integer(BondInterface.BICOLOR)); + // --- Decide whether it's visible + AtomInterface a = b.getIAtomInterface(); + Object obj = a.getProperty(AtomInterface.VISIBLE); + if (obj == null) { + a.setProperty(AtomInterface.VISIBLE, new Boolean(true)); + } + + if (!(Boolean) obj) { + b.setProperty(BondInterface.VISIBLE, new Boolean(false)); + continue; + } + + a = b.getJAtomInterface(); + obj = a.getProperty(AtomInterface.VISIBLE); + if (obj == null) { + a.setProperty(AtomInterface.VISIBLE, new Boolean(true)); + } + + if (!(Boolean) obj) { + b.setProperty(BondInterface.VISIBLE, new Boolean(false)); + continue; + } + b.setProperty(BondInterface.VISIBLE, new Boolean(true)); + } + + } else if (style == MoleculeInterface.STICKS) { + int atomRenderingStyle = AtomInterface.RENDER_SPHERE; + bondRenderingStyle = BondInterface.CYLINDER_BICOLOR; + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface a = molecule.getAtomInterface(i); + a.setProperty(AtomInterface.RENDERING_STYLE, new Integer(atomRenderingStyle)); + a.setProperty(AtomInterface.GR_RADIUS, new Float(BondInterface.DEFAULT_STICKS_RADIUS)); // GR_RADIUS "gradius" is a "graphics radius" + } + for (int i = 0; i < molecule.getNumberOfBonds(); i++) { + BondInterface b = molecule.getBondInterface(i); + + b.setProperty(BondInterface.CYLINDER_RADIUS, new Float(BondInterface.DEFAULT_STICKS_RADIUS)); + b.setProperty(BondInterface.RENDERING_STYLE, new Integer(BondInterface.CYLINDER_BICOLOR)); + b.setProperty(BondInterface.COLOR_SCHEME, new Integer(BondInterface.BICOLOR)); + + // --- Decide whether it's visible + AtomInterface a = b.getIAtomInterface(); + Object obj = a.getProperty(AtomInterface.VISIBLE); + if (obj == null) { + a.setProperty(AtomInterface.VISIBLE, new Boolean(true)); + } + + if (!(Boolean) obj) { + b.setProperty(BondInterface.VISIBLE, new Boolean(false)); + continue; + } + + a = b.getJAtomInterface(); + obj = a.getProperty(AtomInterface.VISIBLE); + if (obj == null) { + a.setProperty(AtomInterface.VISIBLE, new Boolean(true)); + } + + if (!(Boolean) obj) { + b.setProperty(BondInterface.VISIBLE, new Boolean(false)); + continue; + } + + b.setProperty(BondInterface.VISIBLE, new Boolean(true)); + } + + } else if (style == MoleculeInterface.BALL_AND_STICKS) { + int atomRenderingStyle = AtomInterface.RENDER_SPHERE; + bondRenderingStyle = BondInterface.CYLINDER_BICOLOR; + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface a = molecule.getAtomInterface(i); + a.setProperty(AtomInterface.RENDERING_STYLE, new Integer(atomRenderingStyle)); + float radius = ChemicalElements.getCovalentRadius(a.getAtomicNumber()); + radius *= AtomInterface.COVALENT_TO_GRADIUS_FACTOR; + a.setProperty(AtomInterface.GR_RADIUS, new Float(radius)); // GR_RADIUS "gradius" is a "graphics radius" + } + for (int i = 0; i < molecule.getNumberOfBonds(); i++) { + BondInterface b = molecule.getBondInterface(i); + b.setProperty(BondInterface.CYLINDER_RADIUS, new Float(BondInterface.DEFAULT_BONDS_AND_STICKS_RADIUS)); + b.setProperty(BondInterface.RENDERING_STYLE, new Integer(BondInterface.CYLINDER_BICOLOR)); + b.setProperty(BondInterface.COLOR_SCHEME, new Integer(BondInterface.BICOLOR)); + //b.setProperty(BondInterface.COLOR_SCHEME, + // new Integer(BondInterface.BICOLOR)); + + // --- Decide whether it's visible + AtomInterface a = b.getIAtomInterface(); + Object obj = a.getProperty(AtomInterface.VISIBLE); + if (obj == null) { + a.setProperty(AtomInterface.VISIBLE, new Boolean(true)); + } + + if (!(Boolean) obj) { + b.setProperty(BondInterface.VISIBLE, new Boolean(false)); + continue; + } + + a = b.getJAtomInterface(); + obj = a.getProperty(AtomInterface.VISIBLE); + if (obj == null) { + a.setProperty(AtomInterface.VISIBLE, new Boolean(true)); + } + + if (!(Boolean) obj) { + b.setProperty(BondInterface.VISIBLE, new Boolean(false)); + continue; + } + + b.setProperty(BondInterface.VISIBLE, new Boolean(true)); + + } + } else if (style == MoleculeInterface.SPACEFILL) { + int atomRenderingStyle = AtomInterface.RENDER_SPHERE; + bondRenderingStyle = BondInterface.LINE_BICOLOR; + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface a = molecule.getAtomInterface(i); + a.setProperty(AtomInterface.RENDERING_STYLE, + new Integer(atomRenderingStyle)); + float radius = ChemicalElements.getVanDerWaalsRadius(a.getAtomicNumber()); + //radius *= AtomInterface.COVALENT_TO_GRADIUS_FACTOR; + a.setProperty(AtomInterface.GR_RADIUS, new Float(radius)); // GR_RADIUS "gradius" is a "graphics radius" + } + for (int i = 0; i < molecule.getNumberOfBonds(); i++) { + BondInterface b = molecule.getBondInterface(i); + b.setProperty(BondInterface.VISIBLE, new Boolean(false)); + b.setProperty(BondInterface.RENDERING_STYLE, new Integer(BondInterface.LINE_BICOLOR)); + b.setProperty(BondInterface.COLOR_SCHEME, new Integer(BondInterface.BICOLOR)); + + } + + } + + // --- Update them + updateAtomicRadii(); + updateBondRadii(); + } + + /** + * Updates atomic radii (for drawing) + */ + public void updateAtomicRadii() { + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface a = molecule.getAtomInterface(i); + AtomNode atom_node = (AtomNode) a.getProperty(ATOM_NODE); + //AtomNode atom_node = atomNodes.get(i); + + Object obj = a.getProperty(AtomInterface.VISIBLE); + if (obj == null) { + a.setProperty(AtomInterface.VISIBLE, new Boolean(true)); + } + if (!(Boolean) obj) { + continue; + } + + Float R = (Float) a.getProperty(AtomInterface.GR_RADIUS); + if (R != null) { + setAtomicSphereRadius(atom_node, R); + } + } + } + + public void updateBondRadii() { + for (Iterator iter = bondNodes.iterator(); iter.hasNext();) { + BondNode bond = (BondNode) iter.next(); + if (bond == null) { + continue; + } + + BondInterface bi = bond.getBond(); + Object obj = bi.getProperty(BondInterface.VISIBLE); + if (obj == null) { + bi.setProperty(BondInterface.VISIBLE, new Boolean(true)); + } + if (!(Boolean) obj) { + continue; + } + + bond.updateBondRadius(); + } + } + + /** + * Translates geometric center of a molecule to a point with coordinates x,y,z + * + * @param molec MoleculeInterface + * @param x float + * @param y float + * @param z float + */ + public static void centerMolecule(MoleculeInterface molec, float x, float y, + float z) { + if (molec.getNumberOfAtoms() < 1) { + return; + } + AtomInterface a = molec.getAtomInterface(0); + float x_center = a.getX(); + float y_center = a.getY(); + float z_center = a.getZ(); + for (int i = 1; i < molec.getNumberOfAtoms(); i++) { + a = molec.getAtomInterface(i); + x_center += a.getX(); + y_center += a.getY(); + z_center += a.getZ(); + } + + x_center /= (float) molec.getNumberOfAtoms(); + y_center /= (float) molec.getNumberOfAtoms(); + z_center /= (float) molec.getNumberOfAtoms(); + + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + a = molec.getAtomInterface(i); + a.setX(a.getX() - x_center + x); + a.setY(a.getY() - y_center + y); + a.setZ(a.getZ() - z_center + z); + } + + } + + public void resetMoleculeGraphics() { + //detachRoot(); + //root.detach(); + + // --- Clean nodes + mol.detach(); + mol.removeAllChildren(); + + //atomNodes.clear(); + bondNodes.clear(); + + //materialStore.clear(); + atomLabels.clear(); + } + + public void removeMolecule() { + + moleculeTrans.removeAllChildren(); + if (graphicsObjects != null) { + this.graphicsObjects.clear(); + } + molecule = new Molecule(); + addMolecule(molecule); + } + + public void addMolecule(MoleculeInterface m) { + if (molecule != null) { + molecule = null; + } + molecule = m; + + drawMolecule(molecule); + + centerSceneOnScreen(); + } + + public void drawMolecule(MoleculeInterface m) { + Object obj; + //removeMolecule(); + resetMoleculeGraphics(); + + //gAtom a; + AtomInterface a; + + //setBounds(m); + float x = m.getXmax() - m.getXmin(); + float y = m.getYmax() - m.getYmin(); + float ex = Math.max(x, y); + logger.info("ex: " + ex + " " + m.getZmin() + " " + m.getZmax()); + float backPlane = m.getZmax() > 150.0f ? (m.getZmax() + 50.0f) : 150.0f; + //simpleU.getViewer().getView().setBackClipDistance(backPlane); + + //view.setBackClipDistance(backPlane); + //fog.setFrontDistance(0.5f * (m.getZmin() + m.getZmax())); + //fog.setFrontDistance( -5.0f); + //fog.setBackDistance(backPlane); + Transform3D t = new Transform3D(); + + double xField = view.getFieldOfView(); + double yField = view.getFieldOfView(); + if ((float) canvas3D.getWidth() / (float) canvas3D.getHeight() > 1.0f) { + yField = 2.0 + * Math.atan(Math.tan(view.getFieldOfView() / 2.0) * (double) canvas3D.getHeight() / (double) canvas3D.getWidth()); + } else { + xField = 2.0 + * Math.atan(Math.tan(view.getFieldOfView() / 2.0) * (double) canvas3D.getWidth() / (double) canvas3D.getHeight()); + } + + double minX = x / (2.0 * Math.tan(xField / 2.0)); + double minY = y / (2.0 * Math.tan(yField / 2.0)); + double minZ = m.getZmax() - m.getZmin(); + float shift = (float) Math.max(Math.max(minX, minY), minZ); + if (debug) { + logger.info("Field of view: " + view.getFieldOfView() * RADS_TO_DEGS + " X field: " + xField * RADS_TO_DEGS + + " Y field: " + yField * RADS_TO_DEGS); + } + //canvas3D.g + + //t.set(new Vector3f(0.0f, 0.0f, (m.getZmin() - 2.0f * ex))); + t.set(new Vector3f(0.0f, 0.0f, -shift - 5.0f)); + //t.setScale(15.0f/ex); + sceneOffset.setTransform(t); + + fog.setFrontDistance(-5.0f); // !!! Make better with fog + if (shift > 50) { + fog.setBackDistance(3 * shift); + } else { + fog.setBackDistance(150); + } + + if (bondNodes instanceof ArrayList) { + ((ArrayList) bondNodes).ensureCapacity(m.getNumberOfBonds()); + } + + if (atomLabels instanceof ArrayList) { + ((ArrayList) atomLabels).ensureCapacity(m.getNumberOfAtoms()); + } + + for (int i = 0; i < m.getNumberOfAtoms(); i++) { + atomLabels.add(i, null); + } + + // --- Setup rendering style + int atomRenderingStyle = AtomInterface.RENDER_SPHERE; + bondRenderingStyle = BondInterface.CYLINDER_BICOLOR; + + Object rStyle = m.getProperty(MoleculeInterface.RenderingStyle); + if (rStyle != null && rStyle instanceof Integer) { + renderingStyle = ((Integer) rStyle).intValue(); + } else { + if (m.getNumberOfAtoms() > 150) { + renderingStyle = MoleculeInterface.WIREFRAME; + } else { + renderingStyle = MoleculeInterface.BALL_AND_STICKS; + } + } + + if (renderingStyle == MoleculeInterface.WIREFRAME) { + atomRenderingStyle = AtomInterface.RENDER_SMART_POINT; + bondRenderingStyle = BondInterface.LINE_BICOLOR; + } + + // Draw Atoms (Spheres) + for (int i = 0; i < m.getNumberOfAtoms(); i++) { + a = m.getAtomInterface(i); + obj = a.getProperty(AtomInterface.VISIBLE); + if (obj == null) { + a.setProperty(AtomInterface.VISIBLE, new Boolean(true)); + } + + obj = a.getProperty(AtomInterface.RENDERING_STYLE); + if (obj == null) { + a.setProperty(AtomInterface.RENDERING_STYLE, new Integer(atomRenderingStyle)); + } + AtomNode at = new AtomNode(a); // createAtom(a); + + a.setProperty(ATOM_NODE, at); + mol.addChild(at); + //atomNodes.add(at); + + //Material mater = getAtomicNodeMaterial(at); + Material store = cloneMaterial(at.getMaterial()); + a.setProperty(ATOM_NODE_MATERIAL_COPY, store); + //materialStore.add(store); + } + + drawBonds(m); + + //mol.setCapability(BranchGroup.ALLOW_CHILDREN_READ); + //mol.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE); + //mol.setCapability(BranchGroup.ALLOW_PICKABLE_READ); + //mol.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND); + //mol.setCapability(BranchGroup.ALLOW_DETACH); + //mol.setCapability(BranchGroup.ALLOW_PICKABLE_READ); + //mol.setCapability(BranchGroup.ALLOW_PICKABLE_WRITE); + //mol.setCapability(BranchGroup.ALLOW_LOCAL_TO_VWORLD_READ); + //mol.setPickable(true); + // --- Mouse behavior (experimental) + /* + * mouse_picking_behavior = new MousePicking(this, mol, canvas3D, bounds); mouse_picking_behavior.setTolerance(0); + * mouse_picking_behavior.setEnable(false); mol.addChild(mouse_picking_behavior); + */ + addMousePicking(this, mol, canvas3D, bounds); + + Transform3D move = new Transform3D(); + moleculeTrans.setTransform(move); + + //mol.compile(); + //niceGroup.addChild(mol); + moleculeTrans.addChild(mol); + + } + + public void drawBonds(MoleculeInterface m) { + // Draw bonds (Cylinders) + + for (int i = 0; i < m.getNumberOfBonds(); i++) { + BondInterface b = m.getBondInterface(i); + Object obj = b.getProperty(BondInterface.RENDERING_STYLE); + int bRendStyle = bondRenderingStyle; + if (obj == null) { + b.setProperty(BondInterface.RENDERING_STYLE, new Integer(bondRenderingStyle)); + } else if (obj instanceof Integer) { + bRendStyle = ((Integer) obj).intValue(); + } + + BondNode bond = new BondNode(b, bRendStyle); + mol.addChild(bond); + b.setProperty(BOND_NODE, bond); + bondNodes.add(bond); + } + + } + + public void addMousePicking(Java3dUniverse dad, BranchGroup root, Canvas3D canvas, Bounds bounds) { + mouse_picking_behavior = new MousePicking(dad, root, canvas, bounds); + mouse_picking_behavior.setTolerance(0); + mouse_picking_behavior.setEnable(false); + root.addChild(mouse_picking_behavior); + } + + public void centerSceneOnScreen() { + centerMolecule(0, 0, 0); + centerScene(); + //vp.setViewAttachPolicy(View.NOMINAL_SCREEN); + } + + public void setRotationCenterOnSelectedAtoms() { + + if (trackSelectedAtoms.size() < 1) { + return; + } + + AtomInterface a = trackSelectedAtoms.get(0); + float x_center = a.getX(); + float y_center = a.getY(); + float z_center = a.getZ(); + + for (int i = 1; i < trackSelectedAtoms.size(); i++) { + a = trackSelectedAtoms.get(i); + x_center += a.getX(); + y_center += a.getY(); + z_center += a.getZ(); + } + + x_center /= (float) trackSelectedAtoms.size(); + y_center /= (float) trackSelectedAtoms.size(); + z_center /= (float) trackSelectedAtoms.size(); + + Transform3D move = new Transform3D(); + moleculeTrans.getTransform(move); + move.setTranslation(new Vector3f(-x_center, -y_center, -z_center)); + moleculeTrans.setTransform(move); + + //centerMolecule( -x_center, -y_center, -z_center); + centerScene(); + } + + public void centerMolecule(float x, float y, float z) { + + if (molecule == null || molecule.getNumberOfAtoms() < 1) { + return; + } + AtomInterface a = molecule.getAtomInterface(0); + float x_center = a.getX(); + float y_center = a.getY(); + float z_center = a.getZ(); + for (int i = 1; i < molecule.getNumberOfAtoms(); i++) { + a = molecule.getAtomInterface(i); + x_center += a.getX(); + y_center += a.getY(); + z_center += a.getZ(); + } + + x_center /= (float) molecule.getNumberOfAtoms(); + y_center /= (float) molecule.getNumberOfAtoms(); + z_center /= (float) molecule.getNumberOfAtoms(); + + Transform3D move = new Transform3D(); + move.setTranslation(new Vector3f(-x_center + x, -y_center + y, -z_center + z)); + moleculeTrans.setTransform(move); + } + + public void centerScene() { + Transform3D transl = new Transform3D(); + sceneTrans.getTransform(transl); + transl.setTranslation(new Vector3f(0, 0, 0)); + sceneTrans.setTransform(transl); + + } + + public void fillEmptyValences(AtomInterface atom) { + Map store = null; + try { + store = AtomGenerator.fillEmptyValences(molecule, atom, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getAtomTypes()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + // --- Start to add atoms & bonds + List bunch = (List) store.get("atoms"); + for (int i = 0; i < bunch.size(); i++) { + AtomInterface a = (AtomInterface) bunch.get(i); + addAtom(a); + } + + bunch = (List) store.get("bonds"); + for (int i = 0; i < bunch.size(); i++) { + BondInterface bond = (BondInterface) bunch.get(i); + addBond(bond); + } + + } + + public AtomNode createAtom(AtomInterface atom) { + + return new AtomNode(atom); + /* + * // --- Setup radius of atomic sphere float atomRadius = getAtomicSphereRadius(atom); + * + * // --- Setup RGB color of atomic sphere !!! To be done !!! + * + * Color3f color = ChemicalElementsColors.getElementColor(atom. getAtomicNumber()); + * + * // --- Set material of atomic sphere !!! --- To be done !!! + * + * Material material = ChemicalElementsColors.getElementMaterial(atom. getAtomicNumber()); + * + * return createAtom(atom.getX(), atom.getY(), atom.getZ(), atom.getAtomicNumber(), material, atomRadius, color); + */ + } + + /* + * public AtomNode createAtom(float x, float y, float z, int element) { Material material = + * ChemicalElementsColors.getElementMaterial(element); material.setCapability(Material.ALLOW_COMPONENT_READ); + * material.setCapability(Material.ALLOW_COMPONENT_WRITE); float radius = ChemicalElements.getCovalentRadius(element); radius *= + * AtomInterface.COVALENT_TO_GRADIUS_FACTOR; if (radius < 0.001f) { radius = 0.2f; } Color3f color = + * ChemicalElementsColors.getElementColor(element); return createAtom(x, y, z, element, material, radius, color); } + */ + /** + * + */ + /* + * public AtomNode createAtom(float x, float y, float z, int element, Material material, float atomRadius, Color3f color) { + * + * AtomNode atom = createAtomicSphere(atomRadius, x, y, z, 100, color, material); + * + * return atom; } public AtomNode createAtomicSphere(float radius, float x, float y, float z, int divisions, Color3f color, + * Material material) { AtomNode at = new AtomNode(radius, x, y, z, divisions, color, material); + * + * + * temp_Sphere = at.getAtomicSphere(); + * + * return at; } + */ + /** + * Returns BranchGroup of a molecule + * + * @return BranchGroup + */ + public BranchGroup getMoleculeBranchGroup() { + return mol; + } + + public BranchGroup getRootBranchGroup() { + return niceGroup; + } + + public Locale getLocale() { + return locale; + } + + public MoleculeInterface getMolecule() { + return molecule; + } + + public MoleculeInterface getMoleculeInterface() { + return molecule; + } + + public BranchGroup createSceneGraph() { + // Create the root of the branch graph + BranchGroup objRoot = new BranchGroup(); + + // rotate object has composite transformation matrix + rotate = new Transform3D(); + rotate.rotX(Math.PI / 4.0d); + + translate = new Transform3D(); + translate.set(new Vector3f(1.0f, 0.0f, 0.0f)); + + ColoringAttributes ca = new ColoringAttributes(); + ca.setColor(1.0f, 0.5f, 0.7f); + atomAppear = new Appearance(); + atomAppear.setColoringAttributes(ca); + + Material material = new Material(); + material.setCapability(Material.ALLOW_COMPONENT_READ); + material.setCapability(Material.ALLOW_COMPONENT_WRITE); + atomAppear.setMaterial(material); + + PolygonAttributes polyAppear = new PolygonAttributes(); + polyAppear.setCullFace(PolygonAttributes.CULL_BACK); + + atomAppear.setPolygonAttributes(polyAppear); + + // Setup atoms + Sphere atom1 = new Sphere(AtomInterface.COVALENT_TO_GRADIUS_FACTOR, + Sphere.GENERATE_NORMALS, atomAppear); +// atom1.setAppearance( atomAppear ); + + Sphere atom2 = new Sphere(); + atom2.setAppearance(atomAppear); + + // We need only translate a sphere + TransformGroup tr1 = new TransformGroup(translate); + tr1.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + tr1.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); + + objRoot.addChild(tr1); + tr1.addChild(atom1); + + translate.set(new Vector3f(-1.0f, 0.0f, 0.0f)); + + TransformGroup tr2 = new TransformGroup(translate); + tr2.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + tr2.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); + + objRoot.addChild(tr2); + tr2.addChild(atom2); + + objRotate = new TransformGroup(rotate); + objRotate.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + objRotate.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); + +// objRotate.addChild(new ColorCube(0.4)); +// objRoot.addChild(objRotate); + //myMouseRotate = new MyMouseRotate(); + //myMouseRotate.setTransformGroup(tr1); + //myMouseRotate.setSchedulingBounds(new BoundingSphere()); + //objRoot.addChild(myMouseRotate); + myMouseZoom = new MouseZoom(MouseBehavior.INVERT_INPUT); + myMouseZoom.setTransformGroup(tr1); + myMouseZoom.setSchedulingBounds(new BoundingSphere(new Point3d(), + 1000.0)); + objRoot.addChild(myMouseZoom); + + // Lighting + AmbientLight lightA = new AmbientLight(); + lightA.setInfluencingBounds(new BoundingSphere()); + objRoot.addChild(lightA); + + DirectionalLight lightD1 = new DirectionalLight(); + lightD1.setInfluencingBounds(new BoundingSphere()); + // customize DirectionalLight object + objRoot.addChild(lightD1); + + // Let Java 3D perform optimizations on this scene graph. + objRoot.compile(); + + // Create a simple shape leaf node, add it to the scene graph. + // ColorCube is a Convenience Utility class + //objRoot.addChild(new ColorCube(0.4)); + return objRoot; + } // end of createSceneGraph method of HelloJava3Da + + public String getSQLHostName() { + return "jdbc:mysql://localhost/"; + } + + public void doAtomSelection(Point3d origin, Vector3d dir, BranchGroup bgr, + PickResult[] pickingResults) { + + //if (molecule == null || molecule.getNumberOfAtoms() < 1) { + // return; + //} + int closest_atom = findClosestAtom(origin, dir); + doAtomSelection(closest_atom); + } + + public boolean isAtomVisible(AtomInterface a) { + AtomNode atom = (AtomNode) a.getProperty(ATOM_NODE); + + return mol.indexOfChild( atom ) != -1; + } + + public int findClosestAtom(Point3d origin, Vector3d dir) { + + if (molecule == null || molecule.getNumberOfAtoms() < 1) { + return -1; + } + + if (dir == null || dir.z == 0.0) { // View direction is parallel to the VW's Z-plane + System.err.println("dir == null || dir.z == 0.0. Ignoring..."); + return -1; + } + + Point3f xyz = new Point3f(); + + // Get transform to the virtual world (VW) + Transform3D toVW = getVWTransform(); + + // --- Checking all atoms for intersection + int closest_atom = -1; + boolean intersect_sphere = false; + double closest_distance = -1; + + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface a = molecule.getAtomInterface(i); + + if (!isAtomVisible(a)) { // Atom is invisible + continue; + } + + xyz.set(a.getX(), a.getY(), a.getZ()); + //logger.info("Local xyz: " + xyz); + + // --- Coordinates of atom in the VW + toVW.transform(xyz); + //logger.info("VW xyz: " + xyz); + + // --- knowing viewing point and direction of view we can find + // --- intersection point of a direction vector with Z-plane of the VW + // --- which contains a given atom + double t = -(-xyz.z + origin.z) / dir.z; + double x = origin.x + t * dir.x; + double y = origin.y + t * dir.y; + double z = origin.z + t * dir.z; + //logger.info("Intersection with VW Z-plane: " + xyz); + + // --- Get graphics radius + double gr_radius = 0.1; + Object obj = a.getProperty(AtomInterface.GR_RADIUS); + if (obj != null) { + if (obj instanceof Float) { + gr_radius = ((Float) obj).doubleValue(); + } else if (obj instanceof Double) { + gr_radius = ((Double) obj).doubleValue(); + } else if (obj instanceof String) { + try { + gr_radius = Double.parseDouble(obj.toString()); + } catch (Exception ex) { + System.err.println( + "Wrong value for graphical radius: " + obj.toString() + " Ignoring..."); + } + } else { + System.err.println( + "Unsupported data type for graphical radius: " + + obj.getClass().getCanonicalName() + " Ignoring..."); + } + + if (gr_radius < 0.1) { + gr_radius = 0.1; + } + } + + // --- Calculate distance between atom and mouse pick + double dist = Math.sqrt((xyz.x - x) * (xyz.x - x) + + (xyz.y - y) * (xyz.y - y)); + + // --- + // --- Initialization #1 + if (closest_atom == -1 && dist <= gr_radius) { + closest_atom = i; + intersect_sphere = true; + closest_distance = origin.z - z > 0 ? origin.z - z : z - origin.z; + } // --- Initialization #2 + else if (closest_atom == -1 && dist <= 0.1) { + closest_atom = i; + intersect_sphere = false; + closest_distance = origin.z - z > 0 ? origin.z - z : z - origin.z; + } else if (dist <= gr_radius) { + if (!intersect_sphere) { + closest_atom = i; + intersect_sphere = true; + closest_distance = Math.abs(origin.z - z); + } else if (closest_distance > Math.abs(origin.z - z)) { + closest_atom = i; + intersect_sphere = true; + closest_distance = Math.abs(origin.z - z); + } + } + } + + if (debug) { + logger.info("Closest atom: " + closest_atom + " Intersect: " + intersect_sphere + " Dist: " + closest_distance); + } + + return closest_atom; + } + + public int findClosestBond(Point3d origin, Vector3d dir) { + + if (molecule == null || molecule.getNumberOfBonds() < 1) { + return -1; + } + + if (dir == null || dir.z == 0.0) { // View direction is parallel to the VW's Z-plane + System.err.println("dir == null || dir.z == 0.0. Ignoring..."); + return -1; + } + + cct.vecmath.Point3f xyz = new cct.vecmath.Point3f(); + cct.vecmath.Point3f ray_xyz = new cct.vecmath.Point3f(); + + Segment3f ray = new Segment3f(); + ray.p1.setXYZ(origin.x, origin.y, origin.z); + Segment3f bond_segment = new Segment3f(); + + // Get transform to the virtual world (VW) + Transform3D toVW = getVWTransform(); + + // --- Checking all atoms for intersection + int closest_bond = -1; + boolean intersect_bond = false; + double closest_distance_to_ray = -1; + double closest_distance_to_origin = -1; + double b_radius = 0.1; + double minZ = 10000; + Object obj; + BondInterface bond; + + Point3f vw_coords[] = new Point3f[molecule.getNumberOfAtoms()]; + + // --- First fill in array with the VW coordinates + Set visibleAtoms = new HashSet(molecule.getNumberOfAtoms()); + + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface a = molecule.getAtomInterface(i); + if (!isAtomVisible(a)) { // Atom is invisible + continue; + } + visibleAtoms.add(a); + + vw_coords[i] = new Point3f(a.getX(), a.getY(), a.getZ()); + //logger.info("Local xyz: " + vw_coords[i]); + + // --- Coordinates of atom in the VW + toVW.transform(vw_coords[i]); + a.setProperty("_VW_COORD", vw_coords[i]); + //logger.info("VW xyz: " + vw_coords[i]); + if (i == 0) { + minZ = vw_coords[i].z; + } else if (minZ > vw_coords[i].z) { + minZ = vw_coords[i].z; + } + } + + double t = -(-minZ + origin.z) / dir.z; + double x = origin.x + t * dir.x; + double y = origin.y + t * dir.y; + double z = origin.z + t * dir.z; + ray.p2.setXYZ(x, y, z); + + // --- knowing viewing point and direction of view we can find + // --- intersection point of a direction vector with Z-plane of the VW + // --- which contains a given atom + for (int i = 0; i < molecule.getNumberOfBonds(); i++) { + bond = molecule.getBondInterface(i); + AtomInterface a1 = bond.getIAtomInterface(); + if (!visibleAtoms.contains(a1)) { + continue; + } + AtomInterface a2 = bond.getJAtomInterface(); + if (!visibleAtoms.contains(a2)) { + continue; + } + Point3f c1 = (Point3f) a1.getProperty("_VW_COORD"); + Point3f c2 = (Point3f) a2.getProperty("_VW_COORD"); + bond_segment.p1.setXYZ(c1.x, c1.y, c1.z); + bond_segment.p2.setXYZ(c2.x, c2.y, c2.z); + + // --- Calculate distance between bond and mouse pick + //double dist = Geometry3d.segmentToSegmentDistance(ray, bond_segment); + double dist = Geometry3d.segmentToSegmentDistance(ray, bond_segment, ray_xyz, xyz); + + // --- Get bond radius + b_radius = 0.1; + obj = bond.getProperty(BondInterface.CYLINDER_RADIUS); + if (obj != null) { + if (obj instanceof Float) { + b_radius = ((Float) obj).doubleValue(); + } else if (obj instanceof Double) { + b_radius = ((Double) obj).doubleValue(); + } else if (obj instanceof String) { + try { + b_radius = Double.parseDouble(obj.toString()); + } catch (Exception ex) { + System.err.println( + "Wrong value for bond radius: " + obj.toString() + + " Ignoring..."); + } + } else { + System.err.println( + "Unsupported data type for graphical radius: " + + obj.getClass().getCanonicalName() + " Ignoring..."); + } + + if (b_radius < 0.1) { + b_radius = 0.1; + } + } + + // --- Initialization + if (closest_bond == -1) { + // --- Initialization #1 + if (dist <= b_radius) { + closest_bond = i; + intersect_bond = true; + closest_distance_to_ray = dist; + closest_distance_to_origin = ray_xyz.distanceTo(origin.x, + origin.y, origin.z); + } // --- Initialization #2 + else if (dist <= 0.1) { + closest_bond = i; + intersect_bond = false; + closest_distance_to_ray = dist; + closest_distance_to_origin = ray_xyz.distanceTo(origin.x, + origin.y, origin.z); + } + } else if (dist <= b_radius) { + if (!intersect_bond) { + closest_bond = i; + intersect_bond = true; + closest_distance_to_ray = dist; + closest_distance_to_origin = ray_xyz.distanceTo(origin.x, + origin.y, origin.z); + } else if (closest_distance_to_origin > ray_xyz.distanceTo(origin.x, + origin.y, origin.z)) { + closest_bond = i; + intersect_bond = true; + closest_distance_to_origin = ray_xyz.distanceTo(origin.x, + origin.y, origin.z); + } + } + + //logger.info("Bond: " + i + " to ray distance: " + dist); + } + + if (debug) { + logger.info("Closest bond: " + closest_bond + " Intersect: " + intersect_bond + " Dist ro ray: " + + closest_distance_to_ray + " Dist to origin: " + closest_distance_to_origin); + } + + if (closest_bond < 0) { + return closest_bond; + } + if (intersect_bond) { + return closest_bond; + } + return -1; + } + + public int getNumberSelectedAtoms() { + return trackSelectedAtoms.size(); + } + + public void doAtomSelection(int nsel) { + + if (nsel != -1) { + if (selectedMode == SELECTION_ONE_ATOM_ONLY) { + // --- Is atom already selected? + AtomInterface a = molecule.getAtomInterface(nsel); + //if ( molecule.IsAtomSelected(nsel)) { + if (a.isSelected()) { + return; + } + selectAllAtoms(false); + + lastSelectedAtom = nsel; + a.setSelected(true); + AtomNode atom = (AtomNode) a.getProperty(ATOM_NODE); + highlightSelectedAtom(mol, atom, true); + } // --- Select only two atoms at a time + else if (selectedMode == SELECTION_TWO_ATOMS_ONLY) { + // --- Is atom already selected? + AtomInterface a = molecule.getAtomInterface(nsel); + if (a.isSelected()) { + return; + } + + if (lastSelectedAtom == nsel) { + // Do nothing + } else if (selectedAtoms.size() == 0) { + selectedAtoms.add(new Integer(nsel)); + } else if (selectedAtoms.size() == 1) { + selectedAtoms.add(new Integer(nsel)); + } else if (selectedAtoms.size() >= 2) { + //Integer lastSel = (Integer) selectedAtoms.get(1); + // --- unselect atom + //molecule.markAtomAsSelected(lastSel, false); + //BranchGroup atom = (BranchGroup) atomNodes.get(lastSel); + //highlightSelectedAtom(mol, atom, lastSel, false); + //selectedAtoms.remove(1); + // --- new atom in front + //lastSel = nsel; + //selectedAtoms.add(0, lastSel); + + selectAllAtoms(false); + selectedAtoms.clear(); + selectedAtoms.add(new Integer(nsel)); + + } + + lastSelectedAtom = nsel; + a.setSelected(true); + AtomNode atom = (AtomNode) a.getProperty(ATOM_NODE); + highlightSelectedAtom(mol, atom, HighlighSelectedAtoms); + } // --- Select only three atoms at a time + else if (selectedMode == SELECTION_THREE_ATOMS_ONLY) { + // --- Is atom already selected? + AtomInterface a = molecule.getAtomInterface(nsel); + if (a.isSelected()) { + return; + } + + if (lastSelectedAtom == nsel) { + // Do nothing + } else if (selectedAtoms.size() == 0) { + selectedAtoms.add(new Integer(nsel)); + } else if (selectedAtoms.size() == 1) { + if (lastSelectedAtom != nsel) { + selectedAtoms.add(new Integer(nsel)); + } + } else if (selectedAtoms.size() == 2) { + Integer sel = (Integer) selectedAtoms.get(0); + if (lastSelectedAtom != nsel && sel != nsel) { + selectedAtoms.add(new Integer(nsel)); + } + } else if (selectedAtoms.size() >= 3) { + selectAllAtoms(false); + selectedAtoms.clear(); + selectedAtoms.add(new Integer(nsel)); + } + + lastSelectedAtom = nsel; + //molecule.markAtomAsSelected(nsel, true); + a.setSelected(true); + AtomNode atom = (AtomNode) a.getProperty(ATOM_NODE); + //AtomNode atom = atomNodes.get(nsel); + highlightSelectedAtom(mol, atom, HighlighSelectedAtoms); + } // --- Select only four atoms at a time + else if (selectedMode == SELECTION_FOUR_ATOMS_ONLY) { + // --- Is atom already selected? + AtomInterface a = molecule.getAtomInterface(nsel); + if (a.isSelected()) { + return; + } + + if (selectedAtoms.size() >= 4) { + selectAllAtoms(false); + selectedAtoms.clear(); + selectedAtoms.add(new Integer(nsel)); + } else { + selectedAtoms.add(new Integer(nsel)); + } + + lastSelectedAtom = nsel; + //molecule.markAtomAsSelected(nsel, true); + a.setSelected(true); + AtomNode atom = (AtomNode) a.getProperty(ATOM_NODE); + //AtomNode atom = atomNodes.get(nsel); + highlightSelectedAtom(mol, atom, HighlighSelectedAtoms); + } // --- End of special cases.... + // --- General case selection + else { + doProperSelection(nsel); + } + } + + // --- Process selected atom(s) immediately if it's select&process dialog + if (selectAndProcessDialog) { + processSelectedAtoms(); + } + } + + /** + * @deprecated Deprecated function. To be deleted... + * @param bgr BranchGroup + * @param pickingResult PickResult + */ + public void doAtomSelection(BranchGroup bgr, PickResult pickingResult) { + if (pickingResult == null || bgr == null) { + logger.info("No picking..."); + return; + } + + BranchGroup sel_bgr = (BranchGroup) pickingResult.getNode(PickResult.BRANCH_GROUP); + TransformGroup atg = (TransformGroup) pickingResult.getNode(PickResult.TRANSFORM_GROUP); + if (atg != null) { + logger.info("TransformGroup: # children" + atg.numChildren()); + } + Primitive p = (Primitive) pickingResult.getNode(PickResult.PRIMITIVE); + Sphere sel_sphere; + + // --- Atom (Sphere) is selected + if (p instanceof Sphere) { + sel_sphere = (Sphere) pickingResult.getNode(PickResult.PRIMITIVE); + if (sel_sphere != null) { + //int nsel = getSelectedAtomNumber(bgr, sel_sphere); + //int nsel = atomNodes.indexOf(sel_bgr); --- Stupid stuff !!! + int nsel = 0; // Stupid stuff !!! + doAtomSelection(nsel); + + logger.info("Sphere: # children " + sel_sphere.numChildren()); + for (int i = 0; i < sel_sphere.numChildren(); i++) { + Node sc = sel_sphere.getChild(i); + logger.info("Sphere Child: " + sc.getClass().toString()); + } + logger.info("Sphere: Selected atom: " + nsel); + } + } // --- Bond (cylinder) is selected + else if (p instanceof Cylinder) { + Cylinder c = (Cylinder) pickingResult.getNode(PickResult.PRIMITIVE); + if (c != null) { + logger.info("Cylinder: # children" + c.numChildren()); + } + } + } + + public void doProperSelection(int selected_atom) { + // --- Error check + if (selected_atom < 0 || selected_atom >= molecule.getNumberOfAtoms()) { + System.err.println(getClass().getCanonicalName() + ": Internal Error: Wrong selected atom: " + selected_atom + " Ignored..."); + return; + } + + // --- Atom selection + if (selectionType == SELECTION_TYPE.ATOMS) { + + AtomInterface a; + AtomNode atom; + + switch (selectionRule) { + case UNION: + logger.info("Selection: One Atom; Rule: Union"); + lastSelectedAtom = selected_atom; + a = molecule.getAtomInterface(selected_atom); + a.setSelected(true); + atom = (AtomNode) a.getProperty(ATOM_NODE); + highlightSelectedAtom(mol, atom, true); + if (trackSelectedAtoms.indexOf(a) == -1) { + trackSelectedAtoms.add(a); + } + break; + //********************************************************* + case DIFFERENCE: + a = molecule.getAtomInterface(selected_atom); + if (a.isSelected()) { + a.setSelected(false); + atom = (AtomNode) a.getProperty(ATOM_NODE); + highlightSelectedAtom(mol, atom, false); + trackSelectedAtoms.remove(a); + } + logger.info("Selection: One Atom; Rule: Difference"); + break; + //******************************************************** + case INTERSECTION: + a = molecule.getAtomInterface(selected_atom); + boolean selected = a.isSelected(); + selectAllAtoms(false); + trackSelectedAtoms.clear(); + Molecule.selectAllAtoms(molecule, false); + if (selected) { + a.setSelected(true); + highlightSelectedAtom(a, true); + //highlightSelectedAtom(selected_atom, true); + trackSelectedAtoms.add(a); + } + logger.info("Selection: One Atom; Rule: Intersection"); + break; + } + + //if (selectionRule == RULE_UNION) { + // logger.info("Selection: One Atom; Rule: Union"); + // lastSelectedAtom = selected_atom; + // AtomInterface a = molecule.getAtomInterface(selected_atom); + // a.setSelected(true); + // AtomNode atom = (AtomNode) a.getProperty(ATOM_NODE); + // highlightSelectedAtom(mol, atom, true); + // if (trackSelectedAtoms.indexOf(a) == -1) { + // trackSelectedAtoms.add(a); + // } + //} else if (selectionRule == RULE_DIFFERENCE) { + // AtomInterface a = molecule.getAtomInterface(selected_atom); + // if (a.isSelected()) { + // a.setSelected(false); + // AtomNode atom = (AtomNode) a.getProperty(ATOM_NODE); + // highlightSelectedAtom(mol, atom, false); + // trackSelectedAtoms.remove(a); + // } + // logger.info("Selection: One Atom; Rule: Difference"); + //} else if (selectionRule == RULE_INTERSECTION) { + // AtomInterface a = molecule.getAtomInterface(selected_atom); + // boolean selected = a.isSelected(); + // selectAllAtoms(false); + // trackSelectedAtoms.clear(); + // Molecule.selectAllAtoms(molecule, false); + // if (selected) { + // a.setSelected(true); + // highlightSelectedAtom(selected_atom, true); + // trackSelectedAtoms.add(a); + // } + // logger.info("Selection: One Atom; Rule: Intersection"); + //} + } // --- Select monomers + else if (selectionType == SELECTION_TYPE.MONOMERS) { + + AtomInterface atom; + MonomerInterface mono; + int n; + + switch (selectionRule) { + case UNION: + atom = molecule.getAtomInterface(selected_atom); + n = atom.getSubstructureNumber(); + mono = molecule.getMonomerInterface(n); + for (int i = 0; i < mono.getNumberOfAtoms(); i++) { + atom = mono.getAtom(i); + atom.setSelected(true); + highlightSelectedAtom(atom, true); + //n = molecule.getAtomIndex(atom); + //highlightSelectedAtom(n, true); + if (trackSelectedAtoms.indexOf(atom) == -1) { + trackSelectedAtoms.add(atom); + } + } + break; + //*********************************************************** + case DIFFERENCE: + atom = molecule.getAtomInterface(selected_atom); + n = atom.getSubstructureNumber(); + mono = molecule.getMonomerInterface(n); + for (int i = 0; i < mono.getNumberOfAtoms(); i++) { + atom = mono.getAtom(i); + if (!atom.isSelected()) { + continue; + } + atom.setSelected(false); + highlightSelectedAtom(atom, false); + //n = molecule.getAtomIndex(atom); + //highlightSelectedAtom(n, false); + trackSelectedAtoms.remove(atom); + } + break; + //*********************************************************** + case INTERSECTION: + atom = molecule.getAtomInterface(selected_atom); + n = atom.getSubstructureNumber(); + + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + atom = molecule.getAtomInterface(i); + if (atom.getSubstructureNumber() != n) { + atom.setSelected(false); + trackSelectedAtoms.remove(atom); + } + } + highlightSelectedAtoms(); + break; + } + + //if (selectionRule == RULE_UNION) { + // AtomInterface atom = molecule.getAtomInterface(selected_atom); + // int n = atom.getSubstructureNumber(); + // MonomerInterface mono = molecule.getMonomerInterface(n); + // for (int i = 0; i < mono.getNumberOfAtoms(); i++) { + // atom = mono.getAtom(i); + // atom.setSelected(true); + // n = molecule.getAtomIndex(atom); + // highlightSelectedAtom(n, true); + // if (trackSelectedAtoms.indexOf(atom) == -1) { + // trackSelectedAtoms.add(atom); + // } + // } + //} else if (selectionRule == RULE_DIFFERENCE) { + // AtomInterface atom = molecule.getAtomInterface(selected_atom); + // int n = atom.getSubstructureNumber(); + // MonomerInterface mono = molecule.getMonomerInterface(n); + // for (int i = 0; i < mono.getNumberOfAtoms(); i++) { + // atom = mono.getAtom(i); + // if (!atom.isSelected()) { + // continue; + // } + // atom.setSelected(false); + // n = molecule.getAtomIndex(atom); + // highlightSelectedAtom(n, false); + // trackSelectedAtoms.remove(atom); + // } + //} else if (selectionRule == RULE_INTERSECTION) { + // AtomInterface atom = molecule.getAtomInterface(selected_atom); + // int n = atom.getSubstructureNumber(); + // for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + // atom = molecule.getAtomInterface(i); + // if (atom.getSubstructureNumber() != n) { + // atom.setSelected(false); + // trackSelectedAtoms.remove(atom); + // } + // } + // highlightSelectedAtoms(); + //} + } else if (selectionType == SELECTION_TYPE.MOLECULES) { + + AtomInterface atom; + List atoms; + + switch (selectionRule) { + case UNION: + atom = molecule.getAtomInterface(selected_atom); + atoms = Molecule.getMoleculeAtomBelongsTo(atom); + for (int i = 0; i < atoms.size(); i++) { + atom = (AtomInterface) atoms.get(i); + atom.setSelected(true); + highlightSelectedAtom(atom, true); + //int n = molecule.getAtomIndex(atom); + //highlightSelectedAtom(n, true); + if (trackSelectedAtoms.indexOf(atom) == -1) { + trackSelectedAtoms.add(atom); + } + } + break; + //************************************************************ + case DIFFERENCE: + atom = molecule.getAtomInterface(selected_atom); + atoms = Molecule.getMoleculeAtomBelongsTo(atom); + for (int i = 0; i < atoms.size(); i++) { + atom = (AtomInterface) atoms.get(i); + if (!atom.isSelected()) { + continue; + } + atom.setSelected(false); + trackSelectedAtoms.remove(atom); + highlightSelectedAtom(atom, false); + //int n = molecule.getAtomIndex(atom); + //highlightSelectedAtom(n, false); + } + break; + //************************************************************** + case INTERSECTION: + atom = molecule.getAtomInterface(selected_atom); + atoms = Molecule.getMoleculeAtomBelongsTo(atom); + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + atom = molecule.getAtomInterface(i); + if (!atoms.contains(atom)) { + atom.setSelected(false); + trackSelectedAtoms.remove(atom); + } + } + highlightSelectedAtoms(); + break; + } + + //if (selectionRule == RULE_UNION) { + // AtomInterface atom = molecule.getAtomInterface(selected_atom); + // java.util.List atoms = Molecule.getMoleculeAtomBelongsTo(atom); + // for (int i = 0; i < atoms.size(); i++) { + // atom = (AtomInterface) atoms.get(i); + // int n = molecule.getAtomIndex(atom); + // atom.setSelected(true); + // highlightSelectedAtom(n, true); + // if (trackSelectedAtoms.indexOf(atom) == -1) { + // trackSelectedAtoms.add(atom); + // } + // } + //} else if (selectionRule == RULE_DIFFERENCE) { + // AtomInterface atom = molecule.getAtomInterface(selected_atom); + // java.util.List atoms = Molecule.getMoleculeAtomBelongsTo(atom); + // for (int i = 0; i < atoms.size(); i++) { + // atom = (AtomInterface) atoms.get(i); + // if (!atom.isSelected()) { + // continue; + // } + // atom.setSelected(false); + // int n = molecule.getAtomIndex(atom); + // trackSelectedAtoms.remove(atom); + // highlightSelectedAtom(n, false); + // } + //} else if (selectionRule == RULE_INTERSECTION) { + // AtomInterface atom = molecule.getAtomInterface(selected_atom); + // java.util.List atoms = Molecule.getMoleculeAtomBelongsTo(atom); + // for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + // atom = molecule.getAtomInterface(i); + // if (!atoms.contains(atom)) { + // atom.setSelected(false); + // trackSelectedAtoms.remove(atom); + // } + // } + // highlightSelectedAtoms(); + //} + } else { + System.err.println(getClass().getCanonicalName() + ": Internal Error: unknown selection type. Ignored..."); + } + + } + + public void highlighSelectedAtoms(boolean enable) { + HighlighSelectedAtoms = enable; + highlightSelectedAtoms(); + } + + public void highlightSelectedAtoms() { + highlightSelectedAtoms(null); + } + + public void highlightSelectedAtoms(JobProgressInterface progress) { + AtomNode atom; + + if (progress != null) { + //System.out.println("Initiating progress bar..."); + progress.setProgress(0); + } + + int natoms = molecule.getNumberOfAtoms(); + + for (int i = 0; i < natoms; i++) { + AtomInterface a = molecule.getAtomInterface(i); + atom = (AtomNode) a.getProperty( ATOM_NODE); + if (atom == null) { + continue; + } + highlightSelectedAtom(mol, atom, a.isSelected()); + + if (progress != null && i % 1000 == 0) { + int progr = (int) ((double) i / (double) natoms * 100.0); + //System.out.println("Progress done: " + progr + "%"); + progress.setProgress(progr); + + if (progress.isCanceled() && progr < 100) { + progress.setProgressText("Stopping highlighting..."); + break; + } + } + } + } + + public void enableAtomPicking(int n, boolean enable) { + if (n < 0 || n >= molecule.getNumberOfAtoms()) { //n >= atomNodes.size()) { + System.err.println("enablePickingAtom: Warning: n < 0 || n >= atomNodes.size()"); + return; + } + AtomInterface a = molecule.getAtomInterface(n); + AtomNode atom = (AtomNode) a.getProperty(ATOM_NODE); + //AtomNode atom = (BranchGroup) atomNodes.get(n); + if (mol.indexOfChild(atom) == -1) { + System.err.println("enablePickingAtom: Warning: mol.indexOfChild(atom) == -1 for " + n + " atom"); + return; + } + + //atom.detach(); + mol.removeChild(atom); + + if (enable) { + atom.setCapability(BranchGroup.ALLOW_PICKABLE_READ); + atom.setCapability(BranchGroup.ALLOW_PICKABLE_WRITE); + atom.setCapability(BranchGroup.ENABLE_PICK_REPORTING); + } else { + atom.clearCapability(BranchGroup.ENABLE_PICK_REPORTING); + } + + mol.addChild(atom); + } + + public void highlightSelectedAtom(AtomInterface a, boolean highlight) { + AtomNode atom = (AtomNode) a.getProperty(ATOM_NODE); + if (mol.indexOfChild(atom) == -1) { + return; + } + highlightSelectedAtom(mol, atom, highlight); + } + + @Deprecated + public void highlightSelectedAtom(int nsel, boolean highlight) { + if (nsel < 0 || nsel >= molecule.getNumberOfAtoms()) { // atomNodes.size()) { + logger.severe("nsel < 0 || nsel >= molecule.getNumberOfAtoms(): Ignoring... Continueing..."); + return; + } + AtomInterface a = molecule.getAtomInterface(nsel); + AtomNode atom = (AtomNode) a.getProperty(ATOM_NODE); + //AtomNode atom = atomNodes.get(nsel); + if (mol.indexOfChild(atom) == -1) { + return; + } + highlightSelectedAtom(mol, atom, highlight); + } + + /** + * + * @param parent BranchGroup + * @param atom BranchGroup + * @param nsel int + * @param highlight boolean + */ + public void highlightSelectedAtom(MoleculeNode parent, AtomNode atom, boolean enableHighlight) { + + boolean highlight = enableHighlight; + + if (!HighlighSelectedAtoms) { + if (atom.isHighlighted()) { + highlight = false; + } else { + return; + } + } + + if (highlight && atom.isHighlighted()) { + return; + } + if (!highlight && !atom.isHighlighted()) { + return; + } + + parent.removeChild(atom); + + atom.highlightAtom(highlight); + + parent.addChild(atom); + } + + /** + * Finds and returns Sphere in the atom's BranchGroup + * + * @param atom BranchGroup + * @return Sphere - atomic sphere or null + */ + /* + * public static Sphere getAtomicSphere(BranchGroup atom) { // --- general implementation. Assumes that Sphere is in the + * TransformGroup for (int i = 0; i < atom.numChildren(); i++) { Node node = atom.getChild(i); if (! (node instanceof + * TransformGroup)) { continue; } TransformGroup atom_tg = (TransformGroup) node; for (int j = 0; j < atom_tg.numChildren(); j++) + * { Node node2 = atom_tg.getChild(j); if (node2 instanceof Sphere) { Sphere atom_sph = (Sphere) node2; return atom_sph; } else if + * (node2 instanceof TransformGroup) { TransformGroup g2 = (TransformGroup) node2; for (int k = 0; k < g2.numChildren(); k++) { + * Node node3 = g2.getChild(k); if (node3 instanceof Sphere) { return (Sphere) node3; } } } + * + * } + * } + * System.err.println( "getAtomicSphere: Warning: No Sphere in atom's BranchGroup"); return null; + * + * + * } + */ + /** + * Finds TransformGroup which scales sphere's redius + * + * @param atom BranchGroup + * @return TransformGroup + */ + public static TransformGroup getAtomicSphereScale(BranchGroup atom) { + // --- Assumes that Sphere radius is in the TransformGroup + for (int i = 0; i < atom.numChildren(); i++) { + Node node = atom.getChild(i); + if (!(node instanceof TransformGroup)) { + continue; + } + // Assumes that this is a MOVE transform group which contains Scale trasnform group + TransformGroup atom_tg = (TransformGroup) node; + for (int j = 0; j < atom_tg.numChildren(); j++) { + Node node2 = atom_tg.getChild(j); + if (node2 instanceof TransformGroup) { + TransformGroup g2 = (TransformGroup) node2; + return g2; + } + } + } + System.err.println("getAtomicSphereScale: Warning: No SCALE transform group in atom's BranchGroup"); + return null; + } + + public TransformGroup getAtomicTranformGroup(BranchGroup atom) { + return (TransformGroup) atom.getChild(0); + } + + public void setAtomicSphere(BranchGroup atom, Sphere sphere) { + TransformGroup atom_tg = (TransformGroup) atom.getChild(0); + Sphere atom_sph = (Sphere) atom_tg.getChild(0); + atom_tg.removeChild(atom_sph); + atom_tg.insertChild(sphere, 0); + } + + /** + * + * @param enable boolean + */ + public void selectAllAtoms(boolean enable) { + selectAllAtoms(enable, null); + } + + public void selectAllAtoms(boolean enable, JobProgressInterface progress) { + if (!enable) { + lastSelectedAtom = -1; + selectedAtoms.clear(); + trackSelectedAtoms.clear(); + } + + if (molecule == null) { + return; + } + + int natoms = molecule.getNumberOfAtoms(); + + if (progress != null) { + System.out.println("Initiating progress bar..."); + progress.setProgress(0); + } + + for (int i = 0; i < natoms; i++) { + AtomInterface a = molecule.getAtomInterface(i); + a.setSelected(enable); + highlightSelectedAtom(a, enable); + if (enable && trackSelectedAtoms.indexOf(a) == -1) { + trackSelectedAtoms.add(a); + } + + if (progress != null && i % 1000 == 0) { + int progr = (int) ((double) i / (double) natoms * 100.0); + System.out.println("Progress done: " + progr + "%"); + progress.setProgress(progr); + + if (progress.isCanceled() && progr < 100) { + progress.setProgressText("Stopping selection..."); + break; + } + } + } + } + + public void invertSelectedAtoms() { + invertSelectedAtoms(null); + } + + /** + * + */ + public void invertSelectedAtoms(JobProgressInterface progress) { + boolean highLight; + int natoms = molecule.getNumberOfAtoms(); + if (natoms < 1) { + return; + } + if (progress != null) { + progress.setProgress(0); + } + + for (int i = 0; i < natoms; i++) { + AtomInterface a = molecule.getAtomInterface(i); + if (a.isSelected()) { + highLight = false; + this.trackSelectedAtoms.remove(a); + } else { + highLight = true; + if (trackSelectedAtoms.indexOf(a) == -1) { + trackSelectedAtoms.add(a); + } + } + //molecule.markAtomAsSelected(i, highLight); + a.setSelected(highLight); + highlightSelectedAtom(a, highLight); + + if (progress != null && i % 1000 == 0) { + int progr = (int) ((double) i / (double) natoms * 100.0); + //System.out.println("Progress done: " + progr + "%"); + progress.setProgress(progr); + + if (progress.isCanceled() && progr < 100) { + progress.setProgressText("Stopping selection..."); + break; + } + } + } + } + + /** + * + * @param enable + */ + public void displaySelectedAtoms(boolean enable) { + displaySelectedAtoms(enable, null); + } + + /** + * + * @param enable + * @param progress + */ + public void displaySelectedAtoms(boolean enable, JobProgressInterface progress) { + if (progress != null) { + progress.setProgress(0); + progress.setTaskDescription(enable ? "Displaying selected atoms..." : "Undisplaying selected atoms..."); + } + int natoms = molecule.getNumberOfAtoms(); + + for (int i = 0; i < natoms; i++) { + AtomInterface at = molecule.getAtomInterface(i); + AtomNode atom = (AtomNode) at.getProperty(ATOM_NODE); + //BranchGroup atom = (BranchGroup) atomNodes.get(i); + + List bi = at.getBondIndex(); + //logger.info("Atom " + i + " " + atom + " selected: " + molecule.IsAtomSelected(i) ); + if (at.isSelected() && enable) { // Display Atoms + if (mol.indexOfChild(atom) != -1) { + continue; // It's already visible + } + mol.addChild(atom); + for (int j = 0; j < bi.size(); j++) { + BondInterface b = (BondInterface) bi.get(j); + int bindex = molecule.getBondIndex(b); + if (bindex == -1) { + continue; + } + BranchGroup bond = bondNodes.get(bindex); + if (mol.indexOfChild(bond) != -1) { + continue; // It's already visible + } + mol.addChild(bond); + } + + } else if (at.isSelected() && !enable) { // Undisplay Atoms + //logger.info("indexOfChild: " + mol.indexOfChild(atom) ); + if (mol.indexOfChild(atom) == -1) { + continue; // It's already invisible + } + //atom.detach(); + mol.removeChild(atom); + for (int j = 0; j < bi.size(); j++) { + BondInterface b = (BondInterface) bi.get(j); + int bindex = molecule.getBondIndex(b); + if (bindex == -1) { + continue; + } + BondNode bond = bondNodes.get(bindex); + if (mol.indexOfChild(bond) == -1) { + continue; // It's already invisible + } + + //bond.detach(); + mol.removeChild(bond); + } + } + + if (progress != null && i % 1000 == 0) { + progress.setProgress((int) ((double) i / (double) natoms * 100.0)); + } + + } + //mol.compile(); + + if (progress != null) { + progress.setProgress(100); + } + } + + public void createdCentroidForSelectedAtoms() { + float x = 0, y = 0, z = 0; + float count = 0; + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface at = molecule.getAtomInterface(i); + if (!at.isSelected()) { + continue; + } + count += 1; + x += at.getX(); + y += at.getY(); + z += at.getZ(); + } + x /= count; + y /= count; + z /= count; + AtomInterface atom = molecule.getNewAtomInstance(); + atom.setXYZ(x, y, z); + atom.setAtomicNumber(0); + atom.setName("Du"); + + molecule.addMonomer("Centroid"); + int n = molecule.getNumberOfMonomers() - 1; + atom.setSubstructureNumber(n); + + addAtom(atom); + } + + public void deleteAtom(AtomInterface at) { + int n = molecule.getAtomIndex(at); + if (n == -1) { + System.err.println(this.getClass().getCanonicalName() + "deleteAtom: no such atom in molecule. Ignored..."); + return; + } + deleteAtom(n); + } + + public void deleteAtom(int n) { + + // --- Delete Atom Node + AtomInterface at = molecule.getAtomInterface(n); + + List bi = at.getBondIndex(); + AtomNode atom = (AtomNode) at.getProperty(ATOM_NODE); + //AtomNode atom = atomNodes.get(n); + if (mol.indexOfChild(atom) != -1) { + at.setProperty(ATOM_NODE, null); + mol.removeChild(atom); + } else { + System.err.println("deleteAtom: " + "mol.indexOfChild(atom) == -1 Ignored..."); + } + //atomNodes.remove(atom); + //materialStore.remove(n); + atomLabels.remove(n); + + // --- mark bond nodes for deletion + for (int j = 0; j < bi.size(); j++) { + BondInterface b = (BondInterface) bi.get(j); + int bindex = molecule.getBondIndex(b); + if (bindex == -1) { + System.err.println("deleteAtom: " + "bindex == -1 Ignored..."); + continue; + } + + try { + BondNode bond = bondNodes.get(bindex); + bond.markForDeletion(true); + } catch (IndexOutOfBoundsException ex) { + System.err.println("deleteAtom: " + ex.getMessage() + " Ignored..."); + } + } + + // --- Delete marked bond nodes + int del_bonds = 0; + int nb = bondNodes.size(); + for (int i = nb - 1; i > -1; i--) { + BondNode bond = bondNodes.get(i); + if (!bond.isToDelete()) { + continue; + } + bond = bondNodes.remove(i); + if (mol.indexOfChild(bond) != -1) { + mol.removeChild(bond); + ++del_bonds; + } else { + System.err.println("deleteAtom : " + "mol.indexOfChild(bond) == -1 Ignored..."); + } + } + + // --- Now delete "real" atoms in molecule + molecule.deleteAtom(n); + } + + /** + * Deletes selected atoms and associated bonds + */ + public void deleteSelectedAtoms() { + deleteSelectedAtoms(null); + } + + public void deleteSelectedAtoms(JobProgressInterface progress) { + // --- One needs to delete separately Nodes and Atoms + + // --- Some internal error check + int bondsOld = molecule.getNumberOfBonds(); + if (bondNodes.size() != molecule.getNumberOfBonds()) { + System.err.println(getClass().getCanonicalName() + " : " + "bondNodes.size() != molecule.getNumberOfBonds(): " + + bondNodes.size() + " and " + molecule.getNumberOfBonds() + " Ignored..."); + } + + if (progress != null) { + progress.setProgress(0); + progress.setTaskDescription("Deleting selected atoms..."); + } + + // --- Delete Atom Nodes + int natoms = molecule.getNumberOfAtoms(); + + for (int i = natoms - 1, j = 1; i >= 0; i--, j++) { + AtomInterface at = molecule.getAtomInterface(i); + if (!at.isSelected()) { + continue; + } + + deleteAtom(i); + + if (progress != null && i % 1000 == 0) { + progress.setProgress((int) ((double) j / (double) natoms * 100.0)); + } + } + + } + + public void unlabelSelectedAtoms() { + + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface at = molecule.getAtomInterface(i); + //logger.info("Atom: " + i + " Selected: " + molecule.IsAtomSelected(i)); + if (!at.isSelected()) { + continue; + } + + //AtomNode atom = (AtomNode) atomNodes.get(i); + //BranchGroup atom = (BranchGroup) atomNodes.get(i); + //if (mol.indexOfChild(atom) == -1) { // Atom is invisible + // continue; + //} + LabelNode old_label = (LabelNode) atomLabels.get(i); + if (old_label != null) { + //atom.detach(); + old_label.detach(); + //atom.removeChild(old_label); + //if (atom.numChildren() > 1) { + // atom.removeChild(1); // !!! Buggy place + //} + //atom.removeChild(old_label); + //mol.addChild(atom); + } + + atomLabels.set(i, null); + } + + boolean noMoreLabeled = true; + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + LabelNode old_label = (LabelNode) atomLabels.get(i); + if (old_label != null) { + noMoreLabeled = false; + break; + } + } + if (noMoreLabeled) { + enableLabels = false; + } + } + + public void labelSelectedAtoms(String property) { + + enableLabels = false; + + if (otherLabelMethod) { + Point3d origin = new Point3d(); + canvas3D.getCenterEyeInImagePlate(origin); + Transform3D motion = new Transform3D(); + canvas3D.getImagePlateToVworld(motion); + motion.transform(origin); + + Point3f xyz = new Point3f(); + Vector3d dir = new Vector3d(); + + // Get transform to the virtual world (VW) + Transform3D toVW = getVWTransform(); + + // --- Adding atom node + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface at = molecule.getAtomInterface(i); + //logger.info("Atom: " + i + " Selected: " + molecule.IsAtomSelected(i)); + if (!at.isSelected()) { + continue; + } + + enableLabels = true; + + String aname = null; + if (property.equals("Element") && at.getAtomicNumber() > -1) { + aname = ChemicalElements.getElementSymbol(at.getAtomicNumber()); + } else if (property.equals("Atom number")) { + aname = String.valueOf(i + 1); + } else { + Object obj = at.getProperty(property); + if (obj == null) { + continue; + } + if (obj instanceof String) { + aname = (String) obj; + } else { + aname = obj.toString(); + } + if (aname == null) { + continue; + } + } + + // --- Check for old label... + Object old_label = atomLabels.get(i); + if (old_label != null) { + ((LabelNode) old_label).detach(); + } + + // --- prepare a new label + LabelNode label = new LabelNode(new Vector3f(at.getX(), at.getY(), at.getZ()), aname); + + xyz.set(at.getX(), at.getY(), at.getZ()); + //logger.info("Local xyz: " + xyz); + + // --- Coordinates of atom in the VW + toVW.transform(xyz); + //logger.info("VW xyz: " + xyz); + + // --- calculate direction from view point to atom in VW + dir.x = origin.x - xyz.x; + dir.y = origin.y - xyz.y; + dir.z = origin.z - xyz.z; + + // -- transform it into local space + Transform3D t3d = new Transform3D(); + t3d.invert(toVW); + t3d.transform(dir); + dir.normalize(); + + AtomNode atom = (AtomNode) at.getProperty(ATOM_NODE); + //AtomNode atom = (AtomNode) atomNodes.get(i); + + float radius = atom.getAtomicSphereRadius() + 0.1f; + dir.scale(radius); + label.setShift(dir); + + atomLabels.set(i, label); + + mol.addChild(label); + } + + return; + } + + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface at = molecule.getAtomInterface(i); + //logger.info("Atom: " + i + " Selected: " + molecule.IsAtomSelected(i)); + if (!at.isSelected()) { + continue; + } + AtomNode atom = (AtomNode) at.getProperty(ATOM_NODE); + //AtomNode atom = (AtomNode) atomNodes.get(i); + //if (mol.indexOfChild(atom) == -1) { // Atom is invisible + // continue; + //} + enableLabels = true; + + //AtomInterface a = molecule.getAtomInterface(i); + AtomInterface a = atom.getAtomInterface(); + String aname = null; + if (property.equals("Element") && a.getAtomicNumber() > -1) { + aname = ChemicalElements.getElementSymbol(a.getAtomicNumber()); + } else if (property.equals("Atom number")) { + aname = String.valueOf(i + 1); + } else { + Object obj = a.getProperty(property); + if (obj instanceof String) { + aname = (String) obj; + } else { + aname = obj.toString(); + } + if (aname == null) { + continue; + } + } + float radius = AtomNode.getAtomicSphereRadius(a); + + BranchGroup label = new BranchGroup(); + label.setCapability(BranchGroup.ALLOW_DETACH); + //label.setCapability( BranchGroup.); + + //atom.detach(); + mol.removeChild(atom); + + LabelNode old_label = (LabelNode) atomLabels.get(i); + if (old_label != null) { + //atom.removeChild(1); + mol.removeChild(old_label); + } + + Transform3D rotate = new Transform3D(); + Transform3D move = new Transform3D(); + move.set(new Vector3f( a.getX() + radius * (float) 0.7, + a.getY() + radius * (float) 0.7, + a.getZ() )); + + TransformGroup rotate_label = new TransformGroup(move); + rotate_label.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); + rotate_label.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + + Text2D text; + if (aname == null) { + text = new Text2D("", + new Color3f(0.9f, 1.0f, 1.0f), + "Helvetica", 50, Font.ITALIC); + } else { + text = new Text2D(aname, + new Color3f(0.9f, 1.0f, 1.0f), + "Helvetica", 50, Font.ITALIC); + } + + rotate_label.addChild(text); + + label.addChild(rotate_label); + + atomLabels.set(i, label); + atom.addChild(label); + mol.addChild(atom); + } + } + + public synchronized void updateLabels() { + if (!areLabels()) { + return; + } + + if (temp_Matrix == null) { + temp_Matrix = new Matrix3d(); + } + + Transform3D t3d = new Transform3D(); + Transform3D toVW = getVWTransform(); + toVW.invert(); + toVW.get(temp_Matrix); + + if (otherLabelMethod) { + + Point3d origin = new Point3d(); + canvas3D.getCenterEyeInImagePlate(origin); + Transform3D motion = new Transform3D(); + canvas3D.getImagePlateToVworld(motion); + motion.transform(origin); + + Point3f xyz = new Point3f(); + Vector3d dir = new Vector3d(); + + // Get transform to the virtual world (VW) + Transform3D toVWord = getVWTransform(); + + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface a = molecule.getAtomInterface(i); + AtomNode atom = (AtomNode) a.getProperty(ATOM_NODE); + //AtomNode atom = (AtomNode) atomNodes.get(i); + //System.out.print("Atom: " + i + " indexOfChild(atom): " + mol.indexOfChild(atom)); + + if (mol.indexOfChild(atom) == -1) { // Atom is invisible + continue; + } + + LabelNode label = (LabelNode) atomLabels.get(i); + //logger.info(" label: " + label); + if (label == null) { + continue; + } + + label.getCenterCoord(xyz); + //logger.info("Local xyz: " + xyz); + + // --- Coordinates of atom in the VW + toVWord.transform(xyz); + //logger.info("VW xyz: " + xyz); + + // --- calculate direction from view point to atom in VW + dir.x = origin.x - xyz.x; + dir.y = origin.y - xyz.y; + dir.z = origin.z - xyz.z; + + // -- transform it into local space + Transform3D trans = new Transform3D(); + trans.invert(toVWord); + trans.transform(dir); + dir.normalize(); + + float shift = label.getShift(); + dir.scale(shift); + label.setShift(dir); + + label.detach(); + + label.updateRotation(temp_Matrix); + + //atom.addChild(label); + mol.addChild(label); + + } + return; + } + + // --- Old stuff + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + + AtomInterface a = molecule.getAtomInterface(i); + AtomNode atom = (AtomNode) a.getProperty(ATOM_NODE); + //BranchGroup atom = (BranchGroup) atomNodes.get(i); + //System.out.print("Atom: " + i + " indexOfChild(atom): " + mol.indexOfChild(atom)); + + if (mol.indexOfChild(atom) == -1) { // Atom is invisible + continue; + } + + BranchGroup label = (BranchGroup) atomLabels.get(i); + //logger.info(" label: " + label); + if (label == null) { + continue; + } + + label.detach(); + + TransformGroup move_label = (TransformGroup) label.getChild(0); + + move_label.getTransform(t3d); + t3d.setRotation(temp_Matrix); + + move_label.setTransform(t3d); + + atom.addChild(label); + } + + } + + public boolean areLabels() { + return enableLabels; + } + + /** + * + * @param bgr BranchGroup + * @param sel_sphere Sphere + * @return int + */ + public int getSelectedAtomNumber(BranchGroup bgr, Sphere sel_sphere) { + int selected_atom = -1; + if (bgr != null) { + //PickShape shape = pickCanvas.getPickShape(); + //SceneGraphPath sgp = bgr.pickClosest(shape); + //logger.info("Got Branch group: # children " + + // bgr.numChildren()); + for (int i = 0; i < bgr.numChildren(); i++) { + Node n = bgr.getChild(i); + if (n instanceof BranchGroup) { + //logger.info("Child: " + i + " :BranchGroup"); + BranchGroup bg = (BranchGroup) n; + for (int j = 0; j < bg.numChildren(); j++) { + Node n2 = bg.getChild(j); + if (n2 instanceof TransformGroup) { + TransformGroup tg2 = (TransformGroup) n2; + //logger.info("SubChild: " + j + + // " :TransformGroup"); + for (int k = 0; k < tg2.numChildren(); k++) { + Node n3 = tg2.getChild(k); + if (n3 instanceof Sphere) { + //logger.info("SubSubChild: " + k + + // " :Sphere"); + if (sel_sphere == n3) { + //logger.info( + // ">>> Selected Sphere <<<"); + return i; + } + } else if (n3 instanceof Cylinder) { + //logger.info("SubSubChild: " + k + + // " :Cylinder"); + } else { + //logger.info("SubSubChild: " + k + + // " :Unknown"); + } + + } + } else { + //logger.info("SubChild: " + j + " :Unknown"); + } + } + } else { + //logger.info("Child: " + i + " :Unknown"); + } + } + } + + return selected_atom; + } + + /* + * public Transform3D getVWTranform() { if (T3d_1 == null) { T3d_1 = new Transform3D(); } if (T3d_2 == null) { T3d_2 = new + * Transform3D(); } + * + * sceneOffset.getTransform(T3d_1); T3d_2.set(T3d_1); sceneTrans.getTransform(T3d_1); T3d_2.mul(T3d_1); + * + * return T3d_2; } + */ + public Transform3D getVWTransform() { + Transform3D t3d_1 = new Transform3D(); + Transform3D t3d_2 = new Transform3D(); + + sceneOffset.getTransform(t3d_1); + t3d_2.set(t3d_1); + sceneTrans.getTransform(t3d_1); + t3d_2.mul(t3d_1); + moleculeTrans.getTransform(t3d_1); + t3d_2.mul(t3d_1); + + t3d_1 = null; + return t3d_2; + } + + /** + * Transforms coordinates of atoms of the arbitrary molecule into current virtual world space + * + * @param molec MoleculeInterface - Molecule + * @return float[][] - cartesian coordinates float[number_of_atoms][3] + */ + public float[][] getVirtualWorldCoordinates(MoleculeInterface molec) { + if (molec.getNumberOfAtoms() == 0) { + return null; + } + float cartes[][] = new float[molec.getNumberOfAtoms()][3]; + Point3f xyz = new Point3f(); + + // Get transform to the virtual world (VW) + Transform3D toVW = getVWTransform(); + + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface a = molecule.getAtomInterface(i); + xyz.set(a.getX(), a.getY(), a.getZ()); + toVW.transform(xyz); + cartes[i][0] = xyz.x; + cartes[i][1] = xyz.y; + cartes[i][2] = xyz.z; + } + xyz = null; + toVW = null; + return cartes; + } + + /** + * Returns Virtual World coordinates of an atom + * + * @param atom AtomInterface + * @return Point3f + */ + public Point3f getVirtualWorldCoordinates(AtomInterface atom) { + + Point3f xyz = new Point3f(); + + // Get transform to the virtual world (VW) + Transform3D toVW = getVWTransform(); + + xyz.set(atom.getX(), atom.getY(), atom.getZ()); + toVW.transform(xyz); + + return xyz; + } + + public void addAtom(AtomNode new_atom) { + AtomInterface atom = new_atom.getAtomInterface(); + Material store = cloneMaterial(new_atom.getMaterial()); + atom.setProperty(ATOM_NODE_MATERIAL_COPY, store); + //materialStore.add(store); + + // --- Add a "real" atom to the molecule + if (new_atom != null) { + mol.addChild(new_atom); + //atomNodes.add(new_atom); + //atomSpheres.add(getAtomicSphere(new_atom)); + atomLabels.add(null); + } + + //molec.addAtom(atom); + atom.setProperty(ATOM_NODE, new_atom); + molecule.addAtom(atom, atom.getSubstructureNumber()); + } + + public AtomNode addAtom(AtomInterface atom) { + + /* + * BranchGroup new_atom = createAtom(atom.getX(), atom.getY(), atom.getZ(), atom.getAtomicNumber()); Material store = + * ChemicalElementsColors.getElementMaterial(atom. getAtomicNumber()); store.setCapability(Material.ALLOW_COMPONENT_READ); + * store.setCapability(Material.ALLOW_COMPONENT_WRITE); + */ + AtomNode new_atom = new AtomNode(atom); + Material store = cloneMaterial(new_atom.getMaterial()); + atom.setProperty(ATOM_NODE_MATERIAL_COPY, store); + //materialStore.add(store); + + // --- Add a "real" atom to the molecule + if (new_atom != null) { + mol.addChild(new_atom); + //atomNodes.add(new_atom); + //atomSpheres.add(getAtomicSphere(new_atom)); + atomLabels.add(null); + } + + //molec.addAtom(atom); + atom.setProperty(ATOM_NODE, new_atom); + molecule.addAtom(atom, atom.getSubstructureNumber()); + + return new_atom; + + } + + public AtomNode addAtom(Point3d origin, Vector3d dir, float length, boolean scale) { + Point3f xyz = new Point3f(); + + // Get transform to the virtual world (VW) + Transform3D toVW = getVWTransform(); + + // --- Adding atom node + AtomInterface a = molecule.getAtomInterface(lastSelectedAtom); + xyz.set(a.getX(), a.getY(), a.getZ()); + logger.info("Local xyz: " + xyz); + + // --- Coordinates of atom in the VW + toVW.transform(xyz); + logger.info("VW xyz: " + xyz); + + // --- knowing viewing point and direction of view we can find + // --- intersection point of a direction vector with Z-plane of the VW + // --- which contains a given atom + if (dir.z == 0.0) { // View direction is parallel to the VW's Z-plane + return null; + } + + double t = -(-xyz.z + origin.z) / dir.z; + xyz.x = (float) (origin.x + t * dir.x); + xyz.y = (float) (origin.y + t * dir.y); + xyz.z = (float) (origin.z + t * dir.z); + logger.info("Intersection with VW Z-plane: " + xyz); + + Transform3D t3d = new Transform3D(); + t3d.invert(toVW); + t3d.transform(xyz); + + //T3d_1.invert(toVW); + //T3d_1.transform(xyz); + logger.info("New point in Local space: " + xyz); + + if (scale) { + float trueDir[] = new float[3]; + trueDir[0] = xyz.x - a.getX(); + trueDir[1] = xyz.y - a.getY(); + trueDir[2] = xyz.z - a.getZ(); + float norm = (float) Math.sqrt(trueDir[0] * trueDir[0] + + trueDir[1] * trueDir[1] + + trueDir[2] * trueDir[2]); + for (int i = 0; i < 3; i++) { + trueDir[i] /= norm; + } + xyz.x = a.getX() + trueDir[0] * length; + xyz.y = a.getY() + trueDir[1] * length; + xyz.z = a.getZ() + trueDir[2] * length; + } + + int elementNumber = 0; + String atomType = null; + String atomName = null; + if (chooseAtomType instanceof AtomTypeDialog) { + AtomTypeDialog dlg = (AtomTypeDialog) chooseAtomType; + elementNumber = dlg.getElementNumber(); + } else if (chooseAtomType instanceof JAtomTypeDialog) { + JAtomTypeDialog dlg = (JAtomTypeDialog) chooseAtomType; + elementNumber = dlg.getElement(); + atomType = dlg.getAtomType(); + atomName = dlg.getAtomName(); + } else { + logger.info( + "INTERNAL ERROR: Unknown instance of chooseAtomType"); + } + /* + * BranchGroup new_atom = createAtom(xyz.x, xyz.y, xyz.z, elementNumber); Material store = + * ChemicalElementsColors.getElementMaterial(elementNumber); + */ + + // --- Add a "real" atom to the molecule + AtomInterface atom = molecule.getNewAtomInstance(); + atom.setAtomicNumber(elementNumber); + if (atomName != null && atomName.length() > 0) { + atom.setName(atomName); + } else { + atom.setName(ChemicalElements.getElementSymbol(elementNumber)); + } + atom.setXYZ(xyz.x, xyz.y, xyz.z); + if (atomType != null) { + atom.setProperty(AtomInterface.CCT_ATOM_TYPE, atomType); + } + molecule.addAtom(atom); + //molecule.addAtom(elementNumber, Xyz.x, Xyz.y, + // Xyz.z); + + AtomNode new_atom = new AtomNode(atom); + atom.setProperty(ATOM_NODE, new_atom); + + Material store = cloneMaterial(new_atom.getMaterial()); + atom.setProperty(ATOM_NODE_MATERIAL_COPY, store); + //materialStore.add(store); + + xyz = null; + toVW = null; + t3d = null; + + return new_atom; + } + + /** + * Adds a molecule to the main window + * + * @param origin Point3d + * @param dir Vector3d + * @param length float + * @param scale boolean + * @param otherUniverse Java3dUniverse + */ + public void addMolecule(Point3d origin, Vector3d dir, float length, boolean scale, Java3dUniverse otherUniverse) { + + AtomInterface a = molecule.getAtomInterface(lastSelectedAtom); + Point3f xyz = this.getVirtualWorldCoordinates(a); + + //xyz.set(a.getX(), a.getY(), a.getZ()); + //if (Xyz == null) { + //Point3f xyz = new Point3f(); + //} + // Get transform to the virtual world (VW) for main window + //Transform3D toVW = getVWTransform(); + // --- Getting coordinates of the selected atom from the main window + //AtomInterface a = molecule.getAtomInterface(lastSelectedAtom); + //xyz.set(a.getX(), a.getY(), a.getZ()); + //logger.info("Local xyz: " + xyz); + // --- Coordinates of atom in the VW + //toVW.transform(xyz); + logger.info("VW xyz: " + xyz); + + float x_vw = xyz.x; + float y_vw = xyz.y; + float z_vw = xyz.z; + + // --- knowing viewing point and direction of view we can find + // --- intersection point of a direction vector with Z-plane of the VW + // --- which contains a given atom + if (dir.z == 0.0) { // View direction is parallel to the VW's Z-plane + System.err.println("dir.z == 0.0"); + return; + } + + double t = -(-xyz.z + origin.z) / dir.z; + xyz.x = (float) (origin.x + t * dir.x); + xyz.y = (float) (origin.y + t * dir.y); + xyz.z = (float) (origin.z + t * dir.z); + logger.info("Intersection with VW Z-plane: " + xyz); + + // --- Scale distance + if (scale) { + float trueDir[] = new float[3]; + trueDir[0] = xyz.x - x_vw; + trueDir[1] = xyz.y - y_vw; + trueDir[2] = xyz.z - z_vw; + float norm = (float) Math.sqrt(trueDir[0] * trueDir[0] + + trueDir[1] * trueDir[1] + + trueDir[2] * trueDir[2]); + for (int i = 0; i < 3; i++) { + trueDir[i] /= norm; + } + xyz.x = x_vw + trueDir[0] * length; + xyz.y = y_vw + trueDir[1] * length; + xyz.z = z_vw + trueDir[2] * length; + } + + addMolecule(xyz, otherUniverse); + + // Now translate a molecule to be added into Xyz + + /* + * AtomInterface otherAtom = otherMol.getAtomInterface(otherSelected); float x = virtualXYZ[otherSelected][0]; float y = + * virtualXYZ[otherSelected][1]; float z = virtualXYZ[otherSelected][2]; for (int i = 0; i < otherMol.getNumberOfAtoms(); i++) { + * virtualXYZ[i][0] += Xyz.x - x; virtualXYZ[i][1] += Xyz.y - y; virtualXYZ[i][2] += Xyz.z - z; } + * + * // --- transform other molecule into the local coordinates of a main window + * + * T3d_1.invert(toVW); + * + * for (int i = 0; i < otherMol.getNumberOfAtoms(); i++) { Xyz.x = virtualXYZ[i][0]; Xyz.y = virtualXYZ[i][1]; Xyz.z = + * virtualXYZ[i][2]; + * + * T3d_1.transform(Xyz); + * + * virtualXYZ[i][0] = Xyz.x; virtualXYZ[i][1] = Xyz.y; virtualXYZ[i][2] = Xyz.z; } + * + * logger.info("New point in Local space: " + Xyz); + * + * appendMolecule(molecule, otherMol, virtualXYZ); + */ + } + + float[][] transformToLocalCoords(Point3f origin, Java3dUniverse otherUniverse) { + int otherSelected = otherUniverse.getLastSelectedAtom(); + if (otherSelected == -1) { + System.err.println("transformToLocalCoords: otherSelected == -1"); + return null; + } + + // --- Get VW coordinates of a molecule to be added + MoleculeInterface otherMol = otherUniverse.getMoleculeInterface(); + float virtualXYZ[][] = otherUniverse.getVirtualWorldCoordinates(otherMol); + + // Now translate a molecule to be added into origin + AtomInterface otherAtom = otherMol.getAtomInterface(otherSelected); + float x = virtualXYZ[otherSelected][0]; + float y = virtualXYZ[otherSelected][1]; + float z = virtualXYZ[otherSelected][2]; + for (int i = 0; i < otherMol.getNumberOfAtoms(); i++) { + virtualXYZ[i][0] += origin.x - x; + virtualXYZ[i][1] += origin.y - y; + virtualXYZ[i][2] += origin.z - z; + } + + // Get transform to the virtual world (VW) for main window + Transform3D toVW = getVWTransform(); + + // --- transform other molecule into the local coordinates of a main window + Transform3D t3d = new Transform3D(); + t3d.invert(toVW); + + Point3f xyz = new Point3f(); + + for (int i = 0; i < otherMol.getNumberOfAtoms(); i++) { + xyz.x = virtualXYZ[i][0]; + xyz.y = virtualXYZ[i][1]; + xyz.z = virtualXYZ[i][2]; + + t3d.transform(xyz); + + virtualXYZ[i][0] = xyz.x; + virtualXYZ[i][1] = xyz.y; + virtualXYZ[i][2] = xyz.z; + } + + logger.info("New point in Local space: " + xyz); + xyz = null; + toVW = null; + t3d = null; + + return virtualXYZ; + } + + public void addMolecule(Point3f origin, Java3dUniverse otherUniverse) { + + int otherSelected = otherUniverse.getLastSelectedAtom(); + if (otherSelected == -1) { + System.err.println("addMolecule: otherSelected == -1"); + return; + } + + MoleculeInterface otherMol = otherUniverse.getMoleculeInterface(); + float virtualXYZ[][] = transformToLocalCoords(origin, otherUniverse); + + appendMolecule(molecule, otherMol, virtualXYZ); + } + + public void addFragment() { + if (this.otherRenderer == null) { + JOptionPane.showMessageDialog(null, "Internal Error: other renderer is not set!", + "Internal Error", JOptionPane.ERROR_MESSAGE); + return; + } + + if (molecule == null || molecule.getNumberOfAtoms() < 1) { + try { + addFragment(otherRenderer); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, "Error Adding a fragment: " + + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + return; + } else if (lastSelectedAtom == -1) { + //System.err.println("addFragment: lastSelectedAtom == -1"); + return; + } + + try { + addFragment(otherRenderer); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, + "Error Adding a fragment: " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + } + + /** + * Adds a fragment to a molecule + * + * @param otherUniverse Java3dUniverse + * @throws Exception + */ + public void addFragment(Java3dUniverse otherUniverse) throws Exception { + + if (otherUniverse == null || otherUniverse.getMolecule() == null + || otherUniverse.getMolecule().getNumberOfAtoms() < 1) { + System.err.println( + "addFragment: otherUniverse == null || otherUniverse.getMolecule() == null || otherUniverse.getMolecule().getNumberOfAtoms() < 1"); + throw new Exception("No atoms to add"); + } + + if (molecule == null || molecule.getNumberOfAtoms() < 1) { + MoleculeInterface fragment = otherUniverse.getMoleculeInterface().getInstance(); + fragment.appendMolecule(otherUniverse.getMoleculeInterface()); + this.addMolecule(fragment); + this.enableMousePicking(true); + //appendMolecule(otherUniverse.getMoleculeInterface()); + mol.setPickable(true); + //addMousePicking(this, mol, canvas3D, bounds); + return; + } + + if (lastSelectedAtom == -1) { + System.err.println("addFragment: lastSelectedAtom == -1"); + throw new Exception("Select atom in the main window first!"); + } + + int otherSelected = otherUniverse.getLastSelectedAtom(); + /* + * if (otherSelected == -1) { System.err.println("addFragment: otherSelected == -1"); throw new Exception("addFragment: + * otherSelected == -1"); } + */ + + // --- Get VW coordinates of a molecule to be added + MoleculeInterface fragment = otherUniverse.getMoleculeInterface().getInstance(); + fragment.appendMolecule(otherUniverse.getMoleculeInterface()); + + AtomInterface otherAtom = fragment.getAtomInterface(otherSelected); + + if (otherAtom.getNumberOfBondedAtoms() > 1 && lastSelectedAtom != -1) { + System.err.println("addFragment: selected atom in fragment should have only one neighbour"); + throw new Exception("Select atom in Fragment/Molecule first!"); + } + + // --- Getting coordinates of the selected atom from the main window + AtomInterface atom = molecule.getAtomInterface(lastSelectedAtom); + if (atom.getNumberOfBondedAtoms() > 1) { + System.err.println("addFragment: selected atom in main window should have only one neighbour"); + throw new Exception("addFragment: selected atom in main wondow should have only one neighbour"); + } + + // --- Consider particular cases.... + // --- Both selected atoms have no neighbours... + // So, they are just connected with a covalent bond + if (otherAtom.getNumberOfBondedAtoms() == 0 && atom.getNumberOfBondedAtoms() == 0) { + return; + //addMolecule(Point3f origin, otherUniverse); + } // --- Atom in main window has no neighbours... + else if (otherAtom.getNumberOfBondedAtoms() == 1 && atom.getNumberOfBondedAtoms() == 0) { + + List bonded = otherAtom.getBondedToAtoms(); + AtomInterface otherParent = (AtomInterface) bonded.get(0); + int otherParentIndex = fragment.getAtomIndex(otherParent); + + // --- Translate fragment + // First, preserve orientation of the fragment + Point3f origin = new Point3f(atom.getX(), atom.getY(), atom.getZ()); + float virtualXYZ[][] = transformToLocalCoords(origin, otherUniverse); + //for (int i=0; i otherSelected) { + --otherParentIndex; + } + AtomInterface newAtom = molecule.getAtomInterface(oldAtNum + + otherParentIndex); + BondInterface bond = molecule.getNewBondInstance(atom, newAtom); + addBond(bond); + + } // --- Both selected atoms have 1 neighbour... + else if (otherAtom.getNumberOfBondedAtoms() == 1 && atom.getNumberOfBondedAtoms() == 1) { + + List bonded = otherAtom.getBondedToAtoms(); + AtomInterface otherParent = (AtomInterface) bonded.get(0); + int otherParentIndex = fragment.getAtomIndex(otherParent); + + List neighb = atom.getBondedToAtoms(); + AtomInterface parent = (AtomInterface) neighb.get(0); + + cct.vecmath.Point3f otherAxis = new cct.vecmath.Point3f(otherAtom, otherParent); + cct.vecmath.Point3f axis = new cct.vecmath.Point3f(parent, atom); + + cct.vecmath.Point3f rotAxis = axis.crossProduct(otherAxis); + + if (rotAxis.vectorNorm() < 0.00001f) { // So, they are already co-linear + + if (axis.product(otherAxis) < 0) { // Vectors have opposite direction + // Invert coordinates of the fragment + for (int i = 0; i < fragment.getNumberOfAtoms(); i++) { + AtomInterface a = fragment.getAtomInterface(i); + a.setXYZ(-a.getX(), -a.getY(), -a.getZ()); + } + } + //JOptionPane.showMessageDialog(null, + // "addFragment: Rotation Axis cannot be determined", + // "Error", + // JOptionPane.ERROR_MESSAGE); + //return; + } else { + + float angle = angleBetween( (Point3fInterface) axis, otherAxis ); + + // --- Rotate fragment to align both main window and fragment bonds + Molecule.rotateMoleculeAroundAxis(fragment, -angle, rotAxis.getInstance(0, 0, 0), rotAxis); + } + + // --- Translate fragment + float length = ChemicalElements.getCovalentRadius(otherParent.getAtomicNumber()) + + ChemicalElements.getCovalentRadius(parent.getAtomicNumber()); + float bondLength = (float) parent.distanceTo(atom); + float x_dir = (atom.getX() - parent.getX()) / bondLength * length; + float y_dir = (atom.getY() - parent.getY()) / bondLength * length; + float z_dir = (atom.getZ() - parent.getZ()) / bondLength * length; + + Point3f origin = new Point3f(parent.getX() + x_dir, + parent.getY() + y_dir, + parent.getZ() + z_dir); + + float x = otherParent.getX(); + float y = otherParent.getY(); + float z = otherParent.getZ(); + + for (int i = 0; i < fragment.getNumberOfAtoms(); i++) { + AtomInterface a = fragment.getAtomInterface(i); + a.setX(origin.x + a.getX() - x); + a.setY(origin.y + a.getY() - y); + a.setZ(origin.z + a.getZ() - z); + } + + // --- Delete selected atoms + fragment.deleteAtom(otherSelected); + deleteSelectedAtoms(); + + int oldAtNum = molecule.getNumberOfAtoms(); + + this.appendMolecule(fragment, false); + + // --- Add bond between atoms + if (otherParentIndex > otherSelected) { + --otherParentIndex; + } + AtomInterface newAtom = molecule.getAtomInterface(oldAtNum + otherParentIndex); + BondInterface bond = molecule.getNewBondInstance(parent, newAtom); + addBond(bond); + + //addMolecule(Point3f origin, otherUniverse); + } + + } + + public BondNode addBond(BondInterface bond) { + molecule.addBond(bond); + BondNode bn = new BondNode(bond); + mol.addChild(bn); + bondNodes.add(bn); + return bn; + } + + public BondNode createBond(int origin, int target) { + BondNode bn = null; + AtomInterface a_i = molecule.getAtomInterface(origin); + AtomInterface a_j = molecule.getAtomInterface(target); + BondInterface bond = molecule.getNewBondInstance(a_i, a_j); + molecule.addBond(bond); + //Bond b = molecule.addBondBetweenAtoms(origin, target); + if (bond == null) { + return null; + } + bn = new BondNode(bond); + return bn; + } + + public void makeMonomersSelection(Object monomers[]) { + makeMonomersSelection(monomers, null); + } + + public void makeMonomersSelection(Object monomers[], JobProgressInterface progress) { + if (monomers == null || monomers.length < 1) { + logger.warning("monomers == null || monomers.length < 1"); + return; + } + + StringBuilder sb = null; + if (logger.isLoggable(Level.INFO)) { + sb = new StringBuilder(); + } + + int natoms = molecule.getNumberOfAtoms(); + + boolean selectedAtoms[] = new boolean[natoms]; + for (int i = 0; i < selectedAtoms.length; i++) { + selectedAtoms[i] = false; + } + + for (int i = 0; i < molecule.getNumberOfMonomers(); i++) { + MonomerInterface m = molecule.getMonomerInterface(i); + String monName = m.getName(); + for (int j = 0; j < monomers.length; j++) { + if (monName.compareToIgnoreCase(monomers[j].toString()) == 0) { + if (logger.isLoggable(Level.INFO)) { + sb.append(monName + String.valueOf(i + 1) + "\n"); + } + for (int k = 0; k < m.getNumberOfAtoms(); k++) { + AtomInterface atom = m.getAtom(k); + int n = molecule.getAtomIndex(atom); + if (n != -1) { + selectedAtoms[n] = true; + } + } + break; + } + } + } + + makeSelection(selectedAtoms, progress); + + if (logger.isLoggable(Level.INFO)) { + logger.log(Level.INFO, "Selected monomers:\n" + sb.toString()); + } + } + + public void makeMonomersSelection(int monomers[]) { + makeMonomersSelection(monomers, null); + } + + public void makeMonomersSelection(int monomers[], JobProgressInterface progress) { + if (monomers == null || monomers.length < 1) { + return; + } + + boolean selectedAtoms[] = new boolean[molecule.getNumberOfAtoms()]; + for (int i = 0; i < selectedAtoms.length; i++) { + selectedAtoms[i] = false; + } + + for (int i = 0; i < monomers.length; i++) { + MonomerInterface m = molecule.getMonomerInterface(monomers[i]); + for (int k = 0; k < m.getNumberOfAtoms(); k++) { + AtomInterface atom = m.getAtom(k); + int n = molecule.getAtomIndex(atom); + if (n != -1) { + selectedAtoms[n] = true; + } + } + } + + makeSelection(selectedAtoms, progress); + } + + /** + * + * @param elements Object[] + * @param atom_names Object[] + */ + public void makeSelection(Object elements[], Object atom_names[]) { + makeSelection(elements, atom_names, null); + } + + public void makeSelection(Object elements[], Object atom_names[], JobProgressInterface progress) { + + if (elements == null && atom_names == null) { + return; + } + if (elements.length == 0 && atom_names.length == 0) { + return; + } + + int natoms = molecule.getNumberOfAtoms(); + + boolean selectedAtoms[] = new boolean[natoms]; + for (int i = 0; i < selectedAtoms.length; i++) { + selectedAtoms[i] = false; + } + + boolean select_elements = elements != null && elements.length > 0; + boolean select_atom_names = atom_names != null && atom_names.length > 0; + + // --- Process selected elements + if (select_elements) { + int elems[] = new int[elements.length]; + for (int i = 0; i < elements.length; i++) { + String element = (String) elements[i]; + elems[i] = ChemicalElements.getAtomicNumber(element); + } + + for (int i = 0; i < selectedAtoms.length; i++) { + AtomInterface atom = molecule.getAtomInterface(i); + for (int j = 0; j < elements.length; j++) { + if (atom.getAtomicNumber() == elems[j]) { + selectedAtoms[i] = true; + break; + } + } + } + } + + // --- process selected atom names + if (select_atom_names) { + for (int i = 0; i < selectedAtoms.length; i++) { + AtomInterface atom = molecule.getAtomInterface(i); + String atomName = atom.getName(); + for (int j = 0; j < atom_names.length; j++) { + if (atomName.compareToIgnoreCase(atom_names[j].toString()) == 0) { + selectedAtoms[i] = true; + break; + } + } + } + } + + makeSelection(selectedAtoms, progress); + } + + /** + * + * @param selectedAtoms boolean[] + */ + public void makeSelection(boolean selectedAtoms[]) { + makeSelection(selectedAtoms, null); + } + + public void makeSelection(boolean selectedAtoms[], JobProgressInterface progress) { + + // --- Error check + if (molecule.getNumberOfAtoms() != selectedAtoms.length) { + logger.info("INTERNAL ERROR: makeSelection: molecule.getNumberOfAtoms() != selectedAtoms.length"); + JOptionPane.showMessageDialog(new JFrame(), + "INTERNAL ERROR: makeSelection: molecule.getNumberOfAtoms() != selectedAtoms.length", + "Internal Error", JOptionPane.ERROR_MESSAGE); + return; + } + + // --- Make selection + switch (selectionRule) { + case UNION: + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + if (selectedAtoms[i]) { + AtomInterface atom = molecule.getAtomInterface(i); + atom.setSelected(true); + if (trackSelectedAtoms.indexOf(atom) == -1) { + trackSelectedAtoms.add(atom); + } + } + } + break; + //***************************************************** + case DIFFERENCE: + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface atom = molecule.getAtomInterface(i); + if (!selectedAtoms[i]) { + continue; + } + if (atom.isSelected()) { + atom.setSelected(false); + trackSelectedAtoms.remove(atom); + } + } + break; + //********************************************************** + case INTERSECTION: + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface atom = molecule.getAtomInterface(i); + if (selectedAtoms[i] && atom.isSelected()) { + continue; + } + atom.setSelected(false); + trackSelectedAtoms.remove(atom); + } + break; + } + + //if (selectionRule == RULE_UNION) { + // for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + // if (selectedAtoms[i]) { + // AtomInterface atom = molecule.getAtomInterface(i); + // atom.setSelected(true); + // if (trackSelectedAtoms.indexOf(atom) == -1) { + // trackSelectedAtoms.add(atom); + // } + // } + // } + //} else if (selectionRule == RULE_DIFFERENCE) { + // for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + // AtomInterface atom = molecule.getAtomInterface(i); + // if (!selectedAtoms[i]) { + // continue; + // } + // if (atom.isSelected()) { + // atom.setSelected(false); + // trackSelectedAtoms.remove(atom); + // } + // } + //} + //if (selectionRule == RULE_INTERSECTION) { + // for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + // AtomInterface atom = molecule.getAtomInterface(i); + // if (selectedAtoms[i] && atom.isSelected()) { + // continue; + // } + // atom.setSelected(false); + // trackSelectedAtoms.remove(atom); + // } + //} + highlightSelectedAtoms(progress); + } + + public void endProcessingSelectedAtoms() { + + switch (processingSelected) { + case SELECTED_ADD_ATOMS: + selectAllAtoms(false); + break; + + case SELECTED_MODIFY_BONDS: + temp_Group_1 = null; + temp_Group_2 = null; + break; + + case SELECTED_MODIFY_ANGLES: + temp_Group_1 = null; + temp_Group_2 = null; + temp_Group_3 = null; + temp_axis = null; // Rotation axis + break; + + case SELECTED_MODIFY_DIHEDRALS: + temp_Group_1 = null; + temp_Group_2 = null; + temp_axis = null; // Rotation axis + break; + case SELECTED_ADD_MOLECULE: + selectAllAtoms(false); + break; + + } + + selectAllAtoms(false); + enableMousePicking(false); + lastSelectedAtom = -1; // Reset + trackSelectedAtoms.clear(); + } + + public void processSelectedAtoms() { + processSelectedAtoms(null); + } + + /** + * + */ + public void processSelectedAtoms(JobProgressInterface progress) { + switch (processingSelected) { + + case SELECTED_DISPLAY_ATOMS: + displaySelectedAtoms(true, progress); + endProcessingSelectedAtoms(); + break; + case SELECTED_UNDISPLAY_ATOMS: + displaySelectedAtoms(false, progress); + endProcessingSelectedAtoms(); + break; + case SELECTED_DELETE_ATOMS: + deleteSelectedAtoms(progress); + endProcessingSelectedAtoms(); + break; + case SELECTED_LABEL_ATOMS: + List props = Molecule.getAvailableAtomicProperties(molecule); + props.add("Atom number"); + props.add("Element"); + if (atomLabelsDialog == null) { + atomLabelsDialog = new AtomLabelsDialog(new Frame(), "Select Atom Labels", props, true); + atomLabelsDialog.setLocationByPlatform(true); + } + atomLabelsDialog.setProperties(props); + atomLabelsDialog.setVisible(true); + if (atomLabelsDialog.pressedOK()) { + String property = atomLabelsDialog.getSelectedItem(); + labelSelectedAtoms(property); + } + endProcessingSelectedAtoms(); + break; + + case SELECTED_UNLABEL_ATOMS: + unlabelSelectedAtoms(); + endProcessingSelectedAtoms(); + break; + + case SELECTED_CHANGE_ATOM_LABELS_SIZE: + DoubleSpinnerDialog dial = new DoubleSpinnerDialog(new Frame(), "Choose Value", true, + (double) atomLabelsFontSize * (double) referenceText2D.getRectangleScaleFactor(), 0.1, 2.0, 0.05); + dial.setLocationByPlatform(true); + dial.setVisible(true); + if (dial.isOKPressed()) { + double value = dial.getValue(); + updateSelectedAtomLabelsSize(value); + endProcessingSelectedAtoms(); + } + break; + + case SELECTED_CHANGE_ATOM_LABELS_COLOR: + Color c = JColorChooser.showDialog(new Frame(), "Choose Atom Labels Color", this.getAtomLabelsColor()); + if (c != null) { + updateSelectedAtomLabelsColor(c); + } + endProcessingSelectedAtoms(); + break; + + case SELECTED_MODIFY_ATOMS: + setupModifyAtomDialog(); + + //selectAllAtoms(false); + //enableMousePicking(false); + break; + + case SELECTED_MODIFY_BONDS: + if (selectedAtoms.size() == 2) { + setupModifyBondDialog(); + enableMousePicking(false); + temp_Group_1 = null; + temp_Group_2 = null; + if (temp_structure == null + || temp_structure.length < molecule.getNumberOfAtoms()) { + temp_structure = new cct.vecmath.Point3f[molecule.getNumberOfAtoms()]; + } + Molecule.getCoordinates(molecule, temp_structure); + } + break; + + case SELECTED_MODIFY_ANGLES: + if (selectedAtoms.size() == 3) { + setupModifyAngleDialog(); + enableMousePicking(false); + temp_Group_1 = null; + temp_Group_2 = null; + temp_Group_3 = null; + temp_axis = null; // Rotation axis + if (temp_structure == null + || temp_structure.length < molecule.getNumberOfAtoms()) { + temp_structure = new cct.vecmath.Point3f[molecule.getNumberOfAtoms()]; + } + Molecule.getCoordinates(molecule, temp_structure); + } + break; + + case SELECTED_FILL_VALENCES_WITH_HYDROGENS: + + //molecule.setBondInterface(new Bond()); + Atom hydrogen = new Atom(); + hydrogen.setAtomicNumber(1); + hydrogen.setName("H"); + hydrogen.setProperty(AtomInterface.CCT_ATOM_TYPE, "H"); + fillEmptyValences(hydrogen); + endProcessingSelectedAtoms(); + break; + + case SELECTED_MODIFY_DIHEDRALS: + if (selectedAtoms.size() == 4) { + setupModifyDihedralDialog(); + enableMousePicking(false); + temp_Group_1 = null; + temp_Group_2 = null; + temp_axis = null; // Rotation axis + if (temp_structure == null + || temp_structure.length < molecule.getNumberOfAtoms()) { + temp_structure = new cct.vecmath.Point3f[molecule.getNumberOfAtoms()]; + } + Molecule.getCoordinates(molecule, temp_structure); + } + break; + + case SELECTED_ADD_ATOMS: + break; + + case SELECTED_ADD_MOLECULE: + break; + + case SELECTED_ADD_FRAGMENT: + addFragment(); + selectAllAtoms(false); + + //endProcessingSelectedAtoms(); + break; + case SELECTED_CREATE_CENTROID: + createdCentroidForSelectedAtoms(); + endProcessingSelectedAtoms(); + break; + case SELECTED_SOLVATE_CAP: + case SELECTED_SOLVATE_SHELL: + openSolvateMoleculeDialog(processingSelected); + endProcessingSelectedAtoms(); + break; + + case SELECTED_ROTATION_CENTER: + setRotationCenterOnSelectedAtoms(); + endProcessingSelectedAtoms(); + break; + + default: + endProcessingSelectedAtoms(); + } + + } + + public void handleSpotPicking(Point3d origin, Vector3d dir) { + if (origin == null || dir == null) { + logger.info( + "handleSpotPicking: origin == null || dir == null"); + return; + } + + // --- Special cases: + if (processingSelected == SELECTED_ADD_ATOMS + && molecule.getNumberOfAtoms() < 1) { + int elementNumber = 0; + String atomType = null; + String atomName = null; + if (chooseAtomType instanceof AtomTypeDialog) { + AtomTypeDialog dlg = (AtomTypeDialog) chooseAtomType; + elementNumber = dlg.getElementNumber(); + } else if (chooseAtomType instanceof JAtomTypeDialog) { + JAtomTypeDialog dlg = (JAtomTypeDialog) chooseAtomType; + elementNumber = dlg.getElement(); + atomType = dlg.getAtomType(); + if (dlg.getAtomName().length() < 1) { + atomName = ChemicalElements.getElementSymbol(elementNumber); + } else { + atomName = dlg.getAtomName(); + } + } + + AtomInterface atom = molecule.getNewAtomInstance(); + //molecule.addMonomer("no-name"); + atom.setAtomicNumber(elementNumber); + atom.setName(atomName); + atom.setXYZ(0, 0, 0); + //atom.setSubstructureNumber(0); + if (atomType != null) { + atom.setProperty(AtomInterface.CCT_ATOM_TYPE, atomType); + } + //molecule.addAtom(atom); + //this.addMolecule(molecule); + + MoleculeInterface mol = molecule.getInstance(); + mol.addAtom(atom); + this.addMolecule(mol); //.addAtom(atom); + enableMousePicking(true); + return; + } + + // --- Error check + if (lastSelectedAtom == -1 + || lastSelectedAtom >= molecule.getNumberOfAtoms()) { + logger.info("lastSelectedAtom == -1 || lastSelectedAtom >= molecule.getNumberOfAtoms()"); + return; + } + + boolean scale = false; + float length = 1.0f; + + switch (processingSelected) { + case SELECTED_ADD_ATOMS: + + boolean drawBond = false; + boolean useBondLength = false; + boolean covalentBondLength = false; + String bl = null; + String atomType = null; + int element = 0; + + if (chooseAtomType instanceof AtomTypeDialog) { + AtomTypeDialog dlg = (AtomTypeDialog) chooseAtomType; + useBondLength = dlg.isUseBondLength(); + if (useBondLength) { + bl = dlg.getBondLength(); + } + } else if (chooseAtomType instanceof JAtomTypeDialog) { + JAtomTypeDialog dlg = (JAtomTypeDialog) chooseAtomType; + drawBond = dlg.isDrawBond(); + useBondLength = dlg.isUseBondLength(); + covalentBondLength = dlg.isCovalentBondLength(); + if (useBondLength) { + bl = dlg.getBondLength(); + } + atomType = dlg.getAtomType(); + element = dlg.getElement(); + } else { + logger.info( + "INTERNAL ERROR: Unknown instance of chooseAtomType"); + } + + if (useBondLength) { + //bl = chooseAtomType.getBondLength(); + try { + length = Float.parseFloat(bl); + } catch (NumberFormatException e) { + MessageWindow d = new MessageWindow("Error", "Bond length " + bl + " is not a real number", true); + d.setVisible(true); + //logger.info( "Error converting cartesin coordinates"); + return; + } + scale = true; + } else if (covalentBondLength) { + scale = true; + AtomInterface a1 = molecule.getAtomInterface(lastSelectedAtom); + if (a1.getProperty(AtomInterface.CCT_ATOM_TYPE) == null + || atomType == null) { + length = ChemicalElements.guessCovalentBondLength(a1.getAtomicNumber(), element); + } else if (CCTAtomTypes.isValidCCTType(atomType) && CCTAtomTypes.isValidCCTType((String) a1.getProperty( + AtomInterface.CCT_ATOM_TYPE))) { + length = SimpleForceField.guessCovalentBondLength(atomType, (String) a1.getProperty(AtomInterface.CCT_ATOM_TYPE)); + } else { + length = ChemicalElements.guessCovalentBondLength(a1.getAtomicNumber(), element); + } + + if (length < 0.1) { + System.err.println("Covalent bond is too small. Ignoring..."); + scale = false; + } + } + + AtomNode new_atom = addAtom(origin, dir, length, scale); + if (new_atom != null) { + mol.addChild(new_atom); + //atomNodes.add(new_atom); + atomLabels.add(null); + } + + if (chooseAtomType instanceof AtomTypeDialog) { + AtomTypeDialog dlg = (AtomTypeDialog) chooseAtomType; + drawBond = dlg.isDrawBond(); + } else if (chooseAtomType instanceof JAtomTypeDialog) { + JAtomTypeDialog dlg = (JAtomTypeDialog) chooseAtomType; + drawBond = dlg.isDrawBond(); + } else { + logger.info( + "INTERNAL ERROR: Unknown instance of chooseAtomType"); + } + + if (drawBond && new_atom != null) { + BondNode bond = createBond(lastSelectedAtom, + molecule.getNumberOfAtoms() - 1); + if (bond != null) { + mol.addChild(bond); + bondNodes.add(bond); + } + } + + /* + * if ( oneAtomSelectionDialog.pressedOK() ) { enableMousePicking( true ); selectedMode = SELECTION_ONE_ATOM_ONLY; + * processingSelected = SELECTED_ADD_ATOMS; oneAtomSelectionDialog.setMessage("Select Atom to Connect to"); + * oneAtomSelectionDialog.setVisible(true); } + */ + break; + + case SELECTED_ADD_MOLECULE: + scale = this.jAddMoleculeDialog.isPredefinedDistance(); + if (scale) { + length = this.jAddMoleculeDialog.getPredefinedDistance(); + if (length < 0.0f) { + return; + } + } + addMolecule(origin, dir, length, scale, otherRenderer); + + break; + /* + * case SELECTED_MODIFY_DIHEDRALS: if (selectedAtoms.size() == 4) { setupModifyDihedralDialog(); enableMousePicking(false); + * temp_Group_1 = null; temp_Group_2 = null; temp_axis = null; // Rotation axis if (temp_structure == null || + * temp_structure.length < molecule.getNumberOfAtoms()) { temp_structure = new Point3f[molecule.getNumberOfAtoms()]; } + * Molecule.getCoordinates(molecule, temp_structure); } break; + */ + } + } + + public int setNewGeometry(int n) { + List geoms = getGeometries(); + if (n < 0 || n >= geoms.size()) { + logger.info( + "setNewGeometry: n < 0 || n >= Geometries.size()"); + return -1; + } + + MolecularGeometry g = (MolecularGeometry) geoms.get(0); + if (molecule.getNumberOfAtoms() != g.size()) { + logger.info( + "setNewGeometry: molecule.getNumberOfAtoms() != g.size()"); + MessageWindow d = new MessageWindow("Warning Message", + "Geometries do not correspond to the Molecule any more", true); + //molecule.setGeometries(null); + geometrySelectioDialog.setVisible(false); + geometrySelection.setEnabled(false); + d.setVisible(true); + return -1; + } + + setupSelectedGeometry(molecule, n); + addMolecule(molecule); + return n; + } + + public boolean logoutDatabase() { + if (databaseAccess == null) { + return true; + } + connectedToDB = false; + new_chemistryDatabase.setVisible(false); + new_chemistryDatabase = null; + new_sqlChemistryDatabase = null; + return databaseAccess.closeConnection(); + } + + public boolean connectToDatabase() { + + // Invoke a dialog to get hostname, user name, etc... + //ConnectSQLServer server = new ConnectSQLServer(menuFrame, + // So, now we can open only one database during a session + if (sqlServerDialog == null) { + sqlServerDialog = new ConnectSQLServer("Connect to Database Server", true); + if (sqlServerDialog.getDatabase().length() == 0) { + sqlServerDialog.setDatabase("chemistry"); + } + + //server.dispose(); + //menuFrame.sqlServerDialog.setVisible(false); + } + + if (!connectedToDB) { + sqlServerDialog.setVisible(true); + } + + if (!sqlServerDialog.pressedOK()) { + return false; + } + + String host = sqlServerDialog.getHostname(); + String user = sqlServerDialog.getUsername(); + String pass = sqlServerDialog.getPassword(); + String database = sqlServerDialog.getDatabase(); + + // --- Connect to the SQL Server + // --- Load connector and make connection + if (databaseAccess == null) { + databaseAccess = new SQLDatabaseAccess(); + if (databaseAccess.wasError()) { + JOptionPane.showMessageDialog(new JFrame(), + databaseAccess.getErrorMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return false; + + } + } + if (!databaseAccess.isDriverLoaded()) { + return false; + } + if (!databaseAccess.getConnection(host, user, pass)) { + return false; + } + if (!databaseAccess.selectDatabase(database)) { + return false; + } + + connectedToDB = true; + + //SQLChemistryDatabase sql_data = new SQLChemistryDatabase(host, + // --- Testing new database + if (cct.GlobalSettings.isNewDatabase()) { + if (new_sqlChemistryDatabase == null) { + new_sqlChemistryDatabase = new new_SQLChemistryDatabase( + databaseAccess, host, + user, pass, database); + //new_sqlChemistryDatabase.setParentFrame(parentFrame); + } + if (new_sqlChemistryDatabase.isError()) { + logger.info("connectToDatabase: " + + new_sqlChemistryDatabase.getErrorMessage()); + MessageWindow er = new MessageWindow("ERROR", + new_sqlChemistryDatabase.getErrorMessage(), true); + er.setVisible(true); + } else { + //ConnectSQLServer sql = new ConnectSQLServer( menuFrame, "Connect to SQL Server", true ); + if (new_chemistryDatabase == null) { + new_chemistryDatabase = new new_ChemistryDatabaseDialog(this, + new_sqlChemistryDatabase, + "Chemical Database", false); + } + new_chemistryDatabase.setVisible(true); + + } + + } else { + // --- Old Database Design + if (sqlChemistryDatabase == null) { + sqlChemistryDatabase = new SQLChemistryDatabase( + databaseAccess, host, + user, pass, database); + } + + if (sqlChemistryDatabase.isError()) { + logger.info(": " + + sqlChemistryDatabase.getErrorMessage()); + MessageWindow er = new MessageWindow("ERROR", + sqlChemistryDatabase.getErrorMessage(), true); + er.setVisible(true); + } else { + //ConnectSQLServer sql = new ConnectSQLServer( menuFrame, "Connect to SQL Server", true ); + if (chemistryDatabase == null) { + chemistryDatabase = new ChemistryDatabaseDialog( + this, + sqlChemistryDatabase, + "Chemical Database", false); + } + chemistryDatabase.setVisible(true); + + } + } + + return true; + } + + public void startBulkDatabaseLoad(String[] files) { + + // --- First, connect to database + AddNewStructureDialog new_str = null; + AddNewMoleculeDialog new_mol = null; + + if (!connectToDatabase()) { + logger.info( + "startBulkDatabaseLoad: Cannot connect to database"); + return; + } + + String str_name = null; + String notes = null; + + TextEntryDialog str_names = new TextEntryDialog(new Frame(), + "Enter name for all Structures", true); + str_names.setVisible(true); + if (str_names.isTextEntered()) { + str_name = str_names.getValue(); + } else { + return; + } + + YesNoDialog inter = new YesNoDialog(new Frame(), "Do you want to add structures interactively?"); + inter.setVisible(true); + boolean isInteractive = inter.isYes(); + + for (int i = 0; i < files.length; i++) { + String fileName = files[i]; + //String directory = new String("./"); + String directory = new String(""); + MoleculeInterface m = Molecule.getNewInstance(); + GaussianOutput parseGaussianOutput = new GaussianOutput(); + GaussianJob results; + try { + results = parseGaussianOutput.parseFile(m, directory + fileName, false); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + continue; + } + //m = (MoleculeInterface) results.get("molecule"); + m = results.getMolecule(0); // !!! i.e. take molecule from the first step + //Geometries = (ArrayList) results.get("geometries"); + Geometries = results.getGeometries(0); + + if (Geometries.size() > 0) { + // --- Select last geometry + setupSelectedGeometry(m, Geometries.size() - 1); + Molecule.guessCovalentBonds(m); + addMolecule(m); + } else { + MessageWindow d = new MessageWindow("Error Message", "No Geometries...", true); + d.setVisible(true); + continue; + } + + Map prop = m.getProperties(); + + Integer ch = (Integer) prop.get(MoleculeInterface.ChargeProperty); + Integer multiplicity = (Integer) prop.get(MoleculeInterface.MultiplicityProperty); + + String mol_name = fileName.substring(0, fileName.indexOf(".")); + mol_name = mol_name.toUpperCase(); + + // --- Add new molecule + if (new_mol == null) { + new_mol = new AddNewMoleculeDialog("Adding New Molecule", true, mol_name); + } + new_mol.setName(mol_name); + + if (ch == null) { + new_mol.setCharge(0); + } else { + new_mol.setCharge(ch.intValue()); + } + + if (multiplicity == null) { + new_mol.setMultiplicity(1); + } else { + new_mol.setMultiplicity(multiplicity.intValue()); + } + + if (isInteractive) { + new_mol.setVisible(true); + } + if (!new_mol.isOKPressed() && isInteractive) { + continue; + } + String aliases = new_mol.getAliases(); + notes = new_mol.getNotes(); + boolean is_model = new_mol.isModel(); + int charge = new_mol.getCharge(); + int mult = new_mol.getMultiplicity(); + + if (!new_sqlChemistryDatabase.addNewMolecule(mol_name, aliases, + notes, is_model, + charge, mult)) { + continue; + } + + // --- Add structure + if (new_str == null) { + new_str = new AddNewStructureDialog("New Structure", + true, mol_name, + new_sqlChemistryDatabase); + new_str.setName(str_name); + } + + if (isInteractive || i == 0) { + new_str.setVisible(true); + } + if (!new_str.isOKPressed() && isInteractive) { + continue; + } + + str_name = new_str.getName(); + notes = new_str.getNotes(); + + logger.info("New Structure: " + str_name); + + String method = new_str.getMethod(); + + MoleculeInterface mol = getMolecule(); + Map row = new_sqlChemistryDatabase.addNewStructure(mol_name, + str_name, notes, + method, mol); + if (row == null) { + MessageWindow er = new MessageWindow("ERROR", + new_sqlChemistryDatabase.getErrorMessage(), true); + er.setVisible(true); + continue; + } + } + + new_chemistryDatabase.updateData(); + } + + public void addGaussianData(Gaussian gData) { + gaussianData = gData; + } + + public Gaussian getGaussianData() { + return gaussianData; + } + + public Canvas3D getCanvas3D() { + return canvas3D; + } + + public void setRadiusForSelectedAtoms(float radius) { + if (lastSelectedAtom < 0) { //|| lastSelectedAtom >= atomSpheres.size()) { + return; + } + AtomInterface a = molecule.getAtomInterface(lastSelectedAtom); + AtomNode atom_node = (AtomNode) a.getProperty(ATOM_NODE); + //AtomNode atom_node = (AtomNode) atomNodes.get(lastSelectedAtom); + + setAtomicSphereRadius(atom_node, radius); + /* + * atom_node.detach(); + * + * Sphere atom = (Sphere) atomSpheres.get(lastSelectedAtom); Appearance ap = atom.getAppearance(); int divisions = + * atom.getDivisions(); Sphere new_atom = new Sphere(radius, Sphere.GENERATE_NORMALS, divisions, ap); + */ + + Float R = (Float) a.getProperty(AtomInterface.GR_RADIUS); + R = radius; + a.setProperty(AtomInterface.GR_RADIUS, R); + /* + * setAtomicSphere(atom_node, new_atom); atomSpheres.remove(lastSelectedAtom); atomSpheres.add(lastSelectedAtom, new_atom); + * + * mol.addChild(atom_node); + */ + } + + public void setAtomicSphereRadius(AtomNode atom_node, float radius) { + + //atom_node.detach(); + atom_node.setAtomicSphereRadius(radius); + /* + * TransformGroup scale = getAtomicSphereScale(atom_node); + * + * Transform3D value = new Transform3D(); value.setScale(radius); scale.setTransform(value); + */ + //mol.addChild(atom_node); + } + + public void setColorForSelectedAtoms(Color new_color) { + if (lastSelectedAtom < 0) { //|| lastSelectedAtom >= atomSpheres.size()) { + return; + } + + AtomInterface atom = molecule.getAtomInterface(lastSelectedAtom); + AtomNode atom_node = (AtomNode) atom.getProperty(ATOM_NODE); + //AtomNode atom_node = atomNodes.get(lastSelectedAtom); + + highlightSelectedAtom(mol, atom_node, false); + + //atom_node.detach(); + atom_node.setAtomColor(new_color); + + Material store = cloneMaterial(atom_node.getMaterial()); + //materialStore.remove(lastSelectedAtom); + atom.setProperty(ATOM_NODE_MATERIAL_COPY, store); + //materialStore.add(lastSelectedAtom, store); + + //mol.addChild(atom_node); + List bonds = atom.getBondIndex(); + for (int j = 0; j < bonds.size(); j++) { + Bond b = (Bond) bonds.get(j); + int index = molecule.getBondIndex(b); + BondNode bond = bondNodes.get(index); + //bond.detach(); + bond.updateBondColor(); + //mol.addChild(bond); + } + + } + + /** + * Reset rotation of the scene to the identity matrix + */ + public void resetSceneRotation() { + Transform3D reset = new Transform3D(); + sceneTrans.getTransform(reset); + Matrix3d unit = new Matrix3d(); + unit.setIdentity(); + reset.setRotation(unit); + sceneTrans.setTransform(reset); + } + + /** + * Reset the whole scene to the identity matrix + */ + public void resetScene() { + Transform3D reset = new Transform3D(); + sceneTrans.getTransform(reset); + reset.setIdentity(); + sceneTrans.setTransform(reset); + + reset = new Transform3D(); + moleculeTrans.getTransform(reset); + reset.setIdentity(); + moleculeTrans.setTransform(reset); + } + + public void setAtomColor(int natom, Color new_color) { + if (natom < 0 || natom >= molecule.getNumberOfAtoms()) { + return; + } + AtomInterface atom = molecule.getAtomInterface(natom); + setAtomColor(atom, new_color); + } + + public void setAtomColor(AtomInterface atom, Color3f new_color) { + Object obj = atom.getProperty(ATOM_NODE); + if (obj == null) { + System.err.println(this.getClass().getCanonicalName() + ": setAtomColor: atom does not contain AtomNode. Ignored..."); + return; + } + AtomNode atom_node = (AtomNode) obj; + atom_node.setAtomColor(new_color); + atom.setProperty(ATOM_NODE_MATERIAL_COPY, atom_node.getMaterial()); + + List bonds = atom.getBondIndex(); + for (int j = 0; j < bonds.size(); j++) { + Bond b = (Bond) bonds.get(j); + int index = molecule.getBondIndex(b); + BondNode bond = bondNodes.get(index); + bond.updateBondColor(); + } + } + + public void setAtomColor(AtomInterface atom, Color new_color) { + Color3f new_color3f = new Color3f(new_color); + setAtomColor(atom, new_color3f); + } + + public void setAtomColor(int natom, Color3f new_color, Material new_material) { + if (natom < 0) { //|| natom >= atomSpheres.size()) { + return; + } + + AtomInterface atom = molecule.getAtomInterface(natom); + AtomNode atom_node = (AtomNode) atom.getProperty(ATOM_NODE); + //AtomNode atom_node = atomNodes.get(natom); + + highlightSelectedAtom(mol, atom_node, false); + + //atom_node.detach(); + mol.removeChild(atom_node); + + atom_node.setAtomColor(new_color, new_material); + + Material store = cloneMaterial(atom_node.getMaterial()); + atom.setProperty(ATOM_NODE_MATERIAL_COPY, store); + //materialStore.set(natom, store); + + mol.addChild(atom_node); + + } + + public void setLabelForSelectedAtoms(String new_label) { + if (molecule == null) { + return; + } + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface atom = molecule.getAtomInterface(i); + if (!atom.isSelected()) { + continue; + } + atom.setName(new_label); + + // !!! now update label nodes !!! to be done + } + } + + /** + * + */ + private void setupModifyAtomDialog() { + if (lastSelectedAtom < 0) { + return; + } + AtomInterface a = molecule.getAtomInterface(lastSelectedAtom); + logger.info("Selected atom: " + lastSelectedAtom + " :" + ChemicalElements.getElementSymbol(a.getAtomicNumber())); + + int element = a.getAtomicNumber(); + jModifyAtomDialog.selectElement(element); + jModifyAtomDialog.setLabel(a.getName()); + jModifyAtomDialog.setX(a.getX()); + jModifyAtomDialog.setY(a.getY()); + jModifyAtomDialog.setZ(a.getZ()); + Float R = (Float) a.getProperty(AtomInterface.GR_RADIUS); + if (R == null) { + R = ChemicalElements.getCovalentRadius(a.getAtomicNumber()); + a.setProperty(AtomInterface.GR_RADIUS, R); + } + jModifyAtomDialog.setRadius(R); + AtomNode atom = (AtomNode) a.getProperty(ATOM_NODE); + //AtomNode atom = atomNodes.get(lastSelectedAtom); + Color3f c = atom.getColor3f(); //getAtomicNodeColor(atom); + int red = (int) (c.x * 255.0f); + int green = (int) (c.y * 255.0f); + int blue = (int) (c.z * 255.0f); + jModifyAtomDialog.setColor(red, green, blue); + + String currentType = "Atom"; + Map atomTypes = CCTAtomTypes.getPictureMapping(a.getAtomicNumber()); // LinkedHashMap(); + + Object obj = a.getProperty(AtomInterface.CCT_ATOM_TYPE); + String atomType = null; + if (obj != null) { + atomType = (String) obj; + } + + Set aTypes = atomTypes.keySet(); + Iterator iter = aTypes.iterator(); + while (iter.hasNext()) { + String Key = (String) iter.next(); + if (Key.equalsIgnoreCase(atomType)) { + currentType = Key; + } + } + + logger.info("Size of atom types: " + atomTypes.size()); + jModifyAtomDialog.setAtomTypes(atomTypes); + jModifyAtomDialog.setSelectedAtomType(currentType); + jModifyAtomDialog.validate(); + } + + public void setAtomTypeForSelectedAtoms(String new_atomType) { + if (molecule == null) { + return; + } + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface atom = molecule.getAtomInterface(i); + if (!atom.isSelected()) { + continue; + } + if (new_atomType.equalsIgnoreCase("Atom") + || new_atomType.length() == 0) { + atom.setProperty(AtomInterface.CCT_ATOM_TYPE, null); + } else { + atom.setProperty(AtomInterface.CCT_ATOM_TYPE, new_atomType); + } + + // !!! now update label nodes !!! to be done + } + + } + + private void setupModifyBondDialog() { + // --- Error check + + if (selectedAtoms.size() != 2) { + System.err.println( + "setupModifyBondDialog: selectedAtoms.size() != 2. Ignored..."); + return; + } + Integer I = (Integer) selectedAtoms.get(0); + Integer J = (Integer) selectedAtoms.get(1); + + AtomInterface a_i = molecule.getAtomInterface(I); + AtomInterface a_j = molecule.getAtomInterface(J); + + float length = (float) a_i.distanceTo(a_j); + jModifyBondDialog.setBondLenght(length); + + jModifyBondDialog.setDrawBond(a_i.isBondedTo(a_j)); + } + + private void setupModifyAngleDialog() { + + if (selectedAtoms.size() < 3) { + return; + } + + Integer I = (Integer) selectedAtoms.get(0); + Integer J = (Integer) selectedAtoms.get(1); + Integer K = (Integer) selectedAtoms.get(2); + + AtomInterface a_i = molecule.getAtomInterface(I); + AtomInterface a_j = molecule.getAtomInterface(J); + AtomInterface a_k = molecule.getAtomInterface(K); + + //float angle = a_j.angleBetween(a_i, a_k) / 1.74532925199e-2f; + float angle = angleBetween(a_i, a_j, a_k) / 1.74532925199e-2f; + jModifyAngleDialog.setAngle(angle); + + } + + /** + * + * @param new_element int + */ + public void setElementForSelectedAtoms(int new_element) { + if (lastSelectedAtom < 0) { //|| lastSelectedAtom >= atomSpheres.size()) { + return; + } + + AtomInterface a = molecule.getAtomInterface(lastSelectedAtom); + a.setAtomicNumber(new_element); + /* + * float radius = ChemicalElements.getCovalentRadius(a. getAtomicNumber()); radius *= AtomInterface.COVALENT_TO_GRADIUS_FACTOR; + * if (radius < 0.001f) { radius = 0.2f; } Float R = (Float) a.getProperty(AtomInterface.GR_RADIUS); R = radius; + */ + //a.setProperty(AtomInterface.GR_RADIUS, R); + + AtomNode new_atom = new AtomNode(a); //createAtom(a.getX(), a.getY(), a.getZ(), + // new_element); + //Material store = ChemicalElementsColors.getElementMaterial(new_element); + //materialStore.remove(lastSelectedAtom); + //materialStore.add(lastSelectedAtom, new_atom.getMaterial()); + a.setProperty(ATOM_NODE_MATERIAL_COPY, new_atom.getMaterial()); + + AtomNode atom_node = (AtomNode) a.getProperty(ATOM_NODE); + //AtomNode atom_node = atomNodes.get(lastSelectedAtom); + + //atom_node.detach(); + mol.removeChild(atom_node); + + atomLabels.remove(lastSelectedAtom); + atomLabels.add(lastSelectedAtom, null); + + a.setProperty(ATOM_NODE, new_atom); + mol.addChild(new_atom); + + setupModifyAtomDialog(); + } + + public void drawBondBetweenSelectedAtoms(boolean draw_bond) { + + if (selectedAtoms.size() < 2) { + return; // Simple error check + } + + Integer I = (Integer) selectedAtoms.get(0); + Integer J = (Integer) selectedAtoms.get(1); + + AtomInterface a_i = molecule.getAtomInterface(I.intValue()); + AtomInterface a_j = molecule.getAtomInterface(J.intValue()); + + if (draw_bond && (!a_i.isBondedTo(a_j))) { + BondNode bond = createBond(I.intValue(), J.intValue()); + if (bond != null) { + mol.addChild(bond); + bondNodes.add(bond); + } + } else if ((!draw_bond) && a_i.isBondedTo(a_j)) { + deleteBondBetweenAtoms(a_i, a_j); + } + } + + public void deleteBondBetweenAtoms(AtomInterface a_i, AtomInterface a_j) { + BondInterface b = a_i.getBondToAtom(a_j); + int bindex = molecule.getBondIndex(b); + if (bindex == -1) { + logger.info("deleteBondBetweenAtoms: bindex == -1"); + return; + } + + // --- Delete bond node + BondNode bond = bondNodes.get(bindex); + if (mol.indexOfChild(bond) != -1) { + mol.removeChild(bond); + } + bondNodes.remove(bond); + + // --- Now delete "real" bond in molecule + molecule.deleteBond(b); + + } + + public void deleteAllBonds() { + + // --- Delete bond nodes + for (int i = bondNodes.size() - 1; i > -1; i--) { + BondNode bond = bondNodes.get(i); + if (mol.indexOfChild(bond) != -1) { + mol.removeChild(bond); + } + bondNodes.remove(bond); + } + + // --- Now delete "real" bonds in molecule + for (int i = molecule.getNumberOfBonds() - 1; i > -1; i--) { + BondInterface bond = molecule.getBondInterface(i); + molecule.deleteBond(bond); + } + } + + /** + * Status: 0 - Fixed, 1 - translate Atom; 2 - translate group + * + * @param new_distance float + * @param I_atom_status int + * @param J_atom_status int + */ + public void changeDistanceBetweenSelectedAtoms(float new_distance, + int I_atom_status, + int J_atom_status) { + if (selectedAtoms.size() < 2) { + return; // Simple error check + } + + Integer I = (Integer) selectedAtoms.get(0); + Integer J = (Integer) selectedAtoms.get(1); + + AtomInterface a_i = molecule.getAtomInterface(I.intValue()); + AtomInterface a_j = molecule.getAtomInterface(J.intValue()); + + float bondIncrenment = new_distance - (float) a_i.distanceTo(a_j); + float i_inc = bondIncrenment / 2.0f; + float j_inc = bondIncrenment / 2.0f; + if (I_atom_status == 0) { + i_inc = 0; + j_inc = bondIncrenment; + } else if (J_atom_status == 0) { + i_inc = bondIncrenment; + j_inc = 0; + } + + // --- Form unit translation vector + float direction[] = { + 0, 0, 0}; //new float[3]; + float dist = (float) a_i.distanceTo(a_j); + direction[0] = (a_j.getX() - a_i.getX()) / dist; + direction[1] = (a_j.getY() - a_i.getY()) / dist; + direction[2] = (a_j.getZ() - a_i.getZ()) / dist; + + // --- Translate 1st Atom + if (I_atom_status == 1) { + translateAtom(I.intValue(), direction, -i_inc); + } else if (I_atom_status == 2) { + if (temp_Group_1 == null) { + temp_Group_1 = Molecule.noncyclicAtomGroup(a_i, a_j); + } + /* + * logger.info("I: group: "+group.size()); for (int i = 0; i < group.size(); i++) { Atom a = (Atom) group.get(i); int + * atom_index = molecule.getAtomIndex(a); System.out.print(atom_index+"; "); } + */ + translateAtomicGroup(temp_Group_1, direction, -i_inc); + } + + // --- Translate 2nd Atom + if (J_atom_status == 1) { + translateAtom(J.intValue(), direction, j_inc); + } else if (J_atom_status == 2) { + if (temp_Group_2 == null) { + temp_Group_2 = Molecule.noncyclicAtomGroup(a_j, a_i); + } + /* + * logger.info("J: group: "+group.size()); for (int i = 0; i < group.size(); i++) { Atom a = (Atom) group.get(i); int + * atom_index = molecule.getAtomIndex(a); System.out.print(atom_index+"; "); } + */ + translateAtomicGroup(temp_Group_2, direction, j_inc); + } + + //jModifyBondDialog.setBondLenght(new_distance); + } + + public void translateAtomicGroup(List group, float dir[], float increment) { + + // --- Update "real" molecule + if (norm(dir) < 0.001f) { + return; + } + Molecule.translateAtoms(group, dir, increment); + + // --- Update nodes + // --- Update Atom's Coordinates + for (int i = 0; i < group.size(); i++) { + AtomInterface a = (AtomInterface) group.get(i); + int atom_index = molecule.getAtomIndex(a); + + AtomNode atom = (AtomNode) a.getProperty(ATOM_NODE); + //AtomNode atom = atomNodes.get(atom_index); + /* + * TransformGroup tg = getAtomicTranformGroup(atom); + * + * Transform3D t3d = new Transform3D(); tg.getTransform(t3d); Vector3f trans = new Vector3f(a.getCoordinates()); + * t3d.set(trans); + */ + //atom.detach(); + //tg.setTransform(t3d); + atom.setAtomicCoordinates(a); + + //mol.addChild(atom); + } + + // --- Update bonds of the atom + List bonds_to_modify = new ArrayList(); + + for (int i = 0; i < group.size(); i++) { + Atom a = (Atom) group.get(i); + List bonds = a.getBondIndex(); + for (int j = 0; j < bonds.size(); j++) { + Bond b = (Bond) bonds.get(j); + if (bonds_to_modify.contains(b)) { + continue; + } + bonds_to_modify.add(b); + } + } + + for (int i = 0; i < bonds_to_modify.size(); i++) { + Bond b = (Bond) bonds_to_modify.get(i); + + int index = molecule.getBondIndex(b); + + BondNode bnode = bondNodes.get(index); + //bnode.detach(); + bnode.updateBond(); + //mol.addChild(bnode); + } + + } + + public void rotateAtomicGroupAroundAxis(List group, float theta, Point3fInterface p1, Point3fInterface p2) { + + // --- Update "real" molecule + Molecule.rotateAtomsAroundAxis(group, theta, p1, p2); + + // --- Update nodes + // --- Update Atom's Coordinates + for (int i = 0; i < group.size(); i++) { + AtomInterface a = (AtomInterface) group.get(i); + int atom_index = molecule.getAtomIndex(a); + + AtomNode atom = (AtomNode) a.getProperty(ATOM_NODE); + //AtomNode atom = atomNodes.get(atom_index); + /* + * TransformGroup tg = getAtomicTranformGroup(atom); Transform3D t3d = new Transform3D(); tg.getTransform(t3d); Vector3f trans + * = new Vector3f(a.getCoordinates()); t3d.set(trans); + */ + //atom.detach(); + //tg.setTransform(t3d); + atom.setAtomicCoordinates(a); + + //mol.addChild(atom); + } + + // --- Update bonds of the atom + List bonds_to_modify = new ArrayList(); + + for (int i = 0; i < group.size(); i++) { + Atom a = (Atom) group.get(i); + List bonds = a.getBondIndex(); + for (int j = 0; j < bonds.size(); j++) { + Bond b = (Bond) bonds.get(j); + if (bonds_to_modify.contains(b)) { + continue; + } + bonds_to_modify.add(b); + } + } + + for (int i = 0; i < bonds_to_modify.size(); i++) { + Bond b = (Bond) bonds_to_modify.get(i); + + int index = molecule.getBondIndex(b); + + BondNode bnode = bondNodes.get(index); + //bnode.detach(); + bnode.updateBond(); + //mol.addChild(bnode); + } + + } + + /** + * Updates geometry + */ + public void updateMolecularGeometry() { + + if (molecule == null) { + return; + } + + boolean debug = true; + + // --- Update Atom's Coordinates + long start = System.currentTimeMillis(); + + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface a = molecule.getAtomInterface(i); + + AtomNode atom = (AtomNode) a.getProperty(ATOM_NODE); + //AtomNode atom = atomNodes.get(i); + /* + * TransformGroup tg = getAtomicTranformGroup(atom); + * + * Transform3D t3d = new Transform3D(); tg.getTransform(t3d); //Vector3f trans = new Vector3f(a.getCoordinates()); Vector3f + * trans = new Vector3f(a.getX(), a.getY(), a.getZ()); t3d.set(trans); + */ + + //atom.detach(); + //tg.setTransform(t3d); + atom.setAtomicCoordinates(a); + //mol.addChild(atom); + + } + float secs = (float) (System.currentTimeMillis() - start) / 1000.0f; + logger.info("Elapsed time for java3d atoms update: " + secs); + + // --- Update bonds of the atom + start = System.currentTimeMillis(); + for (int i = 0; i < molecule.getNumberOfBonds(); i++) { + BondInterface b = molecule.getBondInterface(i); + + BondNode bnode = bondNodes.get(i); + //bnode.detach(); + bnode.updateBond(); + //mol.addChild(bnode); + } + secs = (float) (System.currentTimeMillis() - start) / 1000.0f; + logger.info("Elapsed time for java3d bonds update: " + secs); + + } + + public void translateAtom(int atom_index, float dir[], float increment) { + + // --- Update "real" molecule + Molecule.translateAtom(molecule, atom_index, dir, increment); + AtomInterface a = molecule.getAtomInterface(atom_index); + + // --- Update nodes + updateAtomNode(atom_index, a); + + } + + public void rotateAtomAroundAxis(int atom_index, float theta, + Point3fInterface p1, + Point3fInterface p2) { + + // --- Update "real" molecule + Molecule.rotateAtomAroundAxis(molecule, atom_index, theta, p1, p2); + AtomInterface a = molecule.getAtomInterface(atom_index); + + // --- Update nodes + updateAtomNode(atom_index, a); + + } + + void updateAtomNode(int atom_index, AtomInterface a) { + // --- Update Atom's Coordinates + + AtomNode atom = (AtomNode) a.getProperty(ATOM_NODE); + //AtomNode atom = atomNodes.get(atom_index); + /* + * TransformGroup tg = getAtomicTranformGroup(atom); + * + * Transform3D t3d = new Transform3D(); tg.getTransform(t3d); Vector3f trans = new Vector3f(a.getX(), a.getY(), a.getZ()); + * t3d.set(trans); + */ + //atom.detach(); + //tg.setTransform(t3d); + atom.setAtomicCoordinates(a); + //mol.addChild(atom); + + // --- Update bonds of the atom + List bonds = a.getBondedToAtoms(); + List bond_index = a.getBondIndex(); + for (int i = 0; i < bonds.size(); i++) { + Atom a_j = (Atom) bonds.get(i); + Bond b = (Bond) bond_index.get(i); + + int index = molecule.getBondIndex(b); + + BondNode bnode = bondNodes.get(index); + //bnode.detach(); + mol.removeChild(bnode); + bnode.updateBond(); + mol.addChild(bnode); + } + + } + + public void changeAngleBetweenSelectedAtoms(float new_angle, + int I_atom_status, + int J_atom_status, + int K_atom_status) { + if (selectedAtoms.size() < 3) { + return; // Simple error check + } + + Integer I = (Integer) selectedAtoms.get(0); + Integer J = (Integer) selectedAtoms.get(1); + Integer K = (Integer) selectedAtoms.get(2); + + AtomInterface a_i = molecule.getAtomInterface(I.intValue()); + AtomInterface a_j = molecule.getAtomInterface(J.intValue()); + AtomInterface a_k = molecule.getAtomInterface(K.intValue()); + + // --- Form axis of rotation + if (temp_axis == null) { + cct.vecmath.Point3f v_ji = new cct.vecmath.Point3f(a_j, a_i); + cct.vecmath.Point3f v_jk = new cct.vecmath.Point3f(a_j, a_k); + temp_axis = v_ji.crossProduct(v_jk); // Rotation axis + + if (temp_axis.vectorNorm() < 0.00001f) { + JOptionPane.showMessageDialog(new JFrame(), + "Rotation Axis cannot be determined", + "Error", + JOptionPane.ERROR_MESSAGE); + //logger.info("axis.vectorSquaredNorm() < 0.00001f"); + return; + } + temp_axis.add(a_j); + logger.info("Rotation Axis determined"); + } + + if (new_angle < 0.01f) { + new_angle = -0.01f; + } else if (new_angle > 179.9f) { + new_angle = 180.1f; + } + + //float angle = a_j.angleBetween(a_i, a_k); + float angle = angleBetween(a_i, a_j, a_k); + float angleIncrement = 1.74532925199e-2f * new_angle - angle; + //logger.info("Angle: "+(angle/1.74532925199e-2f)+" new Angle: "+new_angle+" Increment: "+angleIncrement); + if (Math.abs(angleIncrement) < 0.01f) { + return; + } + //else if (angle + angleIncrement < 0) { + // return; + //} + float i_inc = angleIncrement / 2.0f; + float k_inc = angleIncrement / 2.0f; + /* + * FIXED_ATOM = 0; public static final int ROTATE_GROUP = 1; public static final int TRANSLATE_GROUP = 2; public static final + * int TRANSLATE_ATOM = 3; public static final int ROTATE_ATOM + * + */ + + if (I_atom_status == FIXED_ATOM) { + i_inc = 0; + k_inc = angleIncrement; + } else if (K_atom_status == FIXED_ATOM) { + i_inc = angleIncrement; + k_inc = 0; + } + + // --- Rotate 1st Atom + if (I_atom_status == ROTATE_ATOM) { + rotateAtomAroundAxis(I.intValue(), -i_inc, a_j, temp_axis); + } else if (I_atom_status == ROTATE_GROUP) { + if (temp_Group_1 == null) { + temp_Group_1 = Molecule.noncyclicAtomGroup(a_i, a_j, a_k); + } + rotateAtomicGroupAroundAxis(temp_Group_1, -i_inc, a_j, temp_axis); + //translateAtomicGroup(temp_Group_1, direction, -i_inc); + } else if (I_atom_status == TRANSLATE_GROUP) { + if (temp_Group_1 == null) { + temp_Group_1 = Molecule.noncyclicAtomGroup(a_i, a_j, a_k); + } + cct.vecmath.Point3f point = new cct.vecmath.Point3f(a_i); + Geometry3d.rotatePointAroundArbitraryAxis(point, -i_inc, a_j, + temp_axis); + //logger.info("New XYZ coord: "+point.getX()+point.getY()+point.getZ()); + + float move = (float) a_i.distanceTo(point); + if (move >= 0.01f) { + float direction[] = { + 0, 0, 0}; //new float[3]; + float dist = (float) a_i.distanceTo(point); + direction[0] = (point.getX() - a_i.getX()) / dist; + direction[1] = (point.getY() - a_i.getY()) / dist; + direction[2] = (point.getZ() - a_i.getZ()) / dist; + //float direction[] = a_i.getDirectionTo(point); + translateAtomicGroup(temp_Group_1, direction, move); + } + //logger.info("New angle: "+a_j.angleBetween(a_i, a_k)+" move: "+move); + } + + // --- Rotate 3d Atom + if (K_atom_status == ROTATE_ATOM) { + rotateAtomAroundAxis(K.intValue(), k_inc, a_j, temp_axis); + } else if (K_atom_status == ROTATE_GROUP) { + if (temp_Group_3 == null) { + temp_Group_3 = Molecule.noncyclicAtomGroup(a_k, a_j, a_i); + } + rotateAtomicGroupAroundAxis(temp_Group_3, k_inc, a_j, temp_axis); + //translateAtomicGroup(temp_Group_1, direction, -i_inc); + } else if (K_atom_status == TRANSLATE_GROUP) { + if (temp_Group_3 == null) { + temp_Group_3 = Molecule.noncyclicAtomGroup(a_k, a_j, a_i); + } + cct.vecmath.Point3f point = new cct.vecmath.Point3f(a_k); + Geometry3d.rotatePointAroundArbitraryAxis(point, k_inc, a_j, + temp_axis); + //logger.info("New XYZ coord: "+point.getX()+point.getY()+point.getZ()); + float move = (float) a_k.distanceTo(point); + if (move >= 0.01f) { + float direction[] = { + 0, 0, 0}; //new float[3]; + float dist = (float) a_k.distanceTo(point); + direction[0] = (point.getX() - a_k.getX()) / dist; + direction[1] = (point.getY() - a_k.getY()) / dist; + direction[2] = (point.getZ() - a_k.getZ()) / dist; + //float direction[] = a_k.getDirectionTo(point); + translateAtomicGroup(temp_Group_3, direction, move); + } + //logger.info("New angle: "+a_j.angleBetween(a_i, a_k)+" move: "+move); + } + + //jModifyBondDialog.setBondLenght(new_distance); + } + + public void undoLastSelection() { + if (selectedAtoms.size() == 0) { + return; + } + enableMousePicking(true); + Integer I = (Integer) selectedAtoms.get(selectedAtoms.size() - 1); + AtomInterface at = molecule.getAtomInterface(I); + at.setSelected(false); + //molecule.markAtomAsSelected(I, false); + AtomNode atom = (AtomNode) at.getProperty(ATOM_NODE); + //AtomNode atom = atomNodes.get(I); + highlightSelectedAtom(mol, atom, false); + selectedAtoms.remove(selectedAtoms.size() - 1); + + if (selectedAtoms.size() == 0) { + lastSelectedAtom = -1; + } else { + I = (Integer) selectedAtoms.get(selectedAtoms.size() - 1); + lastSelectedAtom = I; + } + //logger.info("undoLastSelection: selectedAtoms "+selectedAtoms.size()); + + temp_Group_1 = null; + temp_Group_2 = null; + temp_Group_3 = null; + temp_axis = null; + } + + public void resetGeometry() { + Molecule.setCoordinates(molecule, temp_structure); + updateMolecularGeometry(); + + switch (processingSelected) { + case SELECTED_MODIFY_BONDS: + setupModifyBondDialog(); + break; + + case SELECTED_MODIFY_ANGLES: + setupModifyAngleDialog(); + break; + + case SELECTED_MODIFY_DIHEDRALS: + setupModifyDihedralDialog(); + break; + + } + } + + public void confirmChanges() { + selectAllAtoms(false); + enableMousePicking(true); + } + + public void modifyDihedralAngleDialog() { + modifyDihedralAngleDialog(new Frame()); + } + + public void modifyDihedralAngleDialog(Frame parent) { + + if (molecule == null) { + JOptionPane.showMessageDialog(parent, "Load Molecule first!", "Warning", JOptionPane.WARNING_MESSAGE); + return; + } + + if (getMousePickingStatus()) { + JOptionPane.showMessageDialog(parent, "Another Selection is already in progress!", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + if (jModifyTorsionDialog == null) { + jModifyTorsionDialog = new JModifyTorsionDialog(parent, "Modify Selected Dihedral Angle", false); + jModifyTorsionDialog.setLocationRelativeTo(parent); + jModifyTorsionDialog.setTargetClass(this); + } + enableMousePicking(true); + selectedMode = SELECTION_FOUR_ATOMS_ONLY; + processingSelected = SELECTED_MODIFY_DIHEDRALS; + selectAndProcessDialog = true; + jModifyTorsionDialog.setVisible(true); + } + + private void setupModifyDihedralDialog() { + + if (selectedAtoms.size() < 4) { + return; + } + + Integer I = (Integer) selectedAtoms.get(0); + Integer J = (Integer) selectedAtoms.get(1); + Integer K = (Integer) selectedAtoms.get(2); + Integer L = (Integer) selectedAtoms.get(3); + + AtomInterface a_i = molecule.getAtomInterface(I); + AtomInterface a_j = molecule.getAtomInterface(J); + AtomInterface a_k = molecule.getAtomInterface(K); + AtomInterface a_l = molecule.getAtomInterface(L); + + double angle = dihedralAngle(a_i, a_j, a_k, a_l) + / 1.74532925199e-2; + jModifyTorsionDialog.setAngle(angle); + logger.info("jModifyTorsionDialog is setup"); + } + + public void changeDihedralForSelectedAtoms(float new_angle, + int I_atom_status, + int L_atom_status) { + if (selectedAtoms.size() < 4) { + return; // Simple error check + } + + Integer I = (Integer) selectedAtoms.get(0); + Integer J = (Integer) selectedAtoms.get(1); + Integer K = (Integer) selectedAtoms.get(2); + Integer L = (Integer) selectedAtoms.get(3); + + AtomInterface a_i = molecule.getAtomInterface(I.intValue()); + AtomInterface a_j = molecule.getAtomInterface(J.intValue()); + AtomInterface a_k = molecule.getAtomInterface(K.intValue()); + AtomInterface a_l = molecule.getAtomInterface(L.intValue()); + + // --- Form axis of rotation + if (temp_axis == null) { + temp_axis = new cct.vecmath.Point3f(a_j, a_k); // Rotation axis + + if (temp_axis.vectorNorm() < 0.00001f) { + JOptionPane.showMessageDialog(new JFrame(), + "Rotation Axis cannot be determined", + "Error", + JOptionPane.ERROR_MESSAGE); + //logger.info("axis.vectorSquaredNorm() < 0.00001f"); + return; + } + logger.info("Rotation Axis determined"); + } + + if (new_angle < -180.0f) { + new_angle = -180.0f; + } else if (new_angle > 180.0f) { + new_angle = 180.0f; + } + + float angle = (float) dihedralAngle(a_i, a_j, a_k, a_l); + float angleIncrement = 1.74532925199e-2f * new_angle - angle; + //logger.info("Angle: "+(angle/1.74532925199e-2f)+" new Angle: "+new_angle+" Increment: "+angleIncrement); + if (Math.abs(angleIncrement) < 0.01f) { + return; + } + //else if (angle + angleIncrement < 0) { + // return; + //} + float i_inc = angleIncrement / 2.0f; + float l_inc = angleIncrement / 2.0f; + + if (I_atom_status == FIXED_ATOM) { + i_inc = 0; + l_inc = angleIncrement; + } else if (L_atom_status == FIXED_ATOM) { + i_inc = angleIncrement; + l_inc = 0; + } + + // --- Rotate 1st Atom + if (I_atom_status == ROTATE_ATOM) { + rotateAtomAroundAxis(I.intValue(), -i_inc, a_j, a_k); + } else if (I_atom_status == ROTATE_GROUP) { + if (temp_Group_1 == null) { + if (a_i.isBondedTo(a_j)) { + temp_Group_1 = Molecule.noncyclicAtomGroup(a_j, a_k); + } else { + temp_Group_1 = Molecule.noncyclicAtomGroup(a_i, a_j, a_k); + } + //logger.info("I Group size: "+ temp_Group_1.size()); + } + + rotateAtomicGroupAroundAxis(temp_Group_1, -i_inc, a_j, a_k); + //translateAtomicGroup(temp_Group_1, direction, -i_inc); + } + + // --- Rotate 3d Atom + if (L_atom_status == ROTATE_ATOM) { + rotateAtomAroundAxis(L.intValue(), l_inc, a_j, a_k); + } else if (L_atom_status == ROTATE_GROUP) { + if (temp_Group_2 == null) { + if (a_l.isBondedTo(a_k)) { + temp_Group_2 = Molecule.noncyclicAtomGroup(a_k, a_j); + } else { + temp_Group_2 = Molecule.noncyclicAtomGroup(a_l, a_k, a_j); + } + //logger.info("L Group size: "+ temp_Group_2.size()); + } + + rotateAtomicGroupAroundAxis(temp_Group_2, l_inc, a_j, a_k); + //translateAtomicGroup(temp_Group_1, direction, -i_inc); + } + + //jModifyBondDialog.setBondLenght(new_distance); + } + + public void cancelSelection() { + cancelSelection(null); + } + + public void cancelSelection(JobProgressInterface progress) { + selectAllAtoms(false, progress); + enableMousePicking(false); + } + + public void clearSelection() { + clearSelection(null); + //selectAllAtoms(false); + } + + public void clearSelection(JobProgressInterface progress) { + selectAllAtoms(false, progress); + } + + public void selectAll() { + selectAll(null); + } + + public void selectAll(JobProgressInterface progress) { + selectAllAtoms(true, progress); + } + + public void invertSelection() { + invertSelection(null); + } + + public void invertSelection(JobProgressInterface progress) { + invertSelectedAtoms(progress); + } + + public Set getElementsInMolecule() { + return Molecule.getElementsInMolecule(molecule); + } + + public Set getAtomNamesInMolecule() { + return Molecule.getAtomNamesInMolecule(molecule); + } + + @Deprecated + public boolean openMolecularModelingFile(int fileType, String fileName, GlobalSettings.ADD_MOLECULE_MODE read_mode) { + if (fileType == MolecularFileFormats.formatG03_GJF) { // G03 Input file + + if (gaussianInputEditorFrame != null && gaussianInputEditorFrame.isVisible()) { + gaussianInputEditorFrame.setVisible(false); + } + + //Gaussian g = new Gaussian(); + gaussianData = new Gaussian(); + int n = gaussianData.parseGJF(fileName, 0); + logger.info("Number of molecules: " + n); + if (n > 1) { + if (gaussianInputEditorFrame == null) { + gaussianData.setGraphicsRenderer(this); + gaussianInputEditorFrame = new GaussianInputEditorFrame(gaussianData); + gaussianInputEditorFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); + try { + gaussianInputEditorFrame.removeMenuItem("File", "Exit"); + } catch (Exception ex) { + } + JMenuItem item = new JMenuItem("Select current step & return back to Editor"); + //GaussianInputEditorFrame_selectStep_actionAdapter al = new + // GaussianInputEditorFrame_selectStep_actionAdapter(); + + item.addActionListener(this); + gaussianInputEditorFrame.addMenuItem("File", item); + gaussianInputEditorFrame.returnBackButton.setVisible(true); + gaussianInputEditorFrame.returnBackButton.addActionListener(this); + + } + gaussianInputEditorFrame.setupEditor(gaussianData); + JOptionPane.showMessageDialog(null, "Gaussian Input file has more than 1 step\n" + "Select step in the next dialog", + "Info", JOptionPane.INFORMATION_MESSAGE); + + gaussianInputEditorFrame.setVisible(true); + //logger.info("Loading 1st Molecule..."); + } else { + MoleculeInterface m = Molecule.getNewInstance(); + m = gaussianData.getMolecule(m, 0); + if (m == null || m.getNumberOfAtoms() < 1) { + JOptionPane.showMessageDialog(null, "Didn't find atoms in file", "Warning", JOptionPane.WARNING_MESSAGE); + return false; + } + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + //MoleculeInterface m2 = Molecule.divideIntoMolecules(m); + setMolecule(m, read_mode); + } + //addGaussianData(g); + + } else if (fileType == MolecularFileFormats.formatG03_Output) { // G03 output file + MoleculeInterface m = Molecule.getNewInstance(); + GaussianOutput parseGaussianOutput = new GaussianOutput(); + //HashMap results = (HashMap) parseGaussianOutput.parseFile(m, fileName, false); + GaussianJob results; + try { + results = parseGaussianOutput.parseFile(m, fileName, false); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, "Cannot open file " + fileName + ": " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return false; + } + //m = (MoleculeInterface) results.get("molecule"); + m = results.getMolecule(0); + //Geometries = (ArrayList) results.get("geometries"); + Geometries = results.getGeometries(0); + if (Geometries == null || Geometries.size() == 0) { + JOptionPane.showMessageDialog(null, "No molecule found in file", "Error", JOptionPane.ERROR_MESSAGE); + return false; + } + + Frame parent = new Frame(); + + JShowText showResume = new JShowText("Gaussian Results"); + showResume.setSize(600, 640); + showResume.setTitle("Gaussian Results: " + fileName); + showResume.setLocationByPlatform(true); + showResume.setText(parseGaussianOutput.getOutputResume()); + showResume.setVisible(true); + + if (Geometries.size() > 1) { + + JChoiceDialog selectG = new JChoiceDialog(parent, + "Select Structure", true); + for (int i = 0; i < Geometries.size(); i++) { + MolecularGeometry gm = (MolecularGeometry) Geometries.get(i); + selectG.addItem(gm.getName()); + } + selectG.selectIndex(Geometries.size() - 1); + selectG.pack(); + + selectG.setLocationRelativeTo(parent); + selectG.setVisible(true); + if (selectG.isApproveOption()) { + int n = selectG.getSelectedIndex(); + if (n != -1) { + setupSelectedGeometry(m, n); + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, + CCTAtomTypes.getElementMapping()); + //MoleculeInterface m2 = Molecule.divideIntoMolecules(m); + setMolecule(m, read_mode); + } + + } + } else if (Geometries.size() == 1) { + //geometrySelection.setEnabled(false); deactivate geometry selection menu + setupSelectedGeometry(m, 0); + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + //MoleculeInterface m2 = Molecule.divideIntoMolecules(m); + setMolecule(m, read_mode); + } else { + JOptionPane.showMessageDialog(parent, "Didn't find geometries in output file", "Warning", JOptionPane.WARNING_MESSAGE); + } + + } else if (fileType == MolecularFileFormats.formatG03_Fragment) { // Gaussian fragment file + MoleculeInterface m = new Molecule(); + try { + m = GaussianFragment.parseGaussianFragmentFile(m, fileName); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return false; + } + setMolecule(m, read_mode); + } else if (fileType == MolecularFileFormats.format_XMol_XYZ) { // XMol XYZ file + MoleculeInterface m = new Molecule(); + try { + XMolXYZ xMolXYZ = new XMolXYZ(); + m = xMolXYZ.parseXMolXYZ(fileName, m); + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return false; + } + setMolecule(m, read_mode); + } else if (fileType == MolecularFileFormats.format_MDL_Molfile) { // MDL Molfile file + MoleculeInterface m = new Molecule(); + try { + MDLMol mol = new MDLMol(); + m = mol.parseFile(fileName, m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return false; + } + setMolecule(m, read_mode); + } else if (fileType == MolecularFileFormats.format_GRO) { // Gromacs GRO file + MoleculeInterface m = new Molecule(); + try { + m = GromacsParserFactory.parseGromacsCoordFile(fileName, m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return false; + } + setMolecule(m, read_mode); + } else if (fileType == MolecularFileFormats.formatPDB) { // PDB file + Molecule m = new Molecule(); + try { + PDB.parsePDBFile(fileName, m); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return false; + } + setMolecule(m, read_mode); + } else if (fileType == MolecularFileFormats.formatTripos_Mol2) { // Tripos Mol2 file + Molecule m = new Molecule(); + TriposParser triposParser = new TriposParser(); + try { + triposParser.parseMol2File(fileName, m); + setMolecule(m, read_mode); + } catch (Exception ex) { + logger.severe("Error opening " + fileName + " : " + ex.getMessage()); + } + } else if (fileType == MolecularFileFormats.formatCCT) { // CCT file + Molecule m = new Molecule(); + m.setAtomInterface(new Atom()); + m.setBondInterface(new Bond()); + CCTParser cctParser = new CCTParser(m); + List mols = cctParser.parseCCTFile(fileName, m); + m = (Molecule) mols.get(0); + logger.info("Number of atoms: " + m.getNumberOfAtoms()); + setMolecule(m, read_mode); + } + + return true; + } + + @Deprecated + public boolean openMolecularModelingFile(int fileType, String fileName) { + return openMolecularModelingFile(fileType, fileName, GlobalSettings.ADD_MOLECULE_MODE.SET); + } + + @Deprecated + public boolean openMolecularModelingFile(String fileType, String fileName) { + if (fileType == null || fileName == null) { + return false; + } + int formatType = MolecularFileFormats.formatUnknown; + if (fileType.equals(MolecularFileFormats.gaussian03GJF)) { + formatType = MolecularFileFormats.formatG03_GJF; + } else if (fileType.equals(MolecularFileFormats.gaussian03Output)) { + formatType = MolecularFileFormats.formatG03_Output; + } else if (fileType.equals(MolecularFileFormats.gaussianFragment)) { + formatType = MolecularFileFormats.formatG03_Fragment; + } else if (fileType.equals(MolecularFileFormats.pdbFile)) { + formatType = MolecularFileFormats.formatPDB; + } else if (fileType.equals(MolecularFileFormats.triposMol2)) { + formatType = MolecularFileFormats.formatTripos_Mol2; + } else if (fileType.equals(MolecularFileFormats.mdlMolfileFormat)) { + formatType = MolecularFileFormats.format_MDL_Molfile; + } else if (fileType.equals(MolecularFileFormats.gromacsGROFormat)) { + formatType = MolecularFileFormats.format_GRO; + } else if (fileType.equals(MolecularFileFormats.cctFileFormat)) { + formatType = MolecularFileFormats.formatCCT; + } else if (fileType.equals(MolecularFileFormats.xmolXYZFileFormat)) { + formatType = MolecularFileFormats.format_XMol_XYZ; + } + + return openMolecularModelingFile(formatType, fileName); + } + + public void setParentFrame(Frame parent) { + guiFrame = parent; + } + + private void jbInit() throws Exception { + atomLabelsFont = new Font(atomLabelsFontName, atomLabelsFontStyle, + atomLabelsFontSize); + } + + public void setHelper(HelperInterface h) { + helper = h; + super.setHelper(h); + } + + public Color getAtomLabelsColor() { + return new Color(atomLabelsColor.x, atomLabelsColor.y, atomLabelsColor.z); + } + + public void setAtomLabelsColor(Color color) { + if (color == null) { + return; + } + atomLabelsColor.set(color); + } + + public Font getAtomLabelsFont() { + return atomLabelsFont; + } + + public void getAtomLabelsFont(Font font) { + if (font == null) { + return; + } + atomLabelsFont = font; + atomLabelsFontSize = atomLabelsFont.getSize(); + atomLabelsFontStyle = atomLabelsFont.getStyle(); + atomLabelsFontName = atomLabelsFont.getFontName(); + } + + public List getGeometries() { + return Geometries; + } + + public int getSelectedGeometry() { + return selectedGeometry; + } + + public void setGeometries(List geoms) { + Geometries = geoms; + } + + public int getLastSelectedAtom() { + return lastSelectedAtom; + } + + @Deprecated + public int setupSelectedGeometry(MoleculeInterface molec, int n) { + if (n < 0 || n >= Geometries.size()) { + logger.info( + "setupSelectedGeometry: n < 0 || n >= Geometries.size()"); + return -1; + } + MolecularGeometry geom = (MolecularGeometry) Geometries.get(n); + if (geom.size() != molec.getNumberOfAtoms()) { + logger.info( + "setupSelectedGeometry: geom.size() != getNumberOfAtoms() " + + geom.size() + " != " + molec.getNumberOfAtoms()); + return -1; + } + + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + cct.vecmath.Point3f point = geom.getCoordinates(i); + AtomInterface atom = molec.getAtomInterface(i); + atom.setXYZ(point); + } + selectedGeometry = n; + return n; + } + + /** + * @deprecated - use from fragmentDictionaryParser + * @param fragmentDic URL + * @throws Exception + */ + public void setFragmentDictionary(URL fragmentDic) throws Exception { + + fragmentDictionary = fragmentDic; + fragmentsReferences.clear(); + + if (fragmentDic.getProtocol().equalsIgnoreCase("jar") || fragmentDic.getProtocol().equalsIgnoreCase("zip")) { + fragContext = fragmentDic.toString(); + fragContext = fragContext.substring(0, fragContext.indexOf("!/") + 2); + } else { + throw new Exception("setFragmentsBaseDirectory: don't know how to work with protocol: " + fragmentDic.getProtocol()); + } + + logger.info("Protocol: " + fragmentDic.getProtocol() + " Context: " + fragContext); + } + + /** + * @deprecated. Use loadFragment(MoleculeInterface m) + * @param specification String + */ + public void loadFragment(String specification) { + String urlAddress = fragContext + specification; + URL url = null; + try { + url = new URL(urlAddress); + } catch (java.net.MalformedURLException ex) { + JOptionPane.showMessageDialog(null, "Loading fragment: " + specification + " : " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + InputStream is = null; + try { + is = url.openStream(); + } catch (IOException ex) { + JOptionPane.showMessageDialog(null, "Loading fragment: " + specification + " : " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + MoleculeInterface m = new Molecule(); + CCTParser cctParser = new CCTParser(m); + List mols = cctParser.parseCCTFile(is, m); + m = (MoleculeInterface) mols.get(0); + logger.info("Number of atoms: " + m.getNumberOfAtoms()); + + if (m.getNumberOfAtoms() < 1) { + return; + } + + addMolecule(m); + + AtomInterface atom = null; + int nPickable = 0; + int lastPickable = 0; + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + atom = molecule.getAtomInterface(i); + Boolean pickable = (Boolean) atom.getProperty(AtomInterface.PICKABILITY); + logger.info("Atom " + i + " : " + pickable); + if (pickable == null || !pickable.booleanValue()) { + enableAtomPicking(i, false); + logger.info("Atom " + i + " non-pickable"); + } else { + ++nPickable; + lastPickable = i; + } + } + + if (nPickable == 1) { + lastSelectedAtom = lastPickable; + atom.setSelected(true); + this.highlightSelectedAtom(lastPickable, true); + } else if (nPickable == 0) { // Enable picking for H's and Du's + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + atom = molecule.getAtomInterface(i); + if (atom.getAtomicNumber() == 0 || atom.getAtomicNumber() == 1) { + enableAtomPicking(i, true); + } + } + this.enableMousePicking(true); + } else { + this.enableMousePicking(true); + } + } + + public void loadFragment(MoleculeInterface m) { + + if (m.getNumberOfAtoms() < 1) { + return; + } + + addMolecule(m); + + AtomInterface atom = null; + int nPickable = 0; + int lastPickable = 0; + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + atom = molecule.getAtomInterface(i); + Boolean pickable = (Boolean) atom.getProperty(AtomInterface.PICKABILITY); + logger.info("Atom " + i + " : " + pickable); + if (pickable == null || !pickable.booleanValue()) { + enableAtomPicking(i, false); + logger.info("Atom " + i + " non-pickable"); + } else { + ++nPickable; + lastPickable = i; + } + } + + if (nPickable == 1) { + lastSelectedAtom = lastPickable; + atom.setSelected(true); + this.highlightSelectedAtom(lastPickable, true); + } else if (nPickable == 0) { // Enable picking for H's and Du's + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + atom = molecule.getAtomInterface(i); + if (atom.getAtomicNumber() == 0 || atom.getAtomicNumber() == 1) { + enableAtomPicking(i, true); + } + } + this.enableMousePicking(true); + } else { + this.enableMousePicking(true); + } + } + + /** + * Does solvation + * + * @param solvationType int + */ + void openSolvateMoleculeDialog(int solvationType) { + + InputStream is = null; + //if (selectDefaultSolvent == null) { + if (jSolvateShellDialog == null) { + URL fragDic = null; + //ClassLoader cl = cct.resources.Resources.class.getClassLoader(); + ClassLoader cl = Java3dUniverse.class.getClassLoader(); + + try { + //fragDic = cl.getResource(cct.GlobalSettings. + // getDefaultSolventDictionary()); + fragDic = cl.getResource(cct.GlobalSettings.getDefaultSolventDictionary()); + logger.info("File: " + fragDic.getFile() + " path: " + fragDic.getPath() + " " + fragDic.toString()); + logger.info("Protocol: " + fragDic.getProtocol()); + + setSolventDictionary(fragDic); + } catch (Exception ex) { + logger.info( + "Unable to get Resources " + cct.GlobalSettings.getDefaultSolventDictionary() + " Trying System Resources..."); + try { + fragDic = ClassLoader.getSystemResource(cct.GlobalSettings.getDefaultSolventDictionary()); + setSolventDictionary(fragDic); + } catch (Exception e) { + System.err.println(getClass().getCanonicalName() + " : " + ex.getMessage()); + return; + } + } + + try { + + //logger.info("Query: " + fragDic.getQuery()); + is = cl.getResourceAsStream(cct.GlobalSettings.getDefaultSolventDictionary()); + + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, "Error opening default solvent dictionary: " + + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + + System.err.println(getClass().getCanonicalName() + " : " + + ex.getMessage()); + return; + } + FragmentDictionaryParser fdp = new FragmentDictionaryParser(); + Map fragTree = FragmentDictionaryParser.parseFragmentDictionary(is); + // We use only a simpified list... !!! + //ArrayList simpleList = new ArrayList(); + defaultSolventList = new HashMap(); + defaultSolventList = Utils.toSimpleList(fragTree, defaultSolventList); + jSolvateShellDialog = new JSolvateShellDialog(null, "Select Solvation Parameters", true, defaultSolventList); + + jSolvateShellDialog.setAlwaysOnTop( + true); + } + jSolvateShellDialog.setVisible(true); + + if (!jSolvateShellDialog.isOKpressed()) { + return; // Cancel was pressed + } + + float radius = 0; + try { + radius = jSolvateShellDialog.getRadius(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, "ERROR: Wrong value for radius: " + jSolvateShellDialog.getRadiusAsText(), + "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + float closeness = 0; + try { + closeness = jSolvateShellDialog.getCloseness(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, "ERROR: Wrong value for closeness: " + jSolvateShellDialog.getClosenessAsText(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + String solvent = jSolvateShellDialog.getSelectedItem().toString(); + String value = (String) defaultSolventList.get(solvent); + + MoleculeInterface m = null; + + if (processingSelected == SELECTED_SOLVATE_CAP + || processingSelected == SELECTED_SOLVATE_SHELL) { + if (jSolvateShellDialog.isPredefinedSolvent()) { + String urlAddress = solventContext + value; + URL url = null; + try { + url = new URL(urlAddress); + } catch (java.net.MalformedURLException ex) { + JOptionPane.showMessageDialog(null, "Loading solvent: " + value + " : " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + try { + is = url.openStream(); + } catch (IOException ex) { + JOptionPane.showMessageDialog(null, "Loading fragment: " + value + " : " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + m = new Molecule(); + CCTParser cctParser = new CCTParser(m); + List mols = cctParser.parseCCTFile(is, m); + m = (MoleculeInterface) mols.get(0); + } else { // Custom molecule + Object[] obj = jSolvateShellDialog.getCustomObjects(); + if (obj == null || obj.length < 1 || !(obj[0] instanceof MoleculeInterface)) { + JOptionPane.showMessageDialog(null, "No custom solvent molecule", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + m = (MoleculeInterface) obj[0]; + } + + MoleculeInterface shell = Molecule.generateSolventShell(molecule, m, radius, closeness, processingSelected); + + this.appendMolecule(shell, false); + } + + } + + /** + * Setup base directory(URL) for the default Solvent dictionary + * + * @param fragmentDic URL + * @throws Exception + */ + public void setSolventDictionary(URL fragmentDic) throws Exception { + + solventDictionary = fragmentDic; + + if (fragmentDic.getProtocol().equalsIgnoreCase("jar")) { + solventContext = fragmentDic.toString(); + solventContext = solventContext.substring(0, + solventContext.indexOf("!/") + + 2); + } else { + throw new Exception( + "setSolventBaseDirectory: don't know how to work with protocol: " + + fragmentDic.getProtocol()); + } + + logger.info("Protocol: " + fragmentDic.getProtocol() + + " Context: " + solventContext); + + } + + public void getSelectedBranch(String value) { + //SELECTED_SOLVATE_CAP: + //SELECTED_SOLVATE_SHELL: + } + + public void cancelTreeSelection() { + endProcessingSelectedAtoms(); + } + + public void solvateMolecule(MoleculeInterface solvent, int solvationType) { + } + + public void updateAtomColorScheme() { + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface a = molecule.getAtomInterface(i); + //BranchGroup atom = (BranchGroup) atomNodes.get(i); + Color3f color3f = ChemicalElementsColors.getElementColor(a.getAtomicNumber()); + Material material = ChemicalElementsColors.getElementMaterial(a.getAtomicNumber()); + setAtomColor(i, color3f, material); + + List bonds = a.getBondIndex(); + for (int j = 0; j < bonds.size(); j++) { + BondInterface bond = (BondInterface) bonds.get(j); + int bindex = molecule.getBondIndex(bond); + if (bindex == -1) { + continue; + } + BondNode bondNode = this.bondNodes.get(bindex); + //bondNode.detach(); + mol.removeChild(bondNode); + bondNode.updateBondColor(); + mol.addChild(bondNode); + } + } + } + + public BufferedImage getImageCapture() { + BufferedImage bImage = null; + /* + * // Create the off-screen Canvas3D object OffScreenCanvas3D offScreenCanvas3D = new OffScreenCanvas3D(config, true); // Set + * the off-screen size based on a scale factor times the // on-screen size Screen3D sOn = canvas3D.getScreen3D(); Screen3D sOff + * = offScreenCanvas3D.getScreen3D(); Dimension dim = sOn.getSize(); //dim.width *= OFF_SCREEN_SCALE; //dim.height *= + * OFF_SCREEN_SCALE; sOff.setSize(dim); sOff.setPhysicalScreenWidth(sOn.getPhysicalScreenWidth() ); // OFF_SCREEN_SCALE); + * sOff.setPhysicalScreenHeight(sOn.getPhysicalScreenHeight() ); // OFF_SCREEN_SCALE); + * + * // attach the offscreen canvas to the view //view.addCanvas3D(offScreenCanvas3D); + * simpleU.getViewer().getView().addCanvas3D(offScreenCanvas3D); + */ + + Screen3D sOn = canvas3D.getScreen3D(); + Screen3D sOff = offScreenCanvas3D.getScreen3D(); + Dimension dim = sOn.getSize(); + sOff.setSize(dim); + sOff.setPhysicalScreenWidth(sOn.getPhysicalScreenWidth()); + + sOff.setPhysicalScreenHeight(sOn.getPhysicalScreenHeight()); + + Point loc = canvas3D.getLocationOnScreen(); + offScreenCanvas3D.setOffScreenLocation(loc); + dim = canvas3D.getSize(); + //dim.width *= OFF_SCREEN_SCALE; + //dim.height *= OFF_SCREEN_SCALE; + bImage = offScreenCanvas3D.doRender(dim.width, dim.height); + + MediaTracker mediaTracker = new MediaTracker(new Container()); + mediaTracker.addImage(bImage, 0); + try { + mediaTracker.waitForID(0); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + } + + return bImage; + } + + public int findClosestAtom(int x, int y) { + + Point3d origin = new Point3d(); + Point3d mouse_pos = new Point3d(); + + canvas3D.getCenterEyeInImagePlate(origin); + canvas3D.getPixelLocationInImagePlate(x, y, mouse_pos); + + Transform3D motion = new Transform3D(); + canvas3D.getImagePlateToVworld(motion); + motion.transform(origin); + motion.transform(mouse_pos); + + Vector3d dir = new Vector3d(mouse_pos); + dir.sub(origin); + + return findClosestAtom(origin, dir); + } + + public ProcessMouseRotate getMouseRotate() { + return behavior; + } + + public int findClosestBond(int x, int y) { + + Point3d origin = new Point3d(); + Point3d mouse_pos = new Point3d(); + + canvas3D.getCenterEyeInImagePlate(origin); + canvas3D.getPixelLocationInImagePlate(x, y, mouse_pos); + + Transform3D motion = new Transform3D(); + canvas3D.getImagePlateToVworld(motion); + motion.transform(origin); + motion.transform(mouse_pos); + + Vector3d dir = new Vector3d(mouse_pos); + dir.sub(origin); + + return findClosestBond(origin, dir); + } + + public boolean atomInfoPopupEnabled() { + return atomInfoPopup; + } + + public void enableAtomInfoPopup(boolean enable) { + atomInfoPopup = enable; + if (atomInfoPopup) { + canvas3D.addMouseMotionListener(tracer); + } else { + canvas3D.removeMouseMotionListener(tracer); + } + } + + public List getSelectedAtoms() { + return trackSelectedAtoms; + } + + public void setGlobalRenderingStyle(int style) throws Exception { + if (!renderStyles.containsValue(new Integer(style))) { + throw new Exception("Unknown rendering style"); + } + + setRenderingParameters(style); + } + + public void setGlobalRenderingStyle(String style) throws Exception { + if (!renderStyles.containsKey(style)) { + throw new Exception("Unknown rendering style: " + style); + } + Integer st = (Integer) renderStyles.get(style); + setRenderingParameters(st); + + // --- Inform listeners about event + if (renderingListeners.size() > 0) { + RenderingObject rObj = new RenderingObject(this); + for (int i = 0; i < renderingListeners.size(); i++) { + renderingListeners.get(i).renderingChanged(rObj); + } + } + } + + public String[] getRenderingStyles() { + String[] styles = new String[renderStyles.size()]; + Set keys = renderStyles.keySet(); + int i = 0; + for (Iterator iter = keys.iterator(); iter.hasNext(); i++) { + styles[i] = (String) iter.next(); + } + return styles; + } + + public void actionPerformed(ActionEvent e) { + gaussianInputEditorFrame.setVisible(false); + int n = gaussianInputEditorFrame.getSelectedStep(); + MoleculeInterface m = Molecule.getNewInstance(); + m = gaussianData.getMolecule(m, n); + Molecule.guessCovalentBonds(m); + //MoleculeInterface m2 = Molecule.divideIntoMolecules(m); + addMolecule(m); + if (this.processingSelected == SELECTED_ADD_MOLECULE) { + enableMousePicking(true); + } + } + + public void updateSelectedAtomLabelsSize(double value) { + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface a = molecule.getAtomInterface(i); + if (!a.isSelected()) { + continue; + } + + LabelNode label = (LabelNode) this.atomLabels.get(i); + if (label == null) { + continue; + } + label.setTextSize(value); + } + } + + public void updateSelectedAtomLabelsColor(Color color) { + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface a = molecule.getAtomInterface(i); + if (!a.isSelected()) { + continue; + } + + LabelNode label = (LabelNode) this.atomLabels.get(i); + if (label == null) { + continue; + } + label.setColor(color); + } + } + + public void addGraphics(GraphicsObjectInterface graphics) { + if (graphicsObjects == null) { + graphicsObjects = new ArrayList(); + } + + List shape3ds = graphics.getShape3DElements(); + if (shape3ds == null || shape3ds.size() < 1) { + return; + } + + for (int i = 0; i < shape3ds.size(); i++) { + Object obj = shape3ds.get(i); + if (obj instanceof Shape3D) { + Shape3D shape3d = (Shape3D) obj; + BranchGroup bGroup = new BranchGroup(); + bGroup.setCapability(BranchGroup.ALLOW_CHILDREN_READ); + bGroup.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE); + bGroup.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND); + bGroup.setCapability(BranchGroup.ALLOW_DETACH); + try { + bGroup.addChild(shape3d); + moleculeTrans.addChild(bGroup); + } catch (Exception ex) { + System.err.println("Error adding shape: " + ex.getMessage()); + } + } else if (obj instanceof BranchGroup) { + moleculeTrans.addChild((BranchGroup) obj); + } + } + graphicsObjects.add(graphics); + } + + public int getNumberOfGraphicsObjects() { + if (graphicsObjects == null) { + return 0; + } + return graphicsObjects.size(); + } + + public GraphicsObjectInterface getGraphicsObject(int n) { + if (graphicsObjects == null || n < 0 || n >= graphicsObjects.size()) { + System.err.println("graphicsObjects == null || n <0 || n>=graphicsObjects.size()"); + return null; + } + return graphicsObjects.get(n); + } + + public List getGraphicsObjects() { + return graphicsObjects; + + } + + + private class GaussianInputEditorFrame_selectStep_actionAdapter + implements ActionListener { + + public void actionPerformed(ActionEvent e) { + gaussianInputEditorFrame.setVisible(false); + int n = gaussianInputEditorFrame.getSelectedStep(); + MoleculeInterface m = Molecule.getNewInstance(); + m = gaussianData.getMolecule(m, n); + Molecule.guessCovalentBonds(m); + //MoleculeInterface m2 = Molecule.divideIntoMolecules(m); + addMolecule(m); + if (getMousePickingStatus()) { + enableMousePicking(true); + } + } + } +} // End of SampleFrame class + diff --git a/src/main/java/cct/j3d/Java3dUtils.java b/src/main/java/cct/j3d/Java3dUtils.java new file mode 100644 index 0000000..576bbeb --- /dev/null +++ b/src/main/java/cct/j3d/Java3dUtils.java @@ -0,0 +1,138 @@ +package cct.j3d; + +import org.scijava.vecmath.AxisAngle4d; +import org.scijava.vecmath.Matrix3d; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class Java3dUtils { + private Java3dUtils() { + } + + static public void toAxisAngle(Matrix3d m, AxisAngle4d axisAngle4d) { + double angle, x, y, z; // variables for result + double epsilon = 0.01; // margin to allow for rounding errors + double epsilon2 = 0.1; // margin to distinguish between 0 and 180 degrees + // optional check that input is pure rotation, 'isRotationMatrix' is defined at: + // http://www.euclideanspace.com/maths/algebra/matrix/orthogonal/rotation/ + + //assert isRotationMatrix(m):"not valid rotation matrix"; // for debugging + + //if ( (Math.abs(m[0][1] - m[1][0]) < epsilon) + // && (Math.abs(m[0][2] - m[2][0]) < epsilon) + // && (Math.abs(m[1][2] - m[2][1]) < epsilon)) { + + if ( (Math.abs(m.m01 - m.m10) < epsilon) && (Math.abs(m.m02 - m.m20) < epsilon) && (Math.abs(m.m12 - m.m21) < epsilon)) { + + // singularity found + // first check for identity matrix which must have +1 for all terms + // in leading diagonaland zero in other terms + + //if ( (Math.abs(m[0][1] + m[1][0]) < epsilon2) + // && (Math.abs(m[0][2] + m[2][0]) < epsilon2) + // && (Math.abs(m[1][2] + m[2][1]) < epsilon2) + // && (Math.abs(m[0][0] + m[1][1] + m[2][2] - 3) < epsilon2)) { + + if ( (Math.abs(m.m01 + m.m10) < epsilon2) && (Math.abs(m.m02 + m.m20) < epsilon2) && (Math.abs(m.m12 + m.m21) < epsilon2) && + (Math.abs(m.m00 + m.m11 + m.m22 - 3) < epsilon2)) { + + // this singularity is identity matrix so angle = 0 + //return new axisAngle(0, 1, 0, 0); // zero angle, arbitrary axis + axisAngle4d.set(1, 0, 0, 0); + return; + } + + // otherwise this singularity is angle = 180 + angle = Math.PI; + + //double xx = (m[0][0] + 1) / 2; + //double yy = (m[1][1] + 1) / 2; + //double zz = (m[2][2] + 1) / 2; + //double xy = (m[0][1] + m[1][0]) / 4; + //double xz = (m[0][2] + m[2][0]) / 4; + //double yz = (m[1][2] + m[2][1]) / 4; + + double xx = (m.m00 + 1) / 2; + double yy = (m.m11 + 1) / 2; + double zz = (m.m22 + 1) / 2; + double xy = (m.m01 + m.m10) / 4; + double xz = (m.m02 + m.m20) / 4; + double yz = (m.m12 + m.m21) / 4; + + if ( (xx > yy) && (xx > zz)) { // m[0][0] is the largest diagonal term + if (xx < epsilon) { + x = 0; + y = 0.7071; + z = 0.7071; + } + else { + x = Math.sqrt(xx); + y = xy / x; + z = xz / x; + } + } + else if (yy > zz) { // m[1][1] is the largest diagonal term + if (yy < epsilon) { + x = 0.7071; + y = 0; + z = 0.7071; + } + else { + y = Math.sqrt(yy); + x = xy / y; + z = yz / y; + } + } + else { // m[2][2] is the largest diagonal term so base result on this + if (zz < epsilon) { + x = 0.7071; + y = 0.7071; + z = 0; + } + else { + z = Math.sqrt(zz); + x = xz / z; + y = yz / z; + } + } + //return new axisAngle(angle, x, y, z); // return 180 deg rotation + axisAngle4d.set(x, y, z, angle); + return; + } + + // as we have reached here there are no singularities so we can handle normally + //double s = Math.sqrt( (m[2][1] - m[1][2]) * (m[2][1] - m[1][2]) + // + (m[0][2] - m[2][0]) * (m[0][2] - m[2][0]) + // + (m[1][0] - m[0][1]) * (m[1][0] - m[0][1])); // used to normalise + double s = Math.sqrt( (m.m21 - m.m12) * (m.m21 - m.m12) + (m.m02 - m.m20) * (m.m02 - m.m20) + (m.m10 - m.m01) * (m.m10 - m.m01)); // used to normalise + + if (Math.abs(s) < 0.001) { + s = 1; + } + // prevent divide by zero, should not happen if matrix is orthogonal and should be + // caught by singularity test above, but I've left it in just in case + //angle = Math.acos( (m[0][0] + m[1][1] + m[2][2] - 1) / 2); + //x = (m[2][1] - m[1][2]) / s; + //y = (m[0][2] - m[2][0]) / s; + //z = (m[1][0] - m[0][1]) / s; + + angle = Math.acos( (m.m00 + m.m11 + m.m22 - 1) / 2); + x = (m.m21 - m.m12) / s; + y = (m.m02 - m.m20) / s; + z = (m.m10 - m.m01) / s; + + //return new axisAngle(angle, x, y, z); + axisAngle4d.set(x, y, z, angle); + } + +} diff --git a/src/main/java/cct/j3d/KeyHandler.java b/src/main/java/cct/j3d/KeyHandler.java new file mode 100644 index 0000000..89cbda7 --- /dev/null +++ b/src/main/java/cct/j3d/KeyHandler.java @@ -0,0 +1,156 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import java.awt.AWTEvent; +import java.util.Enumeration; +import java.util.logging.Logger; + +import org.scijava.java3d.Behavior; +import org.scijava.java3d.Transform3D; +import org.scijava.java3d.TransformGroup; +import org.scijava.java3d.WakeupOnAWTEvent; + +public class KeyHandler + extends Behavior { + + private TransformGroup targetTG; + private Transform3D rotation = new Transform3D(); + private Transform3D rotationX = new Transform3D(); + private Transform3D rotationY = new Transform3D(); + private double angleX = 0.0; + private double angleY = 0.0; + private WakeupOnAWTEvent KeyEvent = new WakeupOnAWTEvent(java.awt.event.KeyEvent.KEY_PRESSED); + static final Logger logger = Logger.getLogger(KeyHandler.class.getCanonicalName()); + + // create SimpleBehavior + KeyHandler(TransformGroup targetTG) { + this.targetTG = targetTG; + } + + // initialize the Behavior + // set initial wakeup condition + // called when behavior beacomes live + @Override + public void initialize() { + // set initial wakeup condition + this.wakeupOn(KeyEvent); + } + + // behave + // called by Java 3D when appropriate stimulus occures + @Override + public void processStimulus(Enumeration criteria) { + if (KeyEvent.hasTriggered()) { + AWTEvent events[] = KeyEvent.getAWTEvent(); + //java.awt.event.KeyEvent events[] = KeyEvent.getAWTEvent(); + + for (int i = 0; i < events.length; i++) { + String params = events[i].toString(); + //logger.info("KeyHandler: Id:" + events[i].getID() + + // " Param: " + params ); + // decode event + + targetTG.getTransform(rotation); + rotationX.set(Transform3D.IDENTITY); + rotationY.set(Transform3D.IDENTITY); + //if ( params.matches("keyCode=38")) { + if (params.indexOf("keyCode=38") != -1) { + // do what is necessary + angleX = -0.1; + rotationX.rotX(angleX); + //rotationY.rotY(angleY); + //rotation.mul( rotationY ); + //rotation.mul( rotationX ); + rotationX.mul(rotation); + //targetTG.setTransform(rotation); + targetTG.setTransform(rotationX); + logger.info("Rotating..."); + } + else if (params.indexOf("keyCode=40") != -1) { + // do what is necessary + angleX = 0.1; + rotationX.rotX(angleX); + //rotationY.rotY(angleY); + //rotation.mul( rotationY ); + //rotation.mul( rotationX ); + //targetTG.setTransform(rotation); + rotationX.mul(rotation); + targetTG.setTransform(rotationX); + + logger.info("Rotating..."); + } + else if (params.indexOf("keyCode=39") != -1) { + // do what is necessary + angleY = 0.1; + //rotationX.rotX(angleX); + rotationY.rotY(angleY); + //rotation.mul( rotationY ); + rotationY.mul(rotation); + //rotation.mul( rotationX ); + targetTG.setTransform(rotationY); + + logger.info("Rotating..."); + } + else if (params.indexOf("keyCode=37") != -1) { + // do what is necessary + angleY = -0.1; + //rotationX.rotX(angleX); + rotationY.rotY(angleY); + //rotation.mul( rotationX ); + //rotation.mul( rotationY ); + //targetTG.setTransform(rotation); + rotationY.mul(rotation); + targetTG.setTransform(rotationY); + /* + rotationX.rotX(angleX); + rotationY.rotY(angleY); + rotationY.mul( rotationX ); + targetTG.setTransform(rotationY); + */ + + logger.info("Rotating..."); + } + + } + + } + this.wakeupOn(KeyEvent); + } + +} // end of class SimpleBehavior diff --git a/src/main/java/cct/j3d/LabelNode.java b/src/main/java/cct/j3d/LabelNode.java new file mode 100644 index 0000000..0ff1ac5 --- /dev/null +++ b/src/main/java/cct/j3d/LabelNode.java @@ -0,0 +1,267 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import java.awt.Color; +import java.awt.Font; + +import org.scijava.java3d.Appearance; +import org.scijava.java3d.BranchGroup; +import org.scijava.java3d.Group; +import org.scijava.java3d.Material; +import org.scijava.java3d.Shape3D; +import org.scijava.java3d.Transform3D; +import org.scijava.java3d.TransformGroup; +import org.scijava.vecmath.Color3f; +import org.scijava.vecmath.Matrix3d; +import org.scijava.vecmath.Point3f; +import org.scijava.vecmath.Vector3d; +import org.scijava.vecmath.Vector3f; + +import org.scijava.java3d.utils.geometry.Text2D; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +/* + A Text2D object is a representation of a string as a texture mapped rectangle. + The texture for the rectangle shows the string as rendered in the specified color + with a transparent background. The appearance of the characters is specified + using the font indicated by the font name, size and style (see java.awt.Font). + The approximate height of the rendered string will be the font size times the + rectangle scale factor, which has a default value of 1/256. + For example, a 12 point font will produce characters that are about + 12/256 = 0.047 meters tall. The lower left corner of the rectangle is + located at (0,0,0) with the height extending along the positive y-axis + and the width extending along the positive x-axis. + */ + +public class LabelNode + extends BranchGroup { + + BranchGroup branchGroupLabel = new BranchGroup(); + Text2D label; + Transform3D transl_center; + Vector3f coordCenter; + TransformGroup center; + float shiftFromCenter; + Color3f labelColor = new Color3f(Color.green); + Appearance labelAppearance = null; + int fontSize = 75; + int fontStyle = Font.ITALIC; + String fontName = "Helvetica"; + Transform3D move = new Transform3D(); + TransformGroup shift = new TransformGroup(); + Transform3D rotate_label = new Transform3D(); + TransformGroup rotate = new TransformGroup(); + float angle = 0; + float rectangleScaleFactor; + + public LabelNode(Vector3f coord, String text) { + createLabel(coord, text, labelColor, fontName, fontSize, + Font.ITALIC); + } + + public LabelNode(Vector3f coord, String text, Color3f color, Font font) { + this(coord, text, color, font.getFontName(), font.getSize(), + font.getStyle()); + } + + public LabelNode(Vector3f coord, String text, Color3f color, + String font_name, int font_size, int font_style) { + + } + + public void createLabel(Vector3f coord, String text, Color3f color, + String font_name, int font_size, int font_style) { + + fontSize = font_size; + fontStyle = font_style; + fontName = font_name; + + labelColor.set(color); + + coordCenter = coord; + + transl_center = new Transform3D(); + transl_center.setTranslation(coord); + center = new TransformGroup(); + center.setTransform(transl_center); + + label = createLabel(text, color, font_name, font_size, font_style); + rectangleScaleFactor = label.getRectangleScaleFactor(); + + //label = new Text2D(text, color, "Helvetica", 50, Font.ITALIC); + //new Color3f(0.9f, 1.0f, 1.0f), + + branchGroupLabel.setCapability(Group.ALLOW_CHILDREN_READ); + branchGroupLabel.setCapability(Group.ALLOW_CHILDREN_WRITE); + branchGroupLabel.setCapability(BranchGroup.ALLOW_DETACH); + + branchGroupLabel.addChild(label); + + rotate.setTransform(rotate_label); + rotate.addChild(branchGroupLabel); + + shift.setTransform(move); + shift.addChild(rotate); + + center.addChild(shift); + this.addChild(center); + + setCapability(BranchGroup.ALLOW_DETACH); + setCapability(Group.ALLOW_CHILDREN_READ); + setCapability(Group.ALLOW_CHILDREN_WRITE); + + rotate.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); + rotate.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + rotate.setCapability(Group.ALLOW_CHILDREN_READ); + rotate.setCapability(Group.ALLOW_CHILDREN_WRITE); + rotate.setCapability(Group.ALLOW_CHILDREN_EXTEND); + + shift.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); + shift.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + } + + Text2D createLabel(String text, Color3f color, + String font_name, int font_size, int font_style) { + + Text2D label_text = new Text2D(text, color, font_name, font_size, + font_style); + label_text.setCapability(Shape3D.ALLOW_GEOMETRY_READ); + label_text.setCapability(Shape3D.ALLOW_GEOMETRY_WRITE); + label_text.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_READ); + label_text.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_WRITE); + label_text.setCapability(Shape3D.ALLOW_APPEARANCE_READ); + label_text.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); + label_text.setCapability(Shape3D.ALLOW_GEOMETRY_READ); + label_text.setCapability(Shape3D.ALLOW_GEOMETRY_WRITE); + + labelAppearance = label_text.getAppearance(); + labelAppearance.setCapability(Appearance.ALLOW_COLORING_ATTRIBUTES_READ); + labelAppearance.setCapability(Appearance.ALLOW_COLORING_ATTRIBUTES_WRITE); + labelAppearance.setCapability(Appearance.ALLOW_MATERIAL_READ); + labelAppearance.setCapability(Appearance.ALLOW_MATERIAL_WRITE); + + labelAppearance.getMaterial().setCapability(Material.ALLOW_COMPONENT_READ); + labelAppearance.getMaterial().setCapability(Material. + ALLOW_COMPONENT_WRITE); + + labelAppearance.setCapability(Appearance.ALLOW_TEXTURE_ATTRIBUTES_READ); + labelAppearance.setCapability(Appearance.ALLOW_TEXTURE_ATTRIBUTES_WRITE); + + //label = new Text2D(text, color, "Helvetica", 50, Font.ITALIC); + //new Color3f(0.9f, 1.0f, 1.0f), + + return label_text; + } + + public void setShift(Vector3d dir) { + shiftFromCenter = (float) dir.length(); + shift.getTransform(move); + move.setTranslation(dir); + shift.setTransform(move); + } + + public float getShift() { + return shiftFromCenter; + } + + public void updateRotation(Matrix3d rotation) { + rotate.getTransform(rotate_label); + rotate_label.setRotation(rotation); + rotate.setTransform(rotate_label); + } + + public void getCenterCoord(Vector3f coord) { + coord.set(coordCenter); + } + + public void getCenterCoord(Point3f coord) { + coord.set(coordCenter); + } + + public void setTextSize(double value) { + float rectangle_scale_factor = label.getRectangleScaleFactor(); + rectangleScaleFactor = (float) value / fontSize; + label.setRectangleScaleFactor(rectangleScaleFactor); + } + + public void setColor(Color color) { + //ColoringAttributes ca = labelAppearance.getColoringAttributes(); + //ca.setColor(new Color3f(color)); + //labelAppearance.setColoringAttributes(ca); + /* + Material material = labelAppearance.getMaterial(); + Color3f color3f = new Color3f(); + material.getAmbientColor(color3f); + logger.info("Ambient:" + color3f.x + " " + color3f.y + " " + + color3f.z); + material.getDiffuseColor(color3f); + logger.info("Diffuse:" + color3f.x + " " + color3f.y + " " + + color3f.z); + material.getEmissiveColor(color3f); + logger.info("Emissive:" + color3f.x + " " + color3f.y + " " + + color3f.z); + material.getSpecularColor(color3f); + logger.info("Specular:" + color3f.x + " " + color3f.y + " " + + color3f.z); + + TextureAttributes ta = labelAppearance.getTextureAttributes(); + */ + + branchGroupLabel.detach(); + branchGroupLabel.removeChild(label); + String text = label.getString(); + label = this.createLabel(text, new Color3f(color), fontName, fontSize, + fontStyle); + label.setRectangleScaleFactor(rectangleScaleFactor); + branchGroupLabel.addChild(label); + rotate.addChild(branchGroupLabel); + } + +} diff --git a/src/main/java/cct/j3d/MoleculeNode.java b/src/main/java/cct/j3d/MoleculeNode.java new file mode 100644 index 0000000..e562608 --- /dev/null +++ b/src/main/java/cct/j3d/MoleculeNode.java @@ -0,0 +1,85 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.j3d; + +import java.util.HashSet; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.scijava.java3d.BranchGroup; + +/** + * + * @author Vlad + */ +public class MoleculeNode extends BranchGroup { + + static final Logger logger = Logger.getLogger(MoleculeNode.class.getCanonicalName()); + private Level WARNING_LEVEL = Level.WARNING; + private Set atoms = new HashSet(); + private Set bonds = new HashSet(); + + public MoleculeNode() { + super(); + + setCapability(BranchGroup.ALLOW_CHILDREN_READ); + setCapability(BranchGroup.ALLOW_CHILDREN_WRITE); + setCapability(BranchGroup.ALLOW_PICKABLE_READ); + setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND); + setCapability(BranchGroup.ALLOW_DETACH); + setCapability(BranchGroup.ALLOW_PICKABLE_READ); + setCapability(BranchGroup.ALLOW_PICKABLE_WRITE); + setCapability(BranchGroup.ALLOW_LOCAL_TO_VWORLD_READ); + + setPickable(true); + } + + public void addChild(AtomNode atom) { + if (atoms.contains(atom)) { + if (logger.isLoggable(WARNING_LEVEL)) { + logger.warning("Attempt to add already attached atom node. Ignored. Continuing..."); + } + return; + } + atoms.add(atom); + super.addChild(atom); + } + + public void removeChild(AtomNode atom) { + atoms.remove(atom); + super.removeChild(atom); + } + + public void removeChild(BondNode bond) { + bonds.remove(bond); + super.removeChild(bond); + } + + public void addChild(BondNode bond) { + if (bonds.contains(bond)) { + if (logger.isLoggable(WARNING_LEVEL)) { + logger.warning("Attempt to add already attached bond node. Ignored. Continuing..."); + } + return; + } + bonds.add(bond); + super.addChild(bond); + } + + @Override + public void removeAllChildren() { + atoms.clear(); + bonds.clear(); + super.removeAllChildren(); + } + + public boolean contains(AtomNode atom) { + return atoms.contains(atom); + } + + public boolean contains(BondNode bond) { + return bonds.contains(bond); + } +} diff --git a/src/main/java/cct/j3d/MousePicking.java b/src/main/java/cct/j3d/MousePicking.java new file mode 100644 index 0000000..1c4c31b --- /dev/null +++ b/src/main/java/cct/j3d/MousePicking.java @@ -0,0 +1,454 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import java.util.logging.Logger; + +import org.scijava.java3d.Bounds; +import org.scijava.java3d.BranchGroup; +import org.scijava.java3d.Canvas3D; +import org.scijava.java3d.Node; +import org.scijava.java3d.PickBounds; +import org.scijava.java3d.PickConeRay; +import org.scijava.java3d.PickCylinder; +import org.scijava.java3d.PickPoint; +import org.scijava.java3d.PickRay; +import org.scijava.java3d.PickSegment; +import org.scijava.java3d.PickShape; +import org.scijava.java3d.SceneGraphPath; +import org.scijava.java3d.Transform3D; +import org.scijava.java3d.TransformGroup; +import org.scijava.vecmath.Point3d; +import org.scijava.vecmath.Vector3d; + +import cct.modelling.OperationsOnAtoms; + +import org.scijava.java3d.utils.behaviors.mouse.MouseBehaviorCallback; +import org.scijava.java3d.utils.geometry.Cylinder; +import org.scijava.java3d.utils.geometry.Sphere; +import org.scijava.java3d.utils.picking.PickResult; +import org.scijava.java3d.utils.picking.behaviors.PickMouseBehavior; +import org.scijava.java3d.utils.picking.behaviors.PickingCallback; + +/** + * PickRotateBehavior behavior = new PickRotateBehavior(canvas, root, bounds); + * root.addChild(behavior); + */ + +public class MousePicking + extends PickMouseBehavior implements + MouseBehaviorCallback, OperationsOnAtoms { + //MouseRotate drag; + //int pickMode = PickObject.USE_BOUNDS; + private PickingCallback callback = null; + private TransformGroup currentTG; + //private SampleFrame daddy = null; + private Java3dUniverse parent = null; + static final Logger logger = Logger.getLogger(MousePicking.class.getCanonicalName()); + + /** + * Creates a pick/rotate behavior that waits for user mouse events for + * the scene graph. This method has its pickMode set to BOUNDS picking. + * @param root Root of your scene graph. + * @param canvas Java 3D drawing canvas. + * @param bounds Bounds of your scene. + **/ + /* + public MousePicking(SampleFrame dad, BranchGroup root, Canvas3D canvas, + Bounds bounds) { + super(canvas, root, bounds); + this.setSchedulingBounds(bounds); + daddy = dad; + } + */ + + public MousePicking(Java3dUniverse dad, BranchGroup root, Canvas3D canvas, + Bounds bounds) { + super(canvas, root, bounds); + //drag = new MouseRotate(MouseRotate.MANUAL_WAKEUP); + //drag.setTransformGroup(currGrp); + //currGrp.addChild(drag); + //drag.setSchedulingBounds(bounds); + this.setSchedulingBounds(bounds); + parent = dad; + } + + /** + * Creates a pick/rotate behavior that waits for user mouse events for + * the scene graph. + * @param root Root of your scene graph. + * @param canvas Java 3D drawing canvas. + * @param bounds Bounds of your scene. + * @param pickMode specifys PickObject.USE_BOUNDS or PickObject.USE_GEOMETRY. + * Note: If pickMode is set to PickObject.USE_GEOMETRY, all geometry object in + * the scene graph that allows pickable must have its ALLOW_INTERSECT bit set. + **/ + /* + public MousePicking(SampleFrame dad, BranchGroup root, Canvas3D canvas, + Bounds bounds, + int pickMode) { + super(canvas, root, bounds); + //drag = new MouseRotate(MouseRotate.MANUAL_WAKEUP); + //drag.setTransformGroup(currGrp); + //currGrp.addChild(drag); + //drag.setSchedulingBounds(bounds); + this.setSchedulingBounds(bounds); + this.setCapability(Node.ALLOW_LOCAL_TO_VWORLD_READ); + pickCanvas.setMode(PickTool.GEOMETRY_INTERSECT_INFO); + Node node = this; + node.setCapability(Node.ALLOW_LOCAL_TO_VWORLD_READ); + //this.pickMode = pickMode; + daddy = dad; + } + */ + + /** + * Sets the pickMode component of this PickRotateBehavior to the value of + * the passed pickMode. + * @param pickMode the pickMode to be copied. + **/ + + + public void setPickMode(int pickMode) { + //this.pickMode = pickMode; + super.setMode(pickMode); + } + + @Override + public void setTolerance(float tolerance) { + super.setTolerance(tolerance); + } + + /** + * Return the pickMode component of this PickRotateBehavior. + **/ + + public int getPickMode() { + //return pickMode; + return getMode(); + } + + /** + * Update the scene to manipulate any nodes. This is not meant to be + * called by users. Behavior automatically calls this. You can call + * this only if you know what you are doing. + * + * @param xpos Current mouse X pos. + * @param ypos Current mouse Y pos. + **/ + @Override + public void updateScene(int xpos, int ypos) { + + //if ( !daddy.selectionInProgress ) return; + + TransformGroup tg = null; + logger.info("MousePicking: Enter updateScene"); + if (!mevent.isMetaDown() && !mevent.isAltDown()) { + + //Transform3D t3d = new Transform3D(); + + //canvas.getImagePlateToVworld(t3d); + //logger.info("ImagePlateToVworld: " + t3d ); + + //this.getLocalToVworld(t3d); + //logger.info("This: " + t3d ); + + pickCanvas.setShapeLocation(mevent); + + PickShape shape = pickCanvas.getPickShape(); + + Point3d eyePos = pickCanvas.getStartPosition(); + //logger.info("Screen: "+xpos+" "+ypos+" Eye Pos: " + eyePos); + Point3d origin = null; + Vector3d dir = null; + + if (shape instanceof PickBounds) { + logger.info("PickShape: PickBounds"); + } + else if (shape instanceof PickConeRay) { + logger.info("PickShape: PickConeRay"); + origin = new Point3d(); + //origin = eyePos; + PickConeRay pc = (PickConeRay) shape; + + pc.getOrigin(origin); + logger.info("Origin: " + origin.x + " " + origin.y + " " + + origin.z); + dir = new Vector3d(); + pc.getDirection(dir); + logger.info("Direction: " + dir.x + " " + dir.y + " " + + dir.z + " Spread angle: " + + pc.getSpreadAngle() / Math.PI * 180.0); + + pc.set(origin, dir, pc.getSpreadAngle() / 5.0); + + pickCanvas.setShapeRay(origin, dir); + } + else if (shape instanceof PickCylinder) { + logger.info("PickShape: PickCylinder"); + } + else if (shape instanceof PickPoint) { + logger.info("PickShape: PickPoint"); + } + else if (shape instanceof PickRay) { + logger.info("PickShape: PickRay"); + PickRay pc = (PickRay) shape; + origin = new Point3d(); + dir = new Vector3d(); + pc.get(origin, dir); + } + else if (shape instanceof PickSegment) { + logger.info("PickShape: PickSegment"); + } + else { + origin = new Point3d(); + Canvas3D canvas = pickCanvas.getCanvas(); + Point3d mouse_pos = new Point3d(); + + canvas.getCenterEyeInImagePlate(origin); + canvas.getPixelLocationInImagePlate(mevent.getX(), mevent.getY(), + mouse_pos); + + Transform3D motion = new Transform3D(); + canvas.getImagePlateToVworld(motion); + motion.transform(origin); + motion.transform(mouse_pos); + + dir = new Vector3d(mouse_pos); + dir.sub(origin); + } + + //currGrp.getTransform(t3d); + //daddy.handleSpotPicking(origin,dir); + + BranchGroup bgr = pickCanvas.getBranchGroup(); + PickResult[] results = pickCanvas.pickAll(); + if (results != null) { + logger.info("# of picked objects: " + results.length); + } + PickResult result = pickCanvas.pickClosest(); + + Sphere sel_sphere = null; + + if (results != null) { + //logger.info("Array size: " + results.length); + //PickIntersection pi = result.getClosestIntersection(eyePos); + //Transform3D tr = result.getLocalToVworld(); + //if ( tr != null ) + // logger.info("Loc->VW: " + tr); + //if ( pi != null ) { + // Point3d intercept = pi.getPointCoordinatesVW(); + // logger.info("VW intercept: " + intercept); + //} + } + + // --- Call came from Frame (obsolete) + if (false) { + + } + /* + if (daddy != null) { + if (daddy.processingSelected == SELECTED_ADD_ATOMS && result != null) { + daddy.doAtomSelection(bgr, result); + } + else if (daddy.processingSelected == SELECTED_ADD_ATOMS && result == null && + mevent.isShiftDown()) { + //daddy.doAtomSelection(bgr, result); + daddy.handleSpotPicking(origin, dir); + } + + else if (mevent.isShiftDown() && + daddy.selectedMode == SELECTION_SPOT_ONLY) { // dead code + daddy.handleSpotPicking(origin, dir); + } + else if (daddy.selectedMode == SELECTION_UNLIMITED || + daddy.selectedMode == SELECTION_ONE_ATOM_ONLY) { + daddy.doAtomSelection(bgr, result); + } + } + */ + + // --- If call came from class + else { + if (parent.getJobType() == SELECTED_ADD_ATOMS && result != null) { + //parent.doAtomSelection(bgr, result); + parent.doAtomSelection(origin, dir, bgr, results); + } + else if (parent.getJobType() == SELECTED_ADD_ATOMS && result == null && + mevent.isShiftDown()) { + //daddy.doAtomSelection(bgr, result); + parent.handleSpotPicking(origin, dir); + } + else if (parent.getJobType() == SELECTED_ADD_MOLECULE && result == null && + mevent.isShiftDown()) { + //daddy.doAtomSelection(bgr, result); + parent.handleSpotPicking(origin, dir); + } + + else { + //parent.doAtomSelection(bgr, result); + if (dir != null) { + parent.doAtomSelection(origin, dir, bgr, results); + } + } + + /* + else if (parent.getJobType() == SELECTED_MODIFY_ATOMS && result != null ) { + parent.doAtomSelection(bgr, result); + parent.handleSpotPicking(origin, dir); + } + else if (parent.getJobType() == SELECTED_MODIFY_BONDS && result != null ) { + parent.doAtomSelection(bgr, result); + parent.handleSpotPicking(origin, dir); + } + else if (parent.getJobType() == SELECTED_MODIFY_ANGLES && result != null ) { + parent.doAtomSelection(bgr, result); + parent.handleSpotPicking(origin, dir); + } + + else if (parent.getJobType() == SELECTED_MODIFY_DIHEDRALS && result != null ) { + parent.doAtomSelection(bgr, result); + parent.handleSpotPicking(origin, dir); + } + */ + + + /* + else if (mevent.isShiftDown() && + parent.selectedMode == SELECTION_SPOT_ONLY) { // dead code + parent.handleSpotPicking(origin, dir); + } + else if (parent.selectedMode == SELECTION_UNLIMITED || + parent.selectedMode == SELECTION_ONE_ATOM_ONLY) { + parent.doAtomSelection(bgr, result); + } + */ + + } + //bgr.setCapability( BranchGroup.ALLOW_CHILDREN_READ); + + // Make sure the selection exists and is movable. + if ( (tg != null) && + (tg.getCapability(TransformGroup.ALLOW_TRANSFORM_READ)) && + (tg.getCapability(TransformGroup.ALLOW_TRANSFORM_WRITE))) { + //drag.setTransformGroup(tg); + //drag.wakeup(); + currentTG = tg; + } + else if (callback != null) { + callback.transformChanged(PickingCallback.NO_PICK, null); + } + } + } + + /** + * Callback method from MouseRotate + * This is used when the Picking callback is enabled + */ + @Override + public void transformChanged(int type, Transform3D transform) { + callback.transformChanged(PickingCallback.ROTATE, currentTG); + } + + /** + * Register the class @param callback to be called each + * time the picked object moves + */ + /* + public void setupCallback( PickingCallback callback ) { + this.callback = callback; + if (callback==null) + //drag.setupCallback( null ); + else + //drag.setupCallback( this ); + } + */ + public int getSelectedAtomNumber(BranchGroup bgr, Sphere sel_sphere) { + int selected_atom = -1; + if (bgr != null) { + PickShape shape = pickCanvas.getPickShape(); + SceneGraphPath sgp = bgr.pickClosest(shape); + //logger.info("Got Branch group: # children " + + // bgr.numChildren()); + for (int i = 0; i < bgr.numChildren(); i++) { + Node n = bgr.getChild(i); + if (n instanceof BranchGroup) { + //logger.info("Child: " + i + " :BranchGroup"); + BranchGroup bg = (BranchGroup) n; + for (int j = 0; j < bg.numChildren(); j++) { + Node n2 = bg.getChild(j); + if (n2 instanceof TransformGroup) { + TransformGroup tg2 = (TransformGroup) n2; + //logger.info("SubChild: " + j + + // " :TransformGroup"); + for (int k = 0; k < tg2.numChildren(); k++) { + Node n3 = tg2.getChild(k); + if (n3 instanceof Sphere) { + //logger.info("SubSubChild: " + k + + // " :Sphere"); + if (sel_sphere == n3) { + //logger.info( + // ">>> Selected Sphere <<<"); + return i; + } + } + else if (n3 instanceof Cylinder) { + //logger.info("SubSubChild: " + k + + // " :Cylinder"); + } + else { + //logger.info("SubSubChild: " + k + + // " :Unknown"); + } + + } + } + else { + //logger.info("SubChild: " + j + " :Unknown"); + } + } + } + else { + //logger.info("Child: " + i + " :Unknown"); + } + } + } + + return selected_atom; + } +} diff --git a/src/main/java/cct/j3d/MousePickingHandler.java b/src/main/java/cct/j3d/MousePickingHandler.java new file mode 100644 index 0000000..d030f79 --- /dev/null +++ b/src/main/java/cct/j3d/MousePickingHandler.java @@ -0,0 +1,100 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import java.awt.event.MouseEvent; +import java.util.Enumeration; +import java.util.logging.Logger; + +import org.scijava.java3d.Bounds; +import org.scijava.java3d.BranchGroup; +import org.scijava.java3d.Canvas3D; +import org.scijava.java3d.WakeupCriterion; +import org.scijava.java3d.WakeupOnAWTEvent; +import org.scijava.java3d.WakeupOr; + +import org.scijava.java3d.utils.picking.behaviors.PickMouseBehavior; + +public class MousePickingHandler + extends PickMouseBehavior { + WakeupCriterion[] conditions = { + new WakeupOnAWTEvent(java.awt.event. + MouseEvent.MOUSE_CLICKED), + new WakeupOnAWTEvent(java.awt.event. + MouseEvent.MOUSE_PRESSED), + new WakeupOnAWTEvent(java.awt.event. + MouseEvent.MOUSE_RELEASED) + }; + WakeupOr MouseEvent = new WakeupOr(conditions); + + static final Logger logger = Logger.getLogger(MousePickingHandler.class.getCanonicalName()); + + public MousePickingHandler(Canvas3D canvas, BranchGroup root, Bounds bounds) { + super(canvas, root, bounds); + } + + @Override + public void initialize() { + // set initial wakeup condition + wakeupOn(MouseEvent); + } + + private void processMouseEvent(MouseEvent evt) { + buttonPress = false; + logger.info("processMouseEvent: Mouse Clicked"); + if (evt.getID() == java.awt.event.MouseEvent.MOUSE_PRESSED | + evt.getID() == java.awt.event.MouseEvent.MOUSE_CLICKED) { + buttonPress = true; + return; + } + else if (evt.getID() == java.awt.event.MouseEvent.MOUSE_MOVED) { + // Process mouse move event + } + } + + @Override + public void processStimulus(Enumeration criteria) { + logger.info("MouseHandler: Mouse Clicked"); + } + + @Override + public void updateScene(int xpos, int ypos) { + + } + +} diff --git a/src/main/java/cct/j3d/MouseRotationEvent.java b/src/main/java/cct/j3d/MouseRotationEvent.java new file mode 100644 index 0000000..6a67349 --- /dev/null +++ b/src/main/java/cct/j3d/MouseRotationEvent.java @@ -0,0 +1,26 @@ +package cct.j3d; + +import org.scijava.java3d.Transform3D; + +/** + *

Title: Jamberoo - Java Molecular Editor

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2009

+ * + *

Company:

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class MouseRotationEvent { + private Transform3D transform3D; + public MouseRotationEvent(Transform3D t3d) { + transform3D = t3d; + } + + public Transform3D getLocalToVworld() { + return transform3D; + } +} diff --git a/src/main/java/cct/j3d/MouseRotationListener.java b/src/main/java/cct/j3d/MouseRotationListener.java new file mode 100644 index 0000000..1aa916e --- /dev/null +++ b/src/main/java/cct/j3d/MouseRotationListener.java @@ -0,0 +1,17 @@ +package cct.j3d; + +/** + *

Title: Jamberoo - Java Molecular Editor

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2009

+ * + *

Company:

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public interface MouseRotationListener { + void MouseRotated(MouseRotationEvent event); +} diff --git a/src/main/java/cct/j3d/MyMouseListener.java b/src/main/java/cct/j3d/MyMouseListener.java new file mode 100644 index 0000000..46e8000 --- /dev/null +++ b/src/main/java/cct/j3d/MyMouseListener.java @@ -0,0 +1,101 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class MyMouseListener + implements MouseListener { + public MyMouseListener() { + } + + /** + * Invoked when the mouse button has been clicked (pressed and released) on a component. + * @param e MouseEvent + */ + @Override + public void mouseClicked(MouseEvent e) { + + } + + /** + * Invoked when the mouse enters a component. + * @param e MouseEvent + */ + @Override + public void mouseEntered(MouseEvent e) { + + } + + /** + * Invoked when the mouse exits a component. + * @param e MouseEvent + */ + @Override + public void mouseExited(MouseEvent e) { + + } + + /** + * Invoked when a mouse button has been pressed on a component. + * @param e MouseEvent + */ + @Override + public void mousePressed(MouseEvent e) { + + } + + @Override + public void mouseReleased(MouseEvent e) { + + } + +} diff --git a/src/main/java/cct/j3d/MyMouseMotionListener.java b/src/main/java/cct/j3d/MyMouseMotionListener.java new file mode 100644 index 0000000..095666b --- /dev/null +++ b/src/main/java/cct/j3d/MyMouseMotionListener.java @@ -0,0 +1,234 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.j3d; + +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseMotionListener; +import java.util.logging.Logger; + +/** + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2006

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class MyMouseMotionListener + implements MouseMotionListener, ActionListener { + + public MyMouseMotionListener() { + try { + jbInit(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + int pX, pY; + Java3dUniverse daddy = null; + Timer popupTimer = null; + PopupFactory factory = null; + findAtom find = new findAtom(); + Popup popup; + JLabel jLabel = new JLabel(); + static final Logger logger = Logger.getLogger(MyMouseMotionListener.class.getCanonicalName()); + + public MyMouseMotionListener(Java3dUniverse target) { + daddy = target; + + jLabel.setBackground(new Color(10, 49, 255)); + jLabel.setForeground(Color.yellow); + jLabel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.gray, 2), + BorderFactory.createEmptyBorder(0, 5, 0, 5))); + jLabel.setDebugGraphicsOptions(0); + jLabel.setOpaque(true); + jLabel.setDisplayedMnemonic('0'); + jLabel.setText("Selected Atom"); + + } + + /** + * Invoked when a mouse button is pressed on a component and then dragged. + * + * @param e MouseEvent + */ + @Override + public void mouseDragged(MouseEvent e) { + doWork(e); + } + + /** + * Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed. + * + * @param e MouseEvent + */ + @Override + public void mouseMoved(MouseEvent e) { + doWork(e); + } + + synchronized private void doWork(MouseEvent e) { + if (popupTimer != null && popupTimer.isRunning()) { + popupTimer.stop(); + //if (popup != null) { + // popup.hide(); + // popup = null; + //} + //logger.info("Stop old timer"); + } else if (popupTimer != null) { + pX = e.getX(); + pY = e.getY(); + popupTimer.restart(); + //logger.info("Restart timer"); + return; + } + + if (popup != null) { + popup.hide(); + popup = null; + } + + pX = e.getX(); + pY = e.getY(); + popupTimer = new Timer(1000, this); + popupTimer.setRepeats(false); + popupTimer.start(); + //logger.info("Start new timer"); + + //logger.info("x="+e.getX()+" y="+e.getY()); + //daddy.findClosestAtom(e.getX(),e.getY()); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (logger.isLoggable(java.util.logging.Level.INFO)) { + logger.info("Fire popup"); + } + if (find.isAlive()) { + find.interrupt(); + Thread.interrupted(); + } + find = new findAtom(); + find.start(); + } + + private void jbInit() throws Exception { + } + + private class findAtom + extends Thread { + + public findAtom() { + super(); + } + + @Override + public void run() { + boolean isBond = false; + int atom = daddy.findClosestAtom(pX, pY); + if (atom == -1) { + atom = daddy.findClosestBond(pX, pY); + if (atom == -1) { + return; + } + isBond = true; + } + if (factory == null) { + factory = PopupFactory.getSharedInstance(); + //factory = new PopupFactory(); + } + Point point = daddy.getCanvas3D().getLocationOnScreen(); + String info = ""; + + if (isBond) { + BondInterface bond = daddy.getMolecule().getBondInterface(atom); + AtomInterface at = bond.getIAtomInterface(); + int index = daddy.getMolecule().getAtomIndex(at); + String name = at.getName(); + int monomer = at.getSubstructureNumber(); + String monomerName = daddy.getMolecule().getMonomerInterface( + monomer).getName(); + + info = name + "(" + (index + 1) + ": " + monomerName + "-" + + (monomer + 1) + ") - "; + + at = bond.getJAtomInterface(); + index = daddy.getMolecule().getAtomIndex(at); + name = at.getName(); + monomer = at.getSubstructureNumber(); + monomerName = daddy.getMolecule().getMonomerInterface( + monomer).getName(); + + info += name + "(" + (index + 1) + ": " + monomerName + "-" + + (monomer + 1) + ") : "; + + info = String.format("%s%8.4f", info, bond.bondLength()); + } else { + String name = daddy.getMolecule().getAtomInterface(atom).getName(); + int monomer = daddy.getMolecule().getAtomInterface(atom). + getSubstructureNumber(); + String monomerName = daddy.getMolecule().getMonomerInterface( + monomer). + getName(); + + info = (atom + 1) + ": " + name + ": " + monomerName + "-" + + (monomer + 1); + } + + jLabel.setText(info); + popup = factory.getPopup(daddy.getCanvas3D(), jLabel, + point.x + pX + 15, + point.y + pY - 15); + popup.show(); + } + } +} diff --git a/src/main/java/cct/j3d/MyMouseRotate.java b/src/main/java/cct/j3d/MyMouseRotate.java new file mode 100644 index 0000000..827c80e --- /dev/null +++ b/src/main/java/cct/j3d/MyMouseRotate.java @@ -0,0 +1,197 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import java.util.Enumeration; + +import org.scijava.java3d.Transform3D; +import org.scijava.java3d.TransformGroup; +import org.scijava.vecmath.Matrix3d; + +import org.scijava.java3d.utils.behaviors.mouse.MouseBehaviorCallback; +import org.scijava.java3d.utils.behaviors.mouse.MouseRotate; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class MyMouseRotate + extends MouseRotate { + + //private SampleFrame daddy = null; + private Java3dUniverse dad = null; + protected Transform3D inverseTrans = null; + protected Matrix3d rotation = null; + + private MouseBehaviorCallback callback = null; + + /** + * Creates a rotate behavior given the transform group. + * @param transformGroup The transformGroup to operate on. + */ + public MyMouseRotate(TransformGroup transformGroup) { + super(transformGroup); + } + + /** + * Creates a default mouse rotate behavior. + **/ + public MyMouseRotate() { + super(); + } + + /** + * Creates a rotate behavior. + * Note that this behavior still needs a transform + * group to work on (use setTransformGroup(tg)) and + * the transform group must add this behavior. + * @param flags interesting flags (wakeup conditions). + */ + public MyMouseRotate(int flags) { + super(flags); + } + + @Override + public void initialize() { + super.initialize(); + } + + /** + * Return the x-axis movement multipler. + **/ + + @Override + public double getXFactor() { + return super.getXFactor(); + } + + /** + * Return the y-axis movement multipler. + **/ + + @Override + public double getYFactor() { + return super.getYFactor(); + } + + /** + * Set the x-axis amd y-axis movement multipler with factor. + **/ + + @Override + public void setFactor(double factor) { + super.setFactor(factor); + + } + + @Override + public void processStimulus(Enumeration criteria) { + + super.processStimulus(criteria); + + //logger.info("processStimulus: labels; "+ daddy.areLabels()); + + /* + if (daddy != null && daddy.areLabels()) { + daddy.updateLabels(); + } + else if (dad != null && dad.areLabels()) { + dad.updateLabels(); + } + */ + + if (dad != null && dad.areLabels()) { + dad.updateLabels(); + //this.notifyAll(); + } + + } + + /** + * Users can overload this method which is called every time + * the Behavior updates the transform + * + * Default implementation does nothing + */ + @Override + public void transformChanged(Transform3D transform) { + + } + + /** + * The transformChanged method in the callback class will + * be called every time the transform is updated + */ + @Override + public void setupCallback(MouseBehaviorCallback callback) { + this.callback = callback; + } + + // --- And now, custom functions... + + /* + public MyMouseRotate(SampleFrame parent, TransformGroup transformGroup) { + super(transformGroup); + daddy = parent; + } + */ + + public MyMouseRotate(Java3dUniverse parent, TransformGroup transformGroup) { + super(transformGroup); + dad = parent; + } + + /* + public void setParentFrame(SampleFrame dad) { + daddy = dad; + } + */ + + public void setParentFrame(Java3dUniverse parent) { + dad = parent; + } + +} diff --git a/src/main/java/cct/j3d/MyMouseZoom.java b/src/main/java/cct/j3d/MyMouseZoom.java new file mode 100644 index 0000000..e6b7385 --- /dev/null +++ b/src/main/java/cct/j3d/MyMouseZoom.java @@ -0,0 +1,247 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import java.awt.AWTEvent; +import java.awt.event.MouseEvent; +import java.util.Enumeration; + +import org.scijava.java3d.Transform3D; +import org.scijava.java3d.TransformGroup; +import org.scijava.java3d.View; +import org.scijava.java3d.WakeupCriterion; +import org.scijava.java3d.WakeupOnAWTEvent; +import org.scijava.vecmath.Matrix3d; + +import org.scijava.java3d.utils.behaviors.mouse.MouseBehaviorCallback; +import org.scijava.java3d.utils.behaviors.mouse.MouseZoom; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class MyMouseZoom + extends MouseZoom { + + //private SampleFrame daddy = null; + private Java3dUniverse dad = null; + protected Transform3D inverseTrans = null; + protected Matrix3d rotation = null; + + private MouseBehaviorCallback callback = null; + + /** + * Creates a rotate behavior given the transform group. + * @param transformGroup The transformGroup to operate on. + */ + public MyMouseZoom(TransformGroup transformGroup) { + super(transformGroup); + } + + /** + * Creates a default mouse rotate behavior. + **/ + public MyMouseZoom() { + super(); + } + + /** + * Creates a rotate behavior. + * Note that this behavior still needs a transform + * group to work on (use setTransformGroup(tg)) and + * the transform group must add this behavior. + * @param flags interesting flags (wakeup conditions). + */ + public MyMouseZoom(int flags) { + super(flags); + } + + @Override + public void initialize() { + super.initialize(); + } + + /** + * Set the x-axis amd y-axis movement multipler with factor. + **/ + + @Override + public void setFactor(double factor) { + super.setFactor(factor); + + } + + @Override + public void processStimulus(Enumeration criteria) { + + if ( getView().getProjectionPolicy() == View.PARALLEL_PROJECTION) { + WakeupCriterion wakeup; + AWTEvent[] event; + int id; + int dx, dy; + + while (criteria.hasMoreElements()) { + wakeup = (WakeupCriterion) criteria.nextElement(); + if (wakeup instanceof WakeupOnAWTEvent) { + event = ( (WakeupOnAWTEvent) wakeup).getAWTEvent(); + for (int i = 0; i < event.length; i++) { + processMouseEvent( (MouseEvent) event[i]); + + if ( ( (buttonPress) && ( (flags & MANUAL_WAKEUP) == 0)) || + ( (wakeUp) && ( (flags & MANUAL_WAKEUP) != 0))) { + id = event[i].getID(); + if ( (id == MouseEvent.MOUSE_DRAGGED) && + ( (MouseEvent) event[i]).isAltDown() && + ! ( (MouseEvent) event[i]).isMetaDown()) { + + x = ( (MouseEvent) event[i]).getX(); + y = ( (MouseEvent) event[i]).getY(); + + dx = x - x_last; + dy = y - y_last; + + double scale = getView().getScreenScale(); + scale += dy * getFactor()*0.01; + if (scale < 0.0001) { + scale = 0.0001; + } + getView().setScreenScale(scale); + + if (!reset) { + //transformGroup.getTransform(currXform); + + /* + translation.z = dy * getFactor(); + + transformX.set(translation); + + if (invert) { + currXform.mul(currXform, transformX); + } + else { + currXform.mul(transformX, currXform); + } + + transformGroup.setTransform(currXform); + + transformChanged(currXform); + + if (callback != null) { + callback.transformChanged(MouseBehaviorCallback.TRANSLATE, + currXform); + } + */ + } + else { + reset = false; + } + + x_last = x; + y_last = y; + } + else if (id == MouseEvent.MOUSE_PRESSED) { + x_last = ( (MouseEvent) event[i]).getX(); + y_last = ( (MouseEvent) event[i]).getY(); + } + } + } + } + } + + wakeupOn(mouseCriterion); + + } + else { + super.processStimulus(criteria); + } + //logger.info("processStimulus: labels; "+ daddy.areLabels()); + } + + /** + * Users can overload this method which is called every time + * the Behavior updates the transform + * + * Default implementation does nothing + */ + @Override + public void transformChanged(Transform3D transform) { + + } + + /** + * The transformChanged method in the callback class will + * be called every time the transform is updated + */ + @Override + public void setupCallback(MouseBehaviorCallback callback) { + this.callback = callback; + } + + // --- And now, custom functions... + + /* + public MyMouseRotate(SampleFrame parent, TransformGroup transformGroup) { + super(transformGroup); + daddy = parent; + } + */ + + public MyMouseZoom(Java3dUniverse parent, TransformGroup transformGroup) { + super(transformGroup); + dad = parent; + } + + /* + public void setParentFrame(SampleFrame dad) { + daddy = dad; + } + */ + + public void setParentFrame(Java3dUniverse parent) { + dad = parent; + } + +} diff --git a/src/main/java/cct/j3d/OffScreenCanvas3D.java b/src/main/java/cct/j3d/OffScreenCanvas3D.java new file mode 100644 index 0000000..a074499 --- /dev/null +++ b/src/main/java/cct/j3d/OffScreenCanvas3D.java @@ -0,0 +1,77 @@ +package cct.j3d; + +/* + * @(#)OffScreenCanvas3D.java 1.4 02/04/01 15:04:10 + * + * Copyright (c) 1996-2002 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES + * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN + * OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR + * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR + * PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF + * LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, + * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that Software is not designed,licensed or intended + * for use in the design, construction, operation or maintenance of + * any nuclear facility. + */ + +import java.awt.GraphicsConfiguration; +import java.awt.image.BufferedImage; + +import org.scijava.java3d.Canvas3D; +import org.scijava.java3d.ImageComponent; +import org.scijava.java3d.ImageComponent2D; + +class OffScreenCanvas3D + extends Canvas3D { + OffScreenCanvas3D(GraphicsConfiguration graphicsConfiguration, + boolean offScreen) { + + super(graphicsConfiguration, offScreen); + } + + BufferedImage doRender(int width, int height) { + + BufferedImage bImage = + new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); + + ImageComponent2D buffer = + new ImageComponent2D(ImageComponent.FORMAT_RGBA, bImage); + + setOffScreenBuffer(buffer); + renderOffScreenBuffer(); + waitForOffScreenRendering(); + bImage = getOffScreenBuffer().getImage(); + + return bImage; + } + + @Override + public void postSwap() { + // No-op since we always wait for off-screen rendering to complete + } +} diff --git a/src/main/java/cct/j3d/PopupPanel.java b/src/main/java/cct/j3d/PopupPanel.java new file mode 100644 index 0000000..4791ad3 --- /dev/null +++ b/src/main/java/cct/j3d/PopupPanel.java @@ -0,0 +1,100 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.SystemColor; + +import javax.swing.BorderFactory; +import javax.swing.DebugGraphics; +import javax.swing.JLabel; +import javax.swing.JPanel; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class PopupPanel + extends JPanel { + BorderLayout borderLayout1 = new BorderLayout(); + JLabel jLabel = new JLabel(); + JPanel jPanel1 = new JPanel(); + + public PopupPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + jLabel.setBackground(new Color(10, 49, 255)); + jLabel.setForeground(Color.yellow); + jLabel.setBorder(BorderFactory.createCompoundBorder(BorderFactory. + createLineBorder(Color.gray, 2), + BorderFactory.createEmptyBorder(0, 5, 0, 5))); + jLabel.setDebugGraphicsOptions(0); + jLabel.setOpaque(true); + jLabel.setDisplayedMnemonic('0'); + jLabel.setText("Selected Atom"); + + this.setDebugGraphicsOptions(DebugGraphics.LOG_OPTION); + jPanel1.setBackground(new Color(100, 222, 222)); + jPanel1.setBorder(BorderFactory.createLineBorder(SystemColor. + controlShadow, 1)); + this.add(jPanel1, BorderLayout.NORTH); + jPanel1.add(jLabel); + } + + public void setText(String text) { + jLabel.setText(text); + } + +} diff --git a/src/main/java/cct/j3d/PovrayJava3d.java b/src/main/java/cct/j3d/PovrayJava3d.java new file mode 100644 index 0000000..17f117e --- /dev/null +++ b/src/main/java/cct/j3d/PovrayJava3d.java @@ -0,0 +1,239 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import java.util.Enumeration; +import java.util.List; + +import org.scijava.java3d.Appearance; +import org.scijava.java3d.Canvas3D; +import org.scijava.java3d.Group; +import org.scijava.java3d.Shape3D; +import org.scijava.java3d.Transform3D; +import org.scijava.java3d.TransparencyAttributes; +import org.scijava.java3d.TriangleArray; +import org.scijava.java3d.View; +import org.scijava.vecmath.Color3f; +import org.scijava.vecmath.Point3d; + +import cct.gaussian.Gaussian; +import cct.interfaces.GraphicsObjectInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.Molecule; +import cct.povray.Povray; +import cct.vecmath.MeshObject; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class PovrayJava3d + extends Povray { + + public static final double RADIANS_TO_DEGREES = 180.0 / Math.PI; + + Canvas3D canvas3D; + View view; + + public PovrayJava3d(Java3dUniverse j3d) { + super(); + + canvas3D = j3d.getCanvas3D(); + view = canvas3D.getView(); + int pPolicy = view.getProjectionPolicy(); + + if (pPolicy == View.PARALLEL_PROJECTION) { + setProjectionPolicy( PARALLEL_PROJECTION); + } + else if (pPolicy == View.PERSPECTIVE_PROJECTION) { + setProjectionPolicy( PARALLEL_PROJECTION); + } + + super.setFieldOfView( (float) (view.getFieldOfView() * RADIANS_TO_DEGREES)); + + Point3d position = new Point3d(); + canvas3D.getCenterEyeInImagePlate(position); + Transform3D motion = new Transform3D(); + canvas3D.getImagePlateToVworld(motion); + motion.transform(position); + + super.setCameraLocation( (float) position.x, (float) position.y, + (float) position.z); + + Color3f bc = j3d.getBackgroundColor3f(); + super.setBackgroundColor(bc.x, bc.y, bc.z); + + Transform3D t3d = j3d.getVWTransform(); + + float[] matrix = new float[16]; + t3d.get(matrix); + + super.settransformMatrix(matrix); + + super.setMolecule(j3d.getMoleculeInterface()); + + List grObjects = j3d.getGraphicsObjects(); + + if (grObjects != null && grObjects.size() > 0) { + for (int i = 0; i < grObjects.size(); i++) { + GraphicsObjectInterface object = grObjects.get(i); + List shape3ds = object.getShape3DElements(); + if (shape3ds == null || shape3ds.size() < 1) { + continue; + } + + for (int j = 0; j < shape3ds.size(); j++) { + Object obj = shape3ds.get(j); + + if (obj instanceof Group) { + if ( ( (Group) obj).getParent() == null) { + continue; // Invisible + } + } + + Shape3D shape3d = this.getShape3D(obj); + + if (shape3d == null) { + continue; + } + + Object geometry = shape3d.getGeometry(); + if (geometry instanceof TriangleArray) { + TriangleArray triangleArray = (TriangleArray) geometry; + + int n = triangleArray.getVertexCount(); + + float[] coordinates = new float[n * 3]; + triangleArray.getCoordinates(0, coordinates); + + float[] normals = new float[n * 3]; + triangleArray.getNormals(0, normals); + + float[] colors = new float[n * 3]; + triangleArray.getColors(0, colors); + + int[] face_indices = new int[n]; + for (int k = 0; k < n; k++) { + face_indices[k] = k; + } + + MeshObject mesh = new MeshObject(); + try { + mesh.setMeshObjectOfTriangles(n, coordinates, face_indices, normals, colors); + } + catch (Exception ex) { + System.err.println(ex.getMessage()); + } + + if (shape3d.getCapability(Shape3D.ALLOW_APPEARANCE_READ)) { + Appearance app = shape3d.getAppearance(); + if (app.getCapability(Appearance.ALLOW_TRANSPARENCY_ATTRIBUTES_READ)) { + TransparencyAttributes ta = app.getTransparencyAttributes(); + if (ta == null) { + mesh.setOpacity(1.0f); + } + else { + mesh.setTransparency(ta.getTransparency()); + } + } + else { + System.err.println(this.getClass().getCanonicalName() + ": No capability to read TransparencyAttributes..."); + } + + } + else { + System.err.println(this.getClass().getCanonicalName() + ": No capability to read Appearance..."); + } + + super.addMeshObject(mesh); + } + } + } + } + } + + Shape3D getShape3D(Object obj) { + if (obj instanceof Shape3D) { + return (Shape3D) obj; + } + else if (obj instanceof Group) { + Group group = (Group) obj; + Enumeration children = group.getAllChildren(); + while (children.hasMoreElements()) { + Object node = children.nextElement(); + if (node instanceof Group) { + Shape3D shape3d = getShape3D(node); + if (shape3d != null) { + return shape3d; + } + } + else if (node instanceof Shape3D) { + return (Shape3D) node; + } + } + } + return null; + } + + public static void main(String[] args) { + + Gaussian gaussianData = new Gaussian(); + int n = gaussianData.parseGJF(args[0], 0); + MoleculeInterface m = Molecule.getNewInstance(); + m = gaussianData.getMolecule(m, 0); + Java3dUniverse j3d = new Java3dUniverse(); + j3d.addMolecule(m); + + PovrayJava3d povrayjava3d = new PovrayJava3d(j3d); + + try { + povrayjava3d.savePovrayFile("povray.pov"); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } +} diff --git a/src/main/java/cct/j3d/ProcessMouseRotate.java b/src/main/java/cct/j3d/ProcessMouseRotate.java new file mode 100644 index 0000000..b5e1167 --- /dev/null +++ b/src/main/java/cct/j3d/ProcessMouseRotate.java @@ -0,0 +1,215 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import java.util.ArrayList; +import java.util.Enumeration; + +import org.scijava.java3d.Transform3D; +import org.scijava.java3d.TransformGroup; +import org.scijava.vecmath.Matrix3d; + +import org.scijava.java3d.utils.behaviors.mouse.MouseBehaviorCallback; +import org.scijava.java3d.utils.behaviors.mouse.MouseRotate; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class ProcessMouseRotate + extends MouseRotate { + + //private SampleFrame daddy = null; + private Java3dUniverse dad = null; + protected Transform3D inverseTrans = null; + protected Matrix3d rotation = null; + + private MouseBehaviorCallback callback = null; + private java.util.List listeners = new ArrayList (); + + /** + * Creates a rotate behavior given the transform group. + * @param transformGroup The transformGroup to operate on. + */ + public ProcessMouseRotate(TransformGroup transformGroup) { + super(transformGroup); + } + + /** + * Creates a default mouse rotate behavior. + **/ + public ProcessMouseRotate() { + super(); + } + + /** + * Creates a rotate behavior. + * Note that this behavior still needs a transform + * group to work on (use setTransformGroup(tg)) and + * the transform group must add this behavior. + * @param flags interesting flags (wakeup conditions). + */ + public ProcessMouseRotate(int flags) { + super(flags); + } + + public void addMouseRotationListener(MouseRotationListener listener) { + listeners.add(listener); + } + + public void removeMouseRotationListener(MouseRotationListener listener) { + listeners.remove(listener); + } + + @Override + public void initialize() { + super.initialize(); + } + + /** + * Return the x-axis movement multipler. + **/ + + @Override + public double getXFactor() { + return super.getXFactor(); + } + + /** + * Return the y-axis movement multipler. + **/ + + @Override + public double getYFactor() { + return super.getYFactor(); + } + + /** + * Set the x-axis amd y-axis movement multipler with factor. + **/ + + @Override + public void setFactor(double factor) { + super.setFactor(factor); + + } + + @Override + public void processStimulus(Enumeration criteria) { + + super.processStimulus(criteria); + + //logger.info("processStimulus: labels; "+ daddy.areLabels()); + + /* + if (daddy != null && daddy.areLabels()) { + daddy.updateLabels(); + } + else if (dad != null && dad.areLabels()) { + dad.updateLabels(); + } + */ + + if (dad != null && dad.areLabels()) { + dad.updateLabels(); + //this.notifyAll(); + } + + if (listeners.size() > 0) { + Transform3D t3d = new Transform3D(); + this.getLocalToVworld(t3d); + MouseRotationEvent mouseRotationEvent = new MouseRotationEvent(t3d); + for (int i = 0; i < listeners.size(); i++) { + listeners.get(i).MouseRotated(mouseRotationEvent); + } + } + } + + /** + * Users can overload this method which is called every time + * the Behavior updates the transform + * + * Default implementation does nothing + */ + @Override + public void transformChanged(Transform3D transform) { + + } + + /** + * The transformChanged method in the callback class will + * be called every time the transform is updated + */ + @Override + public void setupCallback(MouseBehaviorCallback callback) { + this.callback = callback; + } + + // --- And now, custom functions... + + /* + public MyMouseRotate(SampleFrame parent, TransformGroup transformGroup) { + super(transformGroup); + daddy = parent; + } + */ + + public ProcessMouseRotate(Java3dUniverse parent, TransformGroup transformGroup) { + super(transformGroup); + dad = parent; + } + + /* + public void setParentFrame(SampleFrame dad) { + daddy = dad; + } + */ + + public void setParentFrame(Java3dUniverse parent) { + dad = parent; + } + +} diff --git a/src/main/java/cct/j3d/QueryProperties.java b/src/main/java/cct/j3d/QueryProperties.java new file mode 100644 index 0000000..a8e5fa1 --- /dev/null +++ b/src/main/java/cct/j3d/QueryProperties.java @@ -0,0 +1,169 @@ +/* + * @(#)QueryProperties.java 1.11 02/05/29 16:06:47 + * + * Copyright (c) 1996-2002 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES + * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN + * OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR + * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR + * PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF + * LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, + * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that Software is not designed,licensed or intended + * for use in the design, construction, operation or maintenance of + * any nuclear facility. + */ +package cct.j3d; + +import java.awt.GraphicsConfigTemplate; +import java.awt.GraphicsConfiguration; +import java.awt.GraphicsEnvironment; +import java.io.StringWriter; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; + +import org.scijava.java3d.Canvas3D; +import org.scijava.java3d.GraphicsConfigTemplate3D; +import org.scijava.java3d.VirtualUniverse; + +public class QueryProperties { + + static VirtualUniverse vu = new VirtualUniverse(); + + static Map vuMap = VirtualUniverse.getProperties(); + + static Map c3dMap = null; + + static GraphicsConfigTemplate3D template = new GraphicsConfigTemplate3D(); + + static private QueryProperties props = new QueryProperties(); + static final Logger logger = Logger.getLogger(QueryProperties.class.getCanonicalName()); + + public static Map getVirtualUniverseProperties() { + return vuMap; + } + + private QueryProperties() { + template.setStereo(GraphicsConfigTemplate.PREFERRED); + template.setSceneAntialiasing(GraphicsConfigTemplate.PREFERRED); + GraphicsConfiguration config = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getBestConfiguration( + template); + + c3dMap = new Canvas3D(config).queryProperties(); + } + + public static String getJava3dPropsAsString() { + StringWriter sWriter = new StringWriter(); + + Set set = vuMap.entrySet(); + Iterator i = set.iterator(); + + while (i.hasNext()) { + Map.Entry me = (Map.Entry) i.next(); + sWriter.write(me.getKey().toString() + " = " + me.getValue().toString() + "\n"); + } + + set = c3dMap.entrySet(); + i = set.iterator(); + while (i.hasNext()) { + Map.Entry me = (Map.Entry) i.next(); + sWriter.write(me.getKey().toString() + " = " + me.getValue().toString() + "\n"); + } + + return sWriter.toString(); + } + + public static void main(String[] args) { + + logger.info("version = " + + vuMap.get("j3d.version")); + logger.info("vendor = " + + vuMap.get("j3d.vendor")); + logger.info("specification.version = " + + vuMap.get("j3d.specification.version")); + logger.info("specification.vendor = " + + vuMap.get("j3d.specification.vendor")); + logger.info("renderer = " + + vuMap.get("j3d.renderer") + "\n"); + + /* We need to set this to force choosing a pixel format + that support the canvas. + */ + + logger.info("Renderer version = " + + c3dMap.get("native.version")); + logger.info("doubleBufferAvailable = " + + c3dMap.get("doubleBufferAvailable")); + logger.info("stereoAvailable = " + + c3dMap.get("stereoAvailable")); + logger.info("sceneAntialiasingAvailable = " + + c3dMap.get("sceneAntialiasingAvailable")); + logger.info("sceneAntialiasingNumPasses = " + + c3dMap.get("sceneAntialiasingNumPasses")); + logger.info("textureColorTableSize = " + + c3dMap.get("textureColorTableSize")); + logger.info("textureEnvCombineAvailable = " + + c3dMap.get("textureEnvCombineAvailable")); + logger.info("textureCombineDot3Available = " + + c3dMap.get("textureCombineDot3Available")); + logger.info("textureCombineSubtractAvailable = " + + c3dMap.get("textureCombineSubtractAvailable")); + logger.info("texture3DAvailable = " + + c3dMap.get("texture3DAvailable")); + logger.info("textureCubeMapAvailable = " + + c3dMap.get("textureCubeMapAvailable")); + logger.info("textureSharpenAvailable = " + + c3dMap.get("textureSharpenAvailable")); + logger.info("textureDetailAvailable = " + + c3dMap.get("textureDetailAvailable")); + logger.info("textureFilter4Available = " + + c3dMap.get("textureFilter4Available")); + logger.info("textureAnisotropicFilterDegreeMax = " + + c3dMap.get("textureAnisotropicFilterDegreeMax")); + logger.info("textureBoundaryWidthMax = " + + c3dMap.get("textureBoundaryWidthMax")); + logger.info("textureWidthMax = " + + c3dMap.get("textureWidthMax")); + logger.info("textureHeightMax = " + + c3dMap.get("textureHeightMax")); + logger.info("textureLodOffsetAvailable = " + + c3dMap.get("textureLodOffsetAvailable")); + logger.info("textureLodRangeAvailable = " + + c3dMap.get("textureLodRangeAvailable")); + logger.info("textureUnitStateMax = " + + c3dMap.get("textureUnitStateMax")); + logger.info("compressedGeometry.majorVersionNumber = " + + c3dMap.get("compressedGeometry.majorVersionNumber")); + logger.info("compressedGeometry.minorVersionNumber = " + + c3dMap.get("compressedGeometry.minorVersionNumber")); + logger.info("compressedGeometry.minorMinorVersionNumber = " + + c3dMap.get("compressedGeometry.minorMinorVersionNumber")); + + System.exit(0); + } +} diff --git a/src/main/java/cct/j3d/RenderingListener.java b/src/main/java/cct/j3d/RenderingListener.java new file mode 100644 index 0000000..b2f0424 --- /dev/null +++ b/src/main/java/cct/j3d/RenderingListener.java @@ -0,0 +1,21 @@ +package cct.j3d; + +import java.util.EventListener; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public interface RenderingListener + extends EventListener { + + void renderingChanged(RenderingObject e); +} diff --git a/src/main/java/cct/j3d/RenderingObject.java b/src/main/java/cct/j3d/RenderingObject.java new file mode 100644 index 0000000..a991bbb --- /dev/null +++ b/src/main/java/cct/j3d/RenderingObject.java @@ -0,0 +1,23 @@ +package cct.j3d; + +import java.util.EventObject; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class RenderingObject + extends EventObject { + + public RenderingObject(Object source) { + super(source); + } +} diff --git a/src/main/java/cct/j3d/ScriptProcessorWrapper.java b/src/main/java/cct/j3d/ScriptProcessorWrapper.java new file mode 100644 index 0000000..2d2256b --- /dev/null +++ b/src/main/java/cct/j3d/ScriptProcessorWrapper.java @@ -0,0 +1,151 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import java.util.Arrays; + +import cct.cprocessor.GenericAtom; +import cct.cprocessor.GenericBond; +import cct.cprocessor.MolProcessorInterface; +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.Bond; +import cct.modelling.Molecule; +import cct.modelling.Atom; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class ScriptProcessorWrapper + implements MolProcessorInterface { + + Java3dUniverse editor = null; + + public ScriptProcessorWrapper(Java3dUniverse j3d) { + editor = j3d; + } + + public static void main(String[] args) { + ScriptProcessorWrapper scriptprocessorwrapper = new + ScriptProcessorWrapper(null); + } + + @Override + public void addAtom(Object atom) throws Exception { + if (atom instanceof AtomInterface) { + editor.addAtom( (AtomInterface) atom); + } + else if (atom instanceof AtomNode) { + editor.addAtom( (AtomNode) atom); + } + else if (atom instanceof GenericAtom) { + MoleculeInterface mol = editor.getMoleculeInterface(); + if (mol == null) { + mol = new Molecule(); + editor.addMolecule(mol); + } + GenericAtom a = (GenericAtom) atom; + AtomInterface at = new Atom(a.element, a.x, a.y, a.z); + at.setName(a.name); + at.setSubstructureNumber(a.substructure); + editor.addAtom(at); + } + else { + throw new Exception("addAtom: unknown class: " + + atom.getClass().getCanonicalName()); + } + + //editor.centerSceneOnScreen(); // !!! Remove this !!! + } + + @Override + public void addBond(Object bond) throws Exception { + if (bond instanceof BondInterface) { + editor.addBond( (BondInterface) bond); + } + else if (bond instanceof GenericBond) { + GenericBond b = (GenericBond) bond; + MoleculeInterface mol = editor.getMoleculeInterface(); + AtomInterface a1 = mol.getAtomInterface(b.i); + AtomInterface a2 = mol.getAtomInterface(b.j); + BondInterface bnd = new Bond(a1, a2); + editor.addBond(bnd); + } + else { + throw new Exception("addBond: unknown class: " + + bond.getClass().getCanonicalName()); + } + } + + @Override + public void eraseAtoms(Object atoms) throws Exception { + if (atoms instanceof int[]) { + int[] ats = (int[]) atoms; + Arrays.sort(ats); + //MoleculeInterface mol = editor.getMoleculeInterface(); + for (int i = ats.length - 1; i >= 0; i--) { + editor.deleteAtom(i); + } + } + else { + throw new Exception("eraseAtoms: unknown class: " + + atoms.getClass().getCanonicalName()); + } + } + + @Override + public void centerMolecule(Object center) throws Exception { + editor.centerSceneOnScreen(); + } + + @Override + public void setRenderingStyle(Object style) throws Exception { + String renStyle = (String) style; + editor.setGlobalRenderingStyle(renStyle); + } +} diff --git a/src/main/java/cct/j3d/SimpleRenderer.java b/src/main/java/cct/j3d/SimpleRenderer.java new file mode 100644 index 0000000..5ab3bbb --- /dev/null +++ b/src/main/java/cct/j3d/SimpleRenderer.java @@ -0,0 +1,125 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; + +import org.scijava.java3d.Canvas3D; +import javax.swing.JFrame; +import javax.swing.JPanel; + +import cct.interfaces.GraphicsRendererInterface; +import cct.interfaces.MoleculeInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class SimpleRenderer + extends JFrame implements GraphicsRendererInterface { + + Canvas3D canvas3D; + Java3dUniverse java3dUniverse; + JPanel contentPane; + BorderLayout borderLayout1 = new BorderLayout(); + + public SimpleRenderer() { + try { + setDefaultCloseOperation(HIDE_ON_CLOSE); + java3dUniverse = new Java3dUniverse(); + //setLayout(new BorderLayout()); + canvas3D = java3dUniverse.getCanvas3D(); + contentPane = (JPanel) getContentPane(); + contentPane.setLayout(borderLayout1); + setSize(new Dimension(600, 450)); + setTitle("Molecular Renderer"); + contentPane.add(canvas3D, BorderLayout.CENTER); + } + catch (Exception exception) { + exception.printStackTrace(); + } + + } + + @Override + public MoleculeInterface getMoleculeInterface() { + return java3dUniverse.getMoleculeInterface(); + } + + @Override + public void renderMolecule(MoleculeInterface m) { + java3dUniverse.addMolecule(m); + setVisible(true); + } + + @Override + public void setElementForSelectedAtoms(int new_element) { + java3dUniverse.setElementForSelectedAtoms(new_element); + } + + @Override + public void setColorForSelectedAtoms(Color new_color) { + java3dUniverse.setColorForSelectedAtoms(new_color); + } + + @Override + public void setLabelForSelectedAtoms(String new_label) { + java3dUniverse.setLabelForSelectedAtoms(new_label); + } + + @Override + public void setRadiusForSelectedAtoms(float radius) { + java3dUniverse.setRadiusForSelectedAtoms(radius); + } + + @Override + public void setAtomTypeForSelectedAtoms(String new_atomType) { + java3dUniverse.setAtomTypeForSelectedAtoms(new_atomType); + } + +} diff --git a/src/main/java/cct/j3d/SuperCell.java b/src/main/java/cct/j3d/SuperCell.java new file mode 100644 index 0000000..60bf8b2 --- /dev/null +++ b/src/main/java/cct/j3d/SuperCell.java @@ -0,0 +1,508 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 2.0/LGPL 2.1 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK ***** + */ + +package cct.j3d; + +import java.util.ArrayList; +import java.util.List; + +import cct.interfaces.AtomInterface; +import cct.interfaces.CellViewManagerInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.CELL_PARAMETER; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class SuperCell + implements CellViewManagerInterface { + + private double latticeVectors[][] = null; + private MoleculeInterface molecule = null; + private MoleculeInterface referenceMolecule = null; + private Java3dUniverse java3dUniverse = null; + private boolean drawBondsBetweenCells = false; //!!! + private SuperCube superCube = new SuperCube(); + + private int[] repetitionFactors = { + 1, 1, 1, 0, 0, 0}; // Keeps information about repetition factors in a,b,c,-a,-b,-c directions + + public SuperCell(Java3dUniverse j3d) { + + java3dUniverse = j3d; + + } + + private void initialize() throws Exception { + + if (referenceMolecule != null) { + return; + } + + molecule = java3dUniverse.getMoleculeInterface(); + + if (molecule == null || molecule.getNumberOfAtoms() < 1) { + throw new Exception("No molecule"); + } + + if (latticeVectors != null) { + return; + } + + referenceMolecule = molecule.getInstance(); + referenceMolecule.appendMolecule(molecule); + + List atoms = new ArrayList (molecule.getNumberOfAtoms()); + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + atoms.add(molecule.getAtomInterface(i)); + } + CellObject cellObj = new CellObject(atoms); + superCube.setValue(0, 0, 0, cellObj); + + Object obj = molecule.getProperty(MoleculeInterface.LATTICE_VECTORS); + if (obj instanceof double[][]) { + latticeVectors = new double[3][3]; + double[][] vectors = (double[][]) obj; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + latticeVectors[i][j] = vectors[i][j]; + } + } + } + else if (obj instanceof float[][]) { + latticeVectors = new double[3][3]; + float[][] vectors = (float[][]) obj; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + latticeVectors[i][j] = vectors[i][j]; + } + } + } + else { + System.err.println(this.getClass().getCanonicalName() + + ": no lattice vectors info in molecule. Generating the default one"); + latticeVectors = new double[3][3]; + latticeVectors[0][0] = (molecule.getXmax() - molecule.getXmin()); + latticeVectors[1][1] = (molecule.getYmax() - molecule.getYmin()); + latticeVectors[2][2] = (molecule.getZmax() - molecule.getZmin()); + } + + } + + @Override + public void replicateCell(CELL_PARAMETER direction, int repetition_factor) throws Exception { + + try { + initialize(); + } + catch (Exception ex) { + throw new Exception(ex.getMessage()); + } + + int index = 0; + int index_1, index_2, index_3; + int factor = Math.abs(repetition_factor); + switch (direction) { + case ALPHA: + case BETHA: + case GAMMA: + return; + case A: + index = 0; + if (repetition_factor < 0) { + index = 3; + } + index_1 = 0; + index_2 = 1; + index_3 = 2; + break; + case B: + index = 1; + if (repetition_factor < 0) { + index = 4; + } + index_1 = 1; + index_2 = 0; + index_3 = 2; + break; + case C: + index = 2; + if (repetition_factor < 0) { + index = 5; + } + index_1 = 2; + index_2 = 0; + index_3 = 1; + break; + + default: + return; + } + + if (repetitionFactors[index] == factor) { + return; // Nothing to replicate + } + else if (repetitionFactors[index] < factor) { // Add replicas + + MoleculeInterface cell = referenceMolecule.getInstance(); + cell.appendMolecule(referenceMolecule); + + replicateMolecule(direction, repetition_factor); + } + + else if (repetitionFactors[index] > factor) { // remove replicas + deReplicateMolecule(direction, repetition_factor); + } + } + + private void replicateMolecule(CELL_PARAMETER direction, int repetition_factor) { + + int i_start = -repetitionFactors[3]; + int i_end = repetitionFactors[0]; + int j_start = -repetitionFactors[4]; + int j_end = repetitionFactors[1]; + int k_start = -repetitionFactors[5]; + int k_end = repetitionFactors[2]; + + double x2, y2, z2, an, bn, cn; + + if (repetition_factor < 0) { + switch (direction) { + case A: + i_start = repetition_factor; + break; + case B: + j_start = repetition_factor; + break; + case C: + k_start = repetition_factor; + break; + } + } + else { + switch (direction) { + case A: + i_end = repetition_factor; + break; + case B: + j_end = repetition_factor; + break; + case C: + k_end = repetition_factor; + break; + } + } + + int factor = Math.abs(repetition_factor); + + for (int i = i_start; i < i_end; i++) { + an = i; + for (int j = j_start; j < j_end; j++) { + bn = j; + for (int k = k_start; k < k_end; k++) { + + try { + if (superCube.getValue(i, j, k) != null) { + continue; + } + } + catch (Exception ex) { + + } + if (i == 0 && j == 0 && k == 0) { + continue; + } + + cn = k; + + MoleculeInterface cell = referenceMolecule.getInstance(); + cell.appendMolecule(referenceMolecule); + + List atoms = new ArrayList (cell.getNumberOfAtoms()); + + for (int ind = 0; ind < cell.getNumberOfAtoms(); ind++) { + AtomInterface atom = cell.getAtomInterface(ind); + atoms.add(atom); + + x2 = an * latticeVectors[0][0] + bn * latticeVectors[1][0] + cn * latticeVectors[2][0]; + y2 = an * latticeVectors[0][1] + bn * latticeVectors[1][1] + cn * latticeVectors[2][1]; + z2 = an * latticeVectors[0][2] + bn * latticeVectors[1][2] + cn * latticeVectors[2][2]; + + atom.setX(atom.getX() + (float) x2); + atom.setY(atom.getY() + (float) y2); + atom.setZ(atom.getZ() + (float) z2); + } + + // --- We MERGE molecules, NOT just APPENDING + java3dUniverse.appendMolecule(cell, true); + + CellObject cellObj = new CellObject(atoms); + try { + superCube.setValue(i, j, k, cellObj); + } + catch (Exception ex) { + System.err.println(ex.getMessage() + " Ignored..."); + } + } + } + } + + //x2 = x * vectors[0][0] + y * vectors[1][0] + z * vectors[2][0]; + //y2 = x * vectors[0][1] + y * vectors[1][1] + z * vectors[2][1]; + //z2 = x * vectors[0][2] + y * vectors[1][2] + z * vectors[2][2]; + + if (repetition_factor > 0) { + switch (direction) { + case A: + repetitionFactors[0] = repetition_factor; + break; + case B: + repetitionFactors[1] = repetition_factor; + break; + case C: + repetitionFactors[2] = repetition_factor; + break; + } + //repetitionFactors[0] = factor; + } + else { + switch (direction) { + case A: + repetitionFactors[3] = factor; + break; + case B: + repetitionFactors[4] = factor; + break; + case C: + repetitionFactors[5] = factor; + break; + } + //repetitionFactors[3] = factor; + } + } + + private void deReplicateMolecule(CELL_PARAMETER direction, int repetition_factor) { + + int i_start = -repetitionFactors[3]; + int i_end = repetitionFactors[0]; + int j_start = -repetitionFactors[4]; + int j_end = repetitionFactors[1]; + int k_start = -repetitionFactors[5]; + int k_end = repetitionFactors[2]; + + if (repetition_factor <= 0) { + switch (direction) { + case A: + i_end = repetition_factor; + break; + case B: + j_end = repetition_factor; + break; + case C: + k_end = repetition_factor; + break; + } + } + else { + switch (direction) { + case A: + i_start = repetition_factor; + break; + case B: + j_start = repetition_factor; + break; + case C: + k_start = repetition_factor; + break; + } + + } + + int factor = Math.abs(repetition_factor); + + for (int i = i_start; i < i_end; i++) { + for (int j = j_start; j < j_end; j++) { + for (int k = k_start; k < k_end; k++) { + + try { + if (superCube.getValue(i, j, k) == null) { + continue; + } + } + catch (Exception ex) { + + } + if (i == 0 && j == 0 && k == 0) { + continue; + } + + CellObject cellObj = null; + try { + cellObj = (CellObject) superCube.getValue(i, j, k); + } + catch (Exception ex) { + + } + List atoms = cellObj.getAtoms(); + + for (int ind = 0; ind < atoms.size(); ind++) { + AtomInterface atom = atoms.get(ind); + java3dUniverse.deleteAtom(atom); + } + + try { + superCube.setValue(i, j, k, null); + } + catch (Exception ex) { + System.err.println(ex.getMessage() + " Ignored..."); + } + } + } + } + + //x2 = x * vectors[0][0] + y * vectors[1][0] + z * vectors[2][0]; + //y2 = x * vectors[0][1] + y * vectors[1][1] + z * vectors[2][1]; + //z2 = x * vectors[0][2] + y * vectors[1][2] + z * vectors[2][2]; + + if (repetition_factor > 0) { + switch (direction) { + case A: + repetitionFactors[0] = repetition_factor; + break; + case B: + repetitionFactors[1] = repetition_factor; + break; + case C: + repetitionFactors[2] = repetition_factor; + break; + } + //repetitionFactors[0] = factor; + } + else { + switch (direction) { + case A: + repetitionFactors[3] = factor; + break; + case B: + repetitionFactors[4] = factor; + break; + case C: + repetitionFactors[5] = factor; + break; + } + //repetitionFactors[3] = factor; + } + } + + class SuperCube { + private int iLow = -50, iHigh = 50; + private int jLow = -50, jHigh = 50; + private int kLow = -50, kHigh = 50; + + private boolean reallocatable = true; + + private Object[][][] cube = null; + + public SuperCube() { + cube = new Object[iHigh - iLow][jHigh - jLow][kHigh - kLow]; + } + + public void setValue(int i, int j, int k, Object value) throws Exception { + + checkIndexes(i, j, k); + + int ii = i - iLow; + int jj = j - jLow; + int kk = k - kLow; + + cube[ii][jj][kk] = value; + } + + public Object getValue(int i, int j, int k) throws Exception { + + checkIndexes(i, j, k); + + int ii = i - iLow; + int jj = j - jLow; + int kk = k - kLow; + + return cube[ii][jj][kk]; + } + + private void checkIndexes(int i, int j, int k) throws Exception { + if (i < iLow) { + throw new Exception("i < iLow"); + } + if (j < jLow) { + throw new Exception("j < jLow"); + } + if (k < kLow) { + throw new Exception("k < kLow"); + } + if (i > iHigh) { + throw new Exception("i > iHigh"); + } + if (j > jHigh) { + throw new Exception("j > jHigh"); + } + if (k > kHigh) { + throw new Exception("k > kHigh"); + } + } + } + + class CellObject { + private List atoms = null; + public CellObject(List at) { + atoms = at; + } + + public List getAtoms() { + return atoms; + } + } +} diff --git a/src/main/java/cct/j3d/USER_DATA_FLAG.java b/src/main/java/cct/j3d/USER_DATA_FLAG.java new file mode 100644 index 0000000..6bd3b28 --- /dev/null +++ b/src/main/java/cct/j3d/USER_DATA_FLAG.java @@ -0,0 +1,57 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public enum USER_DATA_FLAG { + FUN_VALUES_AT_VERTICES, MIN_FUN_VALUE_AT_VERTICES, MAX_FUN_VALUE_AT_VERTICES, COLOR_PALETTE_ARRAY, + MIN_CLIP_FUN_VALUE_AT_VERTICES, MAX_CLIP_FUN_VALUE_AT_VERTICES, COLOR_RANGE_SCHEME_OBJECT; + USER_DATA_FLAG() { + } +} diff --git a/src/main/java/cct/j3d/UnitCellGraphics.java b/src/main/java/cct/j3d/UnitCellGraphics.java new file mode 100644 index 0000000..7e6da1a --- /dev/null +++ b/src/main/java/cct/j3d/UnitCellGraphics.java @@ -0,0 +1,449 @@ +package cct.j3d; + +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +import org.scijava.java3d.Appearance; +import org.scijava.java3d.GeometryArray; +import org.scijava.java3d.LineArray; +import org.scijava.java3d.LineAttributes; +import org.scijava.java3d.Node; +import org.scijava.java3d.QuadArray; +import org.scijava.java3d.Shape3D; +import org.scijava.java3d.TransparencyAttributes; +import org.scijava.vecmath.Color3f; +import org.scijava.vecmath.Point3f; + +import cct.interfaces.GraphicsObjectInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class UnitCellGraphics { + + private String graphicsName = "Unit Cell"; + + public UnitCellGraphics(String name) { + graphicsName = name; + } + + public void setGraphicsName(String name) { + graphicsName = name; + } + + public GraphicsObjectInterface getCellGraphicsObject(double[][] vecs) { + float[][] latticeVectors = new float[3][3]; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + latticeVectors[i][j] = (float) vecs[i][j]; + } + } + return getCellGraphicsObject(latticeVectors); + } + + public GraphicsObjectInterface getCellGraphicsObject(float[][] latticeVectors) { + + GraphicsObjectInterface graphics = new VerticesObject(); + graphics.setName(graphicsName); + + GraphicsObjectInterface cellFrame = new VerticesObject(); + cellFrame.setName("Lattice Frame"); + + Shape3D shape3d = new Shape3D(); + shape3d.setCapability(Node.ALLOW_PARENT_READ); + shape3d.setCapability(Shape3D.ALLOW_GEOMETRY_READ); + shape3d.setCapability(Shape3D.ALLOW_GEOMETRY_WRITE); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_READ); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_READ); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_WRITE); + + VerticesObjectProperties voP = new VerticesObjectProperties(); + + Color3f red = new Color3f(1.0f, 0.0f, 0.0f); + Color3f green = new Color3f(0.0f, 1.0f, 0.0f); + Color3f blue = new Color3f(0.0f, 0.0f, 1.0f); + Color3f grey = new Color3f(0.5f, 0.5f, 0.5f); + + Appearance app = voP.getAppearence(red); + + LineAttributes la = new LineAttributes(2.0f, LineAttributes.PATTERN_SOLID, true); + app.setLineAttributes(la); + + //TransparencyAttributes ta = new TransparencyAttributes(); + //ta.setTransparency(0.7f); + //app.setTransparencyAttributes(ta); + + // --- Create frame cell + + LineArray frame = new LineArray(24, GeometryArray.COORDINATES | GeometryArray.COLOR_3); + + // --- OX + Point3f[] coordinates = new Point3f[2]; + coordinates[0] = new Point3f(0, 0, 0); + coordinates[1] = new Point3f(latticeVectors[0][0], latticeVectors[0][1], latticeVectors[0][2]); + frame.setCoordinates(0, coordinates); + frame.setColor(0, red); + frame.setColor(1, red); + // --- OY + coordinates = new Point3f[2]; + coordinates[0] = new Point3f(0, 0, 0); + coordinates[1] = new Point3f(latticeVectors[1][0], latticeVectors[1][1], latticeVectors[1][2]); + frame.setCoordinates(2, coordinates); + frame.setColor(2, green); + frame.setColor(3, green); + // --- OZ + coordinates = new Point3f[2]; + coordinates[0] = new Point3f(0, 0, 0); + coordinates[1] = new Point3f(latticeVectors[2][0], latticeVectors[2][1], latticeVectors[2][2]); + frame.setCoordinates(4, coordinates); + frame.setColor(4, blue); + frame.setColor(5, blue); + + int offset = 6; + float x, y, z; + + // --- Parallel OZ + for (int i = 0; i < 2; i++) { + if (i == 0) { + x = y = z = 0; + } + else { + x = latticeVectors[0][0]; + y = latticeVectors[0][1]; + z = latticeVectors[0][2]; + } + for (int j = 0; j < 2; j++) { + if (i == 0 && j == 0) { + continue; + } + + if (j != 0) { + x += latticeVectors[1][0]; + y += latticeVectors[1][1]; + z += latticeVectors[1][2]; + + } + coordinates = new Point3f[2]; + coordinates[0] = new Point3f(x, y, z); + coordinates[1] = new Point3f(x + latticeVectors[2][0], y + latticeVectors[2][1], z + latticeVectors[2][2]); + + frame.setCoordinates(offset, coordinates); + frame.setColor(offset, grey); + frame.setColor(offset + 1, grey); + offset += 2; + } + } + + // --- Parallel OY + for (int i = 0; i < 2; i++) { + if (i == 0) { + x = y = z = 0; + } + else { + x = latticeVectors[0][0]; + y = latticeVectors[0][1]; + z = latticeVectors[0][2]; + } + for (int j = 0; j < 2; j++) { + if (i == 0 && j == 0) { + continue; + } + + if (j != 0) { + x += latticeVectors[2][0]; + y += latticeVectors[2][1]; + z += latticeVectors[2][2]; + + } + coordinates = new Point3f[2]; + coordinates[0] = new Point3f(x, y, z); + coordinates[1] = new Point3f(x + latticeVectors[1][0], y + latticeVectors[1][1], z + latticeVectors[1][2]); + + frame.setCoordinates(offset, coordinates); + frame.setColor(offset, grey); + frame.setColor(offset + 1, grey); + offset += 2; + } + } + + // --- Parallel OX + for (int i = 0; i < 2; i++) { + if (i == 0) { + x = y = z = 0; + } + else { + x = latticeVectors[1][0]; + y = latticeVectors[1][1]; + z = latticeVectors[1][2]; + } + for (int j = 0; j < 2; j++) { + if (i == 0 && j == 0) { + continue; + } + + if (j != 0) { + x += latticeVectors[2][0]; + y += latticeVectors[2][1]; + z += latticeVectors[2][2]; + + } + coordinates = new Point3f[2]; + coordinates[0] = new Point3f(x, y, z); + coordinates[1] = new Point3f(x + latticeVectors[0][0], y + latticeVectors[0][1], z + latticeVectors[0][2]); + + frame.setCoordinates(offset, coordinates); + frame.setColor(offset, grey); + frame.setColor(offset + 1, grey); + offset += 2; + } + } + + shape3d.setAppearance(app); + shape3d.setGeometry(frame); + + cellFrame.addGraphics("Cell Frame", shape3d); + + // --- Create quads... + + Color3f cyan = new Color3f(0.0f, 1.0f, 1.0f); + Color3f magenta = new Color3f(1.0f, 0.0f, 1.0f); + Color3f yellow = new Color3f(1.0f, 1.0f, 0.0f); + + GraphicsObjectInterface cellWalls = new VerticesObject(); + cellWalls.setName("Lattice faces"); + + shape3d = new Shape3D(); + shape3d.setCapability(Node.ALLOW_PARENT_READ); + shape3d.setCapability(Shape3D.ALLOW_GEOMETRY_READ); + shape3d.setCapability(Shape3D.ALLOW_GEOMETRY_WRITE); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_READ); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_READ); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_WRITE); + + voP = new VerticesObjectProperties(); + + app = voP.getAppearence(red); + TransparencyAttributes ta = new TransparencyAttributes(); + ta.setTransparency(0.9f); + ta.setTransparencyMode(TransparencyAttributes.BLENDED); + app.setTransparencyAttributes(ta); + + QuadArray quadArray = new QuadArray(6 * 4, GeometryArray.COORDINATES | GeometryArray.COLOR_3); + + float[] quadCoords = new float[12]; + + // 1st plane XOY + + quadCoords[0] = 0; + quadCoords[1] = 0; + quadCoords[2] = 0; + + quadCoords[3] = latticeVectors[0][0]; + quadCoords[4] = latticeVectors[0][1]; + quadCoords[5] = latticeVectors[0][2]; + + quadCoords[6] = latticeVectors[0][0] + latticeVectors[1][0]; + quadCoords[7] = latticeVectors[0][1] + latticeVectors[1][1]; + quadCoords[8] = latticeVectors[0][2] + latticeVectors[1][2]; + + quadCoords[9] = latticeVectors[1][0]; + quadCoords[10] = latticeVectors[1][1]; + quadCoords[11] = latticeVectors[1][2]; + + quadArray.setCoordinates(0, quadCoords); + + quadArray.setColor(0, yellow); + quadArray.setColor(1, yellow); + quadArray.setColor(2, yellow); + quadArray.setColor(3, yellow); + + // 2st plane XOZ + + quadCoords = new float[12]; + + quadCoords[0] = 0; + quadCoords[1] = 0; + quadCoords[2] = 0; + + quadCoords[3] = latticeVectors[0][0]; + quadCoords[4] = latticeVectors[0][1]; + quadCoords[5] = latticeVectors[0][2]; + + quadCoords[6] = latticeVectors[0][0] + latticeVectors[2][0]; + quadCoords[7] = latticeVectors[0][1] + latticeVectors[2][1]; + quadCoords[8] = latticeVectors[0][2] + latticeVectors[2][2]; + + quadCoords[9] = latticeVectors[2][0]; + quadCoords[10] = latticeVectors[2][1]; + quadCoords[11] = latticeVectors[2][2]; + + quadArray.setCoordinates(4, quadCoords); + + quadArray.setColor(4, magenta); + quadArray.setColor(5, magenta); + quadArray.setColor(6, magenta); + quadArray.setColor(7, magenta); + + // 3st plane YOZ + + quadCoords = new float[12]; + + quadCoords[0] = 0; + quadCoords[1] = 0; + quadCoords[2] = 0; + + quadCoords[3] = latticeVectors[1][0]; + quadCoords[4] = latticeVectors[1][1]; + quadCoords[5] = latticeVectors[1][2]; + + quadCoords[6] = latticeVectors[1][0] + latticeVectors[2][0]; + quadCoords[7] = latticeVectors[1][1] + latticeVectors[2][1]; + quadCoords[8] = latticeVectors[1][2] + latticeVectors[2][2]; + + quadCoords[9] = latticeVectors[2][0]; + quadCoords[10] = latticeVectors[2][1]; + quadCoords[11] = latticeVectors[2][2]; + + quadArray.setCoordinates(8, quadCoords); + + quadArray.setColor(8, cyan); + quadArray.setColor(9, cyan); + quadArray.setColor(10, cyan); + quadArray.setColor(11, cyan); + + // 4th plane XOY upper + + quadCoords[0] = latticeVectors[2][0]; + quadCoords[1] = latticeVectors[2][1]; + quadCoords[2] = latticeVectors[2][2]; + + quadCoords[3] = latticeVectors[2][0] + latticeVectors[0][0]; + quadCoords[4] = latticeVectors[2][1] + latticeVectors[0][1]; + quadCoords[5] = latticeVectors[2][2] + latticeVectors[0][2]; + + quadCoords[6] = latticeVectors[2][0] + latticeVectors[0][0] + latticeVectors[1][0]; + quadCoords[7] = latticeVectors[2][1] + latticeVectors[0][1] + latticeVectors[1][1]; + quadCoords[8] = latticeVectors[2][2] + latticeVectors[0][2] + latticeVectors[1][2]; + + quadCoords[9] = latticeVectors[2][0] + latticeVectors[1][0]; + quadCoords[10] = latticeVectors[2][1] + latticeVectors[1][1]; + quadCoords[11] = latticeVectors[2][2] + latticeVectors[1][2]; + + quadArray.setCoordinates(12, quadCoords); + + quadArray.setColor(12, grey); + quadArray.setColor(13, grey); + quadArray.setColor(14, grey); + quadArray.setColor(15, grey); + + // 5th plane XOZ upper + + quadCoords = new float[12]; + + quadCoords[0] = latticeVectors[1][0]; + quadCoords[1] = latticeVectors[1][1]; + quadCoords[2] = latticeVectors[1][2]; + + quadCoords[3] = latticeVectors[1][0] + latticeVectors[0][0]; + quadCoords[4] = latticeVectors[1][1] + latticeVectors[0][1]; + quadCoords[5] = latticeVectors[1][2] + latticeVectors[0][2]; + + quadCoords[6] = latticeVectors[1][0] + latticeVectors[0][0] + latticeVectors[2][0]; + quadCoords[7] = latticeVectors[1][1] + latticeVectors[0][1] + latticeVectors[2][1]; + quadCoords[8] = latticeVectors[1][2] + latticeVectors[0][2] + latticeVectors[2][2]; + + quadCoords[9] = latticeVectors[1][0] + latticeVectors[2][0]; + quadCoords[10] = latticeVectors[1][1] + latticeVectors[2][1]; + quadCoords[11] = latticeVectors[1][2] + latticeVectors[2][2]; + + quadArray.setCoordinates(16, quadCoords); + + quadArray.setColor(16, grey); + quadArray.setColor(17, grey); + quadArray.setColor(18, grey); + quadArray.setColor(19, grey); + + // 6st plane YOZ upper + + quadCoords = new float[12]; + + quadCoords[0] = latticeVectors[0][0]; + quadCoords[1] = latticeVectors[0][1]; + quadCoords[2] = latticeVectors[0][2]; + + quadCoords[3] = latticeVectors[0][0] + latticeVectors[1][0]; + quadCoords[4] = latticeVectors[0][1] + latticeVectors[1][1]; + quadCoords[5] = latticeVectors[0][2] + latticeVectors[1][2]; + + quadCoords[6] = latticeVectors[0][0] + latticeVectors[1][0] + latticeVectors[2][0]; + quadCoords[7] = latticeVectors[0][1] + latticeVectors[1][1] + latticeVectors[2][1]; + quadCoords[8] = latticeVectors[0][2] + latticeVectors[1][2] + latticeVectors[2][2]; + + quadCoords[9] = latticeVectors[0][0] + latticeVectors[2][0]; + quadCoords[10] = latticeVectors[0][1] + latticeVectors[2][1]; + quadCoords[11] = latticeVectors[0][2] + latticeVectors[2][2]; + + quadArray.setCoordinates(20, quadCoords); + + quadArray.setColor(20, grey); + quadArray.setColor(21, grey); + quadArray.setColor(22, grey); + quadArray.setColor(23, grey); + + shape3d.setGeometry(quadArray); + shape3d.setAppearance(app); + + cellWalls.addGraphics("VASP Lattice faces", shape3d); + cellWalls.setVisible(false); + + graphics.addGraphics(cellFrame); + graphics.addGraphics(cellWalls); + + return graphics; + } +} diff --git a/src/main/java/cct/j3d/UserData.java b/src/main/java/cct/j3d/UserData.java new file mode 100644 index 0000000..032394f --- /dev/null +++ b/src/main/java/cct/j3d/UserData.java @@ -0,0 +1,60 @@ +package cct.j3d; + +import java.util.HashMap; + +import org.scijava.java3d.SceneGraphObject; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class UserData + extends HashMap { + + public static final String NODE_NAME = "node_name"; + + public UserData() { + super(); + } + + public static void setUserData(SceneGraphObject target, String name, Object data) { + UserData ud = null; + Object obj = target.getUserData(); + if (obj == null) { + ud = new UserData(); + } + else if (obj instanceof UserData) { + ud = (UserData) obj; + } + else { + System.err.println("Expected UserData class, got " + obj.getClass().getCanonicalName() + " Overwitten..."); + ud = new UserData(); + } + ud.put(name, data); + target.setUserData(ud); + } + + public static String getUserDataAsString(SceneGraphObject target, String name) { + UserData ud = null; + Object obj = target.getUserData(); + if (obj == null) { + return ""; + } + else if (obj instanceof UserData) { + ud = (UserData) obj; + } + else { + System.err.println("getUserDataAsString: Expected UserData class, got " + obj.getClass().getCanonicalName() + " Ignored..."); + return ""; + } + return ud.get(name).toString(); + } +} diff --git a/src/main/java/cct/j3d/VerticesObject.java b/src/main/java/cct/j3d/VerticesObject.java new file mode 100644 index 0000000..738925c --- /dev/null +++ b/src/main/java/cct/j3d/VerticesObject.java @@ -0,0 +1,628 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import java.awt.Component; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.scijava.java3d.BranchGroup; +import org.scijava.java3d.Group; +import org.scijava.java3d.Shape3D; + +import cct.interfaces.GraphicsObjectInterface; +import cct.j3d.ui.VerticesPropertyPanel; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class VerticesObject + implements GraphicsObjectInterface { + + String Name; + List Graphics = new ArrayList(); + List Elements = new ArrayList(); + Map visualComponents = new HashMap (); + Map AuxNames = new HashMap(); + VerticesPropertyPanel propPanel = null; + + public VerticesObject() { + } + + public static void main(String[] args) { + VerticesObject verticesobject = new VerticesObject(); + } + + public void setPolygonRendering(int mode) { + for (int i = 0; i < Graphics.size(); i++) { + Object obj = Graphics.get(i); + if (obj instanceof VerticesObject) { + ( (VerticesObject) obj).setPolygonRendering(mode); + } + else if (obj instanceof Shape3D || obj instanceof BranchGroup) { + VerticesPropertyPanel vComp = visualComponents.get(obj); + + if (vComp == null) { + vComp = new VerticesPropertyPanel(); + visualComponents.put(obj, vComp); + } + + try { + vComp.setPolygoneMode(mode); + } + catch (Exception ex) {} + } + else { + System.err.println(this.getClass().getCanonicalName() + ": setPolygonRendering: don't know how to handle class " + + obj.getClass().getCanonicalName()); + } + } + + } + + public void setShininess(float shininess) { + for (int i = 0; i < Graphics.size(); i++) { + Object obj = Graphics.get(i); + if (obj instanceof VerticesObject) { + ( (VerticesObject) obj).setShininess(shininess); + } + else if (obj instanceof Shape3D || obj instanceof BranchGroup) { + VerticesPropertyPanel vComp = visualComponents.get(obj); + + if (vComp == null) { + vComp = new VerticesPropertyPanel(); + visualComponents.put(obj, vComp); + } + + vComp.setShininess(shininess); + } + else { + System.err.println(this.getClass().getCanonicalName() + ": setShininess: don't know how to handle class " + + obj.getClass().getCanonicalName()); + } + + } + } + + public void setTransparency(float transp) { + for (int i = 0; i < Graphics.size(); i++) { + Object obj = Graphics.get(i); + if (obj instanceof VerticesObject) { + ( (VerticesObject) obj).setTransparency(transp); + } + else if (obj instanceof Shape3D || obj instanceof BranchGroup) { + VerticesPropertyPanel vComp = visualComponents.get(obj); + + if (vComp == null) { + vComp = new VerticesPropertyPanel(); + visualComponents.put(obj, vComp); + } + + vComp.setTransparency(transp); + } + else { + System.err.println(this.getClass().getCanonicalName() + ": setTransparency: don't know how to handle class " + + obj.getClass().getCanonicalName()); + } + + } + } + + public void setTransparencyMode(int mode) { + for (int i = 0; i < Graphics.size(); i++) { + Object obj = Graphics.get(i); + if (obj instanceof VerticesObject) { + ( (VerticesObject) obj).setTransparencyMode(mode); + } + else if (obj instanceof Shape3D || obj instanceof BranchGroup) { + VerticesPropertyPanel vComp = visualComponents.get(obj); + + if (vComp == null) { + vComp = new VerticesPropertyPanel(); + visualComponents.put(obj, vComp); + } + + vComp.setTransparencyMode(mode); + } + else { + System.err.println(this.getClass().getCanonicalName() + ": setTransparencyMode: don't know how to handle class " + + obj.getClass().getCanonicalName()); + } + + } + } + + /** + * Returns true is at least one component is opaque + * @return boolean + */ + public boolean isOpaque() { + for (int i = 0; i < Graphics.size(); i++) { + Object obj = Graphics.get(i); + + //if (obj instanceof GraphicsObjectInterface) { + // GraphicsObjectInterface graphics = (GraphicsObjectInterface) obj; + // if ( graphics.isVisible() ) return true; + //} + if (obj instanceof VerticesObject) { + VerticesObject graphics = (VerticesObject) obj; + if (graphics.isOpaque()) { + return true; + } + } + + else if (obj instanceof Shape3D || obj instanceof BranchGroup) { + VerticesPropertyPanel vComp = visualComponents.get(obj); + if (vComp != null && vComp.isObjectOpaque()) { + return true; + } + } + else { + System.err.println( + "isOpaque: don't know how to handle class " + obj.getClass().getCanonicalName()); + } + } + return false; + } + + /** + * Returns "true" if it's visible at least one component + * @return boolean + */ + @Override + public boolean isVisible() { + for (int i = 0; i < Graphics.size(); i++) { + Object obj = Graphics.get(i); + + if (obj instanceof GraphicsObjectInterface) { + GraphicsObjectInterface graphics = (GraphicsObjectInterface) obj; + if (graphics.isVisible()) { + return true; + } + } + else if (obj instanceof Shape3D || obj instanceof BranchGroup) { + VerticesPropertyPanel vComp = visualComponents.get(obj); + if (vComp != null && vComp.isObjectVisible()) { + return true; + } + } + else { + System.err.println( + "isVisible: don't know how to handle class " + obj.getClass().getCanonicalName()); + } + } + return false; + } + + /* + public void setVisible(boolean visible) { + + propPanel.setObjectOpaque(visible); + + for (int i = 0; i < Graphics.size(); i++) { + Object obj = Graphics.get(i); + + if (obj instanceof GraphicsObjectInterface) { + GraphicsObjectInterface graphics = (GraphicsObjectInterface) obj; + graphics.setVisible(visible); + } + else if (obj instanceof Shape3D || obj instanceof BranchGroup) { + VerticesPropertyPanel vComp = visualComponents.get(obj); + if (vComp != null && vComp.isObjectVisible()) { + vComp.setObjectVisible(visible); + } + } + else { + System.err.println( + "setVisible: don't know how to handle class " + obj.getClass().getCanonicalName()); + } + } + } + */ + + @Override + public void addGraphics(GraphicsObjectInterface graphics) { + + Graphics.add(graphics); + visualComponents.put(graphics, null); + Elements.addAll(graphics.getShape3DElements()); + } + + @Override + public void addGraphics(String name, Shape3D graphics) { + + BranchGroup bGroup = new BranchGroup(); + bGroup.setCapability(Group.ALLOW_CHILDREN_READ); + bGroup.setCapability(Group.ALLOW_CHILDREN_WRITE); + bGroup.setCapability(Group.ALLOW_CHILDREN_EXTEND); + bGroup.setCapability(BranchGroup.ALLOW_DETACH); + bGroup.addChild(graphics); + //bGroup.setName(name); // --- >1.4 java3d feature + + Graphics.add(bGroup); + visualComponents.put(graphics, null); + Elements.add(bGroup); + //Elements.add(graphics); + AuxNames.put(graphics, name); + } + + @Override + public void removeAllGraphics() { + int n = Graphics.size() - 1; + + for (int i = n; i >= 0; i--) { + Object obj = Graphics.get(i); + + if (obj instanceof GraphicsObjectInterface) { + GraphicsObjectInterface graphics = (GraphicsObjectInterface) obj; + graphics.removeAllGraphics(); + Graphics.remove(i); + } + else if (obj instanceof Shape3D || obj instanceof BranchGroup) { + this._removeGraphics(obj); + Graphics.remove(i); + } + else { + System.err.println( + "isVisible: don't know how to handle class " + obj.getClass().getCanonicalName()); + } + } + + visualComponents.clear(); + Elements.clear(); + AuxNames.clear(); + } + + private void _removeGraphics(Object graphics) { + + visualComponents.remove(graphics); + Elements.remove(graphics); + AuxNames.remove(graphics); + + // --- Now detach it from root node + + if (graphics instanceof BranchGroup) { + BranchGroup bg = (BranchGroup) graphics; + if (bg.getParent() != null) { + bg.detach(); + bg = null; + } + } + else { + System.err.println( + "_removeGraphics: dont know how to handle class " + graphics.getClass().getCanonicalName()); + } + } + + @Override + public void removeGraphics(Object graphics) { + + if (!Graphics.contains(graphics)) { + System.err.println( + "removeGraphics: !Graphics.contains(graphics)"); + return; + } + + visualComponents.remove(graphics); + + Graphics.remove(graphics); + + Elements.remove(graphics); + + AuxNames.remove(graphics); + + // --- Now detach it from root node + + if (graphics instanceof BranchGroup) { + BranchGroup bg = (BranchGroup) graphics; + if (bg.getParent() != null) { + bg.detach(); + bg = null; + } + } + else { + System.err.println( + "removeGraphics: dont know how to handle class " + graphics.getClass().getCanonicalName()); + } + } + + @Override + public void setVisible(Object graphics, boolean visible) { + + if (!Graphics.contains(graphics)) { + System.err.println( + "setVisible: !Graphics.contains(graphics)"); + return; + } + + if (graphics instanceof GraphicsObjectInterface) { + GraphicsObjectInterface goi = (GraphicsObjectInterface) graphics; + goi.setVisible(visible); + } + else if (graphics instanceof Shape3D || graphics instanceof BranchGroup) { + VerticesPropertyPanel vComp = visualComponents.get(graphics); + if (vComp != null && vComp.isObjectVisible()) { + vComp.setObjectVisible(visible); + } + } + else { + System.err.println( + "setVisible: don't know how to handle class " + graphics.getClass().getCanonicalName()); + } + + visualComponents.remove(graphics); + + Graphics.remove(graphics); + + Elements.remove(graphics); + + AuxNames.remove(graphics); + + // --- Now detach it from root node + + if (graphics instanceof BranchGroup) { + BranchGroup bg = (BranchGroup) graphics; + if (bg.getParent() != null) { + bg.detach(); + bg = null; + } + } + else { + System.err.println( + "removeGraphics: dont know how to handle class " + graphics.getClass().getCanonicalName()); + } + } + + @Override + public String getName() { + return Name; + } + + @Override + public int getNGraphicsElements() { + return Graphics.size(); + } + + @Override + public Object getGraphicsElement(int n) { + if (Graphics == null || n < 0 || n >= Graphics.size()) { + System.err.println( + "getGraphicsElement: Graphics == null || n < 0 || n >=Graphics.size()"); + return null; + } + return Graphics.get(n); + } + + @Override + public List getShape3DElements() { + return new ArrayList(Elements); + } + + @Override + public void setName(String name) { + Name = name; + } + + @Override + public Component getVisualComponent() { + if (propPanel == null) { + + // --- initiate all visual components + + for (int i = 0; i < Graphics.size(); i++) { + Object obj = Graphics.get(i); + + if (obj instanceof GraphicsObjectInterface) { + GraphicsObjectInterface graphics = (GraphicsObjectInterface) obj; + graphics.getVisualComponent(); // just to initiate it... + } + else if (obj instanceof Shape3D) { + getVisualComponent(i); // just to initiate it... + } + else if (obj instanceof BranchGroup) { + getVisualComponent(i); // just to initiate it... + } + + else { + System.err.println( + "getVisualComponent: don't know how to handle class " + obj.getClass().getCanonicalName()); + } + } + + propPanel = new VerticesPropertyPanel(); + try { + propPanel.setPanel(this); + } + catch (Exception ex) { + System.err.println(this.getClass().getCanonicalName() + + ": getVisualComponent: " + ex.getMessage()); + } + + } + + if (Graphics.size() < 1) { + System.err.println(this.getClass().getCanonicalName() + ": getVisualComponent: Graphics.size() < 1"); + return null; + } + boolean graphics = Graphics.get(0) instanceof Shape3D || Graphics.get(0) instanceof BranchGroup; + if (getNGraphicsElements() == 1 && graphics) { + return getVisualComponent(0); + /* + Shape3D shape3d = (Shape3D) Graphics.get(0); + try { + Appearance app = shape3d.getAppearance(); + propPanel.setPanel(app); + } + catch (Exception ex) { + System.err.println(this.getClass().getCanonicalName() + + ": getVisualComponent: " + ex.getMessage()); + } + */ + } + + propPanel.updatePanel(); + return propPanel; + } + + @Override + public Component getVisualComponent(int n) { + + if (Graphics == null || n < 0 || n >= Graphics.size()) { + System.err.println( + "getVisualComponent: Graphics == null || n < 0 || n >=Graphics.size()"); + return null; + } + + Object obj = Graphics.get(n); + + if (obj instanceof GraphicsObjectInterface) { + GraphicsObjectInterface graphics = (GraphicsObjectInterface) obj; + return graphics.getVisualComponent(); + } + + // --- If it's Shape3D + + Shape3D shape3d = null; + + if (obj instanceof Shape3D) { + shape3d = (Shape3D) obj; + } + else if (obj instanceof BranchGroup) { + shape3d = getFirstShape3D( (BranchGroup) obj); + } + else { + System.err.println(this.getClass().getCanonicalName() + ": getVisualComponent: don't know how to handle class " + + obj.getClass().getCanonicalName()); + return null; + } + + // --- Special case + + VerticesPropertyPanel vComp = visualComponents.get(obj); + + if (vComp == null) { + vComp = new VerticesPropertyPanel(); + visualComponents.put(obj, vComp); + } + + try { + //Appearance app = shape3d.getAppearance(); + vComp.setPanel(shape3d); + } + catch (Exception ex) { + System.err.println(this.getClass().getCanonicalName() + + ": getVisualComponent(n): " + ex.getMessage()); + } + + return vComp; + } + + private Shape3D getFirstShape3D(BranchGroup bg) { + for (int i = 0; i < bg.numChildren(); i++) { + if (bg.getChild(i) instanceof Shape3D) { + return (Shape3D) bg.getChild(i); + } + } + return null; + } + + @Override + public void setVisible(boolean visible) { + for (int i = 0; i < Graphics.size(); i++) { + Object obj = Graphics.get(i); + + //if (obj instanceof GraphicsObjectInterface) { + // GraphicsObjectInterface graphics = (GraphicsObjectInterface) obj; + // if ( graphics.isVisible() ) return true; + //} + if (obj instanceof VerticesObject) { + VerticesObject graphics = (VerticesObject) obj; + graphics.setVisible(visible); + } + + else if (obj instanceof Shape3D || obj instanceof BranchGroup) { + VerticesPropertyPanel vComp = visualComponents.get(obj); + if (vComp != null) { + vComp.setObjectVisible(visible); + } + } + else { + System.err.println( + "setVisible: don't know how to handle class " + obj.getClass().getCanonicalName()); + } + } + } + + public void setOpaque(boolean opaque) { + for (int i = 0; i < Graphics.size(); i++) { + Object obj = Graphics.get(i); + + //if (obj instanceof GraphicsObjectInterface) { + // GraphicsObjectInterface graphics = (GraphicsObjectInterface) obj; + // if ( graphics.isVisible() ) return true; + //} + if (obj instanceof VerticesObject) { + VerticesObject graphics = (VerticesObject) obj; + graphics.setOpaque(opaque); + } + + else if (obj instanceof Shape3D || obj instanceof BranchGroup) { + VerticesPropertyPanel vComp = visualComponents.get(obj); + if (vComp != null) { + vComp.setObjectOpaque(opaque); + } + } + else { + System.err.println( + "setOpaque: don't know how to handle class " + obj.getClass().getCanonicalName()); + } + } + } + +} diff --git a/src/main/java/cct/j3d/VerticesObjectProperties.java b/src/main/java/cct/j3d/VerticesObjectProperties.java new file mode 100644 index 0000000..6f40965 --- /dev/null +++ b/src/main/java/cct/j3d/VerticesObjectProperties.java @@ -0,0 +1,358 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.scijava.java3d.Appearance; +import org.scijava.java3d.Material; +import org.scijava.java3d.PolygonAttributes; +import org.scijava.java3d.TransparencyAttributes; +import org.scijava.vecmath.Color3f; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class VerticesObjectProperties { + + public static final int SOLID = 0; + public static final int WIREFRAME = 1; + public static final int POINTS = 2; + + static final String[] Style_name = { + "Solid", "Wireframe", "Points"}; + + static final String[] Transp_modes = { + "Fastest", "Nicest", "Screen Door", "Blended"}; + + static final Map availableTransp = new LinkedHashMap(); + + static { + availableTransp.put("Fastest", new Integer(TransparencyAttributes.FASTEST)); + availableTransp.put("Nicest", new Integer(TransparencyAttributes.NICEST)); + availableTransp.put("Screen Door", + new Integer(TransparencyAttributes.SCREEN_DOOR)); + availableTransp.put("Blended", new Integer(TransparencyAttributes.BLENDED)); + } + + boolean Visible = true; + boolean Lit = true; + int Style = SOLID; + int transparencyMode = TransparencyAttributes.BLENDED; + float Transparency = 0; + int polygonMode = PolygonAttributes.POLYGON_FILL; + int cullFace = PolygonAttributes.CULL_NONE; + boolean backFaceNormalFlip = true; + + public VerticesObjectProperties() { + } + + public static void main(String[] args) { + VerticesObjectProperties verticesobjectproperties = new + VerticesObjectProperties(); + } + + public void setLit(boolean lit) { + Lit = lit; + } + + public boolean isLit() { + return Lit; + } + + public int getStyle() { + return Style; + } + + public void setStyle(int style) { + if (style < SOLID || style > POINTS) { + System.err.println(this.getClass().getCanonicalName() + + ": setStyle: style < SOLID || style > POINTS: ignored..."); + } + else { + Style = style; + } + } + + public String getStyleAsString() { + return Style_name[Style]; + } + + public int getTransparencyMode() { + return transparencyMode; + } + + public void setTransparencyMode(int mode) { + if (mode != TransparencyAttributes.NONE && + mode != TransparencyAttributes.FASTEST && + mode != TransparencyAttributes.NICEST && + mode != TransparencyAttributes.SCREEN_DOOR && + mode != TransparencyAttributes.BLENDED) { + System.err.println(this.getClass().getCanonicalName() + + ": setTransparency: Wrong Transparency value: ignored..."); + return; + } + transparencyMode = mode; + } + + public float getTransparency() { + return Transparency; + } + + /** + * + * @param value float - the appearance's transparency in the range [0.0, 1.0] + * with 0.0 being fully opaque and 1.0 being fully transparent + */ + public void setTransparency(float value) { + if (value < 0) { + value = 0; + } + else if (value > 1) { + value = 1; + } + Transparency = value; + } + + public int getPolygonMode() { + return polygonMode; + } + + /** + * Sets the polygon rasterization mode. + * @param mode int - Could be PolygonAttributes.POLYGON_FILL, PolygonAttributes.POLYGON_LINE, + * or PolygonAttributes.POLYGON_POINT + */ + public void setPolygonMode(int mode) { + if (mode != PolygonAttributes.POLYGON_FILL && + mode != PolygonAttributes.POLYGON_LINE && + mode != PolygonAttributes.POLYGON_POINT) { + System.err.println(this.getClass().getCanonicalName() + + ": setPolygonMode: Wrong Transparency value: ignored..."); + return; + } + polygonMode = mode; + } + + public Appearance getAppearence(Color3f objColor) { + + Color3f black = new Color3f(0.0f, 0.0f, 0.0f); + Color3f white = new Color3f(1.0f, 1.0f, 1.0f); + + Appearance app = new Appearance(); + + app.setCapability(Appearance.ALLOW_COLORING_ATTRIBUTES_READ); + app.setCapability(Appearance.ALLOW_COLORING_ATTRIBUTES_WRITE); + + app.setCapability(Appearance.ALLOW_LINE_ATTRIBUTES_READ); + app.setCapability(Appearance.ALLOW_LINE_ATTRIBUTES_WRITE); + + app.setCapability(Appearance.ALLOW_MATERIAL_READ); + app.setCapability(Appearance.ALLOW_MATERIAL_WRITE); + + app.setCapability(Appearance.ALLOW_POINT_ATTRIBUTES_READ); + app.setCapability(Appearance.ALLOW_POINT_ATTRIBUTES_WRITE); + + app.setCapability(Appearance.ALLOW_POLYGON_ATTRIBUTES_READ); + app.setCapability(Appearance.ALLOW_POLYGON_ATTRIBUTES_WRITE); + + app.setCapability(Appearance.ALLOW_TRANSPARENCY_ATTRIBUTES_READ); + app.setCapability(Appearance.ALLOW_TRANSPARENCY_ATTRIBUTES_WRITE); + + // --- Set up the material properties + + Material material = new Material(); + + // --- Diffuse Color + material.setDiffuseColor(objColor); + + // --- Ambient Color + //material.setAmbientColor(0.1f * objColor.x, 0.1f * objColor.y, 0.1f * objColor.z); + + // --- Emissive Color + //material.setEmissiveColor(0.2f * objColor.x, 0.2f * objColor.y, 0.2f * objColor.z); + material.setEmissiveColor(0, 0, 0); + + // --- Specular Color + //material.setSpecularColor(1.0f, 1.0f, 1.0f); + //material.setSpecularColor(objColor); + + // --- Set Shininess + material.setShininess(15.0f); + + material.setCapability(Material.ALLOW_COMPONENT_READ); + material.setCapability(Material.ALLOW_COMPONENT_WRITE); + + material.setColorTarget(Material.AMBIENT_AND_DIFFUSE); + + app.setMaterial(material); + //app.setMaterial(new Material(objColor, black, objColor, + // white, 80.0f)); + + // --- Set up the transparency properties + + /* + TransparencyAttributes ta = new TransparencyAttributes(); + ta.setTransparencyMode(transparencyMode); + ta.setTransparency(Transparency); + app.setTransparencyAttributes(ta); + */ + + // --- Set up the polygon attributes + + PolygonAttributes pa = new PolygonAttributes(); + + pa.setCapability(PolygonAttributes.ALLOW_MODE_READ); + pa.setCapability(PolygonAttributes.ALLOW_MODE_WRITE); + + pa.setCapability(PolygonAttributes.ALLOW_CULL_FACE_READ); + pa.setCapability(PolygonAttributes.ALLOW_CULL_FACE_WRITE); + + pa.setPolygonMode(polygonMode); + pa.setCullFace(cullFace); + pa.setBackFaceNormalFlip(backFaceNormalFlip); + app.setPolygonAttributes(pa); + + return app; + } + + public static String[] getAvailablePolygonModes() { + return Style_name; + } + + public static String[] getAvailableTranspModes() { + return Transp_modes; + } + + public static int getDefaultPolygonMode() { + return 0; + } + + public static int getDefaultTranspMode() { + return 3; + } + + public static String getTransparencyModeAsString(int mode) { + //static final String[] Transp_modes = { + // "Fastest", "Nicest", "Screen Door", "Blended"}; + + switch (mode) { + case TransparencyAttributes.BLENDED: + return Transp_modes[3]; + case TransparencyAttributes.FASTEST: + return Transp_modes[0]; + case TransparencyAttributes.NICEST: + return Transp_modes[1]; + case TransparencyAttributes.SCREEN_DOOR: + return Transp_modes[2]; + } + return null; + } + + public static int getRenderingMode(String mode) { + //"Solid", "Wireframe", "Points" + if (mode.equals(Style_name[0])) { + return PolygonAttributes.POLYGON_FILL; + } + else if (mode.equals(Style_name[1])) { + return PolygonAttributes.POLYGON_LINE; + } + else if (mode.equals(Style_name[2])) { + return PolygonAttributes.POLYGON_POINT; + } + + System.err.println("Unknown Polygon Attribute: " + mode + " Set to PolygonAttributes.POLYGON_FILL"); + return PolygonAttributes.POLYGON_FILL; + } + + public static String getRenderingModeAsString(int mode) throws Exception { + switch (mode) { + case PolygonAttributes.POLYGON_FILL: + return Style_name[0]; + case PolygonAttributes.POLYGON_LINE: + return Style_name[1]; + case PolygonAttributes.POLYGON_POINT: + return Style_name[2]; + } + + System.err.println("getRenderingModeAsString: unknown polygon mode"); + throw new Exception("getRenderingModeAsString: unknown polygon mode"); + } + + public static void validateRenderingMode(int mode) throws Exception { + switch (mode) { + case PolygonAttributes.POLYGON_FILL: + case PolygonAttributes.POLYGON_LINE: + case PolygonAttributes.POLYGON_POINT: + return; + } + + System.err.println("validateRenderingMode: unknown polygon mode"); + throw new Exception("validateRenderingMode: unknown polygon mode"); + } + + public static int getTransparencyMode(String mode) { + //"Fastest", "Nicest", "Screen Door", "Blended"}; + if (mode.equals(Transp_modes[0])) { + return TransparencyAttributes.FASTEST; + } + else if (mode.equals(Transp_modes[1])) { + return TransparencyAttributes.NICEST; + } + else if (mode.equals(Transp_modes[2])) { + return TransparencyAttributes.SCREEN_DOOR; + } + else if (mode.equals(Transp_modes[3])) { + return TransparencyAttributes.BLENDED; + } + + System.err.println("Unknown Transparency Attribute: " + mode + " Set to TransparencyAttributes.BLENDED"); + return TransparencyAttributes.BLENDED; + } + +} diff --git a/src/main/java/cct/j3d/VibrationsRenderer.java b/src/main/java/cct/j3d/VibrationsRenderer.java new file mode 100644 index 0000000..c70a455 --- /dev/null +++ b/src/main/java/cct/j3d/VibrationsRenderer.java @@ -0,0 +1,674 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.j3d; + +import cct.GlobalSettings; +import org.scijava.java3d.Alpha; +import org.scijava.java3d.BranchGroup; +import org.scijava.java3d.Group; +import org.scijava.java3d.Node; +import org.scijava.java3d.Switch; +import org.scijava.java3d.SwitchValueInterpolator; +import org.scijava.java3d.Transform3D; +import org.scijava.java3d.TransformGroup; + +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; +import cct.interfaces.MoleculeInterface; +import cct.interfaces.OutputResultsInterface; +import cct.interfaces.VibrationsRendererProvider; +import cct.modelling.ChemicalElements; +import cct.modelling.Molecule; +import cct.povray.Povray; +import cct.tools.IOUtils; +import java.awt.Frame; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.JOptionPane; + +/** + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class VibrationsRenderer + implements VibrationsRendererProvider, RenderingListener { + + public static final String DEFAULT_IMAGE_SEQ_POV_FILENAME = "anim-img-seq.pov"; + public static final String DEFAULT_FILE_PREFIX = "vib-"; + + private MoleculeInterface referenceMolecule = null; + private OutputResultsInterface vibProvider = null; + private Java3dUniverse j3d = null; + private DVObject[] dvObjects = null; + private float scale_length = 2.5f; + private float arrowRadius = 0.05f; + private int framesPerHalfCycle = 11; // It's better to use odd number + private long halfCycleDuration = 500; + private long minHalfCycleDuration = 100; + private long maxHalfCycleDuration = 1500; + private long durationStep = 100; + private Node moleculeParentNode = null; + private BranchGroup moleculeBranchGroup = null; + private String filePrefix = DEFAULT_FILE_PREFIX; + + private int currentFrequency = -1; + private boolean animationInProgress = false; + + public VibrationsRenderer(MoleculeInterface molecule, OutputResultsInterface provider, Java3dUniverse renderer) throws Exception { + referenceMolecule = molecule; + vibProvider = provider; + j3d = renderer; + dvObjects = new DVObject[molecule.getNumberOfAtoms() * 3]; + + if (j3d != null) { + j3d.addRenderingListener(this); + + moleculeBranchGroup = j3d.getMoleculeBranchGroup(); + try { + moleculeParentNode = moleculeBranchGroup.getParent(); + if (moleculeParentNode == null) { + System.err.println("Molecule BranchGroup does not have a parent"); + } + + } catch (Exception ex) { + System.err.println("Cannot get parent for molecule BranchGroup: " + ex.getMessage()); + } + } + + } + + public static void main(String[] args) { + //VibrationsRenderer vibrationsrenderer = new VibrationsRenderer(); + } + + @Override + public void showDisplacementVectors(int frequency, boolean show) { + float[][] vectors = vibProvider.getDisplacementVectors(frequency); + if (vectors == null) { + System.err.println("showDisplacementVectors: vectors == null"); + return; + } + if (vectors.length != referenceMolecule.getNumberOfAtoms()) { + System.err.println("showDisplacementVectors: vectors.length != referenceMolecule.getNumberOfAtoms()"); + return; + } + + if (!show && dvObjects[frequency] == null) { + System.err.println("showDisplacementVectors: !show && dvObjects[frequency] == null"); + return; + } + currentFrequency = frequency; + + if (show) { + + if (dvObjects[frequency] == null || dvObjects[frequency].rootBranch == null) { + BranchGroup rootBranch = new BranchGroup(); + rootBranch.setCapability(Group.ALLOW_CHILDREN_READ); + rootBranch.setCapability(Group.ALLOW_CHILDREN_WRITE); + rootBranch.setCapability(Group.ALLOW_CHILDREN_EXTEND); + rootBranch.setCapability(BranchGroup.ALLOW_DETACH); + + for (int i = 0; i < referenceMolecule.getNumberOfAtoms(); i++) { + AtomInterface atom = referenceMolecule.getAtomInterface(i); + float[] origin = { + atom.getX(), atom.getY(), atom.getZ()}; + float length = (float) Math.sqrt(vectors[i][0] * vectors[i][0] + vectors[i][1] * vectors[i][1] + + vectors[i][2] * vectors[i][2]) * scale_length; + if (length < 0.001f) { + continue; + } + ArrowNode arrow = new ArrowNode(origin, vectors[i]); + arrow.setArrowRadius(arrowRadius); + arrow.setArrowLength(length); + arrow.setArrowHeadRadius(arrowRadius + 0.02f); + arrow.setArrowHeadLength(0.2f); + arrow.createArrow(); + arrow.setNodeName(String.format("DVECTOR_%03d_%03d_%s", (currentFrequency + 1), (i + 1), + ChemicalElements.getElementSymbol(atom.getAtomicNumber()))); + rootBranch.addChild(arrow); + } + if (dvObjects[frequency] == null) { + dvObjects[frequency] = new DVObject(); + } + dvObjects[frequency].rootBranch = rootBranch; + } + + //j3d.addGraphicsToMolecule(dvObjects[frequency].rootBranch, true); + if (moleculeParentNode != null) { + addBranchGroupToNode(moleculeParentNode, dvObjects[frequency].rootBranch, true); + } + } else { + //j3d.addGraphicsToMolecule(dvObjects[frequency].rootBranch, false); + if (moleculeParentNode != null) { + addBranchGroupToNode(moleculeParentNode, dvObjects[frequency].rootBranch, false); + } + + } + } + + private void addBranchGroupToNode(Node node, Node child, boolean enable) { + if (node instanceof TransformGroup) { + TransformGroup tg = (TransformGroup) node; + if (enable) { + try { + tg.addChild(child); + } catch (Exception ex) { + System.err.println("addBranchGroupToNode: cannot add a node to TransformGroup: " + ex.getMessage()); + } + } else { + try { + tg.removeChild(child); + } catch (Exception ex) { + System.err.println("addBranchGroupToNode: cannot remove child of TransformGroup: " + ex.getMessage()); + } + + } + } + } + + @Override + public void saveScene(int frequency, String format) throws Exception { + + if (format.equalsIgnoreCase("povray")) { + generatePovrayImageSequence(frequency); + return; + } + + if (!format.equalsIgnoreCase("VRML")) { + throw new Exception(this.getClass().getCanonicalName() + ": currently support only VRML format for saving scene"); + } + + if (j3d == null) { + throw new Exception(this.getClass().getCanonicalName() + ": Java3dUniverse == null"); + } + GroupToVRML vrml = new GroupToVRML(j3d.getLocale()); + vrml.enableColorsPerVertex(false); // Don't write colors per vertex (to be compatible with Acrobat 9,xx) + vrml.setCanvas3D(j3d.getCanvas3D()); + try { + vrml.saveVRMLFile(); + } catch (Exception ex) { + throw new Exception(this.getClass().getCanonicalName() + ": Error Saving VRML file: " + ex.getMessage()); + } + + } + + @Override + public int getMinimumDuration() { + return 0; + } + + @Override + public int getMaximumDuration() { + return (int) ((maxHalfCycleDuration - minHalfCycleDuration) / durationStep); + } + + @Override + public int getDuration() { + return (int) ((halfCycleDuration - minHalfCycleDuration) / durationStep); + } + + @Override + public void setDuration(int duration) { + if (duration < 0) { + duration = 0; + } + int max = (int) ((maxHalfCycleDuration - minHalfCycleDuration) / durationStep); + if (duration > max) { + duration = max; + } + halfCycleDuration = durationStep * duration + minHalfCycleDuration; + if (currentFrequency != -1 && dvObjects[currentFrequency] != null && dvObjects[currentFrequency].alpha != null) { + dvObjects[currentFrequency].alpha.setDecreasingAlphaDuration(halfCycleDuration); + dvObjects[currentFrequency].alpha.setIncreasingAlphaDuration(halfCycleDuration); + } + } + + @Override + public void animateVibrations(int frequency, boolean show) { + float[][] vectors = vibProvider.getDisplacementVectors(frequency); + if (vectors == null) { + System.err.println("animateFrequency: vectors == null"); + return; + } + if (vectors.length != referenceMolecule.getNumberOfAtoms()) { + System.err.println("animateFrequency: vectors.length != referenceMolecule.getNumberOfAtoms()"); + return; + } + + if (!show && dvObjects[frequency] == null) { + System.err.println("animateFrequency: !show && dvObjects[frequency] == null"); + return; + } + + currentFrequency = frequency; + + if (show) { + if (dvObjects[frequency] == null || dvObjects[frequency].animationBranch == null || dvObjects[frequency].renderingChanged) { + + BranchGroup rootBranch = new BranchGroup(); + rootBranch.setCapability(Group.ALLOW_CHILDREN_READ); + rootBranch.setCapability(Group.ALLOW_CHILDREN_WRITE); + rootBranch.setCapability(Group.ALLOW_CHILDREN_EXTEND); + rootBranch.setCapability(BranchGroup.ALLOW_DETACH); + + Switch objSwitch = new Switch(); + objSwitch.setCapability(Switch.ALLOW_SWITCH_WRITE); + + // create Alpha + /* + public Alpha(int loopCount, + int mode, + long triggerTime, + long phaseDelayDuration, + long increasingAlphaDuration, + long increasingAlphaRampDuration, + long alphaAtOneDuration, + long decreasingAlphaDuration, + long decreasingAlphaRampDuration, + long alphaAtZeroDuration) + + This constructor takes all of the Alpha user-definable parameters. + + Parameters: + loopCount - number of times to run this alpha; a value of -1 specifies that the alpha loops indefinitely + mode - indicates whether the increasing alpha parameters or the decreasing alpha parameters or both are active. This parameter accepts the following values, INCREASING_ENABLE or DECREASING_ENABLE, which may be ORed together to specify that both are active. The increasing alpha parameters are increasingAlphaDuration, increasingAlphaRampDuration, and alphaAtOneDuration. The decreasing alpha parameters are decreasingAlphaDuration, decreasingAlphaRampDuration, and alphaAtZeroDuration. + triggerTime - time in milliseconds since the start time that this object first triggers + phaseDelayDuration - number of milliseconds to wait after triggerTime before actually starting this alpha + increasingAlphaDuration - period of time during which alpha goes from zero to one + increasingAlphaRampDuration - period of time during which the alpha step size increases at the beginning of the increasingAlphaDuration and, correspondingly, decreases at the end of the increasingAlphaDuration. This value is clamped to half of increasingAlphaDuration. NOTE: a value of zero means that the alpha step size remains constant during the entire increasingAlphaDuration. + alphaAtOneDuration - period of time that alpha stays at one + decreasingAlphaDuration - period of time during which alpha goes from one to zero + decreasingAlphaRampDuration - period of time during which the alpha step size increases at the beginning of the decreasingAlphaDuration and, correspondingly, decreases at the end of the decreasingAlphaDuration. This value is clamped to half of decreasingAlphaDuration. NOTE: a value of zero means that the alpha step size remains constant during the entire decreasingAlphaDuration. + alphaAtZeroDuration - period of time that alpha stays at zero + + + */ + Alpha alpha = new Alpha(-1, Alpha.INCREASING_ENABLE | Alpha.DECREASING_ENABLE, 0, 0, halfCycleDuration, 10, 10, + halfCycleDuration, 10, 0); + // create switch value interpolator + SwitchValueInterpolator swiInt = new SwitchValueInterpolator(alpha, objSwitch); + swiInt.setSchedulingBounds(j3d.getBoundingSphere()); + + Transform3D t3d = new Transform3D(); + TransformGroup objSwitchPos = new TransformGroup(t3d); + objSwitchPos.addChild(objSwitch); + + rootBranch.addChild(objSwitchPos); + rootBranch.addChild(swiInt); + + float[] lengths = new float[referenceMolecule.getNumberOfAtoms()]; + float[] steps = new float[referenceMolecule.getNumberOfAtoms()]; + float[][] origins = new float[referenceMolecule.getNumberOfAtoms()][3]; + float[][] dirs = new float[referenceMolecule.getNumberOfAtoms()][3]; + float[][] pos = new float[referenceMolecule.getNumberOfAtoms()][3]; + for (int i = 0; i < referenceMolecule.getNumberOfAtoms(); i++) { + AtomInterface atom = referenceMolecule.getAtomInterface(i); + lengths[i] = (float) Math.sqrt(vectors[i][0] * vectors[i][0] + vectors[i][1] * vectors[i][1] + + vectors[i][2] * vectors[i][2]); + if (lengths[i] > 0.001) { + dirs[i][0] = vectors[i][0] / lengths[i]; + dirs[i][1] = vectors[i][1] / lengths[i]; + dirs[i][2] = vectors[i][2] / lengths[i]; + } + + lengths[i] *= scale_length; + steps[i] = lengths[i] / (framesPerHalfCycle - 1); + + origins[i][0] = atom.getX() - dirs[i][0] * lengths[i] / 2.0f; + origins[i][1] = atom.getY() - dirs[i][1] * lengths[i] / 2.0f; + origins[i][2] = atom.getZ() - dirs[i][2] * lengths[i] / 2.0f; + } + + float factor = 1; + + for (int frame = 0; frame < framesPerHalfCycle; frame++) { + factor = frame; + BranchGroup molecule = new BranchGroup(); + UserData.setUserData(molecule, UserData.NODE_NAME, String.format("%03d_FRAME", (frame + 1))); + //molecule.setName(String.format("Frame_%04d", frame)); + + for (int i = 0; i < referenceMolecule.getNumberOfAtoms(); i++) { + AtomInterface atom = referenceMolecule.getAtomInterface(i); + Object obj = atom.getProperty(Java3dUniverse.ATOM_NODE); + if (obj == null) { + continue; + } + AtomNode at = (AtomNode) obj; + AtomNode new_atom = null; + try { + new_atom = (AtomNode) at.clone(); + } catch (Exception ex) { + } + + if (new_atom == null) { + continue; + } + + pos[i][0] = origins[i][0] + dirs[i][0] * steps[i] * factor; + pos[i][1] = origins[i][1] + dirs[i][1] * steps[i] * factor; + pos[i][2] = origins[i][2] + dirs[i][2] * steps[i] * factor; + + new_atom.setAtomicCoordinates(pos[i]); + UserData.setUserData(new_atom, UserData.NODE_NAME, + String.format("%03d_FRAME_Atom_%s", (frame + 1), + ChemicalElements.getElementSymbol(atom.getAtomicNumber()))); + molecule.addChild(new_atom); + } + + for (int i = 0; i < referenceMolecule.getNumberOfBonds(); i++) { + BondInterface b = referenceMolecule.getBondInterface(i); + Object obj = b.getProperty(Java3dUniverse.BOND_NODE); + if (obj == null) { + continue; + } + BondNode bn = (BondNode) obj; + BondNode new_bn = null; + try { + new_bn = (BondNode) bn.clone(); + } catch (Exception ex) { + continue; + } + AtomInterface a1 = b.getIAtomInterface(); + AtomInterface a2 = b.getJAtomInterface(); + int ind_1 = referenceMolecule.getAtomIndex(a1); + int ind_2 = referenceMolecule.getAtomIndex(a2); + + new_bn.updateBond(pos[ind_1], pos[ind_2]); + new_bn.setNodeName(String.format("%03d_FRAME_Bond_%s_%s", (frame + 1), + ChemicalElements.getElementSymbol(a1.getAtomicNumber()), + ChemicalElements.getElementSymbol(a2.getAtomicNumber()))); + + molecule.addChild(new_bn); + } + + objSwitch.addChild(molecule); + + } + + swiInt.setLastChildIndex(objSwitch.numChildren() - 1); // since switch made after interpolator + + if (dvObjects[frequency] == null) { + dvObjects[frequency] = new DVObject(); + } + + if (dvObjects[frequency].animationBranch != null) { + addBranchGroupToNode(moleculeParentNode, dvObjects[frequency].animationBranch, false); + } + + dvObjects[frequency].animationBranch = rootBranch; + dvObjects[frequency].alpha = alpha; + dvObjects[frequency].renderingChanged = false; + + } + + //j3d.addGraphicsToMolecule(dvObjects[frequency].animationBranch, true); + if (moleculeParentNode != null) { + addBranchGroupToNode(moleculeParentNode, dvObjects[frequency].animationBranch, true); + addBranchGroupToNode(moleculeParentNode, moleculeBranchGroup, false); + } + animationInProgress = true; + } else { + animationInProgress = false; + if (dvObjects[frequency].animationBranch != null) { + //j3d.addGraphicsToMolecule(dvObjects[frequency].animationBranch, false); + if (moleculeParentNode != null) { + addBranchGroupToNode(moleculeParentNode, moleculeBranchGroup, true); + addBranchGroupToNode(moleculeParentNode, dvObjects[frequency].animationBranch, false); + } + + } + } + + } + + @Override + public void renderingChanged(RenderingObject e) { + if (!animationInProgress || currentFrequency == -1) { + return; + } + + for (int i = 0; i < dvObjects.length; i++) { + if (dvObjects[i] == null) { + continue; + } + dvObjects[i].renderingChanged = true; + } + + animateVibrations(currentFrequency, true); + + } + + public void generatePovrayImageSequence(int frequency) { + float[][] vectors = vibProvider.getDisplacementVectors(frequency); + if (vectors == null) { + System.err.println("animateFrequency: vectors == null"); + return; + } + if (vectors.length != referenceMolecule.getNumberOfAtoms()) { + System.err.println("animateFrequency: vectors.length != referenceMolecule.getNumberOfAtoms()"); + return; + } + + framesPerHalfCycle = 30; + + // --- Generating animation control file + String name = "vib-animation-cntrl.pov"; + name = (String) JOptionPane.showInputDialog(null, "Animation control file name?", "Animation control file name input", + JOptionPane.QUESTION_MESSAGE, null, new Object[]{name}, name ); + if (name == null || name.trim().length() < 1) { + return; + } + if (!name.endsWith(".pov") && !name.endsWith(".POV")) { + name += ".pov"; + } + + Object obj = JOptionPane.showInputDialog(new Frame(),"Number of repeats", "", JOptionPane.INFORMATION_MESSAGE, + null, null, "1"); + if (obj == null) { + return; + } + int repeat = 1; + try { + repeat = Integer.parseInt(obj.toString()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, "Wrong number " + + obj.toString() + " : " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + int n = JOptionPane.showConfirmDialog(null, "Would you like to rebond for each step?", "Yes - to rebond each time", + JOptionPane.YES_NO_OPTION); + boolean recalculate = true; + recalculate = n == JOptionPane.YES_OPTION; + + String povTemplate = GlobalSettings.getProperty(Povray.IMAGE_SEQ_POV_TEMPLATE_KEY, + Povray.DEFAULT_IMAGE_SEQ_POV_TEMPLATE); + System.out.println("Povray Pov template:\n" + povTemplate); + povTemplate = povTemplate.replaceAll(Povray.FILE_PREFIX_TEMPLATE, DEFAULT_FILE_PREFIX); + try { + IOUtils.saveStringIntoFile(povTemplate, DEFAULT_FILE_PREFIX + Povray.DEFAULT_IMAGE_SEQ_POV_FILENAME); + } catch (Exception ex) { + Logger.getLogger(ImageSequenceManager.class.getName()).log(Level.SEVERE, null, ex); + } + + // --- Generate Povray initemplate + String iniTemplate = GlobalSettings.getProperty( + Povray.IMAGE_SEQ_INI_TEMPLATE_KEY, + Povray.DEFAULT_IMAGE_SEQ_INI_TEMPLATE); + System.out.println("Povray INI template:\n" + iniTemplate); + iniTemplate = iniTemplate.replaceAll(Povray.NUMBER_OF_FRAMES_TEMPLATE, String.valueOf(framesPerHalfCycle * repeat)). + replaceAll(Povray.POVRAY_CONTROL_FILE_NAME_TEMPLATE, DEFAULT_FILE_PREFIX + Povray.DEFAULT_IMAGE_SEQ_POV_FILENAME); + + try { + IOUtils.saveStringIntoFile(iniTemplate, DEFAULT_FILE_PREFIX + Povray.DEFAULT_IMAGE_SEQ_INI_FILENAME); + } catch (Exception ex) { + Logger.getLogger(ImageSequenceManager.class.getName()).log(Level.SEVERE, null, ex); + } + + /* + FileOutputStream out; + try { + out = new FileOutputStream(name); + out.write("// --- File is generated by Jamberoo\n".getBytes()); + out.write("#declare _DEBUG_ = true;\n".getBytes()); + out.write("#declare AnimationLength = 20.0;\n".getBytes()); + out.write("#declare AnimationClock = clock * AnimationLength;\n".getBytes()); + out.write("#declare file = concat(\"vib-\",str(frame_number,-6,0),\".pov\")\n".getBytes()); + out.write("#ifdef (_DEBUG_)\n".getBytes()); + out.write("#debug \"\\n\"\n".getBytes()); + out.write("#debug concat(\"clock = \", str(clock,7,3),\" Frame number: \",str(frame_number,0,0) , \"\\n\")\n".getBytes()); + out.write("#debug concat(\"AnimationClock = \", str(AnimationClock,7,3), \"\\n\")\n".getBytes()); + out.write("#debug concat(\"Rendering \", file, \"\\n\")\n".getBytes()); + out.write("#end\n".getBytes()); + out.write("#include file\n".getBytes()); + } catch (Exception ex) { + return; + } + */ + currentFrequency = frequency; + List mols = new ArrayList(); + + float[] lengths = new float[referenceMolecule.getNumberOfAtoms()]; + float[] steps = new float[referenceMolecule.getNumberOfAtoms()]; + float[][] origins = new float[referenceMolecule.getNumberOfAtoms()][3]; + float[][] dirs = new float[referenceMolecule.getNumberOfAtoms()][3]; + double[][] pos = new double[referenceMolecule.getNumberOfAtoms()][3]; + + for (int i = 0; i < referenceMolecule.getNumberOfAtoms(); i++) { + + AtomInterface atom = referenceMolecule.getAtomInterface(i); + lengths[i] = (float) Math.sqrt(vectors[i][0] * vectors[i][0] + vectors[i][1] * vectors[i][1] + + vectors[i][2] * vectors[i][2]); + if (lengths[i] > 0.001) { + dirs[i][0] = vectors[i][0] / lengths[i]; + dirs[i][1] = vectors[i][1] / lengths[i]; + dirs[i][2] = vectors[i][2] / lengths[i]; + } + + lengths[i] *= scale_length; + steps[i] = lengths[i] / (framesPerHalfCycle - 1); + + origins[i][0] = atom.getX() - dirs[i][0] * lengths[i] / 2.0f; + origins[i][1] = atom.getY() - dirs[i][1] * lengths[i] / 2.0f; + origins[i][2] = atom.getZ() - dirs[i][2] * lengths[i] / 2.0f; + } + + float factor = 1; + + for (int frame = 0; frame < framesPerHalfCycle; frame++) { + factor = frame; + + MoleculeInterface mol = referenceMolecule.getInstance(); + mol.appendMolecule(referenceMolecule); + + for (int i = 0; i < mol.getNumberOfAtoms(); i++) { + AtomInterface atom = mol.getAtomInterface(i); + + pos[i][0] = origins[i][0] + dirs[i][0] * steps[i] * factor; + pos[i][1] = origins[i][1] + dirs[i][1] * steps[i] * factor; + pos[i][2] = origins[i][2] + dirs[i][2] * steps[i] * factor; + + atom.setXYZ(pos[i][0], pos[i][1], pos[i][2]); + } + + if (recalculate) { + Molecule.redoConnectivity(mol); + } + mols.add(mol); + j3d.setMolecule(mol); + + PovrayJava3d povray = new PovrayJava3d(j3d); + try { + povray.savePovrayFile(String.format("vib-%06d", frame) + ".pov"); + } catch (Exception ex) { + System.err.println(ex.getLocalizedMessage()); + return; + } + + } + + // --- + int pointer = framesPerHalfCycle - 1; + int sign = -1; + for (int frame = framesPerHalfCycle; frame < framesPerHalfCycle * repeat; frame++) { + if (pointer == framesPerHalfCycle - 1) { + sign = -1; + } else if (pointer == 0) { + sign = 1; + } + pointer += sign; + + MoleculeInterface mol = mols.get(pointer); + j3d.setMolecule(mol); + PovrayJava3d povray = new PovrayJava3d(j3d); + try { + povray.savePovrayFile(String.format("vib-%06d", frame) + ".pov"); + } catch (Exception ex) { + System.err.println(ex.getLocalizedMessage()); + return; + } + } + + j3d.setMolecule(this.referenceMolecule); + } + class DVObject { + + BranchGroup rootBranch; + BranchGroup animationBranch; + Alpha alpha; + long halfCycleDuration; + boolean renderingChanged = false; + + public DVObject() { + } + } +} diff --git a/src/main/java/cct/j3d/XYZAxes.java b/src/main/java/cct/j3d/XYZAxes.java new file mode 100644 index 0000000..ca434de --- /dev/null +++ b/src/main/java/cct/j3d/XYZAxes.java @@ -0,0 +1,46 @@ +package cct.j3d; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ + +import org.scijava.java3d.BranchGroup; +import org.scijava.java3d.Group; +import org.scijava.vecmath.Color3f; + +public class XYZAxes + extends BranchGroup { + + ArrowNode xAxis = new ArrowNode(new float[] {-10, 0, 0}, new float[] {20, 0, 0}); + ArrowNode yAxis = new ArrowNode(new float[] {0, -10, 0}, new float[] {0, 20, 0}); + ArrowNode zAxis = new ArrowNode(new float[] {0, 0, -10}, new float[] {0, 0, 20}); + + public XYZAxes() { + + this.setCapability(Group.ALLOW_CHILDREN_EXTEND); + this.setCapability(Group.ALLOW_CHILDREN_READ); + this.setCapability(Group.ALLOW_CHILDREN_WRITE); + this.setCapability(BranchGroup.ALLOW_DETACH); + + xAxis.createArrow(); + yAxis.createArrow(); + zAxis.createArrow(); + + xAxis.setColor(new Color3f(1, 0, 0)); + yAxis.setColor(new Color3f(0, 1, 0)); + zAxis.setColor(new Color3f(0, 0, 1)); + + this.addChild(xAxis); + this.addChild(yAxis); + this.addChild(zAxis); + } +} diff --git a/src/main/java/cct/j3d/myKeyNavigatorBehavior.java b/src/main/java/cct/j3d/myKeyNavigatorBehavior.java new file mode 100644 index 0000000..61942a3 --- /dev/null +++ b/src/main/java/cct/j3d/myKeyNavigatorBehavior.java @@ -0,0 +1,89 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d; + +import java.util.logging.Logger; + +import org.scijava.java3d.Transform3D; +import org.scijava.java3d.TransformGroup; +import org.scijava.java3d.WakeupOnAWTEvent; + +import org.scijava.java3d.utils.behaviors.keyboard.KeyNavigatorBehavior; + +// Uncomplete WRONG class (to delete) + +public class myKeyNavigatorBehavior + extends KeyNavigatorBehavior { + private TransformGroup targetTG; + private WakeupOnAWTEvent KeyEvent = new WakeupOnAWTEvent(java.awt.event.KeyEvent.KEY_PRESSED); + java.awt.event.KeyEvent evt; + private Transform3D rotation = new Transform3D(); + private double angle = 0.0; + static final Logger logger = Logger.getLogger(myKeyNavigatorBehavior.class.getCanonicalName()); + + public myKeyNavigatorBehavior(TransformGroup targetTG) { + super(targetTG); + this.targetTG = targetTG; + } + + public myKeyNavigatorBehavior(java.awt.Component c, TransformGroup targetTG) { + super(c, targetTG); + this.targetTG = targetTG; + } + + @Override + public void initialize() { + // set initial wakeup condition + this.wakeupOn(KeyEvent); + + } + + @Override + public void processStimulus(java.util.Enumeration criteria) { + keyPressed(evt); + if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_KP_UP) { + angle += 0.1; + rotation.rotY(angle); + targetTG.setTransform(rotation); + + } + logger.info("KeyHandler: Id" + evt.getID() + " Param: " + + evt.toString()); + this.wakeupOn(KeyEvent); + } +} diff --git a/src/main/java/cct/j3d/ui/ColorGradientPanel.java b/src/main/java/cct/j3d/ui/ColorGradientPanel.java new file mode 100644 index 0000000..a583e5f --- /dev/null +++ b/src/main/java/cct/j3d/ui/ColorGradientPanel.java @@ -0,0 +1,252 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d.ui; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.GradientPaint; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.geom.GeneralPath; +import java.awt.geom.Path2D; +import java.awt.geom.Rectangle2D; +import java.util.ArrayList; +import java.util.logging.Logger; + +import javax.swing.JPanel; +import org.scijava.vecmath.Color3f; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class ColorGradientPanel + extends JPanel { + + final static Color bg = Color.white; + final static Color fg = Color.black; + final static Color red = Color.red; + final static Color white = Color.white; + + FontMetrics fontMetrics; + float fMin = 0, fMax; + java.util.List Colors = null; + + final static int maxCharHeight = 25; + final static int minFontSize = 6; + + int[] charWidth = null; + + private boolean stupidBool = false; + protected BorderLayout borderLayout1 = new BorderLayout(); + static final Logger logger = Logger.getLogger(ColorGradientPanel.class.getCanonicalName()); + + public ColorGradientPanel() { + stupidBool = true; + fMin = -1; + fMax = 1; + Colors = new ArrayList (); + Colors.add(new Color3f(0, 0, 1)); // Blue + Colors.add(new Color3f(0, 1, 0)); // Green + Colors.add(new Color3f(1, 0, 0)); // Red + + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + + } + + public ColorGradientPanel(float min, float max, java.util.List colors) { + stupidBool = false; + setColorGradient(min, max, colors); + + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public void setColorGradient(float min, float max, java.util.List colors) { + stupidBool = false; + + if (colors != null) { + fMin = min; + fMax = max; + Colors = colors; + } + else { + fMin = -1; + fMax = 1; + Colors = new ArrayList (); + Colors.add(new Color3f(0, 0, 1)); // Blue + //Colors.add(new Color3f(0, 0.5f, 1)); // + Colors.add(new Color3f(0, 1, 0)); // Green + //Colors.add(new Color3f(0.5f, 1, 0)); // greenyellow(SVG) rgb(173, 255, 47) + Colors.add(new Color3f(1, 0, 0)); // Red + } + + this.repaint(); + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + this.setMinimumSize(new Dimension(100, 80)); + this.setPreferredSize(new Dimension(100, 80)); + this.setToolTipText(""); + } + + FontMetrics pickFont(Graphics2D g2, String longString, int xSpace) { + boolean fontFits = false; + Font font = g2.getFont(); + FontMetrics fontMetrics = g2.getFontMetrics(); + int size = font.getSize(); + String name = font.getName(); + int style = font.getStyle(); + + while (!fontFits) { + if ( (fontMetrics.getHeight() <= maxCharHeight) + && (fontMetrics.stringWidth(longString) <= xSpace)) { + fontFits = true; + } + else { + if (size <= minFontSize) { + fontFits = true; + } + else { + g2.setFont(font = new Font(name, style, --size)); + fontMetrics = g2.getFontMetrics(); + } + } + } + + return fontMetrics; + } + + @Override + public void paint(Graphics g) { + + Graphics2D g2 = (Graphics2D) g; + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + Dimension d = getSize(); + + Color fg3D = Color.lightGray; + g2.setBackground(fg3D); + //g2.setPaint(fg3D); + //g2.draw3DRect(0, 0, d.width - 1, d.height - 1, true); + + int numberWidth = 60; + fontMetrics = pickFont(g2, "-100.0000", numberWidth); + float fontHight = fontMetrics.getHeight(); + charWidth = fontMetrics.getWidths(); + + float rectHeight = d.height - fontHight - 5; + float rectWidth = (float)d.width / (float)(Colors.size() - 1); + float x = 0; + float y = fontHight + 5; + + for (int i = 0; i < Colors.size() - 1; i++) { + Color3f startColor = Colors.get(i); + Color3f endColor = Colors.get(i + 1); + Color startC = new Color(startColor.x, startColor.y, startColor.z); + Color endC = new Color(endColor.x, endColor.y, endColor.z); + GradientPaint gradientColor = new GradientPaint(x, y, startC, x + rectWidth, y, endC); + g2.setPaint(gradientColor); + g2.fill(new Rectangle2D.Float(x, y, rectWidth, rectHeight)); + + x += rectWidth; + } + + // --- Mark extreme values + g2.setPaint(red); + + String value = null; + if (stupidBool) { + g2.drawString(String.valueOf(fMin), 1, fontHight + 2); + value = String.valueOf(fMax); + } + else { + g2.drawString(String.format("%8.5f", fMin).trim(), 1, fontHight + 2); + value = String.format("%8.5f", fMax).trim(); + } + + int stringLength = getStringLength(value); + g2.drawString(value, d.width - stringLength - 1, fontHight + 2); + + float middle = (fMax - fMin) / 2.0f; + value = String.format("%8.5f", middle).trim(); + stringLength = getStringLength(value); + logger.info("middle=" + middle + " value: " + value + " fmin=" + fMin + " fmax=" + fMax); + g2.drawString(value, d.width / 2 - stringLength / 2 - 1, fontHight + 2); + + // Draw ticks + + GeneralPath polyline; + + polyline = new GeneralPath(Path2D.WIND_EVEN_ODD, 2); + polyline.moveTo(d.width / 2, y); + polyline.lineTo(d.width / 2, y - 2); + g2.draw(polyline); + + } + + int getStringLength(String string) { + byte[] bytes = string.getBytes(); + int length = 0; + for (int i = 0; i < bytes.length; i++) { + length += charWidth[bytes[i]]; + } + return length; + } +} diff --git a/src/main/java/cct/j3d/ui/ControlColorGradientPanel.java b/src/main/java/cct/j3d/ui/ControlColorGradientPanel.java new file mode 100644 index 0000000..97315ad --- /dev/null +++ b/src/main/java/cct/j3d/ui/ControlColorGradientPanel.java @@ -0,0 +1,280 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d.ui; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTextField; +import org.scijava.vecmath.Color3f; + +import cct.j3d.ColorRangeScheme; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class ControlColorGradientPanel + extends JPanel { + + private ColorGradientPanel colorGradientPanel1 = new ColorGradientPanel(); + protected JPanel jPanel1 = new JPanel(); + protected JPanel jPanel2 = new JPanel(); + protected JTextField maxClipTextField = new JTextField(); + protected JTextField minClipTextField = new JTextField(); + protected JLabel jLabel1 = new JLabel(); + protected GridBagLayout gridBagLayout1 = new GridBagLayout(); + protected JLabel minMaxInfoLabel = new JLabel(); + protected FlowLayout flowLayout1 = new FlowLayout(); + + private boolean stupidBool = false; + protected BorderLayout borderLayout2 = new BorderLayout(); + protected GridBagLayout gridBagLayout2 = new GridBagLayout(); + + private MappedSurfaceInterface Mapper = null; + private ColorRangeScheme ColorRange = null; + + private float clipMin, clipMax; + + public ControlColorGradientPanel() { + stupidBool = true; + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(gridBagLayout2); + colorGradientPanel1.setMinimumSize(new Dimension(100, 80)); + colorGradientPanel1.setOpaque(false); + colorGradientPanel1.setPreferredSize(new Dimension(100, 80)); + colorGradientPanel1.setLayout(borderLayout2); + maxClipTextField.setToolTipText("Type New Value and Press Enter"); + maxClipTextField.setText("1"); + maxClipTextField.setColumns(6); + maxClipTextField.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + maxClipTextField_actionPerformed(e); + } + }); + minClipTextField.setToolTipText("Type New Value and Press Enter"); + minClipTextField.setText("-1"); + minClipTextField.setColumns(6); + minClipTextField.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + minClipTextField_actionPerformed(e); + } + }); + jLabel1.setText("<- Enter New Clip Values ->"); + jPanel1.setLayout(gridBagLayout1); + minMaxInfoLabel.setText("Min Vertex Value: -1, Max: 1"); + jPanel2.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + jPanel1.add(minClipTextField, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(maxClipTextField, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(jLabel1, + new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + jPanel2.add(minMaxInfoLabel); + this.add(colorGradientPanel1, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0 + , GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 1, 1)); + this.add(jPanel1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 1, 1)); + this.add(jPanel2, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 1, 1)); + } + + public void setMappedSurfaceInterface(MappedSurfaceInterface mapper) { + Mapper = mapper; + } + + void setColorGradient(float min, float max, float clip_min, float clip_max, java.util.List colors) { + stupidBool = false; + colorGradientPanel1.setColorGradient(clip_min, clip_max, colors); + + setClipValue(minClipTextField, clip_min); + + setClipValue(maxClipTextField, clip_max); + + clipMin = clip_min; + clipMax = clip_max; + + minMaxInfoLabel.setText("Min Vertex Value: " + String.format("%8.4f", min) + ", Max: " + String.format("%8.4f", max)); + } + + void setClipValue(JTextField textField, float new_value) { + textField.setEnabled(false); + textField.setText(String.format("%8.4f", new_value)); + textField.setEnabled(true); + } + + public void setColorGradient(ColorRangeScheme crange) { + + ColorRange = crange; + + float min = crange.getMinFunValue(); + float max = crange.getMaxFunValue(); + float clip_min = crange.getClipMin(); + float clip_max = crange.getClipMax(); + java.util.List colors = crange.getColor3fPalette(); + + setColorGradient(min, max, clip_min, clip_max, colors); + } + + public void minClipTextField_actionPerformed(ActionEvent e) { + if (!minClipTextField.isEnabled()) { + return; + } + + minClipTextField.setEnabled(false); + + float clip_min = 0; + try { + clip_min = Float.parseFloat(minClipTextField.getText().trim()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Cannot parse " + minClipTextField.getText().trim() + " : " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + setClipValue(minClipTextField, clipMin); + minClipTextField.setEnabled(true); + return; + } + + if (clip_min >= clipMax) { + JOptionPane.showMessageDialog(this, + "Minimum clip distance cannot be larger than " + String.valueOf(clipMax) + " got " + + String.valueOf(clip_min), "Error", + JOptionPane.ERROR_MESSAGE); + setClipValue(minClipTextField, clipMin); + minClipTextField.setEnabled(true); + return; + } + + clipMin = clip_min; + ColorRange.setClipMin(clipMin); + + if (Mapper != null) { + Mapper.setNewColorScheme(ColorRange); + } + else { + System.err.println(this.getClass().getCanonicalName() + " : Surface Mapper is not set"); + } + + java.util.List colors = ColorRange.getColor3fPalette(); + colorGradientPanel1.setColorGradient(clipMin, clipMax, colors); + + minClipTextField.setEnabled(true); + } + + /** + * + * @param e ActionEvent + */ + public void maxClipTextField_actionPerformed(ActionEvent e) { + if (!maxClipTextField.isEnabled()) { + return; + } + + maxClipTextField.setEnabled(false); + + float clip_max = 0; + try { + clip_max = Float.parseFloat(maxClipTextField.getText().trim()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Cannot parse " + maxClipTextField.getText().trim() + " : " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + setClipValue(maxClipTextField, clipMax); + maxClipTextField.setEnabled(true); + return; + } + + if (clip_max <= clipMin) { + JOptionPane.showMessageDialog(this, + "Maximum clip value cannot be smaller than " + String.valueOf(clipMin) + " got " + + String.valueOf(clip_max), "Error", + JOptionPane.ERROR_MESSAGE); + setClipValue(maxClipTextField, clipMax); + maxClipTextField.setEnabled(true); + return; + } + + clipMax = clip_max; + ColorRange.setClipMax(clipMax); + + if (Mapper != null) { + Mapper.setNewColorScheme(ColorRange); + } + else { + System.err.println(this.getClass().getCanonicalName() + " : Surface Mapper is not set"); + } + + java.util.List colors = ColorRange.getColor3fPalette(); + colorGradientPanel1.setColorGradient(clipMin, clipMax, colors); + + maxClipTextField.setEnabled(true); + + } + +} diff --git a/src/main/java/cct/j3d/ui/GraphicsObjectPropertiesFrame.java b/src/main/java/cct/j3d/ui/GraphicsObjectPropertiesFrame.java new file mode 100644 index 0000000..274ada0 --- /dev/null +++ b/src/main/java/cct/j3d/ui/GraphicsObjectPropertiesFrame.java @@ -0,0 +1,470 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d.ui; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.HashMap; +import java.util.Map; + +import org.scijava.java3d.BranchGroup; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JFrame; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JTree; +import javax.swing.event.TreeSelectionEvent; +import javax.swing.event.TreeSelectionListener; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreePath; + +import cct.interfaces.GraphicsObjectInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class GraphicsObjectPropertiesFrame + extends JFrame implements TreeSelectionListener { + BorderLayout borderLayout1 = new BorderLayout(); + JSplitPane jSplitPane1 = new JSplitPane(); + JScrollPane leftScrollPane = new JScrollPane(); + JScrollPane rightScrollPane = new JScrollPane(); + JTree gObjectTree = new JTree(); + JPanel emptyPanel = new JPanel(); + Map referenceTable = new HashMap (); + Map goReferenceTable = new HashMap(); + Map parentReferenceTable = new HashMap(); + + JPanel jPanel1 = new JPanel(); + BorderLayout borderLayout2 = new BorderLayout(); + JPanel jPanel2 = new JPanel(); + + ImageIcon deleteObject = new ImageIcon(cct.resources.Resources.class.getResource( + "cct/images/icons16x16/selection_delete.png")); + JButton deleteButton = new JButton(); + FlowLayout flowLayout1 = new FlowLayout(); + java.util.List graphicsObjects = null; + JCheckBox showSelectedOnlyCheckBox = new JCheckBox(); + JPanel buttonPanel = new JPanel(); + JButton hideButton = new JButton(); + JButton helpButton = new JButton(); + public GraphicsObjectPropertiesFrame() { + super("Graphics Object Properties"); + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + @Override + public void valueChanged(TreeSelectionEvent e) { + if (!gObjectTree.isEnabled()) { + return; + } + gObjectTree.setEnabled(false); + + DefaultMutableTreeNode node = (DefaultMutableTreeNode) gObjectTree. + getLastSelectedPathComponent(); + if (node == null) { + if (showSelectedOnlyCheckBox.isSelected()) { + setAllVisible(false); + } + gObjectTree.setEnabled(true); + return; + } + + Object nodeInfo = node.getUserObject(); + + //if (node.isLeaf()) { + Component panel = referenceTable.get(node); + Object object = goReferenceTable.get(node); + // --- Could be GraphicsObjectInterface or BranchGroup + if (object instanceof GraphicsObjectInterface) { + GraphicsObjectInterface graphics = (GraphicsObjectInterface) object; + panel = graphics.getVisualComponent(); + } + else if (object != null) { + System.err.println("??? kljhlkj"); + } + + if (panel == null) { + rightScrollPane.getViewport().removeAll(); + rightScrollPane.getViewport().add(emptyPanel); + } + else { + rightScrollPane.getViewport().removeAll(); + rightScrollPane.getViewport().add(panel); + } + + if (showSelectedOnlyCheckBox.isSelected()) { + setAllVisible(false); + setNodeVisible(node, true); + } + + validate(); + pack(); + //java3d.loadFragment(spec); + //} + + gObjectTree.setEnabled(true); + } + + private void jbInit() throws Exception { + getContentPane().setLayout(borderLayout1); + jSplitPane1.setOrientation(JSplitPane.VERTICAL_SPLIT); + jSplitPane1.setToolTipText(""); + jPanel1.setLayout(borderLayout2); + deleteButton.setMaximumSize(new Dimension(23, 23)); + deleteButton.setMinimumSize(new Dimension(23, 23)); + deleteButton.setPreferredSize(new Dimension(23, 23)); + deleteButton.setToolTipText("Delete Selected Objects"); + deleteButton.setIcon(deleteObject); + deleteButton.setMnemonic('0'); + deleteButton.addActionListener(new GraphicsObjectPropertiesFrame_deleteButton_actionAdapter(this)); + jPanel2.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + gObjectTree.setMaximumSize(new Dimension(74, 0)); + gObjectTree.setPreferredSize(new Dimension(74, 120)); + showSelectedOnlyCheckBox.setText("Display Selected Objects Only"); + showSelectedOnlyCheckBox.addActionListener(new GraphicsObjectPropertiesFrame_showSelectedOnlyCheckBox_actionAdapter(this)); + gObjectTree.setMinimumSize(new Dimension(0, 120)); + hideButton.setToolTipText("Hide Dialog"); + hideButton.setText("Hide"); + hideButton.addActionListener(new GraphicsObjectPropertiesFrame_hideButton_actionAdapter(this)); + helpButton.setEnabled(false); + helpButton.setToolTipText("Get Help"); + helpButton.setText("Help"); + jPanel2.add(deleteButton); + jPanel2.add(showSelectedOnlyCheckBox); + rightScrollPane.getViewport().add(emptyPanel); + this.getContentPane().add(jSplitPane1, BorderLayout.CENTER); + jSplitPane1.add(rightScrollPane, JSplitPane.RIGHT); + jSplitPane1.add(leftScrollPane, JSplitPane.LEFT); + leftScrollPane.getViewport().add(jPanel1); + jPanel1.add(gObjectTree, BorderLayout.CENTER); + this.getContentPane().add(buttonPanel, BorderLayout.SOUTH); + buttonPanel.add(hideButton); + buttonPanel.add(helpButton); + this.getContentPane().add(jPanel2, BorderLayout.NORTH); + } + + public void setTree(java.util.List gObjects) { + graphicsObjects = gObjects; + createNodes(gObjects); + } + + public void updateTree() { + if (graphicsObjects == null || graphicsObjects.size() < 1) { + return; + } + createNodes(graphicsObjects); + } + + private void createNodes(DefaultMutableTreeNode top, GraphicsObjectInterface graphics) { + + DefaultMutableTreeNode gObject = new DefaultMutableTreeNode(graphics.getName()); + top.add(gObject); + referenceTable.put(gObject, graphics.getVisualComponent()); + goReferenceTable.put(gObject, graphics); + + if (graphics.getNGraphicsElements() == 1) { + return; + } + + for (int j = 0; j < graphics.getNGraphicsElements(); j++) { + Object obj = graphics.getGraphicsElement(j); + + if (obj instanceof GraphicsObjectInterface) { + GraphicsObjectInterface go = (GraphicsObjectInterface) obj; + if (go.getNGraphicsElements() < 1) { + continue; + } + + createNodes(gObject, go); + } + else if (obj instanceof BranchGroup) { + DefaultMutableTreeNode leaf = new DefaultMutableTreeNode(String.valueOf(j)); + gObject.add(leaf); + referenceTable.put(leaf, graphics.getVisualComponent(j)); + goReferenceTable.put(leaf, graphics.getGraphicsElement(j)); + parentReferenceTable.put(leaf, graphics); + } + else { + System.err.println(getClass().getCanonicalName() + ": createNodes: don't now how to handle class " + + obj.getClass().getCanonicalName()); + } + } + + } + + private void createNodes(java.util.List gObjects) { + + DefaultMutableTreeNode top = new DefaultMutableTreeNode("Graphics Objects"); + + if (gObjects != null) { + for (int i = 0; i < gObjects.size(); i++) { + GraphicsObjectInterface graphics = gObjects.get(i); + if (graphics.getNGraphicsElements() < 1) { + continue; + } + + createNodes(top, graphics); + } + } + + JTree jTree1 = new JTree(top); + jTree1.addTreeSelectionListener(this); + //jTree1.setSelectionModel(TreeSelectionModel.SINGLE_TREE_SELECTION); + + leftScrollPane.getViewport().remove(gObjectTree); + gObjectTree = jTree1; + leftScrollPane.getViewport().add(gObjectTree); + + validate(); + pack(); + } + + /* + private void createNodes(DefaultMutableTreeNode top, LinkedHashMap fragTree) { + + DefaultMutableTreeNode lastDic = top; + + Set set = fragTree.entrySet(); + Iterator iter = set.iterator(); + + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String dicName = me.getKey().toString(); + Object obj = me.getValue(); + + if (obj instanceof LinkedHashMap) { + DefaultMutableTreeNode dictionary = new DefaultMutableTreeNode( + dicName); + top.add(dictionary); + //LinkedHashMap dic = (LinkedHashMap)obj; + createNodes(dictionary, (LinkedHashMap) obj); + lastDic = dictionary; + } + else if (obj instanceof String) { + DefaultMutableTreeNode fragment = new DefaultMutableTreeNode( + dicName); + lastDic.add(fragment); + String spec = (String) obj; + referenceTable.put(fragment, spec); + } + } + } + */ + + public static void main(String[] args) { + GraphicsObjectPropertiesFrame graphicsobjectpropertiesframe = new + GraphicsObjectPropertiesFrame(); + graphicsobjectpropertiesframe.setVisible(true); + } + + public void deleteButton_actionPerformed(ActionEvent e) { + if (!deleteButton.isEnabled()) { + return; + } + + if (graphicsObjects == null) { + //JOptionPane.showMessageDialog(this, "Graphics objects are not set", "Warning", + // JOptionPane.WARNING_MESSAGE); + return; + } + + TreePath paths[] = gObjectTree.getSelectionPaths(); + if (paths == null) { + JOptionPane.showMessageDialog(this, "Select tree nodes first", "Warning", + JOptionPane.WARNING_MESSAGE); + return; + } + + deleteButton.setEnabled(false); + + for (int i = 0; i < paths.length; i++) { + Object obj = paths[i].getLastPathComponent(); // Get root component + if (obj instanceof DefaultMutableTreeNode) { + Object object = goReferenceTable.get(obj); + // --- Could be GraphicsObjectInterface or BranchGroup + if (object instanceof GraphicsObjectInterface) { + GraphicsObjectInterface graphics = (GraphicsObjectInterface) object; + graphics.removeAllGraphics(); + } + else if (object != null) { + GraphicsObjectInterface parent = (GraphicsObjectInterface) parentReferenceTable.get(obj); + parent.removeGraphics(object); + } + } + } + + // --- Update array list + + int n = graphicsObjects.size(); + for (int i = n - 1; i >= 0; i--) { + GraphicsObjectInterface graphics = graphicsObjects.get(i); + if (graphics.getNGraphicsElements() < 1) { + graphicsObjects.remove(i); + } + } + + this.gObjectTree.removeAll(); + this.setTree(graphicsObjects); + + deleteButton.setEnabled(true); + } + + public void showSelectedOnlyCheckBox_actionPerformed(ActionEvent e) { + if (!showSelectedOnlyCheckBox.isEnabled() || !showSelectedOnlyCheckBox.isSelected()) { + return; + } + + if (graphicsObjects == null) { + return; + } + + showSelectedOnlyCheckBox.setEnabled(false); + + TreePath paths[] = gObjectTree.getSelectionPaths(); + + // --- Nothing is selected, undisplay everything + + setAllVisible(false); + + if (paths == null) { + showSelectedOnlyCheckBox.setEnabled(true); + return; + } + + for (int i = 0; i < paths.length; i++) { + Object obj = paths[i].getLastPathComponent(); // Get root component + if (obj instanceof DefaultMutableTreeNode) { + setNodeVisible( (DefaultMutableTreeNode) obj, true); + } + } + + showSelectedOnlyCheckBox.setEnabled(true); + } + + public JButton getHelpButton() { + return helpButton; + } + + void setAllVisible(boolean visible) { + for (int i = 0; i < graphicsObjects.size(); i++) { + GraphicsObjectInterface graphics = graphicsObjects.get(i); + graphics.setVisible(visible); + } + } + + void setNodeVisible(DefaultMutableTreeNode node, boolean visible) { + Object object = goReferenceTable.get(node); + // --- Could be GraphicsObjectInterface or BranchGroup + if (object instanceof GraphicsObjectInterface) { + GraphicsObjectInterface graphics = (GraphicsObjectInterface) object; + graphics.setVisible(visible); + } + else if (object != null) { + GraphicsObjectInterface parent = (GraphicsObjectInterface) parentReferenceTable.get(node); + parent.setVisible(object, visible); + } + } + + public void hideButton_actionPerformed(ActionEvent e) { + this.setVisible(false); + } + + private class GraphicsObjectPropertiesFrame_showSelectedOnlyCheckBox_actionAdapter + implements ActionListener { + private GraphicsObjectPropertiesFrame adaptee; + GraphicsObjectPropertiesFrame_showSelectedOnlyCheckBox_actionAdapter(GraphicsObjectPropertiesFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.showSelectedOnlyCheckBox_actionPerformed(e); + } + } + + private class GraphicsObjectPropertiesFrame_deleteButton_actionAdapter + implements ActionListener { + private GraphicsObjectPropertiesFrame adaptee; + GraphicsObjectPropertiesFrame_deleteButton_actionAdapter(GraphicsObjectPropertiesFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.deleteButton_actionPerformed(e); + } + } + + private class GraphicsObjectPropertiesFrame_hideButton_actionAdapter + implements ActionListener { + private GraphicsObjectPropertiesFrame adaptee; + GraphicsObjectPropertiesFrame_hideButton_actionAdapter(GraphicsObjectPropertiesFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.hideButton_actionPerformed(e); + } + } + +} diff --git a/src/main/java/cct/j3d/ui/MappedSurfaceInterface.java b/src/main/java/cct/j3d/ui/MappedSurfaceInterface.java new file mode 100644 index 0000000..76fb91e --- /dev/null +++ b/src/main/java/cct/j3d/ui/MappedSurfaceInterface.java @@ -0,0 +1,57 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d.ui; + +import cct.j3d.ColorRangeScheme; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public interface MappedSurfaceInterface { + void setNewColorScheme(ColorRangeScheme crange); + +} diff --git a/src/main/java/cct/j3d/ui/VertexObjectsDialog.java b/src/main/java/cct/j3d/ui/VertexObjectsDialog.java new file mode 100644 index 0000000..9538f57 --- /dev/null +++ b/src/main/java/cct/j3d/ui/VertexObjectsDialog.java @@ -0,0 +1,262 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d.ui; + +import cct.interfaces.GraphicsObjectInterface; +import org.scijava.java3d.BranchGroup; + +import javax.swing.*; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreePath; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class VertexObjectsDialog + extends JDialog { + JPanel panel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JPanel buttonPanel = new JPanel(); + JList surfacesList = new JList(); + JButton cancelButton = new JButton(); + JButton okButton = new JButton(); + + JTree gObjectTree = new JTree(); + JScrollPane leftScrollPane = new JScrollPane(); + + Map referenceTable = new HashMap (); + Map goReferenceTable = new HashMap(); + Map parentReferenceTable = new HashMap(); + protected boolean okPressed = false; + + java.util.List graphicsObjects = null; + + public VertexObjectsDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public VertexObjectsDialog() { + this(new Frame(), "VertexObjectsDialog", false); + } + + private void jbInit() throws Exception { + + leftScrollPane.getViewport().remove(gObjectTree); + + panel1.setLayout(borderLayout1); + surfacesList.setVisibleRowCount(10); + cancelButton.setToolTipText(""); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + cancelButton_actionPerformed(e); + } + }); + okButton.setToolTipText(""); + okButton.setText(" OK "); + okButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + okButton_actionPerformed(e); + } + }); + //getContentPane().add(panel1); + getContentPane().add(leftScrollPane); + buttonPanel.add(okButton); + buttonPanel.add(cancelButton); + panel1.add(surfacesList, BorderLayout.CENTER); + panel1.add(buttonPanel, BorderLayout.SOUTH); + this.getContentPane().add(panel1, BorderLayout.SOUTH); + } + + /* + public void setList(ArrayList g_objects) { + graphicsObjects = new ArrayList (g_objects); + if (graphicsObjects == null || graphicsObjects.size() < 1) { + return; + } + ArrayList list = new ArrayList(graphicsObjects.size()); + for (int i = 0; i < graphicsObjects.size(); i++) { + GraphicsObjectInterface goi = graphicsObjects.get(i); + } + } + */ + + public boolean isOKPressed() { + return okPressed; + } + + public void setTree(java.util.List gObjects) { + graphicsObjects = new ArrayList (gObjects); + createNodes(gObjects); + } + + private void createNodes(java.util.List gObjects) { + + DefaultMutableTreeNode top = new DefaultMutableTreeNode( + "Graphics Objects"); + + if (gObjects != null) { + for (int i = 0; i < gObjects.size(); i++) { + GraphicsObjectInterface graphics = gObjects.get(i); + if (graphics.getNGraphicsElements() < 1) { + continue; + } + + createNodes(top, graphics); + } + } + + JTree jTree1 = new JTree(top); + //jTree1.addTreeSelectionListener(this); + + leftScrollPane.getViewport().remove(gObjectTree); + gObjectTree = jTree1; + leftScrollPane.getViewport().add(gObjectTree); + + validate(); + pack(); + } + + private void createNodes(DefaultMutableTreeNode top, + GraphicsObjectInterface graphics) { + + DefaultMutableTreeNode gObject = new DefaultMutableTreeNode(graphics.getName()); + top.add(gObject); + referenceTable.put(gObject, graphics.getVisualComponent()); + goReferenceTable.put(gObject, graphics); + + if (graphics.getNGraphicsElements() == 1) { + return; + } + + for (int j = 0; j < graphics.getNGraphicsElements(); j++) { + Object obj = graphics.getGraphicsElement(j); + + if (obj instanceof GraphicsObjectInterface) { + GraphicsObjectInterface go = (GraphicsObjectInterface) obj; + if (go.getNGraphicsElements() < 1) { + continue; + } + + createNodes(gObject, go); + } + else if (obj instanceof BranchGroup) { + DefaultMutableTreeNode leaf = new DefaultMutableTreeNode(String.valueOf(j)); + gObject.add(leaf); + referenceTable.put(leaf, graphics.getVisualComponent(j)); + goReferenceTable.put(leaf, graphics.getGraphicsElement(j)); + parentReferenceTable.put(leaf, graphics); + } + else { + System.err.println(getClass().getCanonicalName() + ": createNodes: don't now how to handle class " + + obj.getClass().getCanonicalName()); + } + } + + } + + public void cancelButton_actionPerformed(ActionEvent e) { + okPressed = false; + setVisible(false); + } + + public void okButton_actionPerformed(ActionEvent e) { + okPressed = true; + setVisible(false); + } + + public TreePath[] getSelectionPaths() { + return gObjectTree.getSelectionPaths(); + } + + public java.util.List getSelectedGraphicsObjects() { + TreePath paths[] = gObjectTree.getSelectionPaths(); + if (paths == null) { + return null; + } + + java.util.List shape3ds = new ArrayList(); + + for (int i = 0; i < paths.length; i++) { + Object obj = paths[i].getLastPathComponent(); // Get root component + if (obj instanceof DefaultMutableTreeNode) { + Object object = goReferenceTable.get(obj); + // --- Could be GraphicsObjectInterface or BranchGroup + if (object instanceof GraphicsObjectInterface) { + GraphicsObjectInterface graphics = (GraphicsObjectInterface) object; + //graphics.removeAllGraphics(); + shape3ds.add(graphics); + //ArrayList shape3d = graphics.getShape3DElements(); + } + else if (object != null) { + shape3ds.add(object); + GraphicsObjectInterface parent = (GraphicsObjectInterface) parentReferenceTable.get(obj); + shape3ds.add(parent); + //parent.removeGraphics(object); + } + } + } + return shape3ds; + } + +} diff --git a/src/main/java/cct/j3d/ui/VerticesPropertyPanel.java b/src/main/java/cct/j3d/ui/VerticesPropertyPanel.java new file mode 100644 index 0000000..8527578 --- /dev/null +++ b/src/main/java/cct/j3d/ui/VerticesPropertyPanel.java @@ -0,0 +1,1041 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.j3d.ui; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.SystemColor; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Map; +import java.util.logging.Logger; + +import org.scijava.java3d.Appearance; +import org.scijava.java3d.BranchGroup; +import org.scijava.java3d.Material; +import org.scijava.java3d.PolygonAttributes; +import org.scijava.java3d.Shape3D; +import org.scijava.java3d.TransformGroup; +import org.scijava.java3d.TransparencyAttributes; +import javax.swing.BorderFactory; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JSlider; +import javax.swing.border.Border; +import javax.swing.border.TitledBorder; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import org.scijava.vecmath.Color3f; + +import cct.gaussian.java3d.GaussianJava3dFactory; +import cct.j3d.ColorRangeScheme; +import cct.j3d.USER_DATA_FLAG; +import cct.j3d.VerticesObject; +import cct.j3d.VerticesObjectProperties; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class VerticesPropertyPanel + extends JPanel implements MappedSurfaceInterface { + + static String MIXED_RENDERING = "Mixed Rendering"; + + JLabel jLabel1 = new JLabel(); + JPanel mainPanel = new JPanel(); + JComboBox renderingComboBox = new JComboBox(); + JCheckBox opaqueCheckBox = new JCheckBox(); + JPanel jPanel2 = new JPanel(); + JPanel transparencyPanel = new JPanel(); + BorderLayout borderLayout2 = new BorderLayout(); + JPanel jPanel1 = new JPanel(); + JPanel jPanel4 = new JPanel(); + JComboBox transpComboBox = new JComboBox(); + JLabel jLabel3 = new JLabel(); + BorderLayout borderLayout3 = new BorderLayout(); + FlowLayout flowLayout2 = new FlowLayout(); + JSlider opacitySlider = new JSlider(); + BorderLayout borderLayout4 = new BorderLayout(); + JCheckBox visibleCheckBox = new JCheckBox(); + + Appearance App = null; + Shape3D Shape3d = null; + VerticesObject vObject = null; + Object shape3d_Parent = null; + Object grandParent = null; + Color3f diffuseColorStore = new Color3f(); + Color3f black = new Color3f(0.0f, 0.0f, 0.0f); + float shininessStore = 1.0f; + JPanel jPanel3 = new JPanel(); + JLabel jLabel5 = new JLabel(); + JLabel jLabel6 = new JLabel(); + BorderLayout borderLayout5 = new BorderLayout(); + JPanel shininessPanel = new JPanel(); + JPanel topPanel = new JPanel(); + BorderLayout borderLayout6 = new BorderLayout(); + FlowLayout flowLayout1 = new FlowLayout(); + JSlider shininessSlider = new JSlider(); + JPanel jPanel5 = new JPanel(); + JLabel jLabel2 = new JLabel(); + JLabel jLabel4 = new JLabel(); + BorderLayout borderLayout7 = new BorderLayout(); + BorderLayout borderLayout8 = new BorderLayout(); + protected ControlColorGradientPanel controlColorGradientPanel1 = new ControlColorGradientPanel(); + protected Border border1 = BorderFactory.createLineBorder(SystemColor.controlDkShadow, 1); + protected Border border2 = new TitledBorder(border1, "Color Gradient Control"); + protected GridBagLayout gridBagLayout1 = new GridBagLayout(); + static final Logger logger = Logger.getLogger(VerticesPropertyPanel.class.getCanonicalName()); + + public VerticesPropertyPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(gridBagLayout1); + jLabel1.setToolTipText(""); + jLabel1.setText("Rendering Style: "); + mainPanel.setLayout(borderLayout6); + opaqueCheckBox.setToolTipText("Opaque/Transparent Object"); + opaqueCheckBox.setMargin(new Insets(2, 5, 2, 2)); + opaqueCheckBox.setSelected(true); + opaqueCheckBox.setText("Opaque"); + opaqueCheckBox.addActionListener(new + VerticesPropertyPanel_opaqueCheckBox_actionAdapter(this)); + jPanel2.setLayout(borderLayout2); + transparencyPanel.setLayout(borderLayout3); + transparencyPanel.setBorder(new TitledBorder(BorderFactory. + createLineBorder( + SystemColor.controlShadow, 1), "Transparency Panel")); + jLabel3.setToolTipText(""); + jLabel3.setText("Transparency Mode: "); + jPanel4.setLayout(flowLayout2); + flowLayout2.setAlignment(FlowLayout.LEFT); + opacitySlider.setMajorTickSpacing(10); + opacitySlider.setPaintLabels(true); + opacitySlider.setPaintTicks(true); + opacitySlider.addChangeListener(new VerticesPropertyPanel_opacitySlider_changeAdapter(this)); + jPanel1.setLayout(borderLayout4); + visibleCheckBox.setToolTipText("Show/Hide Object"); + visibleCheckBox.setMargin(new Insets(2, 2, 2, 5)); + visibleCheckBox.setSelected(true); + visibleCheckBox.setText("Visible"); + visibleCheckBox.addActionListener(new VerticesPropertyPanel_visibleCheckBox_actionAdapter(this)); + renderingComboBox.addItemListener(new VerticesPropertyPanel_renderingComboBox_itemAdapter(this)); + transpComboBox.addItemListener(new VerticesPropertyPanel_transpComboBox_itemAdapter(this)); + renderingComboBox.setToolTipText("Polygon rendering mode"); + transpComboBox.setToolTipText("Transparency mode"); + jLabel5.setToolTipText(""); + jLabel5.setText("Opaque"); + jLabel6.setToolTipText(""); + jLabel6.setText("Transparent"); + jPanel3.setLayout(borderLayout5); + topPanel.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + + shininessPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder(SystemColor.controlShadow, 1), "Shininess")); + shininessPanel.setLayout(borderLayout7); + + shininessSlider.setMajorTickSpacing(7); + shininessSlider.setMaximum(128); + shininessSlider.setMinimum(1); + shininessSlider.setPaintLabels(true); + shininessSlider.setPaintTicks(true); + shininessSlider.setValue(1); + Hashtable shininessLabelTable = new Hashtable(); + shininessLabelTable.put(new Integer(1), new JLabel("1")); + shininessLabelTable.put(new Integer(32), new JLabel("32")); + shininessLabelTable.put(new Integer(64), new JLabel("64")); + shininessLabelTable.put(new Integer(96), new JLabel("96")); + shininessLabelTable.put(new Integer(128), new JLabel("128")); + shininessSlider.setLabelTable(shininessLabelTable); + + shininessSlider.addChangeListener(new VerticesPropertyPanel_shininessSlider_changeAdapter(this)); + + //shininessSlider.setBackground(new UIManager(236, 233, 216)); + jLabel2.setToolTipText(""); + jLabel2.setText("Very Shiny"); + jLabel4.setToolTipText(""); + jLabel4.setText("Not Shiny"); + jPanel5.setLayout(borderLayout8); + controlColorGradientPanel1.setBorder(border2); + controlColorGradientPanel1.setMinimumSize(new Dimension(100, 80)); + controlColorGradientPanel1.setPreferredSize(new Dimension(100, 80)); + controlColorGradientPanel1.setToolTipText(""); + jPanel4.add(jLabel3); + jPanel4.add(transpComboBox); + jPanel1.add(opacitySlider, BorderLayout.CENTER); + jPanel3.add(jLabel5, BorderLayout.WEST); + jPanel3.add(jLabel6, BorderLayout.EAST); + mainPanel.add(shininessPanel, BorderLayout.CENTER); + mainPanel.add(topPanel, BorderLayout.NORTH); + topPanel.add(visibleCheckBox); + topPanel.add(jLabel1); + topPanel.add(renderingComboBox); + topPanel.add(opaqueCheckBox); + jPanel5.add(jLabel2, BorderLayout.WEST); + jPanel5.add(jLabel4, BorderLayout.EAST); + shininessPanel.add(shininessSlider, BorderLayout.NORTH); + shininessPanel.add(jPanel5, BorderLayout.SOUTH); + jPanel2.add(transparencyPanel, BorderLayout.CENTER); + transparencyPanel.add(jPanel4, BorderLayout.NORTH); + transparencyPanel.add(jPanel1, BorderLayout.SOUTH); + transparencyPanel.add(jPanel3, BorderLayout.CENTER); + this.add(controlColorGradientPanel1, new GridBagConstraints(0, 2, 1, 1, 1.0, 1.0 + , GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 1, 1)); + this.add(mainPanel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 1, 1)); + this.add(jPanel2, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 1, 1)); + Hashtable labelTable = new Hashtable(); + labelTable.put(new Integer(0), new JLabel("0")); + labelTable.put(new Integer(50), new JLabel("0.5")); + labelTable.put(new Integer(100), new JLabel("1.0")); + opacitySlider.setLabelTable(labelTable); + + String[] modes = VerticesObjectProperties.getAvailablePolygonModes(); + + renderingComboBox.setEnabled(false); + for (int i = 0; i < modes.length; i++) { + renderingComboBox.addItem(modes[i]); + } + renderingComboBox.setSelectedIndex(VerticesObjectProperties. + getDefaultPolygonMode()); + renderingComboBox.setEnabled(true); + + modes = VerticesObjectProperties.getAvailableTranspModes(); + transpComboBox.setEnabled(false); + for (int i = 0; i < modes.length; i++) { + transpComboBox.addItem(modes[i]); + } + transpComboBox.setSelectedIndex(VerticesObjectProperties. + getDefaultTranspMode()); + transpComboBox.setEnabled(true); + + // --- Final touches + + if (opaqueCheckBox.isSelected()) { + opacitySlider.setEnabled(false); + opacitySlider.setValue(0); + transpComboBox.setEnabled(false); + } + else { + transpComboBox.setEnabled(true); + opacitySlider.setEnabled(true); + } + + controlColorGradientPanel1.setMappedSurfaceInterface(this); + } + + public void setPanel(Shape3D shape3d) throws Exception { + + Shape3d = shape3d; + vObject = null; + shape3d_Parent = null; + grandParent = null; + + try { + Shape3d.setAppearanceOverrideEnable(true); + shape3d_Parent = Shape3d.getParent(); + if (shape3d_Parent instanceof BranchGroup) { + grandParent = ( (BranchGroup) shape3d_Parent).getParent(); + } + } + catch (Exception ex) { + System.err.println(this.getClass().getCanonicalName() + ": setPanel: " + ex.getMessage()); + } + + if (shape3d_Parent == null) { + visibleCheckBox.setSelected(false); + } + + try { + + App = Shape3d.getAppearance(); + + if (!App.getCapability(Appearance.ALLOW_POLYGON_ATTRIBUTES_READ)) { + App.setCapability(Appearance.ALLOW_POLYGON_ATTRIBUTES_READ); + } + + PolygonAttributes pa = App.getPolygonAttributes(); + int polygonMode = pa.getPolygonMode(); + + String renderingMode = VerticesObjectProperties.getRenderingModeAsString(polygonMode); + + this.renderingComboBox.setEnabled(false); + this.renderingComboBox.setSelectedItem(renderingMode); + this.renderingComboBox.setEnabled(true); + + if (!App.getCapability(Appearance.ALLOW_TRANSPARENCY_ATTRIBUTES_READ)) { + App.setCapability(Appearance.ALLOW_TRANSPARENCY_ATTRIBUTES_READ); + } + + Material material = App.getMaterial(); + if (material != null) { + float shininess = material.getShininess(); + logger.info("Shininess in Material: " + (int) shininess); + shininessSlider.setEnabled(false); + shininessSlider.setValue( (int) shininess); + shininessSlider.setEnabled(true); + } + else { + this.shininessSlider.setEnabled(false); + } + + TransparencyAttributes ta = App.getTransparencyAttributes(); + + this.opaqueCheckBox.setEnabled(false); + this.opaqueCheckBox.setSelected(ta == null); + this.opaqueCheckBox.setEnabled(true); + + this.opacitySlider.setEnabled(!opaqueCheckBox.isSelected()); + this.transpComboBox.setEnabled(!opaqueCheckBox.isSelected()); + + if (ta != null) { + float transp = ta.getTransparency(); + int transpMode = ta.getTransparencyMode(); + + this.opacitySlider.setEnabled(false); + this.transpComboBox.setEnabled(false); + opacitySlider.setValue( (int) (transp * opacitySlider.getMaximum())); + String transpM = VerticesObjectProperties.getTransparencyModeAsString(transpMode); + if (transpM != null) { + transpComboBox.setSelectedItem(transpM); + } + this.opacitySlider.setEnabled(true); + this.transpComboBox.setEnabled(true); + } + else { + + } + + processOptionalControls(); + } + catch (Exception ex) { + throw new Exception(this.getClass().getCanonicalName() + ": setPanel: " + ex.getMessage()); + } + + validate(); + } + + public void updatePanel() { + // -- check for color gradient panel + processOptionalControls(); + } + + void processOptionalControls() { + + if (Shape3d == null) { + return; + } + + // --- Now we process only the first geometry + Enumeration gIter = Shape3d.getAllGeometries(); + if (!gIter.hasMoreElements()) { + this.controlColorGradientPanel1.setVisible(false); + return; + } + + Object obj = Shape3d.getUserData(); + if (obj instanceof Map) { + Map shape3dUserData = (Map) obj; + if (shape3dUserData != null) { + ColorRangeScheme crange = (ColorRangeScheme) shape3dUserData.get(USER_DATA_FLAG.COLOR_RANGE_SCHEME_OBJECT); + if (crange != null) { + controlColorGradientPanel1.setColorGradient(crange); + } + } + } + /* + while (gIter.hasMoreElements()) { + Geometry geom = (Geometry) gIter.nextElement(); + Object ud = geom.getUserData(); + if (ud == null) { + this.controlColorGradientPanel1.setVisible(false); + break; + } + else if (! (ud instanceof HashMap)) { + this.controlColorGradientPanel1.setVisible(false); + break; + } + + HashMap uData = (HashMap) ud; + ArrayList palette = (ArrayList) uData.get(USER_DATA_FLAG.COLOR_PALETTE_ARRAY); + Float min = (Float) uData.get(USER_DATA_FLAG.MIN_FUN_VALUE_AT_VERTICES); + Float max = (Float) uData.get(USER_DATA_FLAG.MAX_FUN_VALUE_AT_VERTICES); + + Float clipMin = (Float) uData.get(USER_DATA_FLAG.MIN_CLIP_FUN_VALUE_AT_VERTICES); + Float clipMax = (Float) uData.get(USER_DATA_FLAG.MAX_CLIP_FUN_VALUE_AT_VERTICES); + + controlColorGradientPanel1.setColorGradient(min, max, clipMin, clipMax, palette); + this.controlColorGradientPanel1.setVisible(true); + break; + } + */ + + } + + @Override + public void setNewColorScheme(ColorRangeScheme new_color_range) { + if (Shape3d == null) { + System.err.println(this.getClass().getCanonicalName() + ": setNewColorScheme: Shape3d == null"); + return; + } + + Map shape3dUserData = (Map) Shape3d.getUserData(); + shape3dUserData.put(USER_DATA_FLAG.COLOR_RANGE_SCHEME_OBJECT, new_color_range); + + GaussianJava3dFactory.mapSurface(Shape3d, new_color_range); + } + + public void setPanel(VerticesObject v_object) throws Exception { + + App = null; + vObject = v_object; + + // --- Add a new item to rendering... + + renderingComboBox.setEnabled(false); + renderingComboBox.addItem(MIXED_RENDERING); + renderingComboBox.setSelectedItem(MIXED_RENDERING); + renderingComboBox.setEnabled(true); + + // --- Setup visible checkbox + + visibleCheckBox.setEnabled(false); + visibleCheckBox.setSelected(vObject.isVisible()); + visibleCheckBox.setEnabled(true); + + // --- Set opaque checkbox + + this.opaqueCheckBox.setEnabled(false); + this.opaqueCheckBox.setSelected(vObject.isOpaque()); + this.opaqueCheckBox.setEnabled(true); + + this.opacitySlider.setEnabled(!opaqueCheckBox.isSelected()); + this.transpComboBox.setEnabled(!opaqueCheckBox.isSelected()); + + // --- Set color palette + + java.util.List shape3ds = v_object.getShape3DElements(); + if (shape3ds.size() != 1) { + this.controlColorGradientPanel1.setVisible(false); + } + else { + Object obj = shape3ds.get(0); + if (obj instanceof BranchGroup) { + BranchGroup bg = (BranchGroup) obj; + Enumeration enumer = bg.getAllChildren(); + while (enumer.hasMoreElements()) { + Object bgChild = enumer.nextElement(); + if (bgChild instanceof Shape3D) { + Shape3D shape3D = (Shape3D) bgChild; + this.Shape3d = shape3D; + processOptionalControls(); + } + } + //controlColorGradientPanel1.setVisible(false); + } + else { + System.err.println("setPanel(VerticesObject v_object): unknown object " + obj.getClass().getCanonicalName() + + " Ignored..."); + controlColorGradientPanel1.setVisible(false); + } + + } + + validate(); + } + + public void opaqueCheckBox_actionPerformed(ActionEvent e) { + + if (opaqueCheckBox.isSelected()) { + //opacitySlider.setValue(0); + transpComboBox.setEnabled(false); + opacitySlider.setEnabled(false); + + opacitySlider.setEnabled(false); + opacitySlider.setValue(opacitySlider.getMinimum()); + opacitySlider.setEnabled(true); + + if (App != null) { + Appearance newApp = new Appearance(); + newApp.duplicateNodeComponent(App, false); + newApp.setTransparencyAttributes(null); + + //Material material = newApp.getMaterial(); + //material.setDiffuseColor(diffuseColorStore); + //material.setShininess(shininessStore); + //newApp.setMaterial(material); + Shape3d.setAppearance(newApp); + App = newApp; + } + else if (vObject != null) { + vObject.setOpaque(opaqueCheckBox.isSelected()); + } + } + + // --- Set transparent + else { + transpComboBox.setEnabled(true); + opacitySlider.setEnabled(true); + if (App != null) { + try { + Appearance newApp = new Appearance(); + newApp.duplicateNodeComponent(App, false); + TransparencyAttributes ta = newApp.getTransparencyAttributes(); + + //Material material = App.getMaterial(); + + //material.getDiffuseColor(diffuseColorStore); + //material.setDiffuseColor(black); + + //shininessStore = material.getShininess(); + //material.setShininess(1.0f); + + //App.setMaterial(material); + + if (ta == null) { + ta = new TransparencyAttributes(); + } + + float transp = ta.getTransparency(); + int value = (int) (transp * 100.0f); + + opacitySlider.setEnabled(false); + opacitySlider.setValue(value); + opacitySlider.setEnabled(true); + + int transpMode = ta.getTransparencyMode(); + + String transpName = VerticesObjectProperties. + getTransparencyModeAsString(transpMode); + if (transpName != null) { + transpComboBox.setEnabled(false); + transpComboBox.setSelectedItem(transpName); + transpComboBox.setEnabled(true); + } + + Shape3d.setAppearance(newApp); + App = newApp; + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Cannot get transperancy attributes: " + + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + } + } + + else if (vObject != null) { + vObject.setOpaque(opaqueCheckBox.isSelected()); + } + + } + + } + + public void renderingComboBox_itemStateChanged(ItemEvent e) { + + if (e.getStateChange() != ItemEvent.SELECTED) { + return; + } + + if (!renderingComboBox.isEnabled()) { + return; + } + + renderingComboBox.setEnabled(false); + + int polygonMode = VerticesObjectProperties.getRenderingMode(renderingComboBox.getSelectedItem().toString()); + + if (App != null) { + Appearance newApp = new Appearance(); + newApp.duplicateNodeComponent(App, false); + try { + PolygonAttributes pa = newApp.getPolygonAttributes(); + if (pa == null) { + pa = new PolygonAttributes(); + pa.setCapability(PolygonAttributes.ALLOW_MODE_READ); + pa.setCapability(PolygonAttributes.ALLOW_MODE_WRITE); + pa.setCapability(PolygonAttributes.ALLOW_CULL_FACE_READ); + pa.setCapability(PolygonAttributes.ALLOW_CULL_FACE_WRITE); + } + pa.setPolygonMode(polygonMode); + Shape3d.setAppearance(newApp); + App = newApp; + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Cannot set polygon attributes: " + + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + } + } + + // --- Now effect if a mixed rendering is selected + else if (vObject != null && !renderingComboBox.getSelectedItem().toString().equals(MIXED_RENDERING)) { + vObject.setPolygonRendering(polygonMode); + } + + renderingComboBox.setEnabled(true); + } + + public void setPolygoneMode(int mode) throws Exception { + + try { + VerticesObjectProperties.validateRenderingMode(mode); + } + catch (Exception ex) { + mode = PolygonAttributes.POLYGON_FILL; + } + + if (App != null) { + Appearance newApp = new Appearance(); + newApp.duplicateNodeComponent(App, false); + try { + PolygonAttributes pa = newApp.getPolygonAttributes(); + if (pa == null) { + pa = new PolygonAttributes(); + pa.setBackFaceNormalFlip(true); + pa.setCullFace(PolygonAttributes.CULL_NONE); + } + pa.setPolygonMode(mode); + newApp.setPolygonAttributes(pa); + Shape3d.setAppearance(newApp); + App = newApp; + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Cannot set polygon attributes: " + + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + } + } + + String modeName = VerticesObjectProperties.getRenderingModeAsString(mode); + renderingComboBox.setEnabled(false); + renderingComboBox.setSelectedItem(modeName); + renderingComboBox.setEnabled(true); + } + + public void visibleCheckBox_actionPerformed(ActionEvent e) { + enableAllControls(visibleCheckBox.isSelected()); + + // --- If it's a Shape3d + if (Shape3d != null) { + if (shape3d_Parent == null || grandParent == null) { + return; + } + if (shape3d_Parent instanceof BranchGroup) { + if (visibleCheckBox.isSelected()) { + //( (BranchGroup) shape3d_Parent).addChild(Shape3d); + if (grandParent instanceof BranchGroup) { + ( (BranchGroup) grandParent).addChild( (BranchGroup) shape3d_Parent); + } + else if (grandParent instanceof TransformGroup) { + ( (TransformGroup) grandParent).addChild( (BranchGroup) shape3d_Parent); + } + + } + else { + ( (BranchGroup) shape3d_Parent).detach(); + } + } + else { + System.err.println(this.getClass().getCanonicalName() + ": don't know how to handle class " + + shape3d_Parent.getClass().getCanonicalName()); + } + } + + // --- if it's a VerticesObject object + + else if (vObject != null) { + vObject.setVisible(visibleCheckBox.isSelected()); + } + } + + public void setObjectVisible(boolean visible) { + if (visible != visibleCheckBox.isSelected()) { + //visibleCheckBox.setSelected(visible); + visibleCheckBox.doClick(); + validate(); + } + } + + public void setShininess(float shininess) { + + if (shininess < 1.0f) { + shininess = 1.0f; + } + else if (shininess > 128.0f) { + shininess = 128.0f; + } + logger.info("Setting Shininess: " + (int) shininess); + //shininessSlider.setEnabled(false); + this.shininessSlider.setValue( (int) shininess); + //shininessSlider.setEnabled(true); + } + + public void setTransparency(float transp) { + if (opaqueCheckBox.isSelected()) { + return; + } + + if (transp < 0) { + transp = 0; + } + else if (transp > 1) { + transp = 1; + } + + this.opacitySlider.setValue( (int) (transp * opacitySlider.getMaximum())); + } + + public void setTransparencyMode(int mode) { + if (opaqueCheckBox.isSelected()) { + return; + } + + String modeName = VerticesObjectProperties.getTransparencyModeAsString(mode); + if (modeName != null) { + this.transpComboBox.setSelectedItem(modeName); + transpComboBox.revalidate(); + } + } + + public void setObjectOpaque(boolean opaque) { + if (opaque != opaqueCheckBox.isSelected()) { + //visibleCheckBox.setSelected(visible); + opaqueCheckBox.doClick(); + validate(); + } + } + + public void enableAllControls(boolean enable) { + renderingComboBox.setEnabled(enable); + opaqueCheckBox.setEnabled(enable); + transpComboBox.setEnabled(enable); + opacitySlider.setEnabled(enable); + } + + private class VerticesPropertyPanel_renderingComboBox_itemAdapter + implements ItemListener { + private VerticesPropertyPanel adaptee; + VerticesPropertyPanel_renderingComboBox_itemAdapter(VerticesPropertyPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void itemStateChanged(ItemEvent e) { + adaptee.renderingComboBox_itemStateChanged(e); + } + } + + public void transpComboBox_itemStateChanged(ItemEvent e) { + + if (e.getStateChange() != ItemEvent.SELECTED) { + return; + } + + if (!transpComboBox.isEnabled()) { + return; + } + transpComboBox.setEnabled(false); + + int transpMode = VerticesObjectProperties.getTransparencyMode(transpComboBox.getSelectedItem().toString()); + + // --- set shape3d + + if (App != null) { + Appearance newApp = new Appearance(); + newApp.duplicateNodeComponent(App, false); + + try { + TransparencyAttributes ta = newApp.getTransparencyAttributes(); + + if (ta == null) { + ta = new TransparencyAttributes(); + ta.setCapability(TransparencyAttributes.ALLOW_BLEND_FUNCTION_READ); + ta.setCapability(TransparencyAttributes.ALLOW_BLEND_FUNCTION_WRITE); + ta.setCapability(TransparencyAttributes.ALLOW_MODE_READ); + ta.setCapability(TransparencyAttributes.ALLOW_MODE_WRITE); + ta.setCapability(TransparencyAttributes.ALLOW_VALUE_READ); + ta.setCapability(TransparencyAttributes.ALLOW_VALUE_WRITE); + newApp.setTransparencyAttributes(ta); + } + + //PolygonAttributes pa = newApp.getPolygonAttributes(); + //pa.setCullFace(pa.CULL_FRONT); + + float value = opacitySlider.getValue(); + + float transp = value / opacitySlider.getMaximum(); + ta.setTransparency(transp); + ta.setTransparencyMode(transpMode); + + Shape3d.setAppearance(newApp); + App = newApp; + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Cannot set transperancy attributes: " + + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + } + } + + // --- Setup visual object + + else if (vObject != null) { + vObject.setTransparencyMode(transpMode); + } + + transpComboBox.setEnabled(true); + } + + public void opacitySlider_stateChanged(ChangeEvent e) { + if (!opacitySlider.isEnabled()) { + return; + } + + if (opacitySlider.getValueIsAdjusting()) { + return; + } + + opacitySlider.setEnabled(false); + + float value = (float) opacitySlider.getValue() / (float) opacitySlider.getMaximum(); + + // --- Adjust shape3d... + if (Shape3d != null && App != null) { + try { + Appearance newApp = new Appearance(); + newApp.duplicateNodeComponent(App, false); + + TransparencyAttributes ta = newApp.getTransparencyAttributes(); + + if (ta == null) { + ta = new TransparencyAttributes(); + ta.setCapability(TransparencyAttributes.ALLOW_BLEND_FUNCTION_READ); + ta.setCapability(TransparencyAttributes.ALLOW_BLEND_FUNCTION_WRITE); + ta.setCapability(TransparencyAttributes.ALLOW_MODE_READ); + ta.setCapability(TransparencyAttributes.ALLOW_MODE_WRITE); + ta.setCapability(TransparencyAttributes.ALLOW_VALUE_READ); + ta.setCapability(TransparencyAttributes.ALLOW_VALUE_WRITE); + //App.setTransparencyAttributes(ta); + newApp.setTransparencyAttributes(ta); + } + + //PolygonAttributes pa = App.getPolygonAttributes(); + PolygonAttributes pa = newApp.getPolygonAttributes(); + //pa.setCullFace(pa.CULL_FRONT); + + ta.setTransparency(value); + + int transpMode = VerticesObjectProperties.getTransparencyMode(transpComboBox.getSelectedItem().toString()); + ta.setTransparencyMode(transpMode); + + Shape3d.setAppearance(newApp); + App = newApp; + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Cannot set transperancy attributes: " + + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + } + } + + // --- Adjust visual object + + else if (vObject != null) { + vObject.setTransparency(value); + } + + opacitySlider.setEnabled(true); + } + + public boolean isObjectVisible() { + return visibleCheckBox.isSelected(); + } + + public boolean isObjectOpaque() { + return this.opaqueCheckBox.isSelected(); + } + + public void shininessSlider_stateChanged(ChangeEvent e) { + if (!shininessSlider.isEnabled()) { + return; + } + + if (shininessSlider.getValueIsAdjusting()) { + return; + } + + shininessSlider.setEnabled(false); + + float shininess = shininessSlider.getValue(); + logger.info("New Shininess: " + (int) shininess); + + // --- Adjust shape3d... + if (Shape3d != null && App != null) { + try { + Appearance newApp = new Appearance(); + newApp.duplicateNodeComponent(App, false); + + Material material = newApp.getMaterial(); + if (material == null) { + material = new Material(); + material.setCapability(Material.ALLOW_COMPONENT_READ); + material.setCapability(Material.ALLOW_COMPONENT_WRITE); + } + material.setShininess(shininess); + + Shape3d.setAppearance(newApp); + App = newApp; + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Cannot set shininess in Material: " + + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + } + } + + // --- Adjust visual object + + else if (vObject != null) { + vObject.setShininess(shininess); + } + + shininessSlider.setEnabled(true); + + } + + private class VerticesPropertyPanel_opaqueCheckBox_actionAdapter + implements ActionListener { + private VerticesPropertyPanel adaptee; + VerticesPropertyPanel_opaqueCheckBox_actionAdapter(VerticesPropertyPanel + adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.opaqueCheckBox_actionPerformed(e); + } + } + + private class VerticesPropertyPanel_visibleCheckBox_actionAdapter + implements ActionListener { + private VerticesPropertyPanel adaptee; + VerticesPropertyPanel_visibleCheckBox_actionAdapter(VerticesPropertyPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.visibleCheckBox_actionPerformed(e); + } + } + + private class VerticesPropertyPanel_opacitySlider_changeAdapter + implements ChangeListener { + private VerticesPropertyPanel adaptee; + VerticesPropertyPanel_opacitySlider_changeAdapter(VerticesPropertyPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.opacitySlider_stateChanged(e); + } + } + + private class VerticesPropertyPanel_transpComboBox_itemAdapter + implements ItemListener { + private VerticesPropertyPanel adaptee; + VerticesPropertyPanel_transpComboBox_itemAdapter(VerticesPropertyPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void itemStateChanged(ItemEvent e) { + adaptee.transpComboBox_itemStateChanged(e); + } + } + +} + +class VerticesPropertyPanel_shininessSlider_changeAdapter + implements ChangeListener { + private VerticesPropertyPanel adaptee; + VerticesPropertyPanel_shininessSlider_changeAdapter(VerticesPropertyPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.shininessSlider_stateChanged(e); + } +} diff --git a/src/main/java/cct/math/.DS_Store b/src/main/java/cct/math/.DS_Store new file mode 100644 index 0000000..7db9a31 Binary files /dev/null and b/src/main/java/cct/math/.DS_Store differ diff --git a/src/main/java/cct/math/._.DS_Store b/src/main/java/cct/math/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/cct/math/._.DS_Store differ diff --git a/src/main/java/cct/math/Amoeba.java b/src/main/java/cct/math/Amoeba.java new file mode 100644 index 0000000..8c39895 --- /dev/null +++ b/src/main/java/cct/math/Amoeba.java @@ -0,0 +1,266 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.math; + +import java.util.logging.Logger; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Amoeba { + + float TINY = 1.0e-10f; // A small number. + float gamma = 0.01f; // + int NMAX = 5000; // Maximum allowed number of function evaluations + int nfunk; // nfunk gives the number of function evaluations taken. + float psum[]; + float p[][]; + float y[]; + float ptry[]; + boolean print = true; + + float Fmin = 0; + static final Logger logger = Logger.getLogger(Amoeba.class.getCanonicalName()); + + public Amoeba() { + } + + void GET_PSUM(int ndim) { + for (int j = 0; j < ndim; j++) { + float sum = 0.0f; + for (int i = 0; i < ndim + 1; i++) { + sum += p[i][j]; + } + psum[j] = sum; + } + } + + /** + * Multidimensional minimization of the function func(x) where x[ndim] is a vector in ndim + * dimensions, by the downhill simplex method of Nelder and Mead. The matrix p[ndim+1] + * [ndim] is input. Its ndim+1 rows are ndim-dimensional vectors which are the vertices of + * the starting simplex. Also input is the vector y[ndim+1], whose components must be preinitialized + * to the values of func evaluated at the ndim+1 vertices (rows) of p; and ftol the + * fractional convergence tolerance to be achieved in the function value (n.b.!). On output, p and + * y will have been reset to ndim+1 new points all within ftol of a minimum function value, and + * nfunk gives the number of function evaluations taken. + * @param float + */ + public int amoeba(float x[], int ndim, float ftol, + MinimizedFunctionInterface func) { + + int i, ihi, ilo, inhi, j, cond = 0; + float rtol, swap, ysave, ytry; + + //psum=vector(1,ndim); + psum = new float[ndim]; + ptry = new float[ndim]; + p = new float[ndim + 1][ndim]; + y = new float[ndim + 1]; + + // --- Initialization + + // --- Calculate function in initial point + y[0] = func.function(ndim, x); + for (i = 0; i < ndim; i++) { + p[0][i] = x[i]; + } + if (print) { + logger.info("Initial fun value: " + y[0]); + } + + // --- Calculate function in N more points + for (j = 0, i = 1; i < ndim + 1; i++, j++) { + swap = x[j]; + x[j] += gamma; + y[i] = func.function(ndim, x); + + for (int k = 0; k < ndim; k++) { + p[i][k] = x[k]; + } + + x[j] = swap; + } + + // --- Start minimization + + nfunk = 0; + GET_PSUM(ndim); + + for (; ; ) { + ilo = 0; + //First we must determine which point is the highest(worst), + // next - highest, and lowest + // (best), by looping over the points in the simplex. + + //ihi = y[1] > y[2] ? (inhi = 2, 1) : (inhi = 1, 2); + ihi = y[0] > y[1] ? 0 : 1; + inhi = y[0] > y[1] ? 1 : 0; + for (i = 0; i < ndim + 1; i++) { + if (y[i] <= y[ilo]) { + ilo = i; + } + if (y[i] > y[ihi]) { + inhi = ihi; + ihi = i; + } + else if (y[i] > y[inhi] && i != ihi) { + inhi = i; + } + } + + rtol = 2.0f * Math.abs(y[ihi] - y[ilo]) / + ( (Math.abs(y[ihi]) + Math.abs(y[ilo])) + TINY); + + if (print) { + logger.info("Fun value: " + y[ilo] + " rtol: " + rtol); + } + + //Compute the fractional range from highest to lowest and return if satisfactory. + if (rtol < ftol || nfunk >= NMAX) { // If returning, put best point and value in slot 0. + if (nfunk >= NMAX) { + System.err.println("NMAX exceeded"); + cond = 1; + } + + //SWAP(y[1], y[ilo]) + swap = y[0]; + y[0] = y[ilo]; + Fmin = y[ilo]; + y[ilo] = swap; + + for (i = 0; i < ndim; i++) { + // SWAP(p[1][i], p[ilo][i]) + swap = p[0][i]; + p[0][i] = p[ilo][i]; + x[i] = p[ilo][i]; + p[ilo][i] = swap; + } + break; + } + + nfunk += 2; + + // Begin a new iteration.First extrapolate by a factor \u22121through the + // face of the simplex across from the high point, i.e., + // reflect the simplex from the high point. + + ytry = amotry(p, y, psum, ndim, func, ihi, -1.0f); + + if (ytry <= y[ilo]) { + // Gives a result better than the best point, so try + // an additional extrapolation by a factor 2. + ytry = amotry(p, y, psum, ndim, func, ihi, 2.0f); + } + else if (ytry >= y[inhi]) { + // The reflected point is worse than the second - highest, + // so look for an intermediate lower point, i.e., do + // a one - dimensional contraction. + ysave = y[ihi]; + ytry = amotry(p, y, psum, ndim, func, ihi, 0.5f); + if (ytry >= ysave) { + // Can �t seem to get rid of that high point.Better + for (i = 0; i < ndim + 1; i++) { // contract around the lowest(best) point. + if (i != ilo) { + for (j = 0; j < ndim; j++) { + p[i][j] = psum[j] = 0.5f * (p[i][j] + p[ilo][j]); + } + y[i] = func.function(ndim, psum); + } + } + nfunk += ndim; // Keep track of function evaluations. + GET_PSUM(ndim); // Recompute psum. + } + } + else { + --nfunk; // Correct the evaluation count. + } + } + return cond; + } + + // Go back for the test of doneness and the next iteration. + //free_vector(psum, 1, ndim); + + + /** + * Extrapolates by a factor fac through the face of the simplex across + * from the high point, tries it, and replaces the high point if the new point is better. + * + * @param p float[][] + * @param y float[] + * @param psum float[] + * @param ndim int + * @param float + * @return float + */ + float amotry(float p[][], float y[], float psum[], int ndim, + MinimizedFunctionInterface func, int ihi, float fac) { + int j; + float fac1, fac2, ytry; + fac1 = (1.0f - fac) / ndim; + fac2 = fac1 - fac; + for (j = 0; j < ndim; j++) { + ptry[j] = psum[j] * fac1 - p[ihi][j] * fac2; + } + ytry = func.function(ndim, ptry); // Evaluate the function at the trial point. + if (ytry < y[ihi]) { //If it �s better than the highest, then replace the highest. + y[ihi] = ytry; + for (j = 0; j < ndim; j++) { + psum[j] += ptry[j] - p[ihi][j]; + p[ihi][j] = ptry[j]; + } + } +//free_vector(ptry, 1, ndim); + return ytry; + } + + public static void main(String[] args) { + Amoeba amoeba = new Amoeba(); + } + +} diff --git a/src/main/java/cct/math/Crystal.java b/src/main/java/cct/math/Crystal.java new file mode 100644 index 0000000..c46b38a --- /dev/null +++ b/src/main/java/cct/math/Crystal.java @@ -0,0 +1,226 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.math; + +import cct.Constants; +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class Crystal { + + public static final double RADIANS_TO_DEGREES = 180.0 / Math.PI; + + protected Crystal() { + } + + public static double[] latticeParamFromLatticeVectors(double[][] latticeVectors) { + double[] latticeParameters = new double[6]; + double[] d = new double[3]; + for (int i = 0; i < 3; i++) { + d[i] = Math.sqrt(latticeVectors[i][0] * latticeVectors[i][0] + latticeVectors[i][1] * latticeVectors[i][1] + + latticeVectors[i][2] * latticeVectors[i][2]); + if (d[i] < 0.01) { + d[i] = 1.0; + } + latticeParameters[i] = d[i]; + } + + // --- alpha (between b & c) + latticeParameters[3] = Math.acos( (latticeVectors[2][0] * latticeVectors[1][0] + latticeVectors[2][1] * latticeVectors[1][1] + + latticeVectors[2][2] * latticeVectors[1][2]) / (d[2] * d[1])) * RADIANS_TO_DEGREES; + // --- beta (between a & c ) + latticeParameters[4] = Math.acos( (latticeVectors[0][0] * latticeVectors[2][0] + latticeVectors[0][1] * latticeVectors[2][1] + + latticeVectors[0][2] * latticeVectors[2][2]) / (d[0] * d[2])) * RADIANS_TO_DEGREES; + // --- gamma (between a & b ) + + latticeParameters[5] = Math.acos( (latticeVectors[0][0] * latticeVectors[1][0] + latticeVectors[0][1] * latticeVectors[1][1] + + latticeVectors[0][2] * latticeVectors[1][2]) / (d[0] * d[1])) * RADIANS_TO_DEGREES; + + return latticeParameters; + } + + public static double[] getDefaultLatticeParameters(MoleculeInterface molec, double space) { + double[] latticeParameters = new double[6]; + latticeParameters[3] = 90.0; + latticeParameters[4] = 90.0; + latticeParameters[5] = 90.0; + + if (molec == null || molec.getNumberOfAtoms() < 1) { + latticeParameters[0] = 1.0 + 2.0 * space; + latticeParameters[1] = 1.0 + 2.0 * space; + latticeParameters[2] = 1.0 + 2.0 * space; + return latticeParameters; + } + if (space < 0) { + space = 0.001; + } + + AtomInterface atom = molec.getAtomInterface(0); + double xMin = atom.getX(); + double xMax = atom.getX(); + double yMin = atom.getY(); + double yMax = atom.getY(); + double zMin = atom.getZ(); + double zMax = atom.getZ(); + + for (int i = 1; i < molec.getNumberOfAtoms(); i++) { + atom = molec.getAtomInterface(i); + if (xMin > atom.getX()) { + xMin = atom.getX(); + } + else if (xMax < atom.getX()) { + xMax = atom.getX(); + } + if (yMin > atom.getY()) { + yMin = atom.getY(); + } + else if (yMax < atom.getY()) { + yMax = atom.getY(); + } + if (zMin > atom.getZ()) { + zMin = atom.getZ(); + } + else if (zMax < atom.getZ()) { + zMax = atom.getZ(); + } + + } + + latticeParameters[0] = xMax - xMin + 2.0 * space; + latticeParameters[1] = yMax - yMin + 2.0 * space; + latticeParameters[2] = zMax - zMin + 2.0 * space; + latticeParameters[3] = 90.0; + latticeParameters[4] = 90.0; + latticeParameters[5] = 90.0; + + return latticeParameters; + } + + public static double[][] getCartesianToFractionalTransMatrix(double[] latticePars) { + double[][] matrix = new double[3][3]; + + double a = latticePars[0]; + double b = latticePars[1]; + double c = latticePars[2]; + double alpha = latticePars[3] * Constants.DEGREES_TO_RADIANS; + double beta = latticePars[4] * Constants.DEGREES_TO_RADIANS; + double gamma = latticePars[5] * Constants.DEGREES_TO_RADIANS; + + double factor = Math.sqrt(1.0 - Math.cos(alpha) * Math.cos(alpha) - Math.cos(beta) * Math.cos(beta) - + Math.cos(gamma) * Math.cos(gamma) + 2.0 * Math.cos(alpha) * Math.cos(beta) * Math.cos(gamma)); + + matrix[0][0] = 1.0 / a; + matrix[0][1] = 0; + matrix[0][2] = 0; + + matrix[1][0] = -Math.cos(gamma) / (a * Math.sin(gamma)); + matrix[1][1] = 1.0 / (b * Math.sin(gamma)); + matrix[1][2] = 0; + + matrix[2][0] = (Math.cos(alpha) * Math.cos(gamma) - Math.cos(beta)) / (a * Math.sin(gamma) * factor); + matrix[2][1] = (Math.cos(beta) * Math.cos(gamma) - Math.cos(alpha)) / (b * Math.sin(gamma) * factor); + matrix[2][2] = Math.sin(gamma) / (c * factor); + + return matrix; + } + + public static double[][] getCartesianFromFractional(double[][] fractional, int nCenters, double latticeVectors[][]) throws + Exception { + + double[][] coords = new double[nCenters][3]; + + for (int i = 0; i < nCenters; i++) { + coords[i][0] = fractional[i][0] * latticeVectors[0][0] + fractional[i][1] * latticeVectors[1][0] + + fractional[i][2] * latticeVectors[2][0]; + coords[i][1] = fractional[i][0] * latticeVectors[0][1] + fractional[i][1] * latticeVectors[1][1] + + fractional[i][2] * latticeVectors[2][1]; + coords[i][2] = fractional[i][0] * latticeVectors[0][2] + fractional[i][1] * latticeVectors[1][2] + + fractional[i][2] * latticeVectors[2][2]; + } + return coords; + } + + /** + * Validates lattice parameters. Alpha, beta and gamma are expected in degrees + * @param a double + * @param b double + * @param c double + * @param alpha double + * @param beta double + * @param gamma double + * @throws Exception + */ + public static void validateLatticeParameters(double a, double b, double c, double alpha, double beta, double gamma) throws + Exception { + if (a <= 0.0) { + throw new Exception("Lattice parameter \"a\" cannot be less than 0. Got " + a); + } + + if (b <= 0.0) { + throw new Exception("Lattice parameter \"b\" cannot be less than 0. Got " + b); + } + + if (c <= 0.0) { + throw new Exception("Lattice parameter \"c\" cannot be less than 0. Got " + c); + } + + if (alpha <= 0.0 || alpha > 180.0) { + throw new Exception("Lattice parameter \"alpha\" should be 0 < alpha < 180. Got " + alpha); + } + + if (beta <= 0.0 || beta > 180.0) { + throw new Exception("Lattice parameter \"beta\" should be 0 < beta < 180. Got " + beta); + } + + if (gamma <= 0.0 || gamma > 180.0) { + throw new Exception("Lattice parameter \"gamma\" should be 0 < gamma < 180. Got " + gamma); + } + } +} diff --git a/src/main/java/cct/math/DFPMin.java b/src/main/java/cct/math/DFPMin.java new file mode 100644 index 0000000..23bb8c5 --- /dev/null +++ b/src/main/java/cct/math/DFPMin.java @@ -0,0 +1,524 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.math; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; + +import cct.interfaces.MinimizeProgressInterface; +import cct.tools.Utils; + +/** + *

Title:

+ * + *

Description:

+ * The Broyden-Fletcher-Goldfarb-Shanno variant of Davidon-Fletcher-Powell minimization. + * Adopted from the Numerical Recipes in C + * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class DFPMin + implements MinimizerInterface { + + static final List completionMessages = new ArrayList(); + static final Logger logger = Logger.getLogger(DFPMin.class.getCanonicalName()); + + int ITMAX = 1000; // Maximum allowed number of iterations. + double EPS = 3.0e-8; // Machine precision. + double TOLX = (4.0 * EPS); // Convergence criterion on x values. + float MAXGRAD = 0.5f; // Convergence criterion on max gradient value. + float MAXGRMS = 0.25f; // Convergence criterion on max rms gradient value. + double STPMX = 100.0; // Scaled maximum step length allowed in line searches. + int iter; // Actual number of iterations + float fret; // Minimum value of the function + float gTol = 0.01f; + + boolean maxGradConvergence = true; + boolean maxGRMSConvergence = true; + + boolean debug = true; + + MinimizeProgressInterface minimizationProgress = null; + + // --- Temporary storage + + private float[] dg = null; + private float[] g = null; + private float[] hdg = null; + private float[][] hessin = null; + private float[] pnew = null; + private float[] xi = null; + + static { + completionMessages.add(new String("The algorithm has converged")); // =0 + completionMessages.add(new String( + "The maximum number of function evaluations have been used")); // =1 + completionMessages.add(new String("Minimization was cancelled by user")); // =2 + // IF NFLAG=2, THE LINEAR SEARCH HAS FAILED TO + // IMPROVE THE FUNCTION VALUE. THIS IS THE + // USUAL EXIT IF EITHER THE FUNCTION OR THE + // GRADIENT IS INCORRECTLY CODED. + // IF NFLAG=3, THE SEARCH VECTOR WAS NOT + // A DESCENT DIRECTION. THIS CAN ONLY BE CAUSED + // BY ROUNDOFF,AND MAY SUGGEST THAT THE + // CONVERGENCE CRITERION IS TOO STRICT. + } + + public DFPMin() { + } + + public void setGTolerance(float gtol) { + gTol = gtol; + } + + public int getActualIterNum() { + return iter; + } + + public void setMaximumStep(double step) { + STPMX = step; + } + + /** + * Given a starting point p[1..n] that is a vector of length n, the Broyden-Fletcher-Goldfarb- + * Shanno variant of Davidon-Fletcher-Powell minimization is performed on a function func, using + * its gradient as calculated by a routine dfunc. The convergence requirement on zeroing the + * gradient is input as gtol. Returned quantities are p[1..n] (the location of the minimum), + * iter (the number of iterations that were performed), and fret (the minimum value of the + * function). The routine lnsrch is called to perform approximate line minimizations. + * + * @param n int + * @param p float[] + * @param gtol float + * @param iter int + * @param fret float + * @param func MinimizedFunctionInterface + */ + @Override + public int minimizeFunction(int n, float[] p, + MinimizedFunctionInterface func) { + + boolean check = false, isConverged = false, updateVariables = false; + int i, its, j; + float den, fac, fad, fae, fp, stpmax, sum = 0.0f, sumdg, sumxi, temp, + test; + + dg = new float[n]; + g = new float[n]; + hdg = new float[n]; + hessin = new float[n][n]; + pnew = new float[n]; + xi = new float[n]; + + LinearSearch ls = new LinearSearch(); + + if (minimizationProgress != null) { + updateVariables = minimizationProgress.getVariablesFrequencyUpdate() > + 0; + minimizationProgress.minimizationStarted( + "Calculating initial function value and grads..."); + } + /* + dg = vector(1, n); + g = vector(1, n); + hdg = vector(1, n); + hessin = matrix(1, n, 1, n); + pnew = vector(1, n); + xi = vector(1, n); + */ + //fp = ( * func) (p); // Calculate starting function value and gra - + //( * dfunc) (p, g); // dient, + + fp = func.function(n, p, g); + + if (minimizationProgress != null) { + minimizationProgress.minimizationProgressed(String.format( + "Function: %8.4f GRMS: %8.4f Max Grad: %8.4f", fp, getRMS(n, g), + maxGrad(n, g))); + } + + if (debug) { + logger.info("Starting function value: " + fp + " norm: " + + gradNorm(n, g) + " Max grad: " + maxGrad(n, g)); + Utils.printFloatVector(n, g); + } + + isConverged = false; + // --- Check on convergence on max G + float maxG = 0; + if (maxGradConvergence) { + for (i = 0; i < n; i++) { + if (Math.abs(maxG) < Math.abs(g[i])) { + maxG = Math.abs(g[i]); + } + } + if (Math.abs(maxG) <= MAXGRAD) { + logger.info( + "Convergence on max gradient in initial point. Max gradient: " + + maxG); + if (minimizationProgress != null) { + minimizationProgress.minimizationCompleted(); + } + return 0; + } + } + if (maxGRMSConvergence && getRMS(n, g) <= MAXGRMS) { + logger.info( + "Convergence on Max RMS gradient in initial point. GRMS: " + + getRMS(n, g)); + if (minimizationProgress != null) { + minimizationProgress.minimizationCompleted(); + } + return 0; + } + + /* + for (i = 1; i <= n; i++) { // and initialize the inverse Hessian to the + for (j = 1; j <= n; j++) { // unit matrix. + hessin[i][j] = 0.0; + } + hessin[i][i] = 1.0; + xi[i] = -g[i]; // Initial line direction. + sum += p[i] * p[i]; + } + */ + + for (i = 0; i < n; i++) { // and initialize the inverse Hessian to the + for (j = 0; j < n; j++) { // unit matrix. + hessin[i][j] = 0.0f; + } + hessin[i][i] = 1.0f; + xi[i] = -g[i]; // Initial line direction. + sum += p[i] * p[i]; + } + + stpmax = (float) (STPMX * Math.max(Math.sqrt(sum), n)); + //if ( stpmax > (float)STPMX ) stpmax = (float)STPMX; // !!! VLAD + + for (its = 1; its <= ITMAX; its++) { // Main loop over the iterations. + iter = its; + if (debug) { + logger.info("Iteration: " + iter + " stpmax: " + stpmax); + } + + check = ls.lnsrch(n, p, fp, g, xi, pnew, stpmax, func); + fret = ls.getFMin(); + if (debug) { + logger.info("After linear search: " + fret); + } + + //lnsrch(n, p, fp, g, xi, pnew, fret, stpmax, & check, func); + + // The new function evaluation occurs in lnsrch; + // save the function value in fp for the + // next line search.It is usually safe to ignore the value of check. + + fp = fret; + for (i = 0; i < n; i++) { + xi[i] = pnew[i] - p[i]; // Update the line direction, + p[i] = pnew[i]; // and the current point. + } + test = 0.0f; // Test for convergence on deltaX. + for (i = 0; i < n; i++) { + temp = (float) (Math.abs(xi[i]) / Math.max(Math.abs(p[i]), 1.0)); + if (temp > test) { + test = temp; + } + } + + /* Old stuff + if (test < TOLX) { + //freeAll(); // FREEALL + logger.info("Convergence on deltaX was achieved: " + test + + " TOLX: " + TOLX); + return 0; + } + */ + + for (i = 0; i < n; i++) { // Save the old gradient, + dg[i] = g[i]; + } + + // ( * dfunc) (p, g); // and get the new gradient. ??? + fret = func.function(n, p, g); + if (minimizationProgress != null) { + minimizationProgress.minimizationProgressed(String.format( + "Iter: %d Function: %8.4f GRMS: %8.4f Max Grad: %8.4f", iter, + fret, getRMS(n, g), + maxGrad(n, g))); + if (minimizationProgress.isMinimizationCancelled()) { + return 2; + } + if (updateVariables && + iter % minimizationProgress.getVariablesFrequencyUpdate() == 0) { + minimizationProgress.updateVariables(n, p); + } + } + if (debug) { + logger.info("Function value: " + fret); + } + + test = 0.0f; // Test for convergence on zero gradient. + den = (float) Math.max(fret, 1.0); + for (i = 0; i < n; i++) { + temp = (float) (Math.abs(g[i]) * Math.max(Math.abs(p[i]), 1.0)) / + den; + if (temp > test) { + test = temp; + } + } + /* --- Old stuff + if (test < gTol) { + logger.info("Convergence on deltaG was achieved: " + test + + " Gtol: " + gTol); + //freeAll(); //FREEALL + return 0; + } + */ + + // Test for convergence on max gradient. + if (maxGradConvergence) { + for (i = 0; i < n; i++) { + if (Math.abs(maxG) < Math.abs(g[i])) { + maxG = Math.abs(g[i]); + } + } + if (Math.abs(maxG) <= MAXGRAD) { + logger.info( + "Convergence on max gradient was achieved. Max gradient: " + + maxG); + if (minimizationProgress != null) { + minimizationProgress.minimizationCompleted(); + } + return 0; + } + } + + if (maxGRMSConvergence && getRMS(n, g) <= MAXGRMS) { + logger.info( + "Convergence on Max RMS gradient was achieved. GRMS: " + + getRMS(n, g)); + if (minimizationProgress != null) { + minimizationProgress.minimizationCompleted(); + } + return 0; + } + + for (i = 0; i < n; i++) { + dg[i] = g[i] - dg[i]; // Compute difference of gradients, + } + + for (i = 0; i < n; i++) { // and difference times current matrix. + hdg[i] = 0.0f; + for (j = 0; j < n; j++) { + hdg[i] += hessin[i][j] * dg[j]; + } + } + fac = fae = sumdg = sumxi = 0.0f; // Calculate dot products for the denomitators. + for (i = 0; i < n; i++) { + fac += dg[i] * xi[i]; + fae += dg[i] * hdg[i]; + //sumdg += SQR(dg[i]); + //sumxi += SQR(xi[i]); + sumdg += dg[i] * dg[i]; + sumxi += xi[i] * xi[i]; + } + + if (fac > Math.sqrt(EPS * sumdg * sumxi)) { // Skip update if fac not sufficiently positive. + fac = 1.0f / fac; + fad = 1.0f / fae; + + //The vector that makes BFGS different from DFP: + for (i = 0; i < n; i++) { + dg[i] = fac * xi[i] - fad * hdg[i]; + } + for (i = 0; i < n; i++) { // The BFGS updating formula: + for (j = i; j < n; j++) { + hessin[i][j] += fac * xi[i] * xi[j] + - fad * hdg[i] * hdg[j] + fae * dg[i] * dg[j]; + hessin[j][i] = hessin[i][j]; + } + } + } + for (i = 0; i < n; i++) { // Now calculate the next direction to go, + xi[i] = 0.0f; + for (j = 0; j < n; j++) { + xi[i] -= hessin[i][j] * g[j]; + } + } + + // and go back for another iteration. + + } + + System.err.println("too many iterations in dfpmin"); + if (minimizationProgress != null) { + minimizationProgress.minimizationCompleted(); + } + return 1; + //freeAll(); //FREEALL + + } + + void freeAll() { + dg = null; + g = null; + hdg = null; + hessin = null; + pnew = null; + xi = null; + } + + float gradNorm(int n, float g[]) { + float norm = 0; + for (int i = 0; i < n; i++) { + norm += g[i] * g[i]; + } + return (float) Math.sqrt(norm); + } + + float maxGrad(int n, float g[]) { + float max = Math.abs(g[0]); + float value = g[0]; + for (int i = 1; i < n; i++) { + if (Math.abs(g[i]) > max) { + max = Math.abs(g[i]); + value = g[i]; + } + } + return value; + } + + double getRMS(int n, float v[]) { + double s = 0; + for (int i = 0; i < n; i++) { + s += v[i] * v[i]; + } + return Math.sqrt(s / n); + } + + public static void main(String[] args) { + DFPMin dfpmin = new DFPMin(); + } + + // --- Implementation of MinimizerInterface functions + + @Override + public void enableMaxGradConvergence(boolean enable) { + maxGradConvergence = enable; + } + + @Override + public void enableMaxGRMSConvergence(boolean enable) { + maxGRMSConvergence = enable; + } + + @Override + public String getExitCodeDescription(int code) { + if (code < 0 || code >= completionMessages.size()) { + return "Internal Error: No such exit code"; + } + return (String) completionMessages.get(code); + } + + @Override + public float[] getGradients() { + return g; + } + + @Override + public float getMaxGradientConv() { + return MAXGRAD; + } + + @Override + public float getMaxRMSGradientConv() { + return MAXGRMS; + } + + @Override + public int getMaxIterations() { + return ITMAX; + } + + @Override + public String getName() { + return "DFP"; + } + + @Override + public boolean isMaxGradConvergence() { + return maxGradConvergence; + } + + @Override + public boolean isMaxRMSGradConvergence() { + return maxGRMSConvergence; + } + + @Override + public void setMaxGradientConv(float maxgrad) { + MAXGRAD = maxgrad; + } + + @Override + public void setMaxRMSGradientConv(float maxgrms) { + MAXGRMS = maxgrms; + } + + @Override + public void setMaxIterations(int iter) { + ITMAX = iter; + } + + @Override + public boolean useGradients() { + return true; + } + + @Override + public void setMinimizeProgressInterface(MinimizeProgressInterface mpi) { + minimizationProgress = mpi; + } +} diff --git a/src/main/java/cct/math/Interpolator2D.java b/src/main/java/cct/math/Interpolator2D.java new file mode 100644 index 0000000..e7c8fe1 --- /dev/null +++ b/src/main/java/cct/math/Interpolator2D.java @@ -0,0 +1,168 @@ +package cct.math; + +import java.util.logging.Logger; + + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * Interpolates functions of two variables on a regular grid. + * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Interpolator2D { + private double[] origin = new double[2]; + private int[] dimension = new int[2]; + private double[][] funValues = null; + private double step = 1; + private double xMax, yMax; + private double tolerance; + static final Logger logger = Logger.getLogger(Interpolator2D.class.getCanonicalName()); + + private Interpolator2D() { + } + + public Interpolator2D(double xMin, double yMin, int xDim, int yDim, double dx, double[][] values) throws Exception { + origin[0] = xMin; + origin[1] = yMin; + + logger.info("Xmin=" + origin[0] + " Ymin=" + origin[1]); + + if (xDim < 2) { + throw new Exception(this.getClass().getCanonicalName() + ": xDim < 2"); + } + if (yDim < 2) { + throw new Exception(this.getClass().getCanonicalName() + ": yDim < 2"); + } + + dimension[0] = xDim; + dimension[1] = yDim; + logger.info("Dimension: X=" + dimension[0] + " Y=" + dimension[1]); + + if (dx <= 0) { + throw new Exception(this.getClass().getCanonicalName() + ": dx <= 0"); + } + step = dx; + tolerance = 0.001 * step; + + xMax = origin[0] + (xDim - 1) * step; + yMax = origin[1] + (yDim - 1) * step; + logger.info("Xmax=" + xMax + " Ymax" + yMax); + + if (values.length < xDim) { + throw new Exception(this.getClass().getCanonicalName() + ": values.length < xDim"); + } + if (values[0].length < yDim) { + throw new Exception(this.getClass().getCanonicalName() + ": values[0].length < yDim"); + } + funValues = new double[xDim][yDim]; + for (int i = 0; i < xDim; i++) { + for (int j = 0; j < yDim; j++) { + funValues[i][j] = values[i][j]; + } + + } + } + + public void testBounds(double x, double y) throws ValueOutOfBoundsException { + if (x < origin[0] || x > xMax) { + throw new ValueOutOfBoundsException(this.getClass().getCanonicalName() + ": x(" + x + ") < origin[0](" + origin[0] + + ") || x > xMax(" + xMax + ")"); + } + if (y < origin[1] || y > yMax) { + throw new ValueOutOfBoundsException(this.getClass().getCanonicalName() + ": y(" + y + ") < origin[1](" + origin[1] + + ") || y > yMax(" + yMax + ")"); + } + } + + public boolean checkBounds(double x, double y) { + if (x < origin[0] || x > xMax) { + return false; + } + return !(y < origin[1] || y > yMax); + } + + /** + * http://en.wikipedia.org/wiki/Bilinear_interpolation + * @param x double + * @param y double + * @return double + * @throws ValueOutOfBoundsException + */ + public double bilinearInterpolation(double x, double y) throws ValueOutOfBoundsException { + testBounds(x, y); + double indexX = ( (int) ( (x - origin[0]) / step)); + double indexY = ( (int) ( (y - origin[1]) / step)); + + int ind_x = (int) indexX; + int ind_y = (int) indexY; + + double x_floor = indexX * step; + double y_floor = indexY * step; + + // --- Special cases + + if (x - x_floor <= tolerance) { + if (y - y_floor <= tolerance) { + return funValues[ind_x][ind_y]; + } + return ( (y_floor + step - y) * funValues[ind_x][ind_y] + (y - y_floor) * funValues[ind_x][ind_y + 1]) / step; + } + + if (y - y_floor <= tolerance) { + return ( (x_floor + step - x) * funValues[ind_x][ind_y] + (x - x_floor) * funValues[ind_x + 1][ind_y]) / step; + } + + // --- general case + + return ( (x_floor + step - x) * (y_floor + step - y) * funValues[ind_x][ind_y] + + (x - x_floor) * (y_floor + step - y) * funValues[ind_x + 1][ind_y] + + (x_floor + step - x) * (y - y_floor) * funValues[ind_x][ind_y + 1] + + (x - x_floor) * (y - y_floor) * funValues[ind_x + 1][ind_y + 1]) / (step * step); + } + + public static void main(String[] args) { + double xMin = 0; + double yMin = 0; + int xDim = 2; + int yDim = 2; + double dx = 1; + double[][] values = new double[xDim][yDim]; + + values[0][0] = 0; + values[1][0] = 1; + values[1][1] = 2; + values[0][1] = 3; + + Interpolator2D interpolator2d = null; + try { + interpolator2d = new Interpolator2D(xMin, yMin, xDim, yDim, dx, values); + } + catch (Exception ex) { + ex.printStackTrace(); + System.exit(1); + } + try { + logger.info("x,y = 0,0: " + interpolator2d.bilinearInterpolation(0.0, 0.0)); + logger.info("x,y = 0,1: " + interpolator2d.bilinearInterpolation(0.0, 1.0)); + logger.info("x,y = 1,0: " + interpolator2d.bilinearInterpolation(1.0, 0.0)); + logger.info("x,y = 1,1: " + interpolator2d.bilinearInterpolation(1.0, 1.0)); + logger.info("x,y = 0, 0.5: " + interpolator2d.bilinearInterpolation(0.0, 0.5)); + logger.info("x,y = 1, 0.5: " + interpolator2d.bilinearInterpolation(1.0, 0.5)); + logger.info("x,y = 0.5, 0: " + interpolator2d.bilinearInterpolation(0.5, 0.0)); + logger.info("x,y = 0.5 ,1: " + interpolator2d.bilinearInterpolation(0.5, 1)); + logger.info("x,y = 0.5 ,0.5: " + interpolator2d.bilinearInterpolation(0.5, 0.5)); + } + catch (Exception ex) { + ex.printStackTrace(); + System.exit(1); + } + + } +} diff --git a/src/main/java/cct/math/LinearSearch.java b/src/main/java/cct/math/LinearSearch.java new file mode 100644 index 0000000..812f6d7 --- /dev/null +++ b/src/main/java/cct/math/LinearSearch.java @@ -0,0 +1,190 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.math; + +import java.util.logging.Logger; + +import cct.tools.Utils; + +/** + *

Title:

+ * + *

Description:

+ * Adapted from the Numerical Recipes in C + * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class LinearSearch { + public LinearSearch() { + } + + double ALF = 1.0e-4; // Ensures sufficient decrease in function value. + double TOLX = 1.0e-7; // Convergence criterion on \u0394x. + float fMin; // Final minimum function value + boolean debug = false; + static final Logger logger = Logger.getLogger(LinearSearch.class.getCanonicalName()); + + /** + * Given an n-dimensional point xold[1..n], the value of the function and gradient there, fold + * and g[1..n], and a direction p[1..n], finds a new point x[1..n] along the direction p from + * xold where the function func has decreased �sufficiently.� The new function value is returned + * in f. stpmax is an input quantity that limits the length of the steps so that you do not try to + * evaluate the function in regions where it is undefined or subject to overflow. p is usually the + * Newton direction. The output quantity check is false (0) on a normal exit. It is true (1) when + * x is too close to xold. In a minimization algorithm, this usually signals convergence and can + * be ignored. However, in a zero-finding algorithm the calling program should check whether the + * convergence is spurious. Some �difficult� problems may require double precision in this routine. + * @param n int + * @param xold float[] + * @param fold float + * @param g float[] + * @param p float[] + * @param x float[] + * @param float + */ + public boolean lnsrch(int n, float[] xold, float fold, float[] g, + float[] p, + float[] x, + float stpmax, MinimizedFunctionInterface func) { + int i; + double a, alam, alam2 = 0, alamin, b, disc, f2 = 0, rhs1, rhs2, slope, + sum, temp, + test, tmplam; + boolean check = false; + for (sum = 0.0, i = 0; i < n; i++) { + sum += p[i] * p[i]; + } + sum = Math.sqrt(sum); + if (sum > stpmax) { + for (i = 0; i < n; i++) { + p[i] *= stpmax / sum; // Scale if attempted step is too big. + } + } + for (slope = 0.0, i = 0; i < n; i++) { + slope += g[i] * p[i]; + } + + if (debug) { + logger.info("Vector of directions: "); + Utils.printFloatVector(n, p); + } + + if (slope >= 0.0) { + System.err.println("Roundoff problem in lnsrch."); + } + test = 0.0; // Compute Lambda min. + for (i = 0; i < n; i++) { + temp = Math.abs(p[i]) / Math.max(Math.abs(xold[i]), 1.0); + if (temp > test) { + test = temp; + } + } + alamin = TOLX / test; + alam = 1.0; // Always try full Newton step first. + for (int iter = 1; ; iter++) { // Start of iteration loop. + for (i = 0; i < n; i++) { + x[i] = xold[i] + (float) alam * p[i]; // !!! precision !!! + } + + fMin = func.function(n, x); + + if (debug) { + logger.info("Linsearch: Iteration: " + iter + " Func: " + + fMin + " alam: " + alam); + } + + if (alam < alamin) { // Convergence on deltaX. For zero finding, the calling program should verify the convergence. + for (i = 0; i < n; i++) { + x[i] = xold[i]; + } + check = true; + return check; + } + else if (fMin <= fold + ALF * alam * slope) { + return check; // Sufficient function decrease. + } + else { // Backtrack. + if (alam == 1.0) { + tmplam = -slope / (2.0 * (fMin - fold - slope)); // First time. + } + else { // Subsequent backtracks. + rhs1 = fMin - fold - alam * slope; + rhs2 = f2 - fold - alam2 * slope; + a = (rhs1 / (alam * alam) - rhs2 / (alam2 * alam2)) / + (alam - alam2); + b = ( -alam2 * rhs1 / (alam * alam) + + alam * rhs2 / (alam2 * alam2)) / (alam - alam2); + if (a == 0.0) { + tmplam = -slope / (2.0 * b); + } + else { + disc = b * b - 3.0 * a * slope; + if (disc < 0.0) { + tmplam = 0.5 * alam; + } + else if (b <= 0.0) { + tmplam = ( -b + Math.sqrt(disc)) / (3.0 * a); + } + else { + tmplam = -slope / (b + Math.sqrt(disc)); + } + } + if (tmplam > 0.5 * alam) { + tmplam = 0.5 * alam; // \u03BB \u2264 0.5\u03BB1. + } + } + } + alam2 = alam; + f2 = fMin; + alam = Math.max(tmplam, 0.1 * alam); // \u03BB \u2265 0.1\u03BB1. + } // Try again. + } + + public float getFMin() { + return fMin; + } + + public static void main(String[] args) { + LinearSearch minimization = new LinearSearch(); + } +} diff --git a/src/main/java/cct/math/MathExpressionParser.java b/src/main/java/cct/math/MathExpressionParser.java new file mode 100644 index 0000000..37dc585 --- /dev/null +++ b/src/main/java/cct/math/MathExpressionParser.java @@ -0,0 +1,1069 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.math; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +//import cct.math.PREDEFINED_FUNCTION; + +/** + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +//enum TYPE { + +// VARIABLE, LOCAL_VARIABLE, FUNCTION, OPERATION_ADD, OPERATION_SUB, OPERATION_MUL, OPERATION_DIV, OPERATION_POWER, +// LEFT_PARANTHESIS, +// RIGHT_PARANTHESIS, COMMA; +//} + +//enum PREDEFINED_FUNCTION { + +// SQRT, sqrt, SIN, sin, COS, cos, TAN, tan, ASIN, asin, ACOS, acos, ATAN, atan, EXP, exp, LOG, log; +//} + +//enum OPERATION { + + //ADD, SUBSTRACT, MULTIPLY, DEVIDE, POWER; +//} + +//enum PARANTHESIS { + +// LEFT, RIGHT; +//} + +//enum SEPARATOR { + +// COMMA; +//} + +public class MathExpressionParser { + + static final double DEGREES_TO_RADIANS = Math.PI / 180.0; + + private static final char[] validSeparators = { + '+', '-', '*', '/', '^', '(', ')', ','}; + + private static final Map validOperators = new HashMap(); + private static final Map validOperations = new HashMap(); + private static final Map Parantheses = new HashMap(2); + private Map definedFunctions = new HashMap(); + + static { + validOperators.put("+", OPERATION.ADD); + validOperators.put("-", OPERATION.SUBSTRACT); + validOperators.put("*", OPERATION.MULTIPLY); + validOperators.put("/", OPERATION.DEVIDE); + validOperators.put("^", OPERATION.POWER); + + validOperations.put("+", TYPE.OPERATION_ADD); + validOperations.put("-", TYPE.OPERATION_SUB); + validOperations.put("*", TYPE.OPERATION_MUL); + validOperations.put("/", TYPE.OPERATION_DIV); + validOperations.put("^", TYPE.OPERATION_POWER); + + Parantheses.put("(", PARANTHESIS.LEFT); + Parantheses.put(")", PARANTHESIS.RIGHT); + } + + private String Delimiters = " \t"; + private boolean caseSensitive = false; + private boolean inRadians = true; + + Map IDs = new HashMap(); + static final Logger logger = Logger.getLogger(MathExpressionParser.class.getCanonicalName()); + + //MathExpressionParser hiddenInit = new MathExpressionParser(true); // !!! + private MathExpressionParser(boolean something) { + + } + + public MathExpressionParser() { + definedFunctions.put("SQRT_1", new PredefinedFun(PREDEFINED_FUNCTION.SQRT)); + definedFunctions.put("sqrt_1", new PredefinedFun(PREDEFINED_FUNCTION.sqrt)); + definedFunctions.put("SIN_1", new PredefinedFun(PREDEFINED_FUNCTION.SIN)); + definedFunctions.put("sin_1", new PredefinedFun(PREDEFINED_FUNCTION.sin)); + definedFunctions.put("COS_1", new PredefinedFun(PREDEFINED_FUNCTION.COS)); + definedFunctions.put("cos_1", new PredefinedFun(PREDEFINED_FUNCTION.cos)); + definedFunctions.put("TAN_1", new PredefinedFun(PREDEFINED_FUNCTION.TAN)); + definedFunctions.put("tan_1", new PredefinedFun(PREDEFINED_FUNCTION.tan)); + definedFunctions.put("ASIN_1", new PredefinedFun(PREDEFINED_FUNCTION.ASIN)); + definedFunctions.put("asin_1", new PredefinedFun(PREDEFINED_FUNCTION.asin)); + definedFunctions.put("ACOS_1", new PredefinedFun(PREDEFINED_FUNCTION.ACOS)); + definedFunctions.put("acos_1", new PredefinedFun(PREDEFINED_FUNCTION.acos)); + definedFunctions.put("ATAN_1", new PredefinedFun(PREDEFINED_FUNCTION.ATAN)); + definedFunctions.put("atan_1", new PredefinedFun(PREDEFINED_FUNCTION.atan)); + definedFunctions.put("EXP_1", new PredefinedFun(PREDEFINED_FUNCTION.EXP)); + definedFunctions.put("epx_1", new PredefinedFun(PREDEFINED_FUNCTION.exp)); + definedFunctions.put("LOG_1", new PredefinedFun(PREDEFINED_FUNCTION.LOG)); + definedFunctions.put("log_1", new PredefinedFun(PREDEFINED_FUNCTION.log)); + + logger.setLevel(Level.WARNING); + } + + public boolean hasSymbol(String symbol) { + if (!caseSensitive) { + symbol = symbol.toUpperCase(); + } + return IDs.containsKey( symbol ) || definedFunctions.containsKey( symbol ); + } + + public void setInDegrees(boolean in_degrees) { + inRadians = !in_degrees; + } + + public void setInRadians(boolean in_radians) { + inRadians = in_radians; + } + + public boolean addLine(String line) throws Exception { + + line = line.trim(); + if (line.length() < 1) { + return true; + } + + if (!line.contains("=")) { + throw new Exception("Constant or function should be defined using = (equal) sign. Got " + line); + } + + if ((line.indexOf("=") == line.length() - 1) || line.substring(line.indexOf("=") + 1).trim().length() == 0) { + throw new Exception("Should be expression after the = (equal) sign. Got " + line); + } + + if (!caseSensitive) { + line = line.toUpperCase(); + } + + // --- Get id name + String id = line.substring(0, line.indexOf("=")).trim(); + + String expression = line.substring(line.indexOf("=") + 1); + expression = expression.replaceAll("[*][*]", "^"); + + if (id.matches(".+[(].+[)]")) { // Function + parseFunction(id, expression); + //throw new Exception("Definition of functions is not implemented yet"); + } else if (!id.contains("(") && !id.contains(")") && !id.contains(",")) { // Constant + if (IDs.containsKey(id)) { + throw new Exception("Identifier " + id + " is already defined"); + } + IDs.put(id, null); + parseConstant(id, expression); + } else { + throw new Exception("Unknown type of identifier. Should be a constant or a function. Got " + line); + } + return true; + //StringTokenizer st = new StringTokenizer(line, " =,"); + } + + void parseFunction(String definition, String expression) throws Exception { + + Function function; + try { + function = new Function(definition); + function.setFunctionBody(expression); + } catch (Exception ex) { + throw new Exception(definition + " : " + ex.getMessage()); + } + + if (definedFunctions.containsKey(function.internalName)) { + throw new Exception("Function " + function.Name + " with " + function.localParams.size() + + " parameters is already defined"); + } + + definedFunctions.put(function.internalName, function); + + } + + void parseConstant(String name, String expression) throws Exception { + double value = resolveExpression(expression); + Type var = new Type(name, TYPE.VARIABLE); + var.setValue(value); + IDs.put(name, var); + logger.info(name + " = " + var.number); + } + + public void addVariable(String name, double value) { + Type var = new Type(name, TYPE.VARIABLE); + var.setValue(value); + IDs.put(name, var); + logger.info("Added variable: " + name + " = " + var.number); + } + + void resolveTokens(String expression, List Tokens, List tokenTypes) throws Exception { + Tokens.clear(); + tokenTypes.clear(); + + List tokens = new ArrayList(); + int leftParantheses = 0, rightParantheses = 0; + + boolean buildingID = false; + String variable = ""; + for (int i = 0; i < expression.length(); i++) { + //expression.charAt(i); + String symbol = expression.substring(i, i + 1); + + if (Delimiters.contains(symbol)) { + continue; + } + + // --- Math operator + if (validOperators.containsKey(symbol)) { + if (buildingID) { + buildingID = false; + Tokens.add(new Type(variable, TYPE.VARIABLE)); + tokenTypes.add(TYPE.VARIABLE); + tokens.add(variable); + variable = ""; + } + Tokens.add(new Type(validOperators.get(symbol), validOperations.get(symbol))); + tokenTypes.add(validOperations.get(symbol)); + tokens.add(validOperators.get(symbol)); + } else if (symbol.equals("(")) { + ++leftParantheses; + if (buildingID) { + buildingID = false; + Tokens.add(new Type(variable, TYPE.FUNCTION)); + tokenTypes.add(TYPE.FUNCTION); + tokens.add(variable); + variable = ""; + } + Tokens.add(new Type(Parantheses.get(symbol), TYPE.LEFT_PARANTHESIS)); + tokenTypes.add(TYPE.LEFT_PARANTHESIS); + tokens.add(Parantheses.get(symbol)); + } else if (symbol.equals(")")) { + ++rightParantheses; + if (buildingID) { + buildingID = false; + Tokens.add(new Type(variable, TYPE.VARIABLE)); + tokenTypes.add(TYPE.VARIABLE); + tokens.add(variable); + variable = ""; + } + Tokens.add(new Type(Parantheses.get(symbol), TYPE.RIGHT_PARANTHESIS)); + tokenTypes.add(TYPE.RIGHT_PARANTHESIS); + tokens.add(Parantheses.get(symbol)); + } else if (symbol.equals(",")) { + if (buildingID) { + buildingID = false; + Tokens.add(new Type(variable, TYPE.VARIABLE)); + tokenTypes.add(TYPE.VARIABLE); + tokens.add(variable); + variable = ""; + } + Tokens.add(new Type(TYPE.COMMA)); + tokenTypes.add(TYPE.COMMA); + tokens.add(SEPARATOR.COMMA); + } else { + buildingID = true; + variable += symbol; + } + + } + + if (buildingID) { + Tokens.add(new Type(variable, TYPE.VARIABLE)); + tokenTypes.add(TYPE.VARIABLE); + tokens.add(variable); + } + + if (rightParantheses != leftParantheses) { + throw new Exception("Expression: " + expression + "\nLeft and Right Parantheses are not balanced"); + } + + } + + public double resolveExpression(String expression) throws Exception { + + // --- Stupid algorithm + // --- Resolve functions (if any) + // --- Resolve expr in parantheses (if any) + //ArrayList tokens = new ArrayList(); + List Tokens = new ArrayList(); + List tokenTypes = new ArrayList(); + + resolveTokens(expression, Tokens, tokenTypes); + + // --- Resolve variables + for (int i = 0; i < Tokens.size(); i++) { + logger.info(Tokens.get(i).name + " " + Tokens.get(i).type.toString()); + Type type = Tokens.get(i); + switch (type.type) { + case VARIABLE: + + if (!IDs.containsKey(type.name) && !type.isNumber()) { + throw new Exception("Expression: " + expression + "\nVariable " + type.name + " is not defined"); + } + + if (type.isNumber()) { + continue; + } + + Type var = (Type) IDs.get(type.name); + type.setValue(var.number); + break; + + case FUNCTION: + break; + } + } + + double value = 0; + try { + value = evaluateExpression(Tokens, tokenTypes); + } catch (Exception ex) { + throw new Exception("Expression: " + expression + "\n" + ex.getMessage()); + } + return value; + } + + /** + * We assume, no functions inside + * + * @param Tokens ArrayList + * @param tokenTypes ArrayList + * @return double + * @throws Exception + */ + double evaluateFunction(List Tokens, List tokenTypes) throws Exception { + double value = 0; + + if (tokenTypes.size() < 3) { + throw new Exception("Minimal function definition should be function_name()"); + } + + if (tokenTypes.get(0) != TYPE.FUNCTION) { + throw new Exception("Function should start from funcion name. Got " + tokenTypes.get(0).toString()); + } + if (tokenTypes.get(1) != TYPE.LEFT_PARANTHESIS) { + throw new Exception("Left paranthesis should follow the funcion name. Got " + tokenTypes.get(1).toString()); + } + if (tokenTypes.get(tokenTypes.size() - 1) != TYPE.RIGHT_PARANTHESIS) { + throw new Exception("Right paranthesis should close funcion definition. Got " + + tokenTypes.get(tokenTypes.size() - 1).toString()); + } + + // --- start to resolve arguments + if (tokenTypes.size() == 3 && tokenTypes.get(1) != TYPE.RIGHT_PARANTHESIS) { + throw new Exception("Minimal function definition should be function_name()"); + } + List parameters = new ArrayList(); + List Expression = new ArrayList(); + List exprTypes = new ArrayList(); + int leftParanthesisDepth = 0; + for (int i = 2; i < tokenTypes.size(); i++) { + if (tokenTypes.get(i) == TYPE.LEFT_PARANTHESIS) { + ++leftParanthesisDepth; + } else if (tokenTypes.get(i) == TYPE.RIGHT_PARANTHESIS && leftParanthesisDepth > 0) { + --leftParanthesisDepth; + } else if (tokenTypes.get(i) == TYPE.COMMA || tokenTypes.get(i) == TYPE.RIGHT_PARANTHESIS) { + Double Value = evaluateExpression(Expression, exprTypes); + parameters.add(Value); + logger.info("Par: " + parameters.size() + " value: " + Value); + Expression.clear(); + exprTypes.clear(); + continue; + } + Expression.add(Tokens.get(i)); + exprTypes.add(Tokens.get(i).type); + } + + String internalName = Tokens.get(0).name + "_" + String.valueOf(parameters.size()); + + if (!definedFunctions.containsKey(internalName)) { + throw new Exception("Function " + Tokens.get(0).name + " with " + parameters.size() + " parameters is not defined"); + } + + Object obj = definedFunctions.get(internalName); + if (obj instanceof PredefinedFun) { + return ((PredefinedFun) obj).getValue(parameters); + } else if (obj instanceof Function) { + return ((Function) obj).getValue(parameters); + + } + + throw new Exception("Unknown type of Function " + obj.getClass().getCanonicalName()); + } + + double evaluateExpression(List Tokens, List tokenTypes) throws Exception { + double value = 0; + + if (Tokens.size() == 1) { + if (Tokens.get(0).type == TYPE.VARIABLE || Tokens.get(0).type == TYPE.LOCAL_VARIABLE) { + return Tokens.get(0).number; + } + throw new Exception("Single token must be either a variable or a number"); + } + + while (Tokens.size() > 1) { + + if (tokenTypes.contains(TYPE.FUNCTION)) { + List Expression = new ArrayList(); + List exprTypes = new ArrayList(); + int index = tokenTypes.lastIndexOf(TYPE.FUNCTION); + int end, leftParanthesisDepth = -1; + + logger.info("Resolving function " + Tokens.get(index).name); + + for (end = index; end < tokenTypes.size(); end++) { + logger.info(end + " " + Tokens.get(end).type); + Expression.add(Tokens.get(end)); + exprTypes.add(Tokens.get(end).type); + if (tokenTypes.get(end) == TYPE.LEFT_PARANTHESIS) { + ++leftParanthesisDepth; + continue; + } else if (tokenTypes.get(end) == TYPE.RIGHT_PARANTHESIS) { + if (leftParanthesisDepth > 0) { + --leftParanthesisDepth; + continue; + } + } + + if (tokenTypes.get(end) == TYPE.RIGHT_PARANTHESIS) { + value = evaluateFunction(Expression, exprTypes); + logger.info("Function value: " + value); + Type result = new Type(value); + for (int i = index; i <= end; i++) { + Tokens.remove(index); + tokenTypes.remove(index); + } + Tokens.add(index, result); + tokenTypes.add(index, result.type); + break; + } + + } + } else if (tokenTypes.contains(TYPE.LEFT_PARANTHESIS)) { + List Expression = new ArrayList(); + List exprTypes = new ArrayList(); + ((ArrayList) Expression).ensureCapacity(Tokens.size()); + ((ArrayList) exprTypes).ensureCapacity(Tokens.size()); + + int indexEnd; + while (true) { + int indexStart = tokenTypes.lastIndexOf(TYPE.LEFT_PARANTHESIS); + if (indexStart == -1) { + break; + } + + Expression.clear(); + exprTypes.clear(); + + for (indexEnd = indexStart + 1; indexEnd < Tokens.size(); indexEnd++) { + if (Tokens.get(indexEnd).type == TYPE.RIGHT_PARANTHESIS) { + break; + } + Expression.add(Tokens.get(indexEnd)); + exprTypes.add(Tokens.get(indexEnd).type); + } + if (indexEnd == Tokens.size()) { + throw new Exception("Unmatched ("); + } + if (indexEnd - indexStart == 1) { + throw new Exception("No expression within parantheses"); + } + + value = evaluateExpression(Expression, exprTypes); + Type result = new Type(value); + for (int i = indexStart; i <= indexEnd; i++) { + Tokens.remove(indexStart); + tokenTypes.remove(indexStart); + } + Tokens.add(indexStart, result); + tokenTypes.add(indexStart, result.type); + + } + } else { + int index; + while (Tokens.size() > 1) { + // --- Power operation + index = tokenTypes.indexOf(TYPE.OPERATION_POWER); + if (index != -1) { + Type first = getToken(Tokens, index - 1); + Type second = getToken(Tokens, index + 1); + value = Math.pow(first.number, second.number); + Type result = new Type(value); + Tokens.remove(index - 1); + Tokens.remove(index - 1); + Tokens.remove(index - 1); + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + + Tokens.add(index - 1, result); + tokenTypes.add(index - 1, result.type); + continue; + } + + // --- Division + index = tokenTypes.indexOf(TYPE.OPERATION_DIV); + if (index != -1) { + Type first = getToken(Tokens, index - 1); + Type second = getToken(Tokens, index + 1); + value = first.number / second.number; + Type result = new Type(value); + Tokens.remove(index - 1); + Tokens.remove(index - 1); + Tokens.remove(index - 1); + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + + Tokens.add(index - 1, result); + tokenTypes.add(index - 1, result.type); + continue; + } + + // --- Multiplication + index = tokenTypes.indexOf(TYPE.OPERATION_MUL); + if (index != -1) { + Type first = getToken(Tokens, index - 1); + Type second = getToken(Tokens, index + 1); + value = first.number * second.number; + Type result = new Type(value); + Tokens.remove(index - 1); + Tokens.remove(index - 1); + Tokens.remove(index - 1); + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + + Tokens.add(index - 1, result); + tokenTypes.add(index - 1, result.type); + continue; + } + + // --- Sub + index = tokenTypes.indexOf(TYPE.OPERATION_SUB); + if (index != -1) { + Type first; + try { + first = getToken(Tokens, index - 1); + Type second = getToken(Tokens, index + 1); + value = first.number - second.number; + Type result = new Type(value); + + Tokens.remove(index - 1); + Tokens.remove(index - 1); + Tokens.remove(index - 1); + + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + + Tokens.add(index - 1, result); + tokenTypes.add(index - 1, result.type); + } catch (Exception ex) { + Type second = getToken(Tokens, index + 1); + value = -second.number; + Type result = new Type(value); + + Tokens.remove(index); + Tokens.remove(index); + tokenTypes.remove(index); + tokenTypes.remove(index); + + Tokens.add(index, result); + tokenTypes.add(index, result.type); + } + continue; + } + + // --- addition + index = tokenTypes.indexOf(TYPE.OPERATION_ADD); + if (index != -1) { + Type first; + try { + first = getToken(Tokens, index - 1); + Type second = getToken(Tokens, index + 1); + value = first.number + second.number; + Type result = new Type(value); + + Tokens.remove(index - 1); + Tokens.remove(index - 1); + Tokens.remove(index - 1); + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + + Tokens.add(index - 1, result); + tokenTypes.add(index - 1, result.type); + } catch (Exception ex) { + Type second = getToken(Tokens, index + 1); + value = second.number; + Type result = new Type(value); + + Tokens.remove(index); + Tokens.remove(index); + tokenTypes.remove(index); + tokenTypes.remove(index); + + Tokens.add(index, result); + tokenTypes.add(index, result.type); + } + continue; + } + + throw new Exception("INTERNAL ERROR: we should not be here"); + } + return Tokens.get(0).number; + } + } + + return value; + } + + Type getToken(List Tokens, int index) throws Exception { + if (index < 0) { + throw new Exception("No first argument in expression"); + } else if (index >= Tokens.size()) { + throw new Exception("No second argument in expression"); + } + return Tokens.get(index); + } + + public boolean isCaseSensitive() { + return caseSensitive; + } + + public void setCaseSensitive(boolean caseSensitive) { + this.caseSensitive = caseSensitive; + } + + public static void main(String[] args) { + MathExpressionParser mathexpressionparser = new MathExpressionParser(); + mathexpressionparser.setInDegrees(true); + try { + String express = null; + mathexpressionparser.addVariable("var1", 10.0); + mathexpressionparser.addVariable("var2", 20.0); + express = "var1+var2"; + System.out.println("Evaluating: " + express + " : " + mathexpressionparser.resolveExpression(express)); + + mathexpressionparser.caseSensitive = true; + mathexpressionparser.addLine("sqr = sqrt(4*5)"); + mathexpressionparser.addLine("ab = 1"); + mathexpressionparser.addLine("func(x,y,z) = x*ab+y**2-y*z"); + mathexpressionparser.addLine("x = 5"); + mathexpressionparser.addLine("y=func((3+4)*(x-2),4,5*6)+sqrt(4*5)"); + + mathexpressionparser.addLine("RCH = 1.085"); + mathexpressionparser.addLine("XCH = sqrt(3)*(RCH/3)"); + + express = "XCH"; + System.out.println("Evaluating: " + express + " : " + mathexpressionparser.resolveExpression(express)); + express = "-XCH"; + System.out.println("Evaluating: " + express + " : " + mathexpressionparser.resolveExpression(express)); + + express = "0+1"; + System.out.println("Evaluating: " + express + " : " + mathexpressionparser.resolveExpression(express)); + express = "sqr+1"; + System.out.println("Evaluating: " + express + " : " + mathexpressionparser.resolveExpression(express)); + express = "sin(10.0) + SIN(20.0)"; + System.out.println("Evaluating: " + express + " : " + mathexpressionparser.resolveExpression(express)); + // -- + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + String line; + while(!(line=in.readLine()).equals("quit")) { + if (line.matches("\\s*\\w+\\s*=\\s*.+")) { + mathexpressionparser.addLine(line); + } else { + System.out.println(mathexpressionparser.resolveExpression(line)); + } + } + } catch (Exception ex) { + System.err.println(ex.getMessage()); + } + System.exit(0); + } + + private class OpStack + extends ArrayList { + + void push(Object token) { + this.add(0, token); + } + + Object pop() { + if (this.size() == 0) { + return null; + } + Object obj = this.get(0); + this.remove(0); + return obj; + } + + } + + private class Type { + + TYPE type; + OPERATION operation; + PARANTHESIS paranthesis; + String name; + double number; + boolean is_number = false; + + public Type(double value) { + this.name = String.valueOf(value); + this.type = TYPE.VARIABLE; + number = value; + is_number = true; + } + + public Type(String name, TYPE type) { + this.name = name; + this.type = type; + } + + public Type(OPERATION op, TYPE type) { + operation = op; + this.type = type; + } + + public Type(PARANTHESIS par, TYPE type) { + paranthesis = par; + this.type = type; + } + + public Type(TYPE type) throws Exception { + if (type != TYPE.COMMA) { + throw new Exception("INTERNAL ERROR: Not comma"); + } + this.type = type; + } + + public void setValue(double value) { + number = value; + is_number = true; + } + + public boolean isNumber() { + try { + number = Double.parseDouble(name); + is_number = true; + } catch (Exception ex) { + return false; + } + return true; + } + + } + + private class Function { + + String Name; + String internalName; + Map locParams = new HashMap(); + List localParams = new ArrayList(); + List functionTokens; + List functionTokenTypes; + + public Function(String definition) throws Exception { + defineFunction(definition); + } + + void defineFunction(String definition) throws Exception { + List Tokens = new ArrayList(); + List tokenTypes = new ArrayList(); + resolveTokens(definition, Tokens, tokenTypes); + + if (tokenTypes.size() < 3) { + throw new Exception("Minimal Function definition should be: function_name()"); + } + + if (tokenTypes.size() % 2 == 1) { + throw new Exception("Wrong Function definition"); + } + + if (tokenTypes.get(0) != TYPE.FUNCTION) { + throw new Exception("Function definition should start from function_name("); + } + + if (tokenTypes.get(1) != TYPE.LEFT_PARANTHESIS) { + throw new Exception("Left paranthesis should follow function name"); + } + + Name = Tokens.get(0).name; + + int index = 2; + while (tokenTypes.get(index) != TYPE.RIGHT_PARANTHESIS) { + if (index >= tokenTypes.size() - 1) { + break; + } + if (tokenTypes.get(index) != TYPE.VARIABLE) { + throw new Exception("Expecting parameter in Function definition, got " + tokenTypes.get(index).toString()); + } + + if (tokenTypes.get(index + 1) != TYPE.COMMA && tokenTypes.get(index + 1) != TYPE.RIGHT_PARANTHESIS) { + throw new Exception("Expecting comma or right paranthesis in Function definition, got " + + tokenTypes.get(index).toString()); + } + + if (locParams.containsKey(Tokens.get(index).name)) { + throw new Exception("Duplicate definition of parameter " + Tokens.get(index).name); + } + + if (Tokens.get(index).isNumber()) { + throw new Exception("Parameter should be symbolic variable. Got " + Tokens.get(index).name); + } + + locParams.put(Tokens.get(index).name, null); + localParams.add(Tokens.get(index).name); + + index += 2; + if (index >= tokenTypes.size() - 1) { + break; + } + + } + + internalName = Name + "_" + String.valueOf(localParams.size()); + logger.info("Fun name: " + Name + " Internal name: " + internalName + " N params: " + localParams.size()); + for (int i = 0; i < localParams.size(); i++) { + logger.info((i + 1) + " : " + localParams.get(i).toString()); + + } + } + + void setFunctionBody(String body) throws Exception { + List Tokens = new ArrayList(); + List tokenTypes = new ArrayList(); + resolveTokens(body, Tokens, tokenTypes); + if (Tokens.size() < 1) { + throw new Exception("Empty function body"); + } + for (int i = 0; i < Tokens.size(); i++) { + if (tokenTypes.get(i) == TYPE.VARIABLE && locParams.containsKey(Tokens.get(i).name)) { + Tokens.get(i).type = TYPE.LOCAL_VARIABLE; + tokenTypes.set(i, TYPE.LOCAL_VARIABLE); + } else if (tokenTypes.get(i) == TYPE.VARIABLE) { + if (!IDs.containsKey(Tokens.get(i).name) && !Tokens.get(i).isNumber()) { + throw new Exception("Function body: " + body + "\nVariable " + Tokens.get(i).name + " is not defined"); + } else if (IDs.containsKey(Tokens.get(i).name)) { + Type type = (Type) IDs.get(Tokens.get(i).name); + Tokens.set(i, type); + } + } + } + + functionTokens = Tokens; + functionTokenTypes = tokenTypes; + } + + public double getValue(List arguments) throws Exception { + double value = 0; + for (int i = 0; i < functionTokens.size(); i++) { + if (functionTokenTypes.get(i) == TYPE.LOCAL_VARIABLE) { + int index = localParams.indexOf(functionTokens.get(i).name); + if (index == -1) { + throw new Exception("Internal Error: index == -1"); + } + functionTokens.get(i).number = arguments.get(index); + } + } + + List Tokens = new ArrayList(functionTokens); + List tokenTypes = new ArrayList(functionTokenTypes); + + value = evaluateExpression(Tokens, tokenTypes); + return value; + } + } + + private class PredefinedFun { + + PREDEFINED_FUNCTION Type; + + public PredefinedFun(PREDEFINED_FUNCTION type) { + Type = type; + } + + public double getValue(List parameters) throws Exception { + double value; + switch (Type) { + case SQRT: + case sqrt: + if (parameters.size() != 1) { + throw new Exception("Predefined function " + Type.toString() + + " should have only one parameter"); + } + value = parameters.get(0); + return Math.sqrt(value); + + case TAN: + case tan: + if (parameters.size() != 1) { + throw new Exception("Predefined function " + PREDEFINED_FUNCTION.TAN.toString() + + " should have only one parameter"); + } + value = parameters.get(0); + return Math.tan(value); + + case ATAN: + case atan: + if (parameters.size() != 1) { + throw new Exception("Predefined function " + PREDEFINED_FUNCTION.ATAN.toString() + + " should have only one parameter"); + } + value = parameters.get(0); + return Math.atan(value); + + case EXP: + case exp: + if (parameters.size() != 1) { + throw new Exception("Predefined function " + PREDEFINED_FUNCTION.EXP.toString() + + " should have only one parameter"); + } + value = parameters.get(0); + return Math.exp(value); + + case ASIN: + case asin: + if (parameters.size() != 1) { + throw new Exception("Predefined function " + PREDEFINED_FUNCTION.ASIN.toString() + + " should have only one parameter"); + } + value = parameters.get(0); + return Math.asin(value); + + case ACOS: + case acos: + if (parameters.size() != 1) { + throw new Exception("Predefined function " + PREDEFINED_FUNCTION.ACOS.toString() + + " should have only one parameter"); + } + value = parameters.get(0); + return Math.acos(value); + + case LOG: + case log: + if (parameters.size() != 1) { + throw new Exception("Predefined function " + PREDEFINED_FUNCTION.LOG.toString() + + " should have only one parameter"); + } + value = parameters.get(0); + return Math.log(value); + + case SIN: + case sin: + if (parameters.size() != 1) { + throw new Exception("Predefined function " + PREDEFINED_FUNCTION.SIN.toString() + + " should have only one parameter"); + } + value = parameters.get(0); + + if (inRadians) { + return Math.sin(value); + } else { + return Math.sin(value * DEGREES_TO_RADIANS); + } + case COS: + case cos: + if (parameters.size() != 1) { + throw new Exception("Predefined function " + PREDEFINED_FUNCTION.COS.toString() + + " should have only one parameter"); + } + value = parameters.get(0); + + if (inRadians) { + return Math.cos(value); + } else { + return Math.cos(value * DEGREES_TO_RADIANS); + } + + } + throw new Exception("INTERNAL ERROR: Unknown predefined function"); + + } + + public double getValue(double value) throws Exception { + switch (Type) { + case SQRT: + return Math.sqrt(value); + case TAN: + return Math.tan(value); + case ATAN: + return Math.atan(value); + case EXP: + return Math.exp(value); + case ASIN: + return Math.asin(value); + case ACOS: + return Math.acos(value); + case LOG: + return Math.log(value); + + case SIN: + if (inRadians) { + return Math.sin(value); + } else { + return Math.sin(value * DEGREES_TO_RADIANS); + } + case COS: + if (inRadians) { + return Math.cos(value); + } else { + return Math.cos(value * DEGREES_TO_RADIANS); + } + + } + throw new Exception("INTERNAL ERROR: Unknown predefined function"); + } + } + +} diff --git a/src/main/java/cct/math/MinimizedFunctionInterface.java b/src/main/java/cct/math/MinimizedFunctionInterface.java new file mode 100644 index 0000000..2b2bc1d --- /dev/null +++ b/src/main/java/cct/math/MinimizedFunctionInterface.java @@ -0,0 +1,60 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.math; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface MinimizedFunctionInterface { + double function(int n, double[] X, double[] Grads); + + float function(int n, float[] X, float[] Grads); + + double function(int n, double[] X); + + float function(int n, float[] X); +} diff --git a/src/main/java/cct/math/Minimizer.java b/src/main/java/cct/math/Minimizer.java new file mode 100644 index 0000000..797c9dc --- /dev/null +++ b/src/main/java/cct/math/Minimizer.java @@ -0,0 +1,1088 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.math; + +/** + *

Title:

+ * + *

Description:

+ * MINIMIZATION OF UNCONSTRAINED MULTIVARIATE FUNCTIONS + * BY D.F. SHANNO AND K.H. PHUA + * ACM TRANSACTIONS ON MATHEMATICAL SOFTWARE 6 (DECEMBER 1980), 618-622 + * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Minimizer { + + double D0 = 0.01, D1 = 0.05; // convergence for func & RMS grads + double EPS = 0.001; + double ACC = 10.e-20; + boolean fun_and_grad = true; + int ninterp = 100; // maximum number of linear interpolations + int MXFUN = 10000; + int IOUT = 1; + int NMETH = 0; + int STEALTH = 0; // Overwrites IOUT... + + // --- Result of optimization + + double F; // THE LOWEST VALUE OF THE OBJECT FUNCTION OBTAINED + int IFUN; // UPON EXITING FROM CONMIN,IFUN CONTAINS THE NUMBER OF TIMES + // THE FUNCTION AND GRADIENT HAVE BEEN EVALUATED. + int ITER; // UPON EXITING FROM CONMIN,ITER CONTAINS THE + // TOTAL NUMBER OF SEARCH DIRECTIONS CALCULATED + // TO OBTAIN THE CURRENT ESTIMATE TO THE MINIZER. + + + public Minimizer() { + } + + /* + public int minimizeFun(double[] X, double DMAX, + MinimizedFunctionInterface CALCFG) throws Exception { +// +// PURPOSE: SUBROUTINE CONMIN MINIMIZES AN UNCONSTRAINED NONLINEAR +// SCALAR VALUED FUNCTION OF A VECTOR VARIABLE X +// EITHER BY THE BFGS VARIABLE METRIC ALGORITHM OR BY A +// BEALE RESTARTED CONJUGATE GRADIENT ALGORITHM. +// +//USAGE: CONMIN(N,X,F,G,IFUN,ITER,EPS,NFLAG,MXFUN,W, +// IOUT,MDIM,IDEV,ACC,NMETH) +// +//PARAMETERS: N THE NUMBER OF VARIABLES IN THE FUNCTION TO +// BE MINIMIZED. +// X THE VECTOR CONTAINING THE CURRENT ESTIMATE TO +// THE MINIMIZER. ON ENTRY TO CONMIN,X MUST CONTAIN +// AN INITIAL ESTIMATE SUPPLIED BY THE USER. +// ON EXITING,X WILL HOLD THE BEST ESTIMATE TO THE +// MINIMIZER OBTAINED BY CONMIN. X MUST BE DOUBLE +// PRECISIONED AND DIMENSIONED N. +// F ON EXITING FROM CONMIN,F WILL CONTAIN THE LOWEST +// VALUE OF THE OBJECT FUNCTION OBTAINED. +// F IS DOUBLE PRECISIONED. +//* G ON EXITING FROM CONMIN,G WILL CONTAIN THE +//* ELEMENTS OF THE GRADIENT OF F EVALUATED AT THE +//* POINT CONTAINED IN X. G MUST BE DOUBLE +//* PRECISIONED AND DIMENSIONED N. +// IFUN UPON EXITING FROM CONMIN,IFUN CONTAINS THE +// NUMBER OF TIMES THE FUNCTION AND GRADIENT +// HAVE BEEN EVALUATED. +// ITER UPON EXITING FROM CONMIN,ITER CONTAINS THE +// TOTAL NUMBER OF SEARCH DIRECTIONS CALCULATED +// TO OBTAIN THE CURRENT ESTIMATE TO THE MINIZER. +// EPS EPS IS THE USER SUPPLIED CONVERGENCE PARAMETER. +// CONVERGENCE OCCURS WHEN THE NORM OF THE GRADIENT +// IS LESS THAN OR EQUAL TO EPS TIMES THE MAXIMUM +// OF ONE AND THE NORM OF THE VECTOR X. EPS +// MUST BE DOUBLE PRECISIONED. +// NFLAG UPON EXITING FROM CONMIN,NFLAG STATES WHICH +// CONDITION CAUSED THE EXIT. +// IF NFLAG=0, THE ALGORITHM HAS CONVERGED. +// IF NFLAG=1, THE MAXIMUM NUMBER OF FUNCTION +// EVALUATIONS HAVE BEEN USED. +// IF NFLAG=2, THE LINEAR SEARCH HAS FAILED TO +// IMPROVE THE FUNCTION VALUE. THIS IS THE +// USUAL EXIT IF EITHER THE FUNCTION OR THE +// GRADIENT IS INCORRECTLY CODED. +// IF NFLAG=3, THE SEARCH VECTOR WAS NOT +// A DESCENT DIRECTION. THIS CAN ONLY BE CAUSED +// BY ROUNDOFF,AND MAY SUGGEST THAT THE +// CONVERGENCE CRITERION IS TOO STRICT. +// MXFUN MXFUN IS THE USER SUPPLIED MAXIMUM NUMBER OF +// FUNCTION AND GRADIENT CALLS THAT CONMIN WILL +// BE ALLOWED TO MAKE. +//* W W IS A VECTOR OF WORKING STORAGE.IF NMETH=0, +//* W MUST BE DIMENSIONED 5*N+2. IF NMETH=1, +//* W MUST BE DIMENSIONED N*(N+7)/2. IN BOTH CASES, +//* W MUST BE DOUBLE PRECISIONED. +// IOUT IOUT IS A USER SUPPLIED OUTPUT PARAMETER. +// IF IOUT = 0, THERE IS NO PRINTED OUTPUT FROM +// CONMIN. IF IOUT > 0,THE VALUE OF F AND THE +// NORM OF THE GRADIENT SQUARED,AS WELL AS ITER +// AND IFUN,ARE WRITTEN EVERY IOUT ITERATIONS. +//* MDIM MDIM IS THE USER SUPPLIED DIMENSION OF THE +//* VECTOR W. IF NMETH=0,MDIM=5*N+2. IF NMETH=1, +//* MDIM=N*(N+7)/2. +//* IDEV IDEV IS THE USER SUPPLIED NUMBER OF THE OUTPUT +//* DEVICE ON WHICH OUTPUT IS TO BE WRITTEN WHEN +//* IOUT>0. +// ACC ACC IS A USER SUPPLIED ESTIMATE OF MACHINE +// ACCURACY. A LINEAR SEARCH IS UNSUCCESSFULLY +// TERMINATED WHEN THE NORM OF THE STEP SIZE +// BECOMES SMALLER THAN ACC. IN PRACTICE, +// ACC=10.D-20 HAS PROVED SATISFACTORY. ACC IS +// DOUBLE PRECISIONED. +// NMETH NMETH IS THE USER SUPPLIED VARIABLE WHICH +// CHOOSES THE METHOD OF OPTIMIZATION. IF +// NMETH=0,A CONJUGATE GRADIENT METHOD IS +// USED. IF NMETH=1, THE BFGS METHOD IS USED. +// +//REMARKS: IN ADDITION TO THE SPECIFIED VALUES IN THE ABOVE +// ARGUMENT LIST, THE USER MUST SUPPLY A SUBROUTINE +// CALCFG WHICH CALCULATES THE FUNCTION AND GRADIENT AT +// X AND PLACES THEM IN F AND G(1),...,G(N) RESPECTIVELY. +// THE SUBROUTINE MUST HAVE THE FORM: +// SUBROUTINE CALCFG(N,X,F,G) +// DOUBLE PRECISION X(N),G(N),F +// +// AN EXAMPLE SUBROUTINE FOR THE ROSENBROCK FUNCTION IS: +// +// SUBROUTINE CALCFG(N,X,F,G) +// DOUBLE PRECISION X(N),G(N),F,T1,T2 +// T1=X(2)-X(1)*X(1) +// T2=1.0-X(1) +// F=100.0*T1*T1+T2*T2 +// G(1)=-400.0*T1*X(1)-2.0*T2 +// G(2)=200.0*T1 +// RETURN +// END +// + + int NFLAG, I, J, IJ, II, NCONS, NCONS1, NCONS2, NRST, IOUTK; + int NRDPI, NRYPI, NGPI, NRD, NCALLS, NX, NG, NRY, NXPI, NGPJ; + +// --- Error check... + + if (X == null || X.length < 1) { + throw new Exception(this.getClass().getCanonicalName() + + " : no varibles to optimize: X == null || X.length < 1"); + } + + if (CALCFG == null) { + throw new Exception(this.getClass().getCanonicalName() + + " : no function was passed to the minimizer"); + } + + int N = X.length; + + double[] G = new double[N]; + + // W IS A VECTOR OF WORKING STORAGE.IF NMETH=0, + // W MUST BE DIMENSIONED 5*N+2. IF NMETH=1 + // W MUST BE DIMENSIONED N*(N+7)/2. IN BOTH CASES, + // W MUST BE DOUBLE PRECISIONED. + + double[] W; + + if (NMETH == 0) { + W = new double[5 * N + 2]; + } + else if (NMETH == 1) { + W = new double[N * (N + 7) / 2]; + } + + double FP, FMIN, ALPHA = 1.0, AT, AP, GSQ, DG = 1.0, DG1; + // BTW (Vlad) DG was not set in original version... May cause error... + // BTW (Vlad) ALPHA was not set in original version... May cause error... + double DP, STEP, DAL, U1, U2, U3, U4; + double XSQ, RTST; + double gmax, grms; + int RSW; + + if (!STEALTH) { + if (IOUT != 0) { + logger.info( + "\n\n\n *****************************************************"); + logger.info( + " * *"); + if (NMETH == 0) { + logger.info( + " * A BEALE RESTARTED CONJUGATE GRADIENT ALGORITHM *"); + } + else { + logger.info( + " * BFGS VARIABLE METRIC ALGORITHM *"); + } + logger.info( + " * *"); + logger.info( + " *****************************************************\n\n"); + logger.info( + "NUMBER OF VARIABLES: %d GRMS CONVERGENCE: %10.6lf\n", N, + D1); + } + } // end of if ( !STEALTH ) + +// +// INITIALIZE ITER,IFUN,NFLAG,AND IOUTK,WHICH COUNTS OUTPUT ITERATIONS. +// + ITER = 0; + IFUN = 0; + IOUTK = 0; + NFLAG = 0; +// +// SET PARAMETERS TO EXTRACT VECTORS FROM W. +// W(I) HOLDS THE SEARCH VECTOR,W(NX+I) HOLDS THE BEST CURRENT +// ESTIMATE TO THE MINIMIZER,AND W(NG+I) HOLDS THE GRADIENT +// AT THE BEST CURRENT ESTIMATE. +// + NX = N; + NG = NX + N; +// +// TEST WHICH METHOD IS BEING USED. +// IF NMETH=0, W(NRY+I) HOLDS THE RESTART Y VECTOR AND +// W(NRD+I) HOLDS THE RESTART SEARCH VECTOR. +// + if (NMETH == 1) { + // + // IF NMETH=1,W(NCONS+I) HOLDS THE APPROXIMATE INVERSE HESSIAN. + // + NCONS = 3 * N; + //goto L10; + } + else { + NRY = NG + N; + NRD = NRY + N; + NCONS = 5 * N; + NCONS1 = NCONS; + NCONS2 = NCONS + 1; + //goto L20; + } + +// +// CALCULATETHE FUNCTION AND GRADIENT AT THE INITIAL +// POINT AND INITIALIZE NRST,WHICH IS USED TO DETERMINE +// WHETHER A BEALE RESTART IS BEING DONE. NRST=N MEANS THAT THIS +// ITERATION IS A RESTART ITERATION. INITIALIZE RSW, WHICH INDICATES +// THAT THE CURRENT SEARCH DIRECTION IS A GRADIENT DIRECTION. +// + + L20:F = CALCFG(X, G); + ++IFUN; + NRST = N; + RSW = true; +// +// CALCULATE THE INITIAL SEARCH DIRECTION , THE NORM OF X SQUARED, +// AND THE NORM OF G SQUARED. DG1 IS THE CURRENT DIRECTIONAL +// DERIVATIVE,WHILE XSQ AND GSQ ARE THE SQUARED NORMS. +// + DG1 = 0.0; + XSQ = 0.0; + gmax = Math.abs(G[0]); + for (I = 0; I < N; I++) { + W[I] = -G[I]; + XSQ += X[I] * X[I]; + DG1 -= G[I] * G[I]; + if (gmax < Math.abs(G[I])) { + gmax = Math.abs(G[I]); + } + } + GSQ = -DG1; + grms = Math.sqrt(GSQ / (double) N); +// +// Check for gradients +// + if (grms < D1) { + if (!STEALTH) { + System.out.print( + "\n\n ***** RMS GRADIENTS AT INITIAL POINT SATISFIES "); + System.out.print("CONVERGENCE CRITERIUM\n"); + PrintConMinRes(F, IFUN, grms, gmax, NFLAG); + } + return NFLAG; + } + else if (IOUT != 0) { + if (!STEALTH) { + String.format( + "\n\n ***** RMS GRADIENTS AT INITIAL POINT: %8.4lf %lf", + grms, GSQ); + String.format("\nMAXIMUM GRADIENT (ABSOLUTE VALUE): %8.3lf\n", gmax); + + } + } +// +// TEST IF THE INITIAL POINT IS THE MINIMIZER. | VLAD - SKIP THIS CHECK +// +// if ( GSQ <= EPS*EPS*MAX(1.0,XSQ) ) { +// cout<<"\n\n ***** THE ALGORITHM HAS CONVERGED *****\n\n RMS GRADIENT : " +// < ACC) { + //cout<<"\n goto L90"; + goto L90; + } + + // + // TEST IF DIRECTION IS A GRADIENT DIRECTION. + // + if (RSW == false) { + //cout<<"\n goto L20"; + goto L20; + } + + if (!STEALTH) { + System.out.print( + "\n\n ---- THE LINEAR SEARCH HAS FAILED TO IMPROVE THE FUNCTION VALUE"); + System.out.print( + "\n THIS IS THE USUAL EXIT IF EITHER THE FUNCTION OR "); + System.out.print("\n THE GRADIENT IS INCORRECTLY CODED"); + } + + NFLAG = 2; + grms = Math.sqrt(GSQ / (double) N); + if (!STEALTH) { + System.out.print("\n\n CURRENT RMS GRADIENT : %lf", grms); + PrintConMinRes(F, IFUN, grms, gmax, NFLAG); + } + return NFLAG; + // + // CALCULATE THE TRIAL POINT. + // + + double step; + L90:for (I = 0; I < N; I++) { + NXPI = NX + I; + step = ALPHA * W[I]; + if (Math.abs(step) > DMAX[I]) { + step = SIGN(DMAX[I], step); + } + X[I] = W[NXPI] + step; + } + // + // EVALUATE THE FUNCTION AT THE TRIAL POINT. + // + F = CALCFG(X, G); + // + // TEST IF THE MAXIMUM NUMBER OF FUNCTION CALLS HAVE BEEN USED. + // + ++IFUN; + if (IFUN > MXFUN) { + NFLAG = 1; + + gmax = Math.abs(G[0]); + for (I = 0; I < N; I++) { + GSQ += G[I] * G[I]; + if (gmax < Math.abs(G[I])) { + gmax = Math.abs(G[I]); + } + } + grms = Math.sqrt(GSQ / (double) N); + if (!STEALTH) { + PrintConMinRes(F, IFUN, grms, gmax, NFLAG); + } + return NFLAG; + } + // + // COMPUTE THE DERIVATIVE OF F AT ALPHA. + // + DAL = 0.0; + for (I = 0; I < N; I++) { + DAL += G[I] * W[I]; + } + // + // TEST WHETHER THE NEW POINT HAS A NEGATIVE SLOPE BUT A HIGHER + // FUNCTION VALUE THAN ALPHA=0. IF THIS IS THE CASE,THE SEARCH + // HAS PASSED THROUGH A LOCAL MAX AND IS HEADING FOR A DISTANT LOCAL + // MINIMUM. + // + if (F > FMIN && DAL < 0.0) { + //goto L160; + // + // A RELATIVE MAX HAS BEEN PASSED.REDUCE ALPHA AND RESTART THE SEARCH. + // + + //L160:ALPHA /= 3.0; + ALPHA /= 3.0; + AP = 0.0; + FP = FMIN; + DP = DG; + goto L80; + } + // + // IF NOT, TEST WHETHER THE STEPLENGTH CRITERIA HAVE BEEN MET. + // + if (F > (FMIN + (double) .0001 * ALPHA * DG) || + Math.abs(DAL / DG) > 0.9) { + goto L130; + } + + if (F < FMIN) { + goto L170; // --- Vlad + } + + // + // IF THEY HAVE BEEN MET, TEST IF TWO POINTS HAVE BEEN TRIED + // IF NMETH=0 AND IF THE TRUE LINE MINIMUM HAS NOT BEEN FOUND. + // + if ( (IFUN - NCALLS) <= 1 && Math.abs(DAL / DG) > EPS && + NMETH == 0) { + goto L130; + } + goto L170; + // + // A NEW POINT MUST BE TRIED. USE CUBIC INTERPOLATION TO FIND + // THE TRIAL POINT AT. + // + L130:U1 = DP + DAL - 3.0 * (FP - F) / (AP - ALPHA); + U2 = U1 * U1 - DP * DAL; + if (U2 < 0.0) { + U2 = 0.0; + } + U2 = Math.sqrt(U2); + AT = ALPHA - + (ALPHA - AP) * (DAL + U2 - U1) / (DAL - DP + 2.0 * U2); + // + // TEST WHETHER THE LINE MINIMUM HAS BEEN BRACKETED. + // + if ( (DAL / DP) > 0.0) { + goto L140; + } + // + // THE MINIMUM HAS BEEN BRACKETED. TEST WHETHER THE TRIAL POINT LIES + // SUFFICIENTLY WITHIN THE BRACKETED INTERVAL. + // IF IT DOES NOT, CHOOSE AT AS THE MIDPOINT OF THE INTERVAL. + // + if (AT < (1.01 * Math.min(ALPHA, AP)) || + AT > (0.99 * Math.max(ALPHA, AP))) { + AT = (ALPHA + AP) / 2.0; + } + goto L150; + // + // THE MINIMUM HAS NOT BEEN BRACKETED. TEST IF BOTH POINTS ARE + // GREATER THAN THE MINIMUM AND THE TRIAL POINT IS SUFFICIENTLY + // SMALLER THAN EITHER. + // + + L140:if (DAL > 0.0 && 0.0 < AT && AT < (0.99 * Math.min(AP, ALPHA))) { + goto L150; + } + + // + // TEST IF BOTH POINTS ARE LESS THAN THE MINIMUM AND THE TRIAL POINT + // IS SUFFICIENTLY LARGE. + // + + if (DAL <= 0.0 && AT > ( (double) 1.01 * Math.max(AP, ALPHA))) { + goto L150; + } + + // + // IF THE TRIAL POINT IS TOO SMALL,DOUBLE THE LARGEST PRIOR POINT. + // + + if (DAL <= 0.0) { + AT = (double) 2.0 * Math.max(AP, ALPHA); + } + + // + // IF THE TRIAL POINT IS TOO LARGE, HALVE THE SMALLEST PRIOR POINT. + // + + if (DAL > 0.0) { + AT = Math.min(AP, ALPHA) / 2.0; + } + + // + // SET AP=ALPHA, ALPHA=AT,AND CONTINUE SEARCH. + // + + L150:AP = ALPHA; + FP = F; + DP = DAL; + ALPHA = AT; + goto L80; + + // + // A RELATIVE MAX HAS BEEN PASSED.REDUCE ALPHA AND RESTART THE SEARCH. + // + + //L160:ALPHA /= 3.0; + //AP = 0.0; + //FP = FMIN; + //DP = DG; + //goto L80; + + // + // THE LINE SEARCH HAS CONVERGED. TEST FOR CONVERGENCE OF THE ALGORITHM. + // + + L170:GSQ = 0.0; + XSQ = 0.0; + gmax = Math.abs(G[0]); + for (I = 0; I < N; I++) { + GSQ += G[I] * G[I]; + XSQ += X[I] * X[I]; + if (gmax < Math.abs(G[I])) { + gmax = Math.abs(G[I]); + } + } + grms = Math.sqrt(GSQ / (double) N); + + if (Math.abs(F - FMIN) < D0 && grms < D1) { + if (!STEALTH) { + System.out.print( + "\n\n ************************************************"); + System.out.print( + "\n *** TESTS ON F AND G WERE SATISFIED ***"); + System.out.print( + "\n ************************************************"); + PrintConMinRes(F, IFUN, grms, gmax, NFLAG); + } + return NFLAG; + } + + if (grms < D1) { + if (!STEALTH) { + System.out.print( + "\n\n ************************************************"); + System.out.print( + "\n *** TESTS ON G WERE SATISFIED ***"); + System.out.print( + "\n ************************************************"); + PrintConMinRes(F, IFUN, grms, gmax, NFLAG); + } + return NFLAG; + } + + if (GSQ <= EPS * EPS * Math.max(1.0, XSQ)) { + if (!STEALTH) { + System.out.print("\n\n ***** THE ALGORITHM HAS CONVERGED *****"); + PrintConMinRes(F, IFUN, grms, gmax, NFLAG); + } + return NFLAG; + } + + // + // SEARCH CONTINUES. SET W(I)=ALPHA*W(I),THE FULL STEP VECTOR. + // + + for (I = 0; I < N; I++) { + W[I] *= ALPHA; + } + + // + // COMPUTE THE NEW SEARCH VECTOR. FIRST TEST WHETHER A + // CONJUGATE GRADIENT OR A VARIABLE METRIC VECTOR IS USED. + // + if (NMETH == 1) { + goto L330; + } + + // + // CONJUGATE GRADIENT UPDATE SECTION. + // TEST IF A POWELL RESTART IS INDICATED. + // + RTST = 0.0; + for (I = 0; I < N; I++) { + NGPI = NG + I; + RTST += G[I] * W[NGPI]; + } + if (Math.abs(RTST / GSQ) > 0.2) { + NRST = N; + } + + // + // IF A RESTART IS INDICATED, SAVE THE CURRENT D AND Y + // AS THE BEALE RESTART VECTORS AND SAVE D'Y AND Y'Y + // IN W(NCONS+1) AND W(NCONS+2). + // + + if (NRST != N) { + goto L220; + } + // W(NCONS+1)=0. + // W(NCONS+2)=0. + W[NCONS] = 0.0; + W[NCONS + 1] = 0.0; + for (I = 0; I < N; I++) { + NRDPI = NRD + I; + NRYPI = NRY + I; + NGPI = NG + I; + W[NRYPI] = G[I] - W[NGPI]; + W[NRDPI] = W[I]; + W[NCONS1] += W[NRYPI] * W[NRYPI]; + W[NCONS2] += W[I] * W[NRYPI]; + } + + // + // CALCULATE THE RESTART HESSIAN TIMES THE CURRENT GRADIENT. + // + + L220:U1 = 0.0; + U2 = 0.0; + for (I = 0; I < N; I++) { + NRDPI = NRD + I; + NRYPI = NRY + I; + U1 -= W[NRDPI] * G[I] / W[NCONS1]; + U2 += W[NRDPI] * G[I] * 2. / W[NCONS2] - + W[NRYPI] * G[I] / W[NCONS1]; + } + + U3 = W[NCONS2] / W[NCONS1]; + for (I = 0; I < N; I++) { + NXPI = NX + I; + NRDPI = NRD + I; + NRYPI = NRY + I; + W[NXPI] = -U3 * G[I] - U1 * W[NRYPI] - U2 * W[NRDPI]; + } + // + // IF THIS IS A RESTART ITERATION,W(NX+I) CONTAINS THE NEW SEARCH + // VECTOR. + // + + if (NRST == N) { + goto L300; + } + + // + // NOT A RESTART ITERATION. CALCULATE THE RESTART HESSIAN + // TIMES THE CURRENT Y. + // + + U1 = 0.0; + U2 = 0.0; + U3 = 0.0; + U4 = 0.0; + for (I = 0; I < N; I++) { + NGPI = NG + I; + NRDPI = NRD + I; + NRYPI = NRY + I; + U1 -= (G[I] - W[NGPI]) * W[NRDPI] / W[NCONS1]; + U2 -= (G[I] - W[NGPI]) * W[NRYPI] / W[NCONS1] - + 2.0 * W[NRDPI] * (G[I] - W[NGPI]) / W[NCONS2]; + U3 += W[I] * (G[I] - W[NGPI]); + } + + STEP = 0.0; + for (I = 0; I < N; I++) { + NGPI = NG + I; + NRDPI = NRD + I; + NRYPI = NRY + I; + STEP = (W[NCONS2] / W[NCONS1]) * (G[I] - W[NGPI]) + + U1 * W[NRYPI] + U2 * W[NRDPI]; + U4 += STEP * (G[I] - W[NGPI]); + W[NGPI] = STEP; + } + // + // CALCULATE THE DOUBLY UPDATED HESSIAN TIMES THE CURRENT + // GRADIENT TO OBTAIN THE SEARCH VECTOR. + // + U1 = 0.0; + U2 = 0.0; + for (I = 0; I < N; I++) { + U1 -= W[I] * G[I] / U3; + NGPI = NG + I; + U2 += (1.0 + U4 / U3) * W[I] * G[I] / U3 - W[NGPI] * G[I] / U3; + } + for (I = 0; I < N; I++) { + NGPI = NG + I; + NXPI = NX + I; + W[NXPI] = W[NXPI] - U1 * W[NGPI] - U2 * W[I]; + } + // + // CALCULATE THE DERIVATIVE ALONG THE NEW SEARCH VECTOR. + // + + L300:DG1 = 0.0; + for (I = 0; I < N; I++) { + NXPI = NX + I; + W[I] = W[NXPI]; + DG1 += W[I] * G[I]; + } + // + // IF THE NEW DIRECTION IS NOT A DESCENT DIRECTION,STOP. + // + + if (DG1 > 0.0) { + //goto L320; + //L320: + // printf("\n\n ----- THE SEARCH VECTOR WAS NOT A DESCENT DIRECTION"); + // printf("\n THIS CAN ONLY BE CAUSED BY ROUNDOFF, AND MAY SUGGEST"); + // printf("\n THAT THE CONVERGENCE CRITERION IS TOO STRICT"); + // printf("\n\n CURRENT RMS GRADIENT : %lf",sqrt(GSQ/(double)N)); + NFLAG = 3; + gmax = Math.abs(G[0]); + for (I = 0; I < N; I++) { + GSQ += G[I] * G[I]; + if (gmax < Math.abs(G[I])) { + gmax = Math.abs(G[I]); + } + } + grms = Math.sqrt(GSQ / (double) N); + if (!STEALTH) { + PrintConMinRes(F, IFUN, grms, gmax, NFLAG); + } + return NFLAG; + } + + // + // UPDATE NRST TO ASSURE AT LEAST ONE RESTART EVERY N ITERATIONS. + // + if (NRST == N) { + NRST = 0; + } + ++NRST; + RSW = false; + //goto L40; + continue; + // + // ROUNDOFF HAS PRODUCED A BAD DIRECTION. + // + + L320: + // printf("\n\n ----- THE SEARCH VECTOR WAS NOT A DESCENT DIRECTION"); + // printf("\n THIS CAN ONLY BE CAUSED BY ROUNDOFF, AND MAY SUGGEST"); + // printf("\n THAT THE CONVERGENCE CRITERION IS TOO STRICT"); + // printf("\n\n CURRENT RMS GRADIENT : %lf",sqrt(GSQ/(double)N)); + // fflush(stdout); + NFLAG = 3; + gmax = Math.abs(G[0]); + for (I = 0; I < N; I++) { + GSQ += G[I] * G[I]; + if (gmax < Math.abs(G[I])) { + gmax = Math.abs(G[I]); + } + } + grms = Math.sqrt(GSQ / (double) N); + if (!STEALTH) { + PrintConMinRes(F, IFUN, grms, gmax, NFLAG); + } + return NFLAG; + + // + // A VARIABLE METRIC ALGORITM IS BEING USED. CALCULATE Y AND D'Y. + // + + L330:U1 = 0.0; + for (I = 0; I < N; I++) { + NGPI = NG + I; + W[NGPI] = G[I] - W[NGPI]; + U1 += W[I] * W[NGPI]; + } + //cout<<"\n L330: U1 "< 0.0) { + //goto L320; + //L320: + // printf("\n\n ----- THE SEARCH VECTOR WAS NOT A DESCENT DIRECTION"); + // printf("\n THIS CAN ONLY BE CAUSED BY ROUNDOFF, AND MAY SUGGEST"); + // printf("\n THAT THE CONVERGENCE CRITERION IS TOO STRICT"); + // printf("\n\n CURRENT RMS GRADIENT : %lf",sqrt(GSQ/(double)N)); + + NFLAG = 3; + gmax = Math.abs(G[0]); + for (I = 0; I < N; I++) { + GSQ += G[I] * G[I]; + if (gmax < Math.abs(G[I])) { + gmax = Math.abs(G[I]); + } + } + grms = Math.sqrt(GSQ / (double) N); + if (!STEALTH) { + PrintConMinRes(F, IFUN, grms, gmax, NFLAG); + } + return NFLAG; + } + + RSW = false; + //goto L40; + } + } // --- End of CONMIN + + */ + + void PrintConMinRes(double FUN, int NGRAD, double DGG, double GMAX, + int NFLAG) { + +// * +// PRINT RESULTS OF OPTIMIZATION +// * + + System.out.println("\n\n*** OPTIMIZATION SUMMARY ***"); + System.out.println("\n FUNCTION GRMS MAX GRAD # CALLS COND"); + System.out.printf(" %10.4f %10.4f %10.4f %6d %2d\n", FUN, DGG, + GMAX,NGRAD, NFLAG); + System.out.println("===> "); + + if (NFLAG == 0) { + System.out.print("THE ALGORITHM HAS CONVERGED"); + } + else if (NFLAG == 1) { + System.out.print( + "THE MAXIMUM NUMBER OF FUNCTION EVALUATIONS HAVE BEEN USED"); + } + else if (NFLAG == 2) { + System.out.print( + "THE LINEAR SEARCH HAS FAILED TO IMPROVE THE FUNCTION VALUE. THIS IS THE"); + System.out.print( + "\nUSUAL EXIT IF EITHER THE FUNCTION OR THE GRADIENT IS INCORRECTLY CODED"); + + } + else if (NFLAG == 3) { + System.out.print( + "THE SEARCH VECTOR WAS NOT A DESCENT DIRECTION. THIS CAN ONLY BE CAUSED"); + System.out.print( + "\nBY ROUNDOFF,AND MAY SUGGEST THAT THE CONVERGENCE CRITERION IS TOO STRICT"); + + } + System.out.print("\n\n"); + } + + double SIGN(double A, double B) { + if (B >= 0.0) { + return A > 0.0 ? A : -A; + } + else { + return A < 0.0 ? A : -A; + } + } + + public static void main(String[] args) { + Minimizer minimizer = new Minimizer(); + } +} diff --git a/src/main/java/cct/math/MinimizerInterface.java b/src/main/java/cct/math/MinimizerInterface.java new file mode 100644 index 0000000..2b9a944 --- /dev/null +++ b/src/main/java/cct/math/MinimizerInterface.java @@ -0,0 +1,87 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.math; + +import cct.interfaces.MinimizeProgressInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface MinimizerInterface { + + void enableMaxGradConvergence(boolean enable); + + void enableMaxGRMSConvergence(boolean enable); + + String getExitCodeDescription(int code); + + float[] getGradients(); + + float getMaxGradientConv(); + + float getMaxRMSGradientConv(); + + int getMaxIterations(); + + String getName(); + + boolean isMaxGradConvergence(); + + boolean isMaxRMSGradConvergence(); + + int minimizeFunction(int n, float[] p, MinimizedFunctionInterface func); + + void setMaxGradientConv(float maxgrad); + + void setMaxRMSGradientConv(float maxgrms); + + void setMaxIterations(int iter); + + void setMinimizeProgressInterface(MinimizeProgressInterface mpi); + + boolean useGradients(); +} diff --git a/src/main/java/cct/math/OPERATION.java b/src/main/java/cct/math/OPERATION.java new file mode 100644 index 0000000..522db50 --- /dev/null +++ b/src/main/java/cct/math/OPERATION.java @@ -0,0 +1,14 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.math; + +/** + * + * @author vvv900 + */ +public enum OPERATION { + ADD, SUBSTRACT, MULTIPLY, DEVIDE, POWER +} diff --git a/src/main/java/cct/math/PARANTHESIS.java b/src/main/java/cct/math/PARANTHESIS.java new file mode 100644 index 0000000..ad55f04 --- /dev/null +++ b/src/main/java/cct/math/PARANTHESIS.java @@ -0,0 +1,14 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.math; + +/** + * + * @author vvv900 + */ +public enum PARANTHESIS { + LEFT, RIGHT +} diff --git a/src/main/java/cct/math/PREDEFINED_FUNCTION.java b/src/main/java/cct/math/PREDEFINED_FUNCTION.java new file mode 100644 index 0000000..cffde50 --- /dev/null +++ b/src/main/java/cct/math/PREDEFINED_FUNCTION.java @@ -0,0 +1,14 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.math; + +/** + * + * @author vvv900 + */ +public enum PREDEFINED_FUNCTION { + SQRT, sqrt, SIN, sin, COS, cos, TAN, tan, ASIN, asin, ACOS, acos, ATAN, atan, EXP, exp, LOG, log +} diff --git a/src/main/java/cct/math/PointGroup.java b/src/main/java/cct/math/PointGroup.java new file mode 100644 index 0000000..58c104c --- /dev/null +++ b/src/main/java/cct/math/PointGroup.java @@ -0,0 +1,679 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.math; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import cct.interfaces.Point3fInterface; +import cct.vecmath.Geometry3d; +import cct.vecmath.Point3f; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class PointGroup { + + static double Tolerance = 0.0001; + static final float TWO_PI_FLOAT = (float) (2.0 * Math.PI); + static final float PI_FLOAT = (float) Math.PI; + static final float HALF_PI_FLOAT = (float) (Math.PI / 2.0); + static final Set validSymmetrySymbols = new HashSet(); + + static { + validSymmetrySymbols.add("C1"); + validSymmetrySymbols.add("CS"); + validSymmetrySymbols.add("CI"); + validSymmetrySymbols.add("CN"); + //validSymmetrySymbols.add("S2N"); + //validSymmetrySymbols.add("CNH"); + //validSymmetrySymbols.add("NH"); + //validSymmetrySymbols.add("CNV"); + //validSymmetrySymbols.add("DN"); + //validSymmetrySymbols.add("DNH"); + //validSymmetrySymbols.add("DND"); + //validSymmetrySymbols.add("T"); + //validSymmetrySymbols.add("TH"); + //validSymmetrySymbols.add("TD"); + //validSymmetrySymbols.add("O"); + //validSymmetrySymbols.add("OH"); + } + + private PointGroup() { + } + + /** + * Not implemented yet.... + * @param symbol String + * @param axisOrder int + * @param points ArrayList + * @throws Exception + */ + public static void applySymmetry(String symbol, int axisOrder, List points) throws Exception { + if (!validSymmetrySymbols.contains(symbol.toUpperCase())) { + throw new Exception("Don't know how to apply symmetry " + symbol); + } + + } + + /** + * + * @param symbol String + * @param axisOrder int + * @param point Point3fInterface + * @return Point3fInterface[] + */ + public static Object[] generatePoints(String symbol, int axisOrder, Point3fInterface point) { + + Object[] p = null; + + // --- C1 group + if (symbol.toUpperCase().equals("C1")) { + return p; + } // --- Ci group + else if (symbol.toUpperCase().equals("CI")) { + Point3fInterface testPoint = point.getInstance(point); + // invert a point + testPoint.setXYZ(-point.getX(), -point.getY(), -point.getZ()); + if (point.distanceTo(testPoint) > Tolerance) { + p = new Object[1]; + p[0] = testPoint; + return p; + } + } // --- Cs group + else if (symbol.toUpperCase().equals("CS")) { + + if (Math.abs(point.getZ()) < Tolerance) { + return null; + } + + Point3fInterface testPoint = point.getInstance(point); + testPoint.setXYZ(point.getX(), point.getY(), -point.getZ()); + p = new Object[1]; + p[0] = testPoint; + return p; + } // --- CN group + else if (symbol.toUpperCase().equals("CN")) { + + if (Math.abs(point.getX()) < Tolerance && Math.abs(point.getY()) < Tolerance) { + // --- Point is on the Z axis + return null; + } + + float theta = TWO_PI_FLOAT / axisOrder; + Point3fInterface p1 = new Point3f(0, 0, 0); + Point3fInterface p2 = new Point3f(0, 0, 1); + + p = new Object[axisOrder - 1]; + + for (int i = 1, j = 0; i < axisOrder; i++, j++) { + Point3fInterface testPoint = point.getInstance(point); + Geometry3d.rotatePointAroundArbitraryAxis(testPoint, + theta * i, p1, p2); + p[j] = testPoint; + } + return p; + } else if (symbol.toUpperCase().equals("CNV")) { + if (Math.abs(point.getX()) < Tolerance + && Math.abs(point.getY()) < Tolerance) { + // --- Point is on the Z axis + return null; + } + + float theta = TWO_PI_FLOAT / axisOrder; + Point3fInterface p1 = new Point3f(0, 0, 0); + Point3fInterface p2 = new Point3f(0, 0, 1); + + List allP = new ArrayList(); + allP.add(point); + p = new Object[axisOrder - 1]; + //p[axisOrder - 1] = point; + + for (int i = 1, j = 0; i < axisOrder; i++, j++) { + Point3fInterface testPoint = point.getInstance(point); + Geometry3d.rotatePointAroundArbitraryAxis(testPoint, theta * i, p1, p2); + p[j] = testPoint; + allP.add(testPoint); + } + + theta /= 2.0f; + float finalTheta; + for (int j = 0; j < axisOrder; j++) { + + // --- Normals of Sigma(v) plane + finalTheta = theta * j + HALF_PI_FLOAT; + float xn = (float) Math.cos(finalTheta); + float yn = (float) Math.sin(finalTheta); + + Point3fInterface testPoint = point.getInstance(point); + float d = testPoint.getX() * xn + testPoint.getY() * yn; + if (Math.abs(d) > Tolerance) { // Point is not on the plane + testPoint.setX(testPoint.getX() - 2 * d * xn); + testPoint.setY(testPoint.getY() - 2 * d * yn); + allP.add(testPoint); + } + + // Now reflect points in planes + for (int i = 0; i < p.length; i++) { + testPoint = (Point3fInterface) p[i]; + // - Distance to the plane + d = testPoint.getX() * xn + testPoint.getY() * yn; + if (Math.abs(d) < Tolerance) { // Point is on the plane + continue; + } + + // --- Reflect point + + Point3fInterface reflectedPoint = testPoint.getInstance( + testPoint); + reflectedPoint.setX(reflectedPoint.getX() - 2 * d * xn); + reflectedPoint.setY(reflectedPoint.getY() - 2 * d * yn); + allP.add(reflectedPoint); + } + } + + // --- remove degenerated points + + return removeDegeneratePoints(point, p, allP); + /* + int degeneratedPoints = 0; + for (int j = 0; j < allP.size(); j++) { + Point3fInterface testPoint = (Point3fInterface) allP.get(j); + if (testPoint.distanceTo(point) < Tolerance) { + allP.set(j, null); + ++degeneratedPoints; + continue; + } + for (int i = 0; i < p.length; i++) { + Point3fInterface rotatedPoint = (Point3fInterface) p[i]; + if (testPoint.distanceTo(rotatedPoint) < Tolerance) { + allP.set(j, null); + ++degeneratedPoints; + break; + } + } + } + + if (degeneratedPoints == allP.size()) { + return p; + } + + Object[] finalPoints = new Object[p.length + allP.size() - + degeneratedPoints]; + for (int i = 0; i < p.length; i++) { + finalPoints[i] = p[i]; + } + int count = p.length; + for (int j = 0; j < allP.size(); j++) { + Point3fInterface testPoint = (Point3fInterface) allP.get(j); + if (testPoint == null) { + continue; + } + finalPoints[count] = testPoint; + ++count; + } + return finalPoints; + */ + } else if (symbol.toUpperCase().equals("CNH")) { + if (Math.abs(point.getX()) < Tolerance + && Math.abs(point.getY()) < Tolerance + && Math.abs(point.getZ()) < Tolerance) { + // --- Point is in the origin + return null; + } + + boolean notOnZAxis = true; + + if (Math.abs(point.getX()) < Tolerance + && Math.abs(point.getY()) < Tolerance) { + // --- Point is on the Z axis + notOnZAxis = false; + } + + float theta = TWO_PI_FLOAT / axisOrder; + List allP = new ArrayList(); + allP.add(point); + p = null; + + // --- Rotate around principal axis + + if (notOnZAxis) { + Point3fInterface p1 = new Point3f(0, 0, 0); + Point3fInterface p2 = new Point3f(0, 0, 1); + + p = new Object[axisOrder - 1]; + //p[axisOrder - 1] = point; + + for (int i = 1, j = 0; i < axisOrder; i++, j++) { + Point3fInterface testPoint = point.getInstance(point); + Geometry3d.rotatePointAroundArbitraryAxis(testPoint, theta * i, p1, p2); + p[j] = testPoint; + allP.add(testPoint); + } + + } + + // -- Reflect in Sigma-h + + if (Math.abs(point.getZ()) > Tolerance) { + Point3fInterface testPoint = point.getInstance(point); + testPoint.setZ(testPoint.getZ()); + allP.add(testPoint); + } + + if (p != null) { + for (int i = 0; i < p.length; i++) { + Point3fInterface testPoint = (Point3fInterface) p[i]; + if (Math.abs(point.getZ()) < Tolerance) { + continue; + } + Point3fInterface reflectedPoint = point.getInstance(testPoint); + reflectedPoint.setZ(reflectedPoint.getZ()); + allP.add(reflectedPoint); + + } + + } + + // --- remove degenerated points + + return removeDegeneratePoints(point, p, allP); + } // --- DN Symmetry transformations + else if (symbol.toUpperCase().equals("DN")) { + if (Math.abs(point.getX()) < Tolerance + && Math.abs(point.getY()) < Tolerance + && Math.abs(point.getZ()) < Tolerance) { + // --- Point is in the origin + return null; + } + + boolean notOnZAxis = true; + + if (Math.abs(point.getX()) < Tolerance + && Math.abs(point.getY()) < Tolerance) { + // --- Point is on the Z axis + notOnZAxis = false; + } + + float theta = TWO_PI_FLOAT / axisOrder; + Point3fInterface p1 = new Point3f(0, 0, 0); + Point3fInterface p2 = new Point3f(0, 0, 1); + List allP = new ArrayList(); + allP.add(point); + p = null; + + if (notOnZAxis) { + + p = new Object[axisOrder - 1]; + //p[axisOrder - 1] = point; + + for (int i = 1, j = 0; i < axisOrder; i++, j++) { + Point3fInterface testPoint = point.getInstance(point); + Geometry3d.rotatePointAroundArbitraryAxis(testPoint, + theta * i, p1, p2); + p[j] = testPoint; + allP.add(testPoint); + } + } + + // Rotate around two-fold axis + + float finalTheta; + + p2.setZ(0); + for (int j = 0; j < axisOrder; j++) { + + finalTheta = theta / 2.0f * j; + p2.setX((float) Math.cos(finalTheta)); + p2.setY((float) Math.sin(finalTheta)); + + Point3fInterface testPoint = point.getInstance(point); + Geometry3d.rotatePointAroundArbitraryAxis(testPoint, PI_FLOAT, + p1, p2); + allP.add(testPoint); + + if (p != null) { + for (int i = 0; i < p.length; i++) { + Point3fInterface rotatedPoint = point.getInstance((Point3fInterface) p[i]); + Geometry3d.rotatePointAroundArbitraryAxis(rotatedPoint, + PI_FLOAT, p1, p2); + allP.add(rotatedPoint); + } + } + } + + // --- remove degenerated points + + return removeDegeneratePoints(point, p, allP); + + } // --- DNH Symmetry transformations + else if (symbol.toUpperCase().equals("DNH")) { + if (Math.abs(point.getX()) < Tolerance + && Math.abs(point.getY()) < Tolerance + && Math.abs(point.getZ()) < Tolerance) { + // --- Point is in the origin + return null; + } + + boolean notOnZAxis = true; + + if (Math.abs(point.getX()) < Tolerance + && Math.abs(point.getY()) < Tolerance) { + // --- Point is on the Z axis + notOnZAxis = false; + } + + float theta = TWO_PI_FLOAT / axisOrder; + Point3fInterface p1 = new Point3f(0, 0, 0); + Point3fInterface p2 = new Point3f(0, 0, 1); + List allP = new ArrayList(); + allP.add(point); + p = null; + + if (notOnZAxis) { + + p = new Object[axisOrder - 1]; + //p[axisOrder - 1] = point; + + for (int i = 1, j = 0; i < axisOrder; i++, j++) { + Point3fInterface testPoint = point.getInstance(point); + Geometry3d.rotatePointAroundArbitraryAxis(testPoint, + theta * i, p1, p2); + p[j] = testPoint; + allP.add(testPoint); + } + } + + // Rotate around two-fold axis + + float finalTheta; + + p2.setZ(0); + for (int j = 0; j < axisOrder; j++) { + + finalTheta = theta / 2.0f * j; + p2.setX((float) Math.cos(finalTheta)); + p2.setY((float) Math.sin(finalTheta)); + + Point3fInterface testPoint = point.getInstance(point); + Geometry3d.rotatePointAroundArbitraryAxis(testPoint, PI_FLOAT, + p1, p2); + allP.add(testPoint); + + if (p != null) { + for (int i = 0; i < p.length; i++) { + Point3fInterface rotatedPoint = point.getInstance((Point3fInterface) p[i]); + Geometry3d.rotatePointAroundArbitraryAxis(rotatedPoint, + PI_FLOAT, p1, p2); + allP.add(rotatedPoint); + } + } + } + + // Reflect in Sigma-h + + if (Math.abs(point.getZ()) > Tolerance) { + Point3fInterface testPoint = point.getInstance(point); + testPoint.setZ(-testPoint.getZ()); + allP.add(testPoint); + } + + if (p != null) { + for (int i = 0; i < p.length; i++) { + Point3fInterface reflectedPoint = point.getInstance((Point3fInterface) p[i]); + if (Math.abs(reflectedPoint.getZ()) < Tolerance) { + continue; + } + reflectedPoint.setZ(-reflectedPoint.getZ()); + allP.add(reflectedPoint); + } + } + + // --- remove degenerated points + return removeDegeneratePoints(point, p, allP); + + } // --- DND Symmetry transformations + else if (symbol.toUpperCase().equals("DND")) { + if (Math.abs(point.getX()) < Tolerance + && Math.abs(point.getY()) < Tolerance + && Math.abs(point.getZ()) < Tolerance) { + // --- Point is in the origin + return null; + } + + boolean notOnZAxis = true; + + if (Math.abs(point.getX()) < Tolerance + && Math.abs(point.getY()) < Tolerance) { + // --- Point is on the Z axis + notOnZAxis = false; + } + + float theta = TWO_PI_FLOAT / axisOrder; + Point3fInterface p1 = new Point3f(0, 0, 0); + Point3fInterface p2 = new Point3f(0, 0, 1); + List allP = new ArrayList(); + allP.add(point); + p = null; + + if (notOnZAxis) { + + p = new Object[axisOrder - 1]; + //p[axisOrder - 1] = point; + + for (int i = 1, j = 0; i < axisOrder; i++, j++) { + Point3fInterface testPoint = point.getInstance(point); + Geometry3d.rotatePointAroundArbitraryAxis(testPoint, + theta * i, p1, p2); + p[j] = testPoint; + allP.add(testPoint); + } + } + + // Rotate around two-fold axis + + float finalTheta; + + p2.setZ(0); + for (int j = 0; j < axisOrder; j++) { + + finalTheta = theta / 2.0f * j; + p2.setX((float) Math.cos(finalTheta)); + p2.setY((float) Math.sin(finalTheta)); + + Point3fInterface testPoint = point.getInstance(point); + Geometry3d.rotatePointAroundArbitraryAxis(testPoint, PI_FLOAT, + p1, p2); + allP.add(testPoint); + + if (p != null) { + for (int i = 0; i < p.length; i++) { + Point3fInterface rotatedPoint = point.getInstance((Point3fInterface) p[i]); + Geometry3d.rotatePointAroundArbitraryAxis(rotatedPoint, + PI_FLOAT, p1, p2); + allP.add(rotatedPoint); + } + } + } + + // --- Reflect in mirror planes Sigma-d + + theta /= 2.0f; + for (int j = 0; j < axisOrder; j++) { + + // --- Normals of Sigma(v) plane + finalTheta = theta * j + theta / 2.0f + HALF_PI_FLOAT; + float xn = (float) Math.cos(finalTheta); + float yn = (float) Math.sin(finalTheta); + + if (Math.abs(point.getZ()) > Tolerance) { + Point3fInterface testPoint = point.getInstance(point); + float d = testPoint.getX() * xn + testPoint.getY() * yn; + testPoint.setX(testPoint.getX() - 2 * d * xn); + testPoint.setY(testPoint.getY() - 2 * d * yn); + allP.add(testPoint); + } + + // Now reflect points in planes + if (p != null) { + for (int i = 0; i < p.length; i++) { + Point3fInterface testPoint = (Point3fInterface) p[i]; + // - Distance to the plane + float d = testPoint.getX() * xn + testPoint.getY() * yn; + if (Math.abs(d) < Tolerance) { // Point is on the plane + continue; + } + + // --- Reflect point + + Point3fInterface reflectedPoint = testPoint.getInstance( + testPoint); + reflectedPoint.setX(reflectedPoint.getX() - 2 * d * xn); + reflectedPoint.setY(reflectedPoint.getY() - 2 * d * yn); + allP.add(reflectedPoint); + } + } + } + + // --- remove degenerated points + + return removeDegeneratePoints(point, p, allP); + + } + + return null; + } + + private static Object[] removeDegeneratePoints(Point3fInterface originalPoint, Object p[], List points) { + removeDegeneratePoints(points); + + int degeneratedPoints = 0; + for (int j = 0; j < points.size(); j++) { + Point3fInterface testPoint = (Point3fInterface) points.get(j); + if (testPoint == null) { + ++degeneratedPoints; + continue; + } + if (testPoint.distanceTo(originalPoint) < Tolerance) { + points.set(j, null); + ++degeneratedPoints; + continue; + } + if (p != null) { + for (int i = 0; i < p.length; i++) { + Point3fInterface rotatedPoint = (Point3fInterface) p[i]; + if (rotatedPoint == null) { + ++degeneratedPoints; + continue; + } + if (testPoint.distanceTo(rotatedPoint) < Tolerance) { + points.set(j, null); + ++degeneratedPoints; + break; + } + } + } + } + + if (degeneratedPoints == points.size()) { + return p; + } + + Object[] finalPoints; + if (p != null) { + finalPoints = new Object[p.length + points.size() + - degeneratedPoints]; + for (int i = 0; i < p.length; i++) { + finalPoints[i] = p[i]; + } + int count = p.length; + for (int j = 0; j < points.size(); j++) { + Point3fInterface testPoint = (Point3fInterface) points.get(j); + if (testPoint == null) { + continue; + } + finalPoints[count] = testPoint; + ++count; + } + + } else { + finalPoints = new Object[points.size() - degeneratedPoints]; + int count = 0; + for (int j = 0; j < points.size(); j++) { + Point3fInterface testPoint = (Point3fInterface) points.get(j); + if (testPoint == null) { + continue; + } + finalPoints[count] = testPoint; + ++count; + } + + } + + return finalPoints; + + } + + private static void removeDegeneratePoints(List points) { + for (int i = 0; i < points.size() - 1; i++) { + Point3fInterface Point = (Point3fInterface) points.get(i); + if (Point == null) { + continue; + } + for (int j = i + 1; j < points.size(); j++) { + Point3fInterface testPoint = (Point3fInterface) points.get(j); + if (testPoint == null) { + continue; + } + if (Point.distanceTo(testPoint) < Tolerance) { + points.set(j, null); + } + } + } + } +} diff --git a/src/main/java/cct/math/SEPARATOR.java b/src/main/java/cct/math/SEPARATOR.java new file mode 100644 index 0000000..ec8c57c --- /dev/null +++ b/src/main/java/cct/math/SEPARATOR.java @@ -0,0 +1,14 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.math; + +/** + * + * @author vvv900 + */ +public enum SEPARATOR { + COMMA +} diff --git a/src/main/java/cct/math/Simplex.java b/src/main/java/cct/math/Simplex.java new file mode 100644 index 0000000..e013643 --- /dev/null +++ b/src/main/java/cct/math/Simplex.java @@ -0,0 +1,274 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.math; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Simplex { + + static int Ok = 0; + boolean SilentMode; + float p[][]; + float y[], psum[], ptry[]; + int ndim; + float F0 = 0; + + public Simplex(int n) { + SilentMode = false; + y = new float[n + 1]; + psum = new float[n]; + ptry = new float[n]; + p = new float[n + 1][n]; + //for(int i=0; i= 0) { + p[j][k] += gamma; + } + y[j] = func.function(nvar, p[j]); + } + + //GET_PSUM + GET_PSUM(nvar); + + while (true) { +// --- First we must define which point is the highest (worst), next-highest, +// --- and lowest (best), by looping over the points in the simplex. + lowest = 0; + //highest = y[0] > y[1] ? (next_highest = 1, 0) : (next_highest = 0, 1); + highest = y[0] > y[1] ? 0 : 1; + next_highest = y[0] > y[1] ? 1 : 0; + for (i = 0; i < mpts; i++) { + if (y[i] <= y[lowest]) { + lowest = i; + } + if (y[i] > y[highest]) { + next_highest = highest; + highest = i; + } + else if (y[i] > y[next_highest] && i != highest) { + next_highest = i; + } + } + + rtol = (float) (2.0 * Math.abs(y[highest] - y[lowest]) / + (Math.abs(y[highest]) + Math.abs(y[lowest]))); + +// --- Compute the fractional range from highest to lowest and return if +// satisfactory + + F0 = y[lowest]; + if (rtol < ftol) { // --- Put best point and value in set + for (i = 0; i < nvar; i++) { + set[i] = p[lowest][i]; + } + if (!SilentMode) { + System.out.print("\n\nOptimization finished after " + ncalls + " function calls"); + System.out.print("\nFunction value : " + F0); + System.out.print( + "\n\n ********** E N D O F S I M P L E X ********** "); + } + return Ok; + } + + if (ncalls > 0 && (rtol >= Math.abs(F0 - Fvalue))) { // --- Check delta F + //++ntimes; + //if (ntimes > 20) { + for (i = 0; i < nvar; i++) { + set[i] = p[lowest][i]; + } + if (!SilentMode) { + System.out.print( + "\n\nConvergence on F is achieved after " + ncalls + " function calls"); + System.out.print("\nFunction value : " + F0); + System.out.print( + "\n\n ********** E N D O F S I M P L E X ********** "); + } + return Ok; + //} + } + else { + Fvalue = F0; + //ntimes = 0; + } + + if (ncalls > NMAX) { + for (i = 0; i < nvar; i++) { + set[i] = p[lowest][i]; + } + if (!SilentMode) { + System.out.print("\n\nNUMBER OF MAXIMUM CALLS " + NMAX + " IS EXCEEDED"); + System.out.print("\n Function value : " + F0); + System.out.print( + "\n\n ********** E N D O F S I M P L E X ********** "); + } + return Ok; + } + + if (!SilentMode) { + + System.out.print("\n\nNCALLS " + ncalls + " FUN: " + y[lowest] + "\n"); + + } + + //fflush(stdout); + + ncalls += 2; + +// --- Begin a new iteration. First extrapolate by a factor -1, i.e. +// --- reflex the simplex from the high point + + ytry = NewTrial(p, y, psum, ptry, nvar, func, highest, -1.0f); + if (ytry <= y[lowest]) { + ytry = NewTrial(p, y, psum, ptry, nvar, func, highest, 2.0f); + } + else if (ytry >= y[next_highest]) { + ysave = y[highest]; + ytry = NewTrial(p, y, psum, ptry, nvar, func, highest, 0.5f); + if (ytry >= ysave) { + for (i = 0; i < mpts; i++) { + if (i != lowest) { + for (j = 0; j < nvar; j++) { + p[i][j] = psum[j] = 0.5f * (p[i][j] + p[lowest][j]); + } + y[i] = func.function(nvar, psum); + } + } + ncalls += nvar; + //GET_PSUM + GET_PSUM(nvar); + } + } + else { + --ncalls; + } + + } // --- while( True ) + } + + float NewTrial(float p[][], float y[], float psum[], float ptry[], int nvar, + MinimizedFunctionInterface func, int highest, float fac) { + + int j; + float fac1, fac2, ytry; + + fac1 = (1.0f - fac) / nvar; + fac2 = fac1 - fac; + for (j = 0; j < nvar; j++) { + ptry[j] = psum[j] * fac1 - p[highest][j] * fac2; + } + ytry = func.function(nvar, ptry); + + if (ytry < y[highest]) { // --- Replace the highest + y[highest] = ytry; + for (j = 0; j < nvar; j++) { + psum[j] += ptry[j] - p[highest][j]; + p[highest][j] = ptry[j]; + } + } + return ytry; + } // --- real NewTrial + +} diff --git a/src/main/java/cct/math/Statistics.java b/src/main/java/cct/math/Statistics.java new file mode 100644 index 0000000..a9d9401 --- /dev/null +++ b/src/main/java/cct/math/Statistics.java @@ -0,0 +1,956 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.math; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * + * @author vvv900 + */ +public class Statistics { + + public static double mean(double[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = 0.0; + for (double i : x) { + mean += i; + } + return mean / (double) x.length; + } + + public static double mean(Double[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = 0.0; + for (double i : x) { + mean += i; + } + return mean / (double) x.length; + } + + public static double mean(float[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = 0.0; + for (double i : x) { + mean += i; + } + return mean / (double) x.length; + } + + public static double mean(Float[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = 0.0; + for (double i : x) { + mean += i; + } + return mean / (double) x.length; + } + + public static double mean(List x) throws Exception { + if (x == null || x.size() == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = 0.0; + for (Object i : x) { + mean += ((Number) i).doubleValue(); + } + return mean / (double) x.size(); + } + + public static double mean(Number[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = 0.0; + for (Number i : x) { + mean += i.doubleValue(); + } + return mean / (double) x.length; + } + + public static double mean(Object[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = 0.0; + for (Object i : x) { + mean += ((Number) i).doubleValue(); + } + return mean / (double) x.length; + } + + public static double median(double[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + double[] y = Arrays.copyOf(x, x.length); + Arrays.sort(y); + return y.length % 2 == 0 ? 0.5 * (y[y.length / 2] + y[y.length / 2 + 1]) : y[(y.length + 1) / 2]; + } + + public static double median(Double[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + Double[] y = Arrays.copyOf(x, x.length); + Arrays.sort(y); + return y.length % 2 == 0 ? 0.5 * (y[y.length / 2] + y[y.length / 2 + 1]) : y[(y.length + 1) / 2]; + } + + public static double median(float[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + float[] y = Arrays.copyOf(x, x.length); + Arrays.sort(y); + return y.length % 2 == 0 ? 0.5 * (y[y.length / 2] + y[y.length / 2 + 1]) : y[(y.length + 1) / 2]; + } + + public static double median(Float[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + Float[] y = Arrays.copyOf(x, x.length); + Arrays.sort(y); + return y.length % 2 == 0 ? 0.5 * (y[y.length / 2] + y[y.length / 2 + 1]) : y[(y.length + 1) / 2]; + } + + public static double median(Number[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + Number[] y = Arrays.copyOf(x, x.length); + Arrays.sort(y); + return y.length % 2 == 0 + ? 0.5 * (y[y.length / 2].doubleValue() + y[y.length / 2 + 1].doubleValue()) + : y[(y.length + 1) / 2].doubleValue(); + } + + public static double median(Object[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + Object[] y = Arrays.copyOf(x, x.length); + Arrays.sort(y); + return y.length % 2 == 0 + ? 0.5 * (((Number) y[y.length / 2]).doubleValue() + ((Number) y[y.length / 2 + 1]).doubleValue()) + : ((Number) y[(y.length + 1) / 2]).doubleValue(); + } + + public static double median(List x) throws Exception { + if (x == null || x.size() == 0) { + throw new Exception("Got null instead of data array"); + } + Object[] y = x.toArray(); + Arrays.sort(y); + return y.length % 2 == 0 + ? 0.5 * (((Number) y[y.length / 2]).doubleValue() + ((Number) y[y.length / 2 + 1]).doubleValue()) + : ((Number) y[(y.length + 1) / 2]).doubleValue(); + } + + /** + * estimates the mean squared deviation of x from its mean value + * + * @param x - 1d array + * @return + * @throws Exception + */ + public static double variance(double[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.length == 1) { + throw new Exception("Array length should be more than 1 to calculate variance"); + } + double mean = mean(x); + double variance = 0.0; + for (double i : x) { + variance += (i - mean) * (i - mean); + } + return variance / (double) (x.length - 1); + } + + /** + * estimates the mean squared deviation of x from its mean value + * + * @param x + * @return + * @throws Exception + */ + public static double variance(Double[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.length == 1) { + throw new Exception("Array length should be more than 1 to calculate variance"); + } + double mean = mean(x); + double variance = 0.0; + for (double i : x) { + variance += (i - mean) * (i - mean); + } + return variance / (double) (x.length - 1); + } + + public static double variance(float[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.length == 1) { + throw new Exception("Array length should be more than 1 to calculate variance"); + } + double mean = mean(x); + double variance = 0.0; + for (double i : x) { + variance += (i - mean) * (i - mean); + } + return variance / (double) (x.length - 1); + } + + public static double variance(Float[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.length == 1) { + throw new Exception("Array length should be more than 1 to calculate variance"); + } + double mean = mean(x); + double variance = 0.0; + for (double i : x) { + variance += (i - mean) * (i - mean); + } + return variance / (double) (x.length - 1); + } + + public static double variance(Number[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.length == 1) { + throw new Exception("Array length should be more than 1 to calculate variance"); + } + double mean = mean(x); + double variance = 0.0; + for (Number i : x) { + variance += (i.doubleValue() - mean) * (i.doubleValue() - mean); + } + return variance / (double) (x.length - 1); + } + + public static double variance(Object[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.length == 1) { + throw new Exception("Array length should be more than 1 to calculate variance"); + } + double mean = mean(x); + double variance = 0.0; + for (Object i : x) { + variance += (((Number) i).doubleValue() - mean) * (((Number) i).doubleValue() - mean); + } + return variance / (double) (x.length - 1); + } + + public static double variance(List x) throws Exception { + if (x == null || x.size() == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.size() == 1) { + throw new Exception("Array length should be more than 1 to calculate variance"); + } + double mean = mean(x); + double variance = 0.0; + for (Object i : x) { + variance += (((Number) i).doubleValue() - mean) * (((Number) i).doubleValue() - mean); + } + return variance / (double) (x.size() - 1); + } + + public static double standardDeviation(double[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.length == 1) { + throw new Exception("Array length should be more than 1 to calculate Standard Deviation"); + } + return Math.sqrt(variance(x)); + } + + public static double standardDeviation(Double[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.length == 1) { + throw new Exception("Array length should be more than 1 to calculate Standard Deviation"); + } + return Math.sqrt(variance(x)); + } + + public static double standardDeviation(float[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.length == 1) { + throw new Exception("Array length should be more than 1 to calculate Standard Deviation"); + } + return Math.sqrt(variance(x)); + } + + public static double standardDeviation(Float[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.length == 1) { + throw new Exception("Array length should be more than 1 to calculate Standard Deviation"); + } + return Math.sqrt(variance(x)); + } + + public static double standardDeviation(Number[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.length == 1) { + throw new Exception("Array length should be more than 1 to calculate Standard Deviation"); + } + return Math.sqrt(variance(x)); + } + + public static double standardDeviation(Object[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.length == 1) { + throw new Exception("Array length should be more than 1 to calculate Standard Deviation"); + } + return Math.sqrt(variance(x)); + } + + public static double standardDeviation(List x) throws Exception { + if (x == null || x.size() == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.size() == 1) { + throw new Exception("Array length should be more than 1 to calculate Standard Deviation"); + } + return Math.sqrt(variance(x)); + } + + /** + * A robust estimator of the width is the average deviation or mean absolute deviation, defined by Sum( abs(Xi-Mean) ) + * / N + * + * @param x - 1d array + * @return mean absolute deviation + * @throws Exception + */ + public static double meanAbsoluteDeviation(double[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = mean(x); + double deviation = 0.0; + for (double i : x) { + deviation += Math.abs(i - mean); + } + return deviation / (double) x.length; + } + + public static double meanAbsoluteDeviation(Double[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = mean(x); + double deviation = 0.0; + for (double i : x) { + deviation += Math.abs(i - mean); + } + return deviation / (double) x.length; + } + + public static double meanAbsoluteDeviation(float[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = mean(x); + double deviation = 0.0; + for (double i : x) { + deviation += Math.abs(i - mean); + } + return deviation / (double) x.length; + } + + public static double meanAbsoluteDeviation(Float[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = mean(x); + double deviation = 0.0; + for (double i : x) { + deviation += Math.abs(i - mean); + } + return deviation / (double) x.length; + } + + public static double meanAbsoluteDeviation(Number[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = mean(x); + double deviation = 0.0; + for (Number i : x) { + deviation += Math.abs(i.doubleValue() - mean); + } + return deviation / (double) x.length; + } + + public static double meanAbsoluteDeviation(Object[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = mean(x); + double deviation = 0.0; + for (Object i : x) { + deviation += Math.abs(((Number) i).doubleValue() - mean); + } + return deviation / (double) x.length; + } + + public static double meanAbsoluteDeviation(List x) throws Exception { + if (x == null || x.size() == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = mean(x); + double deviation = 0.0; + for (Object i : x) { + deviation += Math.abs(((Number) i).doubleValue() - mean); + } + return deviation / (double) x.size(); + } + + /** + * The skewness characterizes the degree of asymmetry of a distribution around its mean. While the mean, standard + * deviation, and average deviation are dimensional quantities, that is, have the same units as the measured + * quantities Xj, the skewness is conventionally defined in such a way as to make it non-dimensional. It is a pure + * number that characterizes only the shape of the distribution. A positive value of skewness signifies a distribution + * with an asymmetric tail extending out towards more positive X; a negative value signifies a distribution whose tail + * extends out towards more negative X + * + * @param x + * @return + * @throws Exception + */ + public static double skew(double[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.length == 1) { + throw new Exception("Array length should be more than 1 to calculate Skewness"); + } + double mean = mean(x); + double sigma = standardDeviation(x); + double skew = 0.0; + for (double i : x) { + skew += Math.pow((i - mean) / sigma, 3); + } + return skew / (double) x.length; + } + + public static double skew(Double[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.length == 1) { + throw new Exception("Array length should be more than 1 to calculate Skewness"); + } + double mean = mean(x); + double sigma = standardDeviation(x); + double skew = 0.0; + for (double i : x) { + skew += Math.pow((i - mean) / sigma, 3); + } + return skew / (double) x.length; + } + + public static double skew(float[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.length == 1) { + throw new Exception("Array length should be more than 1 to calculate Skewness"); + } + double mean = mean(x); + double sigma = standardDeviation(x); + double skew = 0.0; + for (double i : x) { + skew += Math.pow((i - mean) / sigma, 3); + } + return skew / (double) x.length; + } + + public static double skew(Float[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.length == 1) { + throw new Exception("Array length should be more than 1 to calculate Skewness"); + } + double mean = mean(x); + double sigma = standardDeviation(x); + double skew = 0.0; + for (double i : x) { + skew += Math.pow((i - mean) / sigma, 3); + } + return skew / (double) x.length; + } + + public static double skew(Number[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.length == 1) { + throw new Exception("Array length should be more than 1 to calculate Skewness"); + } + double mean = mean(x); + double sigma = standardDeviation(x); + double skew = 0.0; + for (Number i : x) { + skew += Math.pow((i.doubleValue() - mean) / sigma, 3); + } + return skew / (double) x.length; + } + + public static double skew(Object[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.length == 1) { + throw new Exception("Array length should be more than 1 to calculate Skewness"); + } + double mean = mean(x); + double sigma = standardDeviation(x); + double skew = 0.0; + for (Object i : x) { + skew += Math.pow((((Number) i).doubleValue() - mean) / sigma, 3); + } + return skew / (double) x.length; + } + + public static double skew(List x) throws Exception { + if (x == null || x.size() == 0) { + throw new Exception("Got null instead of data array"); + } else if (x.size() == 1) { + throw new Exception("Array length should be more than 1 to calculate Skewness"); + } + double mean = mean(x); + double sigma = standardDeviation(x); + double skew = 0.0; + for (Object i : x) { + skew += Math.pow((((Number) i).doubleValue() - mean) / sigma, 3); + } + return skew / (double) x.size(); + } + + public static double linearCorrelationCoefficient(double[] x, double[] y) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of x data array"); + } else if (x.length == 1) { + throw new Exception("X Array length should be more than 1 to calculate a Linear Correlation Coefficient"); + } else if (y == null || y.length == 0) { + throw new Exception("Got null instead of y data array"); + } else if (x.length == 1) { + throw new Exception("Y Array length should be more than 1 to calculate a Linear Correlation Coefficient"); + } else if (x.length != y.length) { + throw new Exception("Both data arrays should be of equal length"); + } + double meanX = mean(x); + double meanY = mean(y); + double numerator = 0.0, xSq = 0.0, ySq = 0.0; + + for (int i = 0; i < x.length; i++) { + numerator += (x[i] - meanX) * (y[i] - meanY); + xSq += (x[i] - meanX) * (x[i] - meanX); + ySq += (y[i] - meanY) * (y[i] - meanY); + } + double denominator = Math.sqrt(xSq * ySq); + if (denominator == 0) { + throw new Exception("Denominator is equal to zero"); + } + return numerator / denominator; + } + + public static double linearCorrelationCoefficient(float[] x, float[] y) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of x data array"); + } else if (x.length == 1) { + throw new Exception("X Array length should be more than 1 to calculate a Linear Correlation Coefficient"); + } else if (y == null || y.length == 0) { + throw new Exception("Got null instead of y data array"); + } else if (x.length == 1) { + throw new Exception("Y Array length should be more than 1 to calculate a Linear Correlation Coefficient"); + } else if (x.length != y.length) { + throw new Exception("Both data arrays should be of equal length"); + } + double meanX = mean(x); + double meanY = mean(y); + double numerator = 0.0, xSq = 0.0, ySq = 0.0; + + for (int i = 0; i < x.length; i++) { + numerator += (x[i] - meanX) * (y[i] - meanY); + xSq += (x[i] - meanX) * (x[i] - meanX); + ySq += (y[i] - meanY) * (y[i] - meanY); + } + double denominator = Math.sqrt(xSq * ySq); + if (denominator == 0) { + throw new Exception("Denominator is equal to zero"); + } + return numerator / denominator; + } + + public static double linearCorrelationCoefficient(Object[] x, Object[] y) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of x data array"); + } else if (x.length == 1) { + throw new Exception("X Array length should be more than 1 to calculate a Linear Correlation Coefficient"); + } else if (y == null || y.length == 0) { + throw new Exception("Got null instead of y data array"); + } else if (x.length == 1) { + throw new Exception("Y Array length should be more than 1 to calculate a Linear Correlation Coefficient"); + } else if (x.length != y.length) { + throw new Exception("Both data arrays should be of equal length"); + } + double meanX = mean(x); + double meanY = mean(y); + double numerator = 0.0, xSq = 0.0, ySq = 0.0; + + for (int i = 0; i < x.length; i++) { + numerator += (((Number) x[i]).doubleValue() - meanX) * (((Number) y[i]).doubleValue() - meanY); + xSq += (((Number) x[i]).doubleValue() - meanX) * (((Number) x[i]).doubleValue() - meanX); + ySq += (((Number) y[i]).doubleValue() - meanY) * (((Number) y[i]).doubleValue() - meanY); + } + double denominator = Math.sqrt(xSq * ySq); + if (denominator == 0) { + throw new Exception("Denominator is equal to zero"); + } + return numerator / denominator; + } + + public static double linearCorrelationCoefficient(Number[] x, Number[] y) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of x data array"); + } else if (x.length == 1) { + throw new Exception("X Array length should be more than 1 to calculate a Linear Correlation Coefficient"); + } else if (y == null || y.length == 0) { + throw new Exception("Got null instead of y data array"); + } else if (x.length == 1) { + throw new Exception("Y Array length should be more than 1 to calculate a Linear Correlation Coefficient"); + } else if (x.length != y.length) { + throw new Exception("Both data arrays should be of equal length"); + } + double meanX = mean(x); + double meanY = mean(y); + double numerator = 0.0, xSq = 0.0, ySq = 0.0; + + for (int i = 0; i < x.length; i++) { + numerator += (x[i].doubleValue() - meanX) * (y[i].doubleValue() - meanY); + xSq += (x[i].doubleValue() - meanX) * (x[i].doubleValue() - meanX); + ySq += (y[i].doubleValue() - meanY) * (y[i].doubleValue() - meanY); + } + double denominator = Math.sqrt(xSq * ySq); + if (denominator == 0) { + throw new Exception("Denominator is equal to zero"); + } + return numerator / denominator; + } + + /** + * The kurtosis is a non-dimensional quantity. It measures the relative peakedness or flatness of a distribution + * relative to a normal distribution. A distribution with positive kurtosis is termed leptokurtic; the outline of the + * Matterhorn is an example. A distribution with negative kurtosis is termed platykurtic; the outline of a loaf of + * bread is an example. And, as you no doubt expect, an in-between distribution is termed mesokurtic. + * + * @param x + * @return + * @throws Exception + */ + public static double kurtosis(double[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = mean(x); + double sigma = standardDeviation(x); + double value = 0.0; + for (double i : x) { + value += Math.pow((i - mean) / sigma, 4); + } + return value / (double) x.length - 3.0; + } + + public static double kurtosis(Double[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = mean(x); + double sigma = standardDeviation(x); + double value = 0.0; + for (double i : x) { + value += Math.pow((i - mean) / sigma, 4); + } + return value / (double) x.length - 3.0; + } + + public static double kurtosis(float[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = mean(x); + double sigma = standardDeviation(x); + double value = 0.0; + for (double i : x) { + value += Math.pow((i - mean) / sigma, 4); + } + return value / (double) x.length - 3.0; + } + + public static double kurtosis(Float[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = mean(x); + double sigma = standardDeviation(x); + double value = 0.0; + for (double i : x) { + value += Math.pow((i - mean) / sigma, 4); + } + return value / (double) x.length - 3.0; + } + + public static double kurtosis(Number[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = mean(x); + double sigma = standardDeviation(x); + double value = 0.0; + for (Number i : x) { + value += Math.pow((i.doubleValue() - mean) / sigma, 4); + } + return value / (double) x.length - 3.0; + } + + public static double kurtosis(Object[] x) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = mean(x); + double sigma = standardDeviation(x); + double value = 0.0; + for (Object i : x) { + value += Math.pow((((Number) i).doubleValue() - mean) / sigma, 4); + } + return value / (double) x.length - 3.0; + } + + public static double kurtosis(List x) throws Exception { + if (x == null || x.size() == 0) { + throw new Exception("Got null instead of data array"); + } + double mean = mean(x); + double sigma = standardDeviation(x); + double value = 0.0; + for (Object i : x) { + value += Math.pow((((Number) i).doubleValue() - mean) / sigma, 4); + } + return value / (double) x.size() - 3.0; + } + + public static double[] timeCorrelationFunction(double[] x, double[] y) throws Exception { + if (x == null || x.length == 0) { + throw new Exception("Got null instead of x data array"); + } else if (x.length == 1) { + throw new Exception("X Array length should be more than 1 to calculate a Linear Correlation Coefficient"); + } else if (y == null || y.length == 0) { + throw new Exception("Got null instead of y data array"); + } else if (x.length == 1) { + throw new Exception("Y Array length should be more than 1 to calculate a Linear Correlation Coefficient"); + } else if (x.length != y.length) { + throw new Exception("Both data arrays should be of equal length"); + } + + int minDim = Math.max(x.length, y.length); + double norm = 0.0; + for (int i = 0; i < minDim; i++) { + norm += x[i] * y[i]; + } + norm /= (double) minDim; + + List list = new ArrayList(); + list.add(1.0); + + for (int k = 1; k < minDim - 1; k++) { + double corr = 0.0, n = 0.0; + for (int i = 0; i < Math.min(minDim, y.length - k); i++) { + corr += x[i] * y[i + k]; + n += 1.0; + } + corr /= n * norm; + list.add(corr); + } + + double[] tcf = new double[list.size()]; + for (int i = 0; i < tcf.length; i++) { + tcf[i] = list.get(i); + } + + return tcf; + } + + public static double[] timeCorrelationFunction(List x, List y) throws Exception { + if (x == null || x.size() == 0) { + throw new Exception("Got null instead of x data array"); + } else if (x.size() == 1) { + throw new Exception("X Array length should be more than 1 to calculate a Linear Correlation Coefficient"); + } else if (y == null || y.size() == 0) { + throw new Exception("Got null instead of y data array"); + } else if (x.size() == 1) { + throw new Exception("Y Array length should be more than 1 to calculate a Linear Correlation Coefficient"); + } else if (x.size() != y.size()) { + throw new Exception("Both data arrays should be of equal length"); + } + + int minDim = Math.max(x.size(), y.size()); + double norm = 0.0; + for (int i = 0; i < minDim; i++) { + norm += ((Number) x.get(i)).doubleValue() * ((Number) y.get(i)).doubleValue(); + } + norm /= (double) minDim; + + List list = new ArrayList(); + list.add(1.0); + + for (int k = 1; k < minDim - 1; k++) { + double corr = 0.0, n = 0.0; + for (int i = 0; i < Math.min(minDim, y.size() - k); i++) { + corr += ((Number) x.get(i)).doubleValue() * ((Number) y.get(i + k)).doubleValue(); + ++n; + } + corr /= (n * norm); + list.add(corr); + } + + double[] tcf = new double[list.size()]; + for (int i = 0; i < tcf.length; i++) { + tcf[i] = list.get(i); + } + + return tcf; + } + + public static int[] histogram(List x, double start, double end, int nCells) throws Exception { + if (x == null || x.size() == 0) { + throw new Exception("Got null instead of x data array"); + } else if (x.size() == 1) { + throw new Exception("X Array length should be more than 1 to calculate a Linear Correlation Coefficient"); + } else if (x.size() == 1) { + throw new Exception("Y Array length should be more than 1 to calculate a Linear Correlation Coefficient"); + } + + int[] xxx = new int[nCells]; + double n_cells = (double) nCells; + + for (int i = 0; i < x.size(); i++) { + double value = ((Number) x.get(i)).doubleValue(); + if (value < start || value > end) { + continue; + } + int index = (int) ((value - start) / (end - start) * n_cells); + if (index == nCells) { + --index; + } + ++xxx[index]; + } + + return xxx; + } + + public static List acf(List x) throws Exception { + if (x == null || x.size() == 0) { + throw new Exception("Got null instead of x data array"); + } else if (x.size() == 1) { + throw new Exception("X Array length should be more than 1 to calculate a Linear Correlation Coefficient"); + } else if (x.size() == 1) { + throw new Exception("Y Array length should be more than 1 to calculate a Linear Correlation Coefficient"); + } + + double mean = mean(x); + double normFactor = 0.0; + for (int i = 0; i < x.size(); i++) { + normFactor += (((Number) x.get(i)).doubleValue() - mean) * (((Number) x.get(i)).doubleValue() - mean); + } + + List list = new ArrayList(); + list.add(1.0); + + for (int k = 1; k < x.size() - 1; k++) { + double corr = 0.0; + for (int i = 0; i < x.size() - k; i++) { + corr += (((Number) x.get(i)).doubleValue() - mean) * (((Number) x.get(i + k)).doubleValue() - mean); + } + corr /= normFactor; + list.add(corr); + } + + return list; + } + + /** + * The Root Mean Square Error (RMSE) (also called the root mean square deviation, RMSD) is a frequently used measure + * of the difference between values predicted by a model and the values actually observed from the environment that is + * being modelled. These individual differences are also called residuals, and the RMSE serves to aggregate them into + * a single measure of predictive power. + * + * @param v1 + * @param v2 + * @return - RMSE + */ + public static double rootMeanSquareError(double[] v1, double[] v2) { + double rmse = 0.0; + for (int i = 0; i < v1.length; i++) { + rmse += (v1[i] - v2[i]) * (v1[i] - v2[i]); + } + return Math.sqrt(rmse / (double) v1.length); + } + + public static double rootMeanSquareError(float[] v1, float[] v2) { + double rmse = 0.0; + for (int i = 0; i < v1.length; i++) { + rmse += (v1[i] - v2[i]) * (v1[i] - v2[i]); + } + return Math.sqrt(rmse / (double) v1.length); + } +} diff --git a/src/main/java/cct/math/TYPE.java b/src/main/java/cct/math/TYPE.java new file mode 100644 index 0000000..3df6065 --- /dev/null +++ b/src/main/java/cct/math/TYPE.java @@ -0,0 +1,16 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.math; + +/** + * + * @author vvv900 + */ +public enum TYPE { + VARIABLE, LOCAL_VARIABLE, FUNCTION, OPERATION_ADD, OPERATION_SUB, OPERATION_MUL, OPERATION_DIV, OPERATION_POWER, + LEFT_PARANTHESIS, + RIGHT_PARANTHESIS, COMMA +} diff --git a/src/main/java/cct/math/ValueOutOfBoundsException.java b/src/main/java/cct/math/ValueOutOfBoundsException.java new file mode 100644 index 0000000..a116d0b --- /dev/null +++ b/src/main/java/cct/math/ValueOutOfBoundsException.java @@ -0,0 +1,24 @@ +package cct.math; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class ValueOutOfBoundsException + extends Exception { + public ValueOutOfBoundsException() { + super(); + } + + public ValueOutOfBoundsException(String message) { + super(message); + } +} diff --git a/src/main/java/cct/math/VolumeData.java b/src/main/java/cct/math/VolumeData.java new file mode 100644 index 0000000..f771103 --- /dev/null +++ b/src/main/java/cct/math/VolumeData.java @@ -0,0 +1,341 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.math; + +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.prefs.Preferences; + +import javax.swing.JFileChooser; + +import cct.GlobalConstants; +import cct.tools.FileFilterImpl; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public abstract class VolumeData + implements GlobalConstants { + + protected String commentLine_1 = null, commentLine_2 = null; + + protected float dataOrigin[] = new float[3]; + protected int numberOfVoxels[] = new int[3]; + protected float axisVectors[][] = new float[3][3]; + + protected int nVolumetrics = 1; + protected int labels[] = null; + protected double data[][][][] = null; + + protected float minFValue = 0, maxFValue = 0; + + private static final String RAW_FILE_DESCRIPTION = "Raw Volume Data (*.raw)"; + + private static String lastPWDKey = "lastPWD"; + private Preferences prefs = Preferences.userNodeForPackage(getClass()); + private File currentWorkingDirectory = null; + private JFileChooser chooser = null; + protected FileFilterImpl[] filters = null; + + public VolumeData() { + filters = new FileFilterImpl[1]; + + filters[0] = new FileFilterImpl(); + filters[0].addExtension("raw"); + filters[0].addExtension("RAW"); + filters[0].setDescription(RAW_FILE_DESCRIPTION); + } + + public javax.swing.filechooser.FileFilter[] getDefaultSaveFileFilters() { + return filters; + } + + public abstract void parseVolumetricData(String filename) throws Exception; + + public float[] getDataOrigin() { + return dataOrigin; + } + + public int[] getNumberOfVoxels() { + return numberOfVoxels; + } + + public float[][] getAxisVectors() { + return axisVectors; + } + + public double[][][] getVolumetricData() { + return data[0]; + } + + public double[][][] getVolumetricData(int n) { + return data[n]; + } + + public void removeVolumetricData(int n) { + + if (nVolumetrics < 1) { + System.err.println("removeVolumetricData: nVolumetrics < 1"); + return; + } + + if (n < 0 || n >= nVolumetrics) { + System.err.println("removeVolumetricData: n < 0 || n>= nVolumetrics"); + return; + } + + if (nVolumetrics == 1) { + data = null; + nVolumetrics = 0; + return; + } + + double[][][][] newData = new double[data.length - 1][][][]; + for (int i = 0, j = 0; i < data.length; i++) { + if (i != n) { + newData[j] = data[i]; + ++j; + } + } + --nVolumetrics; + + data = newData; + newData = null; + } + + public int countCubes() { + return nVolumetrics; + } + + public String getCubeLabel(int n) { + if (n < 0 || n >= nVolumetrics) { + System.err.println(this.getClass().getCanonicalName() + " getVolumetricLabel: n<0 || n>=nVolumetrics"); + return null; + } + if (labels == null) { + return ""; + } + return "MO: " + String.valueOf(labels[n]); + } + + public String getTitle() { + return this.commentLine_1; + } + + public String getCubeDescription() { + return this.commentLine_2; + } + + public float getMinFunValue() { + return minFValue; + } + + public float getMaxFunValue() { + return maxFValue; + } + + public void checkCubeNumber(int n) throws Exception { + if (nVolumetrics < 1) { + System.err.println("saveVolumeData: nVolumetrics < 1"); + throw new Exception("saveVolumeData: nVolumetrics < 1"); + } + + if (n < 0 || n >= nVolumetrics) { + System.err.println("saveVolumeData: n < 0 || n>=nVolumetrics"); + throw new Exception("saveVolumeData: n < 0 || n>=nVolumetrics"); + } + } + + public void saveVolumeData(int n) throws Exception { + + checkCubeNumber(n); + + if (chooser == null) { + chooser = new JFileChooser(); + for (int i = 0; i < filters.length; i++) { + chooser.addChoosableFileFilter(filters[i]); + } + } + + chooser.setDialogTitle("Save Volume Data File"); + chooser.setDialogType(JFileChooser.SAVE_DIALOG); + + if (currentWorkingDirectory != null) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } + else { + String lastPWD = prefs.get(lastPWDKey, ""); + if (lastPWD.length() > 0) { + currentWorkingDirectory = new File(lastPWD); + if (currentWorkingDirectory.isDirectory() && currentWorkingDirectory.exists()) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } + } + } + + int returnVal = JFileChooser.CANCEL_OPTION; + + returnVal = chooser.showSaveDialog(null); + + if (returnVal == JFileChooser.CANCEL_OPTION) { + return; + } + + if (returnVal == JFileChooser.APPROVE_OPTION) { + + javax.swing.filechooser.FileFilter selectedFilter = chooser.getFileFilter(); + String fileName = chooser.getSelectedFile().getPath(); + + if (selectedFilter.getDescription().equals(RAW_FILE_DESCRIPTION)) { + + } + else { + throw new Exception("Unknown volume data file description: " + selectedFilter.getDescription()); + } + + currentWorkingDirectory = chooser.getCurrentDirectory(); + try { + prefs.put(lastPWDKey, currentWorkingDirectory.getAbsolutePath()); + } + catch (Exception ex) { + System.err.println("Cannot save cwd: " + ex.getMessage() + " Ignored..."); + } + + saveVolumeData(n, fileName, selectedFilter.getDescription()); + } + } + + public void saveVolumeData(int n, String file_name, String format) throws Exception { + if (format.equals(RAW_FILE_DESCRIPTION)) { + + if (file_name.endsWith(".")) { + file_name += "raw"; + } + else if (!file_name.endsWith(".raw") && !file_name.endsWith(".RAW")) { + file_name += ".raw"; + } + + try { + FileOutputStream fos = new FileOutputStream(file_name); + // Wrap the FileOutputStream with a DataOutputStream + DataOutputStream data_out = new DataOutputStream(fos); + data_out.writeByte(8); // --- float - 4 bytes per voxel + data_out.writeInt(numberOfVoxels[0]); // --- NX + data_out.writeInt(numberOfVoxels[1]); // --- NY + data_out.writeInt(numberOfVoxels[2]); // --- NZ + // --- volume data is the complete volumetric data with Z as the fastest varying loop index. + for (int i = 0; i < numberOfVoxels[0]; i++) { + for (int j = 0; j < numberOfVoxels[1]; j++) { + for (int k = 0; k < numberOfVoxels[2]; k++) { + data_out.writeFloat( (float) data[n][i][j][k]); + } + } + } + data_out.close(); + } + catch (Exception ex) { + throw new Exception("Error saving " + file_name + " : " + ex.getMessage()); + } + } + else { + throw new Exception("Unknown volume data file format: " + format); + } + + } + + public void getNormalizedHistogram(double[] x, double[] y, int nBins, int n) throws Exception { + getHistogram(x, y, nBins, n); + double norm = numberOfVoxels[0] * numberOfVoxels[1] * numberOfVoxels[2]; + for (int i = 0; i < nBins; i++) { + y[i] /= norm; + } + } + + public void getHistogram(double[] x, double[] y, int nBins, int n) throws Exception { + checkCubeNumber(n); + + // -- Find min & max function values + double fmin = data[n][0][0][0]; + double fmax = data[n][0][0][0]; + + for (int i = 0; i < numberOfVoxels[0]; i++) { + for (int j = 0; j < numberOfVoxels[1]; j++) { + for (int k = 0; k < numberOfVoxels[2]; k++) { + if (fmin > data[n][i][j][k]) { + fmin = data[n][i][j][k]; + } + else if (fmax < data[n][i][j][k]) { + fmax = data[n][i][j][k]; + } + } + } + } + + double width = (fmax - fmin) / nBins; + for (int i = 0; i < nBins; i++) { + x[i] = fmin + width * i; + y[i] = 0; + } + + for (int i = 0; i < numberOfVoxels[0]; i++) { + for (int j = 0; j < numberOfVoxels[1]; j++) { + for (int k = 0; k < numberOfVoxels[2]; k++) { + int index = (int) ( (data[n][i][j][k] - fmin) / width); + if (index >= nBins) { + index = nBins - 1; + } + ++y[index]; + } + } + } + } + + public static void main(String[] args) { + //VolumeData volumedata = new VolumeData(); + } +} diff --git a/src/main/java/cct/math/expparser/ClassInterface.java b/src/main/java/cct/math/expparser/ClassInterface.java new file mode 100644 index 0000000..9cb4fc4 --- /dev/null +++ b/src/main/java/cct/math/expparser/ClassInterface.java @@ -0,0 +1,58 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.math.expparser; + +/** + * + * @author vvv900 + */ +public interface ClassInterface { + + ClassInterface ciAllocateClass(Object[] args) throws Exception; + + Object ciExecuteMethod(String method, Object[] args) throws Exception; + + String ciGetName(); + + void ciSetName(String name) throws Exception; + + String[] ciGetAllMethods(); + + boolean ciHasMethod(String methodName); + + void ciSetExpressionParser(ExpressionParser expressionParser); +} diff --git a/src/main/java/cct/math/expparser/ExpressionParser.java b/src/main/java/cct/math/expparser/ExpressionParser.java new file mode 100644 index 0000000..8e983f6 --- /dev/null +++ b/src/main/java/cct/math/expparser/ExpressionParser.java @@ -0,0 +1,1602 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.math.expparser; + +import cct.math.*; +import static cct.math.expparser.SYMBOL_TYPE.CLASS; +import static cct.math.expparser.SYMBOL_TYPE.VARIABLE; +import cct.tools.Utils; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.Stack; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Pattern; + +/** + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +//enum PREDEFINED_FUNCTION { +// SQRT, sqrt, SIN, sin, COS, cos, TAN, tan, ASIN, asin, ACOS, acos, ATAN, atan, EXP, exp, LOG, log; +//} +enum SEPARATOR { + + COMMA +} + +public class ExpressionParser { + + protected String EXP_PARSER_PROPERTY_FILE = ExpressionParser.class.getCanonicalName(); + protected String EXP_PARSER_TYPES_PROPERTY_FILE = ExpressionParser.class.getCanonicalName(); + static final double DEGREES_TO_RADIANS = Math.PI / 180.0; + static private Set stringSeparators = new HashSet(); + + protected char[] validSeparators = {'+', '-', '*', '/', '^', '(', ')', ','}; + + private Map validOperators = new HashMap(); + private Map validOperations = new HashMap(); + private static final Map Parantheses = new HashMap(2); + private Map definedFunctions = new HashMap(); + private Map definedClasses = new HashMap(); + private Pattern objectTypeDeclaration; + private Set dataTypes = new HashSet(); + private Stack ifStack = new Stack(); + private int lineNumber = 0; + + static { + + Parantheses.put("(", PARANTHESIS.LEFT); + Parantheses.put(")", PARANTHESIS.RIGHT); + + stringSeparators.add("\""); + //stringSeparators.add('\"'); + } + + private static String Delimiters = " \t"; + private boolean caseSensitive = false; + private boolean allowRedefineVariables = true; + private boolean inRadians = true; + private Properties expressionParserProperties = null; + + private int ifStatementDepth = 0; + + Map IDs = new HashMap(); + static final Logger logger = Logger.getLogger(ExpressionParser.class.getCanonicalName()); + + //MathExpressionParser hiddenInit = new MathExpressionParser(true); // !!! + private ExpressionParser(boolean something) { + + } + + public ExpressionParser() { + EXP_PARSER_PROPERTY_FILE = EXP_PARSER_PROPERTY_FILE.replaceAll("[.]", "/") + ".properties"; + EXP_PARSER_TYPES_PROPERTY_FILE = EXP_PARSER_TYPES_PROPERTY_FILE.replaceAll("[.]", "/") + "Types.properties"; + + validOperators.put("!", OPERATION.Unary_logical_negation); + validOperators.put("+", OPERATION.ADD); + validOperators.put("-", OPERATION.SUBSTRACT); + validOperators.put("*", OPERATION.MULTIPLY); + validOperators.put("/", OPERATION.DEVIDE); + validOperators.put("^", OPERATION.POWER); + validOperators.put("%", OPERATION.MODULUS); + validOperators.put("<", OPERATION.Relational_less_than); + validOperators.put("<=", OPERATION.Relational_less_than_or_equal); + validOperators.put(">", OPERATION.Relational_greater_than); + validOperators.put(">=", OPERATION.Relational_greater_than_or_equal); + validOperators.put("instanceof", OPERATION.Type_comparison); + validOperators.put("==", OPERATION.Relational_is_equal_to); + validOperators.put("!=", OPERATION.Relational_is_not_equal_to); + validOperators.put("&", OPERATION.Bitwise_AND); + //validOperators.put("^", OPERATION.Bitwise_AND); + validOperators.put("|", OPERATION.Bitwise_inclusive_OR); + validOperators.put("&&", OPERATION.Logical_AND); + validOperators.put("||", OPERATION.Logical_OR); + validOperators.put("?", OPERATION.Ternary_conditional); + + validOperations.put("+", SYMBOL_TYPE.OPERATION_ADD); + validOperations.put("-", SYMBOL_TYPE.OPERATION_SUB); + validOperations.put("*", SYMBOL_TYPE.OPERATION_MUL); + validOperations.put("/", SYMBOL_TYPE.OPERATION_DIV); + validOperations.put("^", SYMBOL_TYPE.OPERATION_POWER); + + try { + this.addSymbol("true", new Variable("true", new Boolean(true), true)); + this.addSymbol("TRUE", new Variable("TRUE", new Boolean(true), true)); + this.addSymbol("false", new Variable("false", new Boolean(false), true)); + this.addSymbol("FALSE", new Variable("FALSE", new Boolean(false), true)); + this.addSymbol("PI", new Variable("PI", new Double(Math.PI), true)); + this.addSymbol("E", new Variable("E", new Double(Math.E), true)); + } catch (Exception ex) { + } + + logger.setLevel(Level.WARNING); + + try { + expressionParserProperties = getProperties(); + } catch (Exception ex) { + logger.log(Level.WARNING, null, ex); + } + + try { + addFunctionDefenitions(expressionParserProperties); + } catch (Exception ex) { + logger.log(Level.SEVERE, null, ex); + } + + // ---- + try { + Properties props = Utils.getProperties(EXP_PARSER_TYPES_PROPERTY_FILE); + addClassesDefenitions(props); + } catch (Exception ex) { + logger.log(Level.SEVERE, null, ex); + } + } + + public void addClassesDefenitions(Properties classesProperties) throws Exception { + if (classesProperties == null) { + return; + } + for (Map.Entry entry : classesProperties.entrySet()) { + String name = entry.getKey().toString(); + String className = entry.getValue().toString(); + + Class builderClass = null; + ClassLoader loader = null; + try { + // Get the Class object associated with builder + builderClass = Class.forName(className); + + // Get the ClassLoader object associated with this Class. + loader = builderClass.getClassLoader(); + + if (loader == null) { + logger.severe("loader == null while attempting to load class " + className + " Ignored..."); + continue; + } else { + // Verify that this ClassLoader is associated with the builder class. + Class loaderClass = loader.getClass(); + + if (logger.isLoggable(Level.INFO)) { + logger.info("Class associated with ClassLoader: " + loaderClass.getName()); + } + } + } catch (ClassNotFoundException ex) { + logger.severe("Cannot load class " + className + " : " + ex.getMessage() + " Ignored..."); + continue; + } + + try { + Class cl = loader.loadClass(className); + Object obj = cl.newInstance(); + if (logger.isLoggable(Level.INFO)) { + logger.info("Classr " + className + " was loaded"); + } + // ---- + if (!(obj instanceof ClassInterface)) { + logger.severe("Class " + className + " does not implement " + ClassInterface.class.getName() + + " interface. Ignored..."); + continue; + } + // ---- + ClassInterface ci = (ClassInterface) obj; + ci.ciSetName(name); + ci.ciSetExpressionParser(this); + definedClasses.put(name, ci); + } catch (Exception ex) { + logger.severe("Error while loading Class " + className + ex.getMessage() + " Ignored..."); + continue; + } + dataTypes.add(name); + } + // --- + StringBuilder sb = new StringBuilder(); + sb.append("("); + for (String type : dataTypes) { + if (sb.length() > 1) { + sb.append("|"); + } + sb.append(type); + } + sb.append(")"); + String pattern = "\\s*" + sb.toString() + "\\s*?(\\[\\w+\\])*+\\s+\\w+([(].*[)])*?"; + System.out.println("Type definition pattern: " + pattern); + objectTypeDeclaration = Pattern.compile(pattern); + } + + public void addFunctionDefenitions(Properties funProperties) throws Exception { + if (funProperties == null) { + return; + } + for (Map.Entry entry : funProperties.entrySet()) { + String name = entry.getKey().toString(); + String className = entry.getValue().toString(); + + Class builderClass = null; + ClassLoader loader = null; + try { + // Get the Class object associated with builder + builderClass = Class.forName(className); + + // Get the ClassLoader object associated with this Class. + loader = builderClass.getClassLoader(); + + if (loader == null) { + logger.severe("loader == null while attempting to load class " + className + " Ignored..."); + throw new Exception("loader == null while attempting to load class " + className + " Ignored..."); + } else { + // Verify that this ClassLoader is associated with the builder class. + Class loaderClass = loader.getClass(); + + if (logger.isLoggable(Level.INFO)) { + logger.info("Class associated with ClassLoader: " + loaderClass.getName()); + } + } + } catch (ClassNotFoundException ex) { + logger.severe("Cannot load class " + className + " : " + ex.getMessage() + " Ignored..."); + throw new Exception("Cannot load class " + className + " : " + ex.getMessage() + " Ignored..."); + } + + try { + Class cl = loader.loadClass(className); + Object obj = cl.newInstance(); + if (logger.isLoggable(Level.INFO)) { + logger.info("Classr " + className + " was loaded"); + } + // ---- + if (!(obj instanceof FunctionInterface)) { + logger.severe("Class " + className + " does not implement " + FunctionInterface.class.getName() + + " interface. Ignored..."); + throw new Exception("Class " + className + " does not implement " + FunctionInterface.class.getName() + + " interface. Ignored..."); + } + // ---- + FunctionInterface fi = (FunctionInterface) obj; + fi.fiSetName(name); + fi.fiSetExpressionParser(this); + definedFunctions.put(name, fi); + } catch (Exception ex) { + logger.severe("Error while loading Class " + className + ex.getMessage() + " Ignored..."); + throw new Exception("Error while loading Class " + className + ex.getMessage() + " Ignored..."); + } + + } + } + + public boolean isInRadians() { + return inRadians; + } + + public boolean isInDegrees() { + return !inRadians; + } + + public boolean isNumber(Object obj) { + if (obj == null) { + return false; + } + if (obj instanceof Number) { + return true; + } + + try { + Integer num = Integer.parseInt(obj.toString()); + return true; + } catch (Exception ex) { + + } + try { + Double num = Double.parseDouble(obj.toString()); + return true; + } catch (Exception ex) { + + } + return false; + } + + public Number getNumber(Object obj) throws Exception { + if (obj == null) { + throw new Exception("Cannot convert null object into a number"); + } + if (obj instanceof Number) { + return (Number) obj; + } + + try { + Integer num = Integer.parseInt(obj.toString()); + return num; + } catch (Exception ex) { + + } + try { + Double num = Double.parseDouble(obj.toString()); + return num; + } catch (Exception ex) { + + } + throw new Exception("Object " + obj.toString() + " is not a number"); + } + + public Properties getProperties() throws Exception { + + expressionParserProperties = Utils.getProperties(EXP_PARSER_PROPERTY_FILE); + return expressionParserProperties; + } + + public boolean isAllowRedefineVariables() { + return allowRedefineVariables; + } + + public void setAllowRedefineVariables(boolean allowRedefineVariables) { + this.allowRedefineVariables = allowRedefineVariables; + } + + public boolean hasSymbol(String symbol) { + if ((symbol != null) && (!caseSensitive)) { + symbol = symbol.toUpperCase(); + } + return IDs.containsKey( symbol ) || definedFunctions.containsKey( symbol ); + } + + public boolean hasObjectType(String symbol) { + if (!caseSensitive) { + symbol = symbol.toUpperCase(); + } + return this.definedClasses.containsKey( symbol ); + } + + public Object getObjectTypeInstance(String symbol) throws Exception { + if (!this.definedClasses.containsKey(symbol)) { + throw new Exception("Cannot allocate variable of unknown type: " + symbol); + } + return definedClasses.get(symbol).ciAllocateClass(null); + } + + public Object getSymbol(String symbol) { + if (!caseSensitive) { + symbol = symbol.toUpperCase(); + } + if (IDs.containsKey(symbol)) { + return IDs.get(symbol); + } else if (definedFunctions.containsKey(symbol)) { + return definedFunctions.get(symbol); + } + return null; + } + + public void setInDegrees(boolean in_degrees) { + inRadians = !in_degrees; + } + + public void setInRadians(boolean in_radians) { + inRadians = in_radians; + } + + public boolean isObjectTypeDeclaration(String line) { + return objectTypeDeclaration.matcher(line).matches(); + } + + public boolean addLine(String line) throws Exception { + ++lineNumber; + + line = line.trim(); + if (line.length() < 1) { + return true; + } + + if (line.matches("\\s*if.*")) { + if (line.matches("\\s*if\\s*[(].+[)]\\s*then\\s*")) { // If block statement starts + System.out.println("Start of if block"); + ++ifStatementDepth; + String expression = line.substring(line.indexOf("(") + 1, line.lastIndexOf(")")).trim(); + Object result = resolveExpression(expression); + boolean ifTrue = false; + if (result == null) { + ifTrue = false; + } else if (result instanceof Boolean) { + ifTrue = (Boolean) result; + } else if (result instanceof Number) { + ifTrue = !(((Number) result).doubleValue() == 0); + } else { + ifTrue = true; + } + ifStack.push(ifTrue); + return true; + } else if (line.matches("\\s*else\\s*if\\s*[(].+[)]\\s*then\\s*")) { // else if block statement starts + + } else if (line.matches("\\s*else\\s*")) { // else block statement starts + + } else if (line.matches("\\s*endif\\s*")) { // endif of if block statement + + } + + } + + if (!ifStack.empty() && !ifStack.peek()) { + System.out.println("Skip line: \"" + line + "\" because of previous if condition"); + return true; + } + + // --- Check for variable declaration + if (isObjectTypeDeclaration(line)) { + System.out.println("Found variable declaration: " + line); + parseObjectTypeDeclaration(line); + return true; + } + + if (!line.matches("\\s*\\w+([(].*[)])?\\s*([+]=|-=|[*]=|/=|[%]=|=)\\s*.*")) { + throw new Exception("Constant or function should be defined using = (equal) sign. Got: " + line); + } + + if ((line.indexOf("=") == line.length() - 1) || line.substring(line.indexOf("=") + 1).trim().length() == 0) { + throw new Exception("Should be expression after the = (equal) sign. Got: " + line); + } + + if (!caseSensitive) { + line = line.toUpperCase(); + } + + boolean newOperator = false; + if (line.matches("\\w+\\s*=\\s*(new|NEW)\\s+\\w+.*")) { + System.out.println("New Operator: " + line); + newOperator = true; + } + // --- Get id name + String operator = null; + String id = line.substring(0, line.indexOf("=")).trim(); + if (id.matches(".*([+]|-|[*]|/|%){1}$")) { + operator = id.substring(id.length() - 1); + id = id.substring(0, id.length() - 1); + } + + String expression = line.substring(line.indexOf("=") + 1).trim(); + expression = expression.replaceAll("[*][*]", "^"); + + if (newOperator) { + System.err.println("New Operator is not implemented yet"); + if (expression.contains("new")) { + expression = line.substring(line.indexOf("new") + 3).trim(); + } else if (expression.contains("NEW")) { + expression = line.substring(line.indexOf("NEW") + 3).trim(); + } + allocateClass(id, expression); + } else if (id.matches(".+[(].+[)]")) { // Function + parseFunction(id, expression); + //throw new Exception("Definition of functions is not implemented yet"); + } else if (!id.contains("(") && !id.contains(")") && !id.contains(",")) { // Constant + if (this.hasSymbol(id) && (!this.allowRedefineVariables)) { + throw new Exception("Identifier " + id + " is already defined"); + } + addSymbol(id, null); + parseConstant(id, expression); + } else { + throw new Exception("Unknown type of identifier. Should be a constant or a function. Got " + line); + } + return true; + //StringTokenizer st = new StringTokenizer(line, " =,"); + } + + void parseFunction(String definition, String expression) throws Exception { + + Function function; + try { + function = new Function(definition, this); + //function.setExpressionParser(this); + function.setFunctionBody(expression); + } catch (Exception ex) { + throw new Exception(definition + " : " + ex.getMessage()); + } + + if (definedFunctions.containsKey(function.getInternalName())) { + throw new Exception("Function " + function.getName() + " with " + function.getArgsNumber() + + " parameters is already defined"); + } + + definedFunctions.put(function.getInternalName(), function); + + } + + void allocateClass(String name, String expression) throws Exception { + Object obj = this.resolveExpression(expression); + Variable var = new Variable(name, SYMBOL_TYPE.CLASS); + var.setValue(obj); + addSymbol(name, var); + logger.info(name + " = " + (var.getValue() != null ? var.getValue().toString() : var.getValue())); + } + + void parseConstant(String name, String expression) throws Exception { + Object obj = resolveExpression(expression); + Variable var = new Variable(name, SYMBOL_TYPE.VARIABLE); + var.setValue(obj); + addSymbol(name, var); + logger.info(name + " = " + (var.getValue() != null ? var.getValue().toString() : var.getValue())); + } + + void parseObjectTypeDeclaration(String line) throws Exception { + + List Tokens = new ArrayList(); + List tokenTypes = new ArrayList(); + + resolveTokens(line, Tokens, tokenTypes); + + if (Tokens.get(0).getType() != CLASS) { + throw new Exception("The first token must be a valid data type. Unknown data type: " + Tokens.get(0).getName()); + } + + String type = Tokens.get(0).getName(); + if (!hasObjectType(type)) { // Double check + throw new Exception("Unknown Object type declaration: " + type); + } + + // --- For now we don't process arrays... + if (Tokens.get(1).getType() == VARIABLE) { + String varName = Tokens.get(1).getName(); + Variable var = new Variable(varName, SYMBOL_TYPE.VARIABLE); + var.setValue(getObjectTypeInstance(type)); + addSymbol(varName, var); + } else if (Tokens.get(1).getType() == SYMBOL_TYPE.FUNCTION) { + //File file("filename") -> file File("filename") + Variable constructor = Tokens.get(0); + Variable var = Tokens.get(1); + Tokens.remove(var); + Tokens.get(0).setType(SYMBOL_TYPE.FUNCTION); + Object obj = evaluateFunction(Tokens); + var.setValue(obj); + var.setType(SYMBOL_TYPE.VARIABLE); + addSymbol(var.getName(), var); + } + + if (false) { + String[] tokens = line.split("\\s+"); + if (tokens.length < 2) { + throw new Exception("Object type declaration should cocnsist of at least two tokens. Got: " + line); + } + type = tokens[0]; + if (!hasObjectType(type)) { + throw new Exception("Unknown Object type declaration: " + type); + } + String varName = tokens[1]; + Variable var = new Variable(varName, SYMBOL_TYPE.VARIABLE); + var.setValue(getObjectTypeInstance(type)); + addSymbol(varName, var); + } + } + + public void addVariable(String name, double value) throws Exception { + if (!caseSensitive) { + name = name.toUpperCase(); + } + Variable var = new Variable(name, SYMBOL_TYPE.VARIABLE); + try { + var.setValue(value); + } catch (Exception ex) { + } + addSymbol(name, var); + logger.info("Added variable: " + name + " = " + (var.getValue() != null ? var.getValue().toString() : var.getValue())); + } + + public Object getVariable(String name) throws Exception { + Object obj = this.getSymbol(name); + if (obj == null) { + throw new Exception("No such symbol " + name); + } + return obj; + } + + public double getVariableAsDouble(String name) throws Exception { + Object obj = getVariable(name); + if (obj instanceof Number) { + return ((Number) obj).doubleValue(); + } else if (obj instanceof Variable) { + Object value = ((Variable) obj).getValue(); + if (value == null) { + throw new Exception("Variable " + name + " is not set"); + } + if (value instanceof Number) { + return ((Number) value).doubleValue(); + } + } + throw new Exception("Variable " + name + " cannot be converted into a double value"); + } + + public void addSymbol(String name, Object value) throws Exception { + if (IDs.containsKey(name) && IDs.get(name) instanceof Variable && ((Variable) IDs.get(name)).isConstant()) { + throw new Exception(name + " is a reserved constant and cannot be changed"); + } + IDs.put(name, value); + logger.info("Added symbol: " + name + " = " + (value != null ? value.toString() : "null")); + } + + public boolean isDataType(String symbolic) { + if (symbolic == null) { + return false; + } + return this.definedClasses.containsKey(symbolic); + } + + private void processSymbolicConstant(String symbolic, List Tokens, List tokenTypes, List tokens) + throws Exception { + if (!caseSensitive) { + symbolic = symbolic.toUpperCase(); + } + if (isDataType(symbolic)) { + Tokens.add(new Variable(symbolic, SYMBOL_TYPE.CLASS)); + tokenTypes.add(SYMBOL_TYPE.CLASS); + tokens.add(symbolic); + return; + } + // --- + if (this.hasSymbol(symbolic)) { // if it's a defined variable or a function + Variable var = (Variable) getSymbol(symbolic); + Tokens.add(var); + } else if (this.isNumber(symbolic)) { // Is it a number + Number num = this.getNumber(symbolic); + Variable var = new Variable(num); + Tokens.add(var); + } else { //Probably it's a local variable + Tokens.add(new Variable(symbolic, SYMBOL_TYPE.VARIABLE)); + //throw new Exception("Variable " + variable + " is not defined"); + } + + tokenTypes.add(SYMBOL_TYPE.VARIABLE); + tokens.add(symbolic); + } + + void resolveTokens(String expression, List Tokens, List tokenTypes) throws Exception { + Tokens.clear(); + tokenTypes.clear(); + + List tokens = new ArrayList(); + int leftParantheses = 0, rightParantheses = 0; + int leftSquareBrackets = 0; + + boolean buildingID = false; + boolean buildingString = false; + String symbol = null; + StringBuilder variable = new StringBuilder(); + for (int i = 0; i < expression.length(); i++) { + //expression.charAt(i); + symbol = expression.substring(i, i + 1); + + if (Delimiters.contains(symbol)) { + if (buildingString) { + variable.append(symbol); + } else if (buildingID) { + buildingID = false; + processSymbolicConstant(variable.toString(), Tokens, tokenTypes, tokens); + variable.delete(0, variable.length()); + } + continue; + } + + // --- Math operator + if (validOperators.containsKey(symbol) && (!buildingString)) { + if (buildingID) { + buildingID = false; + processSymbolicConstant(variable.toString(), Tokens, tokenTypes, tokens); + variable.delete(0, variable.length()); + } + Tokens.add(new Variable(validOperators.get(symbol), validOperations.get(symbol))); + tokenTypes.add(validOperations.get(symbol)); + tokens.add(validOperators.get(symbol)); + } else if (symbol.equals("(") && (!buildingString)) { + ++leftParantheses; + if (buildingID) { + buildingID = false; + Tokens.add(new Variable(variable.toString(), SYMBOL_TYPE.FUNCTION)); + tokenTypes.add(SYMBOL_TYPE.FUNCTION); + tokens.add(variable.toString()); + variable.delete(0, variable.length()); + } + Tokens.add(new Variable(Parantheses.get(symbol), SYMBOL_TYPE.LEFT_PARANTHESIS)); + tokenTypes.add(SYMBOL_TYPE.LEFT_PARANTHESIS); + tokens.add(Parantheses.get(symbol)); + } else if (symbol.equals(")") && (!buildingString)) { + ++rightParantheses; + if (buildingID) { + buildingID = false; + processSymbolicConstant(variable.toString(), Tokens, tokenTypes, tokens); + variable.delete(0, variable.length()); + } + Tokens.add(new Variable(Parantheses.get(symbol), SYMBOL_TYPE.RIGHT_PARANTHESIS)); + tokenTypes.add(SYMBOL_TYPE.RIGHT_PARANTHESIS); + tokens.add(Parantheses.get(symbol)); + } else if (symbol.equals(",") && (!buildingString)) { + if (buildingID) { + buildingID = false; + processSymbolicConstant(variable.toString(), Tokens, tokenTypes, tokens); + variable.delete(0, variable.length()); + } + Tokens.add(new Variable(SYMBOL_TYPE.COMMA)); + tokenTypes.add(SYMBOL_TYPE.COMMA); + tokens.add(SEPARATOR.COMMA); + + } else if (symbol.equals("[") && (!buildingString)) { + ++leftSquareBrackets; + if (buildingID) { + buildingID = false; + processSymbolicConstant(variable.toString(), Tokens, tokenTypes, tokens); + variable.delete(0, variable.length()); + } + Tokens.add(new Variable(SYMBOL_TYPE.LEFT_SQUARE_BRACKET)); + tokenTypes.add(SYMBOL_TYPE.LEFT_SQUARE_BRACKET); + tokens.add(SYMBOL_TYPE.LEFT_SQUARE_BRACKET); + } else if (symbol.equals("])") && (!buildingString)) { + --leftSquareBrackets; + if (buildingID) { + buildingID = false; + processSymbolicConstant(variable.toString(), Tokens, tokenTypes, tokens); + variable.delete(0, variable.length()); + } + Tokens.add(new Variable(SYMBOL_TYPE.RIGHT_SQUARE_BRACKET)); + tokenTypes.add(SYMBOL_TYPE.RIGHT_SQUARE_BRACKET); + tokens.add(SYMBOL_TYPE.RIGHT_SQUARE_BRACKET); + } else if (stringSeparators.contains(symbol) || buildingString) { + // --- Start to build a string + if (!buildingString) { + if (buildingID) { + throw new Exception("String should be separated by valid separator in expression"); + } + buildingString = true; + continue; + } + // --- appending a string + if (i != (expression.length() - 1) && expression.substring(i + 1, i + 2).equals("\"")) { + variable.append(symbol); + continue; + } + if (!stringSeparators.contains(symbol)) { + variable.append(symbol); + continue; + } + // --- End of a string definition + buildingString = false; + Variable var = new Variable(variable.toString()); + Tokens.add(var); + tokenTypes.add(var.getType()); + tokens.add(variable.toString()); + variable.delete(0, variable.length()); + continue; + } // --- Building variable name... + else { + buildingID = true; + variable.append(symbol); + } + + } + + // --- End of a loop + if (buildingID) { + processSymbolicConstant(variable.toString(), Tokens, tokenTypes, tokens); + } else if (buildingString) { + //if (!symbol.equals("\"")) { + // variable.append(symbol); + //} + Tokens.add(new Variable(variable.toString())); + tokenTypes.add(SYMBOL_TYPE.VARIABLE); + tokens.add(variable.toString()); + } + + if (rightParantheses != leftParantheses) { + throw new Exception("Expression: " + expression + "\nLeft and Right Parantheses are not balanced"); + } + if (leftSquareBrackets != 0) { + throw new Exception("Expression: " + expression + "\nLeft and Right Square Brackets are not balanced"); + } + } + + public Object resolveExpression(String expression) throws Exception { + + // --- Stupid algorithm + // --- Resolve functions (if any) + // --- Resolve expr in parantheses (if any) + //ArrayList tokens = new ArrayList(); + List Tokens = new ArrayList(); + List tokenTypes = new ArrayList(); + + resolveTokens(expression, Tokens, tokenTypes); + + // --- Resolve variables + for (int i = 0; i < Tokens.size(); i++) { + logger.info(Tokens.get(i).getName() + " " + Tokens.get(i).getType().toString()); + Variable type = Tokens.get(i); + switch (type.getType()) { + case VARIABLE: + + if (type.getName() == null) { + // --- Temporary variable + } else if (type.getName() != null && (!this.hasSymbol(type.getName()))) { + throw new Exception("Expression: " + expression + "\nVariable " + type.getName() + " is not defined"); + } + + //if (type.isNumber()) { + // continue; + //} + //Variable var = (Variable) this.getSymbol(type.getName()); + //type.setValue(var.getValue()); + break; + + case FUNCTION: + break; + } + } + + Object value; + try { + value = evaluateExpression(Tokens, tokenTypes); + } catch (Exception ex) { + throw new Exception("Expression: " + expression + "\n" + ex.getMessage()); + } + return value; + } + + /** + * We assume, no functions inside + * + * @param Tokens ArrayList + * @param tokenTypes ArrayList + * @return double + * @throws Exception + */ + //public Object evaluateFunction(List Tokens, List tokenTypes) throws Exception { + public Object evaluateFunction(List Tokens) throws Exception { + double value = 0; + + //if (tokenTypes.size() < 3) { + if (Tokens.size() < 3) { + throw new Exception("Minimal function definition should be function_name()"); + } + + //if (tokenTypes.get(0) != SYMBOL_TYPE.FUNCTION) { + if (Tokens.get(0).getType() != SYMBOL_TYPE.FUNCTION) { + throw new Exception("Function should start from funcion name. Got " + Tokens.get(0).getType().toString()); + } + //if (tokenTypes.get(1) != SYMBOL_TYPE.LEFT_PARANTHESIS) { + if (Tokens.get(1).getType() != SYMBOL_TYPE.LEFT_PARANTHESIS) { + throw new Exception("Left paranthesis should follow the funcion name. Got " + Tokens.get(1).getType().toString()); + } + //if (tokenTypes.get(tokenTypes.size() - 1) != SYMBOL_TYPE.RIGHT_PARANTHESIS) { + if (Tokens.get(Tokens.size() - 1).getType() != SYMBOL_TYPE.RIGHT_PARANTHESIS) { + throw new Exception("Right paranthesis should close funcion definition. Got " + + Tokens.get(Tokens.size() - 1).getType().toString()); + } + + // --- start to resolve arguments + //if (tokenTypes.size() == 3 && tokenTypes.get(2) != SYMBOL_TYPE.RIGHT_PARANTHESIS) { + if (Tokens.size() == 3 && Tokens.get(2).getType() != SYMBOL_TYPE.RIGHT_PARANTHESIS) { + throw new Exception("Minimal function definition should be function_name()"); + } + //List parameters = new ArrayList(); + List parameters = new ArrayList(); + List Expression = new ArrayList(); + List exprTypes = new ArrayList(); + int leftParanthesisDepth = 0; + //for (int i = 2; i < tokenTypes.size(); i++) { + for (int i = 2; i < Tokens.size(); i++) { + //if (tokenTypes.get(i) == SYMBOL_TYPE.LEFT_PARANTHESIS) { + if (Tokens.get(i).getType() == SYMBOL_TYPE.LEFT_PARANTHESIS) { + ++leftParanthesisDepth; + } else if (Tokens.get(i).getType() == SYMBOL_TYPE.RIGHT_PARANTHESIS && leftParanthesisDepth > 0) { + --leftParanthesisDepth; + } else if (Tokens.get(i - 1).getType() == SYMBOL_TYPE.LEFT_PARANTHESIS + && Tokens.get(i).getType() == SYMBOL_TYPE.RIGHT_PARANTHESIS) { + --leftParanthesisDepth; + } else if (Tokens.get(i).getType() == SYMBOL_TYPE.COMMA + || Tokens.get(i).getType() == SYMBOL_TYPE.RIGHT_PARANTHESIS) { + Object Value = evaluateExpression(Expression, exprTypes); + parameters.add(Value); + logger.info("Par: " + parameters.size() + " value: " + Value); + Expression.clear(); + exprTypes.clear(); + continue; + } + Expression.add(Tokens.get(i)); + exprTypes.add(Tokens.get(i).getType()); + } + + Object obj; + String internalName = Tokens.get(0).getName() + "_" + String.valueOf(parameters.size()); + if (definedFunctions.containsKey(Tokens.get(0).getName())) { + obj = definedFunctions.get(Tokens.get(0).getName()); + } else if (this.definedClasses.containsKey(Tokens.get(0).getName())) { + obj = definedClasses.get(Tokens.get(0).getName()); + } else if (Tokens.get(0).getName().matches("\\w+[.]\\w+")) { // Class or variable method + String[] methodsChain = Tokens.get(0).getName().split("[.]"); + if (!this.hasSymbol(methodsChain[0])) { + throw new Exception("No such variable-class " + methodsChain[0] + " in method invocation " + Tokens.get(0).getName()); + } + obj = this.getSymbol(methodsChain[0]); + return evaluateMethod(obj, methodsChain, parameters.toArray()); + } else if (definedFunctions.containsKey(internalName)) { + obj = definedFunctions.get(internalName); + } else { + throw new Exception("Function " + Tokens.get(0).getName() + " with " + parameters.size() + " parameters is not defined"); + } + + //if (obj instanceof PredefinedFun) { + // return ((PredefinedFun) obj).getValue(parameters); + //} else + if (obj instanceof Function) { + return ((Function) obj).getValue(parameters); + } else if (obj instanceof FunctionInterface) { + return ((FunctionInterface) obj).fiEvaluateFunction(parameters.toArray()); + } else if (obj instanceof ClassInterface) { + return ((ClassInterface) obj).ciAllocateClass(parameters.toArray()); + } + + throw new Exception("Unknown type of Function " + obj.getClass().getCanonicalName()); + } + + Object evaluateMethod(Object obj, String[] tokens, Object[] args) throws Exception { + if (obj == null) { + throw new Exception("Variable-class " + tokens[0] + " is not defined"); + } + Object varC = obj; + if (obj instanceof Variable) { + varC = ((Variable) obj).getValue(); + } + if (varC == null) { + throw new Exception("Variable-class " + tokens[0] + " is not defined"); + } + + if (!(varC instanceof ClassInterface)) { + throw new Exception("Variable-class " + tokens[0] + " is not an instanceof ClassInterface"); + } + + ClassInterface ci = (ClassInterface) varC; + if (!ci.ciHasMethod(tokens[1])) { + throw new Exception("Variable-class " + tokens[0] + " does not have method " + tokens[1]); + } + return ci.ciExecuteMethod(tokens[1], args); + } + + Object evaluateExpression(List Tokens, List tokenTypes) throws Exception { + //Object evaluateExpression(List Tokens ) throws Exception { + Object value = null; + + if (Tokens.size() == 1) { + if (Tokens.get(0).getType() == SYMBOL_TYPE.VARIABLE || Tokens.get(0).getType() == SYMBOL_TYPE.LOCAL_VARIABLE) { + return Tokens.get(0).getValue(); + } + throw new Exception("Single token must be either a variable or a number"); + } + + while (Tokens.size() > 1) { + + if (tokenTypes.contains(SYMBOL_TYPE.FUNCTION)) { + List Expression = new ArrayList(); + List exprTypes = new ArrayList(); + int index = tokenTypes.lastIndexOf(SYMBOL_TYPE.FUNCTION); + int end, leftParanthesisDepth = -1; + + logger.info("Resolving function " + Tokens.get(index).getName()); + + for (end = index; end < tokenTypes.size(); end++) { + logger.info(end + " " + Tokens.get(end).getType()); + Expression.add(Tokens.get(end)); + exprTypes.add(Tokens.get(end).getType()); + if (tokenTypes.get(end) == SYMBOL_TYPE.LEFT_PARANTHESIS) { + ++leftParanthesisDepth; + continue; + } else if (tokenTypes.get(end) == SYMBOL_TYPE.RIGHT_PARANTHESIS) { + if (leftParanthesisDepth > 0) { + --leftParanthesisDepth; + continue; + } + } + + if (tokenTypes.get(end) == SYMBOL_TYPE.RIGHT_PARANTHESIS) { + //value = evaluateFunction(Expression, exprTypes); + value = evaluateFunction(Expression); + logger.info("Function value: " + (value != null ? value.toString() : value)); + Variable result = new Variable(value); + for (int i = index; i <= end; i++) { + Tokens.remove(index); + tokenTypes.remove(index); + } + Tokens.add(index, result); + tokenTypes.add(index, result.getType()); + break; + } + + } + } else if (tokenTypes.contains(SYMBOL_TYPE.LEFT_PARANTHESIS)) { + List Expression = new ArrayList(); + List exprTypes = new ArrayList(); + ((ArrayList) Expression).ensureCapacity(Tokens.size()); + ((ArrayList) exprTypes).ensureCapacity(Tokens.size()); + + int indexEnd; + while (true) { + int indexStart = tokenTypes.lastIndexOf(SYMBOL_TYPE.LEFT_PARANTHESIS); + if (indexStart == -1) { + break; + } + + Expression.clear(); + exprTypes.clear(); + + for (indexEnd = indexStart + 1; indexEnd < Tokens.size(); indexEnd++) { + if (Tokens.get(indexEnd).getType() == SYMBOL_TYPE.RIGHT_PARANTHESIS) { + break; + } + Expression.add(Tokens.get(indexEnd)); + exprTypes.add(Tokens.get(indexEnd).getType()); + } + if (indexEnd == Tokens.size()) { + throw new Exception("Unmatched ("); + } + if (indexEnd - indexStart == 1) { + throw new Exception("No expression within parantheses"); + } + + //value = evaluateExpression(Expression, exprTypes); + Object obj = evaluateExpression(Expression, exprTypes); + Variable result = new Variable(obj); + for (int i = indexStart; i <= indexEnd; i++) { + Tokens.remove(indexStart); + tokenTypes.remove(indexStart); + } + Tokens.add(indexStart, result); + tokenTypes.add(indexStart, result.getType()); + + } + } else { + int index; + while (Tokens.size() > 1) { + // --- Power operation + index = tokenTypes.indexOf(SYMBOL_TYPE.OPERATION_POWER); + if (index != -1) { + Variable first = getToken(Tokens, index - 1); + Variable second = getToken(Tokens, index + 1); + value = Math.pow(first.getValueAsDouble(), second.getValueAsDouble()); + Variable result = new Variable(value); + Tokens.remove(index - 1); + Tokens.remove(index - 1); + Tokens.remove(index - 1); + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + + Tokens.add(index - 1, result); + tokenTypes.add(index - 1, result.getType()); + continue; + } + + // --- Division + index = tokenTypes.indexOf(SYMBOL_TYPE.OPERATION_DIV); + if (index != -1) { + Variable first = getToken(Tokens, index - 1); + Variable second = getToken(Tokens, index + 1); + value = first.getValueAsDouble() / second.getValueAsDouble(); + Variable result = new Variable(value); + Tokens.remove(index - 1); + Tokens.remove(index - 1); + Tokens.remove(index - 1); + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + + Tokens.add(index - 1, result); + tokenTypes.add(index - 1, result.getType()); + continue; + } + + // --- Multiplication + index = tokenTypes.indexOf(SYMBOL_TYPE.OPERATION_MUL); + if (index != -1) { + Variable first = getToken(Tokens, index - 1); + Variable second = getToken(Tokens, index + 1); + value = first.getValueAsDouble() * second.getValueAsDouble(); + Variable result = new Variable(value); + Tokens.remove(index - 1); + Tokens.remove(index - 1); + Tokens.remove(index - 1); + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + + Tokens.add(index - 1, result); + tokenTypes.add(index - 1, result.getType()); + continue; + } + + // --- Sub + index = tokenTypes.indexOf(SYMBOL_TYPE.OPERATION_SUB); + if (index != -1) { + Variable first; + try { + first = getToken(Tokens, index - 1); + Variable second = getToken(Tokens, index + 1); + value = first.getValueAsDouble() - second.getValueAsDouble(); + Variable result = new Variable(value); + + Tokens.remove(index - 1); + Tokens.remove(index - 1); + Tokens.remove(index - 1); + + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + + Tokens.add(index - 1, result); + tokenTypes.add(index - 1, result.getType()); + } catch (Exception ex) { + Variable second = getToken(Tokens, index + 1); + value = -second.getValueAsDouble(); + Variable result = new Variable(value); + + Tokens.remove(index); + Tokens.remove(index); + tokenTypes.remove(index); + tokenTypes.remove(index); + + Tokens.add(index, result); + tokenTypes.add(index, result.getType()); + } + continue; + } + + // --- addition + index = tokenTypes.indexOf(SYMBOL_TYPE.OPERATION_ADD); + if (index != -1) { + Variable first; + try { + first = getToken(Tokens, index - 1); + Variable second = getToken(Tokens, index + 1); + if (first.isString() || second.isString()) { + value = this.concatAsStrings(first.getValue(), second.getValue()); + } else { + value = first.getValueAsDouble() + second.getValueAsDouble(); + } + + Variable result = new Variable(value); + + Tokens.remove(index - 1); + Tokens.remove(index - 1); + Tokens.remove(index - 1); + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + tokenTypes.remove(index - 1); + + Tokens.add(index - 1, result); + tokenTypes.add(index - 1, result.getType()); + } catch (Exception ex) { + Variable second = getToken(Tokens, index + 1); + value = second.getValueAsDouble(); + Variable result = new Variable(value); + + Tokens.remove(index); + Tokens.remove(index); + tokenTypes.remove(index); + tokenTypes.remove(index); + + Tokens.add(index, result); + tokenTypes.add(index, result.getType()); + } + continue; + } + // --- Then should be << , >> and >>> operators + + throw new Exception("INTERNAL ERROR: we should not be here"); + } + if (Tokens.get(0) != null && Tokens.get(0).isNumber()) { + return Tokens.get(0).getValueAsDouble(); + } + } + } + + return value; + } + + String concatAsStrings(Object first, Object second) { + String s1 = null; + if (first instanceof String) { + s1 = (String) first; + } else if (first instanceof Number) { + if (first instanceof Double || first instanceof Float || first instanceof java.math.BigDecimal) { + s1 = String.valueOf(((Number) first).doubleValue()); + } else { + s1 = String.valueOf(((Number) first).intValue()); + } + } else if (first != null) { + s1 = first.toString(); + } + String s2 = null; + if (second instanceof String) { + s2 = (String) second; + } else if (second instanceof Number) { + if (second instanceof Double || second instanceof Float || second instanceof java.math.BigDecimal) { + s2 = String.valueOf(((Number) second).doubleValue()); + } else { + s2 = String.valueOf(((Number) second).intValue()); + } + } else if (second != null) { + s2 = second.toString(); + } + return s1 + s2; + } + + Variable getToken(List Tokens, int index) throws Exception { + if (index < 0) { + throw new Exception("No first argument in expression"); + } else if (index >= Tokens.size()) { + throw new Exception("No second argument in expression"); + } + return Tokens.get(index); + } + + public boolean isCaseSensitive() { + return caseSensitive; + } + + public void setCaseSensitive(boolean caseSensitive) { + this.caseSensitive = caseSensitive; + } + + public static void main(String[] args) { + ExpressionParser expressionparser = new ExpressionParser(); + expressionparser.setInDegrees(false); + expressionparser.caseSensitive = true; + try { + String express = null; + + express = "if (false) then"; + expressionparser.addLine(express); + + express = "List list"; + expressionparser.addLine(express); + + express = "Writer log(\"test.log\")"; + expressionparser.addLine(express); + express = "log"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + express = "println(\"Printing a Writer class object: \"+log)"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + express = "log.write(\"This is the first line: \"+log)"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + express = "log.newLine()"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + express = "log.write(\"This is the second line\")"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + express = "log.close()"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "Reader reader(\"test.log\")"; + expressionparser.addLine(express); + express = "res = reader.readLine()"; + expressionparser.addLine(express); + express = "res"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + express = "res = reader.readLine()"; + expressionparser.addLine(express); + express = "res"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + express = "reader.close()"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "true"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + express = "TRUE"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + express = "false"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + express = "FALSE"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + express = "PI"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + express = "E"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + double var1 = 10.0, var2 = 20.; + expressionparser.addVariable("var1", var1); + expressionparser.addVariable("var2", var2); + express = "var1+var2"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express) + + " Ref: " + (var1 + var2)); + + express = "sqr = sqrt(4*5)"; + expressionparser.addLine(express); + express = "sqr"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express) + + " Ref: " + Math.sqrt(4 * 5)); + + double RCH = 1.085; + express = "RCH = 1.085"; + expressionparser.addLine(express); + express = "RCH"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express) + + " Ref: " + RCH); + + double XCH = Math.sqrt(3) * (RCH / 3); + express = "XCH = sqrt(3)*(RCH/3)"; + expressionparser.addLine(express); + express = "XCH"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express) + + " Ref: " + XCH); + + express = "atan2(6,7)"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express) + + " Ref: " + Math.atan2(6, 7)); + + express = "abs(6)"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express) + + " Ref: " + Math.abs(6)); + + express = "abs(-6)"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express) + + " Ref: " + Math.abs(-6)); + + express = "cbrt(27)"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express) + + " Ref: " + Math.cbrt(27)); + + express = "cbrt(-27)"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express) + + " Ref: " + Math.cbrt(-27)); + + express = "exp(1)"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express) + + " Ref: " + Math.exp(1)); + + express = "list.add(5)"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "list.add(7)"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "list.add(0,100)"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "list.size()"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "list.isEmpty()"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "list.get(0)"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "list.get(1)"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "list.get(2)"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "list.remove(1)"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "list.size()"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "list.set(0,1006)"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "list.get(0)"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "list.clear()"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "list.size()"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "list.isEmpty()"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "exp(1+1-1)"; + expressionparser.addLine("ab = 1"); + + expressionparser.addLine("func(x,y,z) = x*ab+y**2-y*z"); + expressionparser.addLine("x = 5"); + expressionparser.addLine("y=func((3+4)*(x-2),4,5*6)+sqrt(4*5)"); + + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + express = "func(6,7,8)"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + express = "XCH"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + express = "-XCH"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "0+1"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + express = "sqr+1"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + express = "sin(10.0) + SIN(20.0)"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express) + + " Ref: " + (Math.sin(10) + Math.sin(20.0))); + // --- + express = "str = \"This is a string"; + expressionparser.addLine(express); + express = "str"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "str = \"This is a string\""; + expressionparser.addLine(express); + express = "str"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "str = \"This is a string\" + \" plus another string"; + expressionparser.addLine(express); + express = "str"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "str = \"This is a string plus a number: \" + 1001"; + expressionparser.addLine(express); + express = "str"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "str = 1001 +\" - This is a string appended to a number: \""; + expressionparser.addLine(express); + express = "str"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "str = \"This is a string plus a numerical variable (sqr): \" + sqr"; + expressionparser.addLine(express); + express = "str"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "str = \"sqr = \" + sqr"; + expressionparser.addLine(express); + express = "str"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + + express = "str = \"sqrt(900) = \" + sqrt(900)"; + expressionparser.addLine(express); + express = "str"; + System.out.println("Evaluating: " + express + " : " + expressionparser.resolveExpression(express)); + // --- + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + String line; + while (!(line = in.readLine()).equals("quit")) { + try { + line = line.trim(); + if (line.matches("\\s*\\w+\\s*=\\s*.+") || expressionparser.isObjectTypeDeclaration(line)) { + expressionparser.addLine(line); + } else { + System.out.println(expressionparser.resolveExpression(line)); + } + } catch (Exception ex) { + System.err.println(ex.getMessage()); + } + } + } catch (Exception ex) { + System.err.println(ex.getMessage()); + } + System.exit(0); + + } + + private class OpStack + extends ArrayList { + + void push(Object token) { + this.add(0, token); + } + + Object pop() { + if (this.size() == 0) { + return null; + } + Object obj = this.get(0); + this.remove(0); + return obj; + } + + } + + /** + * private class PredefinedFun { + * + * PREDEFINED_FUNCTION Type; + * + * public PredefinedFun(PREDEFINED_FUNCTION type) { Type = type; } + * + * public double getValue(List parameters) throws Exception { double value; switch (Type) { case SQRT: case + * sqrt: if (parameters.size() != 1) { throw new Exception("Predefined function " + Type.toString() + " should have + * only one parameter"); } value = parameters.get(0); return Math.sqrt(value); + * + * case TAN: case tan: if (parameters.size() != 1) { throw new Exception("Predefined function " + + * PREDEFINED_FUNCTION.TAN.toString() + " should have only one parameter"); } value = parameters.get(0); return + * Math.tan(value); + * + * case ATAN: case atan: if (parameters.size() != 1) { throw new Exception("Predefined function " + + * PREDEFINED_FUNCTION.ATAN.toString() + " should have only one parameter"); } value = parameters.get(0); return + * Math.atan(value); + * + * case EXP: case exp: if (parameters.size() != 1) { throw new Exception("Predefined function " + + * PREDEFINED_FUNCTION.EXP.toString() + " should have only one parameter"); } value = parameters.get(0); return + * Math.exp(value); + * + * case ASIN: case asin: if (parameters.size() != 1) { throw new Exception("Predefined function " + + * PREDEFINED_FUNCTION.ASIN.toString() + " should have only one parameter"); } value = parameters.get(0); return + * Math.asin(value); + * + * case ACOS: case acos: if (parameters.size() != 1) { throw new Exception("Predefined function " + + * PREDEFINED_FUNCTION.ACOS.toString() + " should have only one parameter"); } value = parameters.get(0); return + * Math.acos(value); + * + * case LOG: case log: if (parameters.size() != 1) { throw new Exception("Predefined function " + + * PREDEFINED_FUNCTION.LOG.toString() + " should have only one parameter"); } value = parameters.get(0); return + * Math.log(value); + * + * case SIN: case sin: if (parameters.size() != 1) { throw new Exception("Predefined function " + + * PREDEFINED_FUNCTION.SIN.toString() + " should have only one parameter"); } value = parameters.get(0); + * + * if (inRadians) { return Math.sin(value); } else { return Math.sin(value * DEGREES_TO_RADIANS); } case COS: case + * cos: if (parameters.size() != 1) { throw new Exception("Predefined function " + PREDEFINED_FUNCTION.COS.toString() + * + " should have only one parameter"); } value = parameters.get(0); + * + * if (inRadians) { return Math.cos(value); } else { return Math.cos(value * DEGREES_TO_RADIANS); } + * + * } + * throw new Exception("INTERNAL ERROR: Unknown predefined function"); + * + * } + * + * public double getValue(double value) throws Exception { switch (Type) { case SQRT: return Math.sqrt(value); case + * TAN: return Math.tan(value); case ATAN: return Math.atan(value); case EXP: return Math.exp(value); case ASIN: + * return Math.asin(value); case ACOS: return Math.acos(value); case LOG: return Math.log(value); + * + * case SIN: if (inRadians) { return Math.sin(value); } else { return Math.sin(value * DEGREES_TO_RADIANS); } case + * COS: if (inRadians) { return Math.cos(value); } else { return Math.cos(value * DEGREES_TO_RADIANS); } + * + * } + * throw new Exception("INTERNAL ERROR: Unknown predefined function"); } } + */ +} diff --git a/src/main/java/cct/math/expparser/ExpressionParser.properties b/src/main/java/cct/math/expparser/ExpressionParser.properties new file mode 100644 index 0000000..f015fe8 --- /dev/null +++ b/src/main/java/cct/math/expparser/ExpressionParser.properties @@ -0,0 +1,38 @@ +# To change this license header, choose License Headers in Project Properties. +# To change this template file, choose Tools | Templates +# and open the template in the editor. + +print = cct.math.expparser.InbuiltFunctions +PRINT = cct.math.expparser.InbuiltFunctions +println = cct.math.expparser.InbuiltFunctions +PRINTLN = cct.math.expparser.InbuiltFunctions +atan2 = cct.math.expparser.InbuiltFunctions +ATAN2 = cct.math.expparser.InbuiltFunctions +cosh = cct.math.expparser.InbuiltFunctions +COSH = cct.math.expparser.InbuiltFunctions +abs = cct.math.expparser.InbuiltFunctions +ABS = cct.math.expparser.InbuiltFunctions +cbrt = cct.math.expparser.InbuiltFunctions +CBRT = cct.math.expparser.InbuiltFunctions +ceil = cct.math.expparser.InbuiltFunctions +CEIL = cct.math.expparser.InbuiltFunctions +exp = cct.math.expparser.InbuiltFunctions +EXP = cct.math.expparser.InbuiltFunctions +expm1 = cct.math.expparser.InbuiltFunctions +EXPM1 = cct.math.expparser.InbuiltFunctions +sqrt = cct.math.expparser.InbuiltFunctions +SQRT = cct.math.expparser.InbuiltFunctions +sin = cct.math.expparser.InbuiltFunctions +SIN = cct.math.expparser.InbuiltFunctions +cos = cct.math.expparser.InbuiltFunctions +COS = cct.math.expparser.InbuiltFunctions +asin = cct.math.expparser.InbuiltFunctions +ASIN = cct.math.expparser.InbuiltFunctions +acos = cct.math.expparser.InbuiltFunctions +ACOS = cct.math.expparser.InbuiltFunctions +tan = cct.math.expparser.InbuiltFunctions +TAN = cct.math.expparser.InbuiltFunctions +atan = cct.math.expparser.InbuiltFunctions +ATAN = cct.math.expparser.InbuiltFunctions +log = cct.math.expparser.InbuiltFunctions +LOG = cct.math.expparser.InbuiltFunctions diff --git a/src/main/java/cct/math/expparser/ExpressionParserTypes.properties b/src/main/java/cct/math/expparser/ExpressionParserTypes.properties new file mode 100644 index 0000000..8054051 --- /dev/null +++ b/src/main/java/cct/math/expparser/ExpressionParserTypes.properties @@ -0,0 +1,20 @@ +# To change this license header, choose License Headers in Project Properties. +# To change this template file, choose Tools | Templates +# and open the template in the editor. + +int = cct.math.expparser.InbuiltClasses +INT = cct.math.expparser.InbuiltClasses +integer = cct.math.expparser.InbuiltClasses +INTEGER = cct.math.expparser.InbuiltClasses +real = cct.math.expparser.InbuiltClasses +REAL = cct.math.expparser.InbuiltClasses +bool = cct.math.expparser.InbuiltClasses +BOOL = cct.math.expparser.InbuiltClasses +logical = cct.math.expparser.InbuiltClasses +LOGICAL = cct.math.expparser.InbuiltClasses +List = cct.math.expparser.InbuiltClasses +LIST = cct.math.expparser.InbuiltClasses +Writer = cct.math.expparser.InbuiltClasses +WRITER = cct.math.expparser.InbuiltClasses +Reader = cct.math.expparser.InbuiltClasses +READER = cct.math.expparser.InbuiltClasses \ No newline at end of file diff --git a/src/main/java/cct/math/expparser/Function.java b/src/main/java/cct/math/expparser/Function.java new file mode 100644 index 0000000..6ff65f2 --- /dev/null +++ b/src/main/java/cct/math/expparser/Function.java @@ -0,0 +1,204 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.math.expparser; + +import static cct.math.expparser.ExpressionParser.logger; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * + * @author vvv900 + */ +public class Function { + + private String Name; + private String internalName; + private Map locParams = new HashMap(); + private List localParams = new ArrayList(); + private List functionTokens; + private List functionTokenTypes; + private ExpressionParser expressionParser; + + public Function(String definition, ExpressionParser expressionParser) throws Exception { + this.expressionParser = expressionParser; + defineFunction(definition); + } + + void defineFunction(String definition) throws Exception { + List Tokens = new ArrayList(); + List tokenTypes = new ArrayList(); + expressionParser.resolveTokens(definition, Tokens, tokenTypes); + + if (tokenTypes.size() < 3) { + throw new Exception("Minimal Function definition should be: function_name()"); + } + + if (tokenTypes.size() % 2 == 1) { + throw new Exception("Wrong Function definition"); + } + + if (tokenTypes.get(0) != SYMBOL_TYPE.FUNCTION) { + throw new Exception("Function definition should start from function_name("); + } + + if (tokenTypes.get(1) != SYMBOL_TYPE.LEFT_PARANTHESIS) { + throw new Exception("Left paranthesis should follow function name"); + } + + Name = Tokens.get(0).getName(); + + int index = 2; + while (tokenTypes.get(index) != SYMBOL_TYPE.RIGHT_PARANTHESIS) { + if (index >= tokenTypes.size() - 1) { + break; + } + if (tokenTypes.get(index) != SYMBOL_TYPE.VARIABLE) { + throw new Exception("Expecting parameter in Function definition, got " + tokenTypes.get(index).toString()); + } + + if (tokenTypes.get(index + 1) != SYMBOL_TYPE.COMMA && tokenTypes.get(index + 1) != SYMBOL_TYPE.RIGHT_PARANTHESIS) { + throw new Exception("Expecting comma or right paranthesis in Function definition, got " + + tokenTypes.get(index).toString()); + } + + if (locParams.containsKey(Tokens.get(index).getName())) { + throw new Exception("Duplicate definition of parameter " + Tokens.get(index).getName()); + } + + if (Tokens.get(index).isNumber()) { + throw new Exception("Parameter should be symbolic variable. Got " + Tokens.get(index).getName()); + } + + Tokens.get(index).setType(SYMBOL_TYPE.LOCAL_VARIABLE); + locParams.put(Tokens.get(index).getName(), null); + localParams.add(Tokens.get(index).getName()); + + index += 2; + if (index >= tokenTypes.size() - 1) { + break; + } + + } + + internalName = Name + "_" + String.valueOf(localParams.size()); + logger.info("Fun name: " + Name + " Internal name: " + internalName + " N params: " + localParams.size()); + for (int i = 0; i < localParams.size(); i++) { + logger.info((i + 1) + " : " + localParams.get(i).toString()); + + } + } + + public String getInternalName() { + return internalName; + } + + public void setInternalName(String internalName) { + this.internalName = internalName; + } + + void setFunctionBody(String body) throws Exception { + List Tokens = new ArrayList(); + List tokenTypes = new ArrayList(); + expressionParser.resolveTokens(body, Tokens, tokenTypes); + if (Tokens.size() < 1) { + throw new Exception("Empty function body"); + } + for (int i = 0; i < Tokens.size(); i++) { + if (tokenTypes.get(i) == SYMBOL_TYPE.VARIABLE && locParams.containsKey(Tokens.get(i).getName())) { + Tokens.get(i).setType(SYMBOL_TYPE.LOCAL_VARIABLE); + tokenTypes.set(i, SYMBOL_TYPE.LOCAL_VARIABLE); + // --- + } else if (tokenTypes.get(i) == SYMBOL_TYPE.VARIABLE) { + boolean isNumber = Tokens.get(i).isNumber(); + String varName = Tokens.get(i).getName(); + if (expressionParser == null) { + throw new Exception("Function body: expressionParser == null"); + } else if ( (!expressionParser.hasSymbol(varName)) && (!isNumber) ) { + throw new Exception("Function body: " + body + "\nVariable " + varName + " is not defined"); + } else if (expressionParser.hasSymbol(varName)) { + Variable type = (Variable) expressionParser.getSymbol(varName); + Tokens.set(i, type); + } + } + } + + functionTokens = Tokens; + functionTokenTypes = tokenTypes; + } + + public Object getValue(List arguments) throws Exception { + Object value; + for (int i = 0; i < functionTokens.size(); i++) { + if (functionTokenTypes.get(i) == SYMBOL_TYPE.LOCAL_VARIABLE) { + int index = localParams.indexOf(functionTokens.get(i).getName()); + if (index == -1) { + throw new Exception("Internal Error: index == -1"); + } + functionTokens.get(i).setValue(arguments.get(index)); + } + } + + List Tokens = new ArrayList(functionTokens); + List tokenTypes = new ArrayList(functionTokenTypes); + + value = expressionParser.evaluateExpression(Tokens, tokenTypes); + return value; + } + + public int getArgsNumber() { + return localParams.size(); + } + + public Object executeCommand(Object[] args) throws Exception { + return null; + } + + public String getName() { + return this.Name; + } + + public void setName(String name) { + this.Name = name; + } + + public void setExpressionParser(ExpressionParser expressionParser) { + this.expressionParser = expressionParser; + } +} diff --git a/src/main/java/cct/math/expparser/FunctionInterface.java b/src/main/java/cct/math/expparser/FunctionInterface.java new file mode 100644 index 0000000..f2f567e --- /dev/null +++ b/src/main/java/cct/math/expparser/FunctionInterface.java @@ -0,0 +1,52 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.math.expparser; + +/** + * + * @author vvv900 + */ +public interface FunctionInterface { + + Object fiEvaluateFunction(Object[] args) throws Exception; + + String fiGetName(); + + void fiSetName(String name); + + void fiSetExpressionParser(ExpressionParser expressionParser); +} diff --git a/src/main/java/cct/math/expparser/InbuiltClasses.java b/src/main/java/cct/math/expparser/InbuiltClasses.java new file mode 100644 index 0000000..854dfac --- /dev/null +++ b/src/main/java/cct/math/expparser/InbuiltClasses.java @@ -0,0 +1,485 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.math.expparser; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileReader; +import java.io.FileWriter; +import java.nio.CharBuffer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * + * @author vvv900 + */ +public class InbuiltClasses implements ClassInterface { + + enum CLASS { + + integer, real, bool, logical, List, Writer, Reader + + } + + private static Map allClasses = new HashMap(); + private static Map> classMethods = new HashMap>(); + + enum LIST_METHOD { + + add, size, get, isEmpty, clear, contains, indexOf, iterator, toArray, lastIndexOf, remove, set + } + + enum WRITER_METHOD { + + close, flush, newLine, write + } + + enum READER_METHOD { + + close, mark, markSupported, read, readLine, ready, reset, skip + } + + private String name; + private CLASS classType; + private List list; + private BufferedWriter bufferedWriter; + private BufferedReader bufferedReader; + + public InbuiltClasses() { + if (allClasses.size() == 0) { + allClasses.put("int", CLASS.integer); + allClasses.put("INT", CLASS.integer); + allClasses.put("integer", CLASS.integer); + allClasses.put("INTEGER", CLASS.integer); + allClasses.put("real", CLASS.real); + allClasses.put("REAL", CLASS.real); + allClasses.put("logical", CLASS.logical); + allClasses.put("LOGICAL", CLASS.logical); + allClasses.put("bool", CLASS.logical); + allClasses.put("BOOL", CLASS.logical); + allClasses.put("List", CLASS.List); + allClasses.put("LIST", CLASS.List); + allClasses.put(CLASS.Writer.name(), CLASS.Writer); + allClasses.put(CLASS.Writer.name().toUpperCase(), CLASS.Writer); + allClasses.put(CLASS.Reader.name(), CLASS.Reader); + allClasses.put(CLASS.Reader.name().toUpperCase(), CLASS.Reader); + // --- + classMethods.put(CLASS.List, new HashSet()); + for (LIST_METHOD lm : LIST_METHOD.values()) { + classMethods.get(CLASS.List).add(lm); + } + classMethods.put(CLASS.Writer, new HashSet()); + for (WRITER_METHOD wm : WRITER_METHOD.values()) { + classMethods.get(CLASS.Writer).add(wm); + } + classMethods.put(CLASS.Reader, new HashSet()); + for (READER_METHOD wm : READER_METHOD.values()) { + classMethods.get(CLASS.Reader).add(wm); + } + } + } + + public InbuiltClasses(CLASS classType, Object[] args) throws Exception { + this(); + this.classType = classType; + name = classType.name(); + switch (classType) { + case List: + list = new ArrayList(); + return; + case Writer: + if (args == null || args.length == 0 || args.length > 2) { + throw new Exception("Constructor of Class " + classType.name() + " must have either 1 or 2 arguments"); + } + // --- + if (args.length == 1) { // File name or something else + if (args[0] == null) { + throw new Exception("The first argument of a Constructor of Class " + classType.name() + + " must be non-zero"); + } + } + if (args.length == 2 && args[1] == null) { + throw new Exception("The second argument of a Constructor of Class " + classType.name() + + " must be non-zero"); + } + Boolean append = new Boolean(false); + if (args.length == 2) { + if (args[2] instanceof Boolean) { + append = (Boolean) args[1]; + } else { + try { + append = Boolean.parseBoolean(args[1].toString()); + } catch (Exception ex) { + throw new Exception("The second argument of a Constructor of Class " + classType.name() + + " must be of boolean type. Gor: " + args[1].getClass().getCanonicalName()); + } + } + } + bufferedWriter = new BufferedWriter(new FileWriter(args[0].toString(), append)); + return; + // --- + case Reader: + if (args == null || args.length == 0 || args.length > 2) { + throw new Exception("Constructor of Class " + classType.name() + " must have either 1 or 2 arguments"); + } + // --- + if (args.length == 1) { // File name or something else + if (args[0] == null) { + throw new Exception("The first argument of a Constructor of Class " + classType.name() + + " must be non-zero"); + } + } + if (args.length == 2 && args[1] == null) { + throw new Exception("The second argument of a Constructor of Class " + classType.name() + + " must be non-zero"); + } + Integer sz = new Integer(64 * 1024); + if (args.length == 2) { + if (args[2] instanceof Number) { + sz = ((Number) args[1]).intValue(); + System.out.println("Using buffer size: " + sz); + } else { + try { + sz = Integer.parseInt(args[1].toString()); + } catch (Exception ex) { + throw new Exception("The second argument of a Constructor of Class " + classType.name() + + " must be of integer type. Got: " + args[1].getClass().getCanonicalName()); + } + } + } + bufferedReader = new BufferedReader(new FileReader(args[0].toString())); + return; + } + throw new Exception("Constructor for Class " + classType.name() + " is not implemented"); + } + + public InbuiltClasses(String className) throws Exception { + this(); + ciSetName(className); + } + + public ClassInterface ciAllocateClass(Object[] args) throws Exception { + + return new InbuiltClasses(classType, args); + } + + public Object ciExecuteMethod(String method, Object[] args) throws Exception { + switch (classType) { + case List: + if (!ciHasMethod(method)) { + throw new Exception("Class of type" + classType.name() + " does not have method \"" + method + "\""); + } + if (method.equals(LIST_METHOD.add.name())) { + if (args.length < 1 || args.length > 2) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has either 1 or 2 arguments"); + } + if (args.length == 1) { + return list.add(args[0]); + } else if (args.length == 2) { + list.add(((Number) args[0]).intValue(), args[1]); + return Void.class; + } + } else if (method.equals(LIST_METHOD.set.name())) { + if (args == null || args.length != 2) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has 2 arguments"); + } else if (args.length == 2) { + return list.set(((Number) args[0]).intValue(), args[1]); + + }// -------- + } else if (method.equals(LIST_METHOD.size.name())) { + if (args != null && args.length > 0) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has no argument(s)"); + } + return list.size(); + } else if (method.equals(LIST_METHOD.isEmpty.name())) { + if (args != null && args.length > 0) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has no argument(s)"); + } + return list.isEmpty(); + } else if (method.equals(LIST_METHOD.iterator.name())) { + if (args != null) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has no argument(s)"); + } + return list.iterator(); + } else if (method.equals(LIST_METHOD.toArray.name())) { + if (args != null) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has no argument(s)"); + } + return list.toArray(); + } else if (method.equals(LIST_METHOD.clear.name())) { + if (args != null && args.length > 0) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has no argument(s)"); + } + list.clear(); + return Void.class; + } else if (method.equals(LIST_METHOD.get.name())) { + if (args == null || args.length != 1) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has only 1 argument"); + } + return list.get(((Number) args[0]).intValue()); + + } else if (method.equals(LIST_METHOD.contains.name())) { + if (args == null || args.length != 1) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has only 1 argument"); + } + return list.contains(args[0]); + } else if (method.equals(LIST_METHOD.remove.name())) { + if (args == null || args.length != 1) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has only 1 argument"); + } + if (args[0] instanceof Integer || args[0] instanceof Long || args[0] instanceof Short) { + return list.remove(((Number) args[0]).intValue()); + } else { + return list.remove(args[0]); + } + } else if (method.equals(LIST_METHOD.lastIndexOf.name())) { + if (args == null || args.length != 1) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has only 1 argument"); + } + return list.lastIndexOf(args[0]); + } else if (method.equals(LIST_METHOD.indexOf.name())) { + if (args == null || args.length != 1) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has only 1 argument"); + } + return list.indexOf(args[0]); + } + break; + // ---- + case Writer: + return executeWriterMethod(method, args); + // ---- + case Reader: + return executeReaderMethod(method, args); + } + throw new Exception("\"" + method + "\" of Class " + classType.name() + " is not implemented"); + } + + public String ciGetName() { + return name; + } + + public void ciSetName(String name) throws Exception { + if (!allClasses.containsKey(name)) { + throw new Exception("There is no inbuilt type " + name); + } + this.classType = allClasses.get(name); + name = classType.name(); + switch (classType) { + case List: + list = new ArrayList(); + break; + } + } + + public String[] ciGetAllMethods() { + Object[] obj; + String[] methods; + obj = classMethods.get(classType).toArray(); + methods = new String[obj.length]; + for (int i = 0; i < obj.length; i++) { + methods[i] = obj[i].toString(); + } + return methods; + } + + public boolean ciHasMethod(String methodName) { + try { + switch (classType) { + case List: + LIST_METHOD.valueOf(methodName); + return true; + //return classMethods.get(classType).contains(methodName); + case Writer: + WRITER_METHOD.valueOf(methodName); + return true; + //return classMethods.get(classType).contains(methodName); + case Reader: + READER_METHOD.valueOf(methodName); + return true; + } + } catch (Exception ex) { + } + return false; + } + + public void ciSetExpressionParser(ExpressionParser expressionParser) { + + } + + public Object executeWriterMethod(String method, Object[] args) throws Exception { + WRITER_METHOD wm = WRITER_METHOD.valueOf(method); + switch (wm) { + case close: + if (args != null && args.length > 0) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has no argument(s)"); + } + bufferedWriter.close(); + return Void.class; + + case flush: + if (args != null && args.length > 0) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has no argument(s)"); + } + bufferedWriter.flush(); + return Void.class; + + case newLine: + if (args != null && args.length > 0) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has no argument(s)"); + } + bufferedWriter.newLine(); + return Void.class; + + case write: + if (args == null || args.length == 2) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " must have either 1 or 3 arguments"); + } + if (args.length > 3) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " cannot have more than 3 arguments"); + } + // --- + if (args.length == 1) { + if (args[0] instanceof char[]) { + bufferedWriter.write((char[]) args[0]); + } else if (args[0] instanceof Integer || args[0] instanceof Long || args[0] instanceof Short) { + bufferedWriter.write(((Number) args[0]).intValue()); + } else { + bufferedWriter.write(args[0].toString()); + } + return Void.class; + } + } + throw new Exception("\"" + method + "\" of Class " + classType.name() + " is not implemented"); + } + + public Object executeReaderMethod(String method, Object[] args) throws Exception { + READER_METHOD rm = READER_METHOD.valueOf(method); //mark, read, ready, reset, skip + switch (rm) { + case close: + if (args != null && args.length > 0) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has no argument(s)"); + } + bufferedReader.close(); + return Void.class; + + case markSupported: + if (args != null && args.length > 0) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has no argument(s)"); + } + return bufferedReader.markSupported(); + + case ready: + if (args != null && args.length > 0) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has no argument(s)"); + } + return bufferedReader.ready(); + + case reset: + if (args != null && args.length > 0) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has no argument(s)"); + } + bufferedReader.reset(); + return Void.class; + + case readLine: + if (args != null && args.length > 0) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " has no argument(s)"); + } + return bufferedReader.readLine(); + + case mark: + if (args != null || args.length != 1 || args[0] == null) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " must have one argument"); + } + if (args[0] instanceof Number) { + bufferedReader.mark(((Number) args[0]).intValue()); + return Void.class; + } + int readAheadLimit = Integer.parseInt(args[0].toString()); + bufferedReader.mark(readAheadLimit); + return Void.class; + + case skip: + if (args != null || args.length != 1 || args[0] == null) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " must have one argument"); + } + if (args[0] instanceof Number) { + return bufferedReader.skip(((Number) args[0]).longValue()); + } + long n = Long.parseLong(args[0].toString()); + return bufferedReader.skip(n); + + case read: + if (args == null || args.length == 0) { + return bufferedReader.read(); + } + + if (args == null || args.length == 1) { + if (args[0] == null) { + throw new Exception("\"" + method + "\"(buffer) of Class " + classType.name() + ": buffer must be non-zero"); + } + if (args[0] instanceof char[]) { + return bufferedReader.read((char[]) args[0]); + } else if (args[0] instanceof CharBuffer) { + return bufferedReader.read((CharBuffer) args[0]); + } + throw new Exception("\"" + method + "\"(buffer) of Class " + classType.name() + ": buffer must be of type " + + "char[] or CharBuffer. Got: " + args[0].getClass().getCanonicalName()); + } + // --- + if (args.length != 3) { + throw new Exception("\"" + method + "\" of Class " + classType.name() + " cannot can have 0, 1 or 3 arguments"); + } + // --- + int off = ((Number) args[1]).intValue(); + int len = ((Number) args[2]).intValue(); + + if (args[0] instanceof char[]) { + return bufferedReader.read((char[]) args[0], off, len); + } + throw new Exception("\"" + method + "\"(char[] cbuf, int off, int len) of Class " + classType.name() + + " check parameters type"); + + } + throw new Exception("\"" + method + "\" of Class " + classType.name() + " is not implemented"); + } +} diff --git a/src/main/java/cct/math/expparser/InbuiltFunctions.java b/src/main/java/cct/math/expparser/InbuiltFunctions.java new file mode 100644 index 0000000..fe935c0 --- /dev/null +++ b/src/main/java/cct/math/expparser/InbuiltFunctions.java @@ -0,0 +1,197 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.math.expparser; + +import static cct.math.expparser.ExpressionParser.DEGREES_TO_RADIANS; + +/** + * + * @author vvv900 + */ +public class InbuiltFunctions implements FunctionInterface { + + enum INBUILT_FUNCTION { + + print, PRINT, println, PRINTLN, + atan2, ATAN2, cosh, COSH, abs, ABS, cbrt, CBRT, ceil, CEIL, exp, EXP, expm1, EXPM1, + SQRT, sqrt, SIN, sin, COS, cos, TAN, tan, ASIN, asin, ACOS, acos, ATAN, atan, LOG, log + } + + private String name; + private INBUILT_FUNCTION type; + private ExpressionParser expressionParser; + + public InbuiltFunctions() { + + } + + public Object fiEvaluateFunction(Object[] args) throws Exception { + switch (type) { + case print: + case PRINT: + if (args.length != 1) { + throw new Exception("Function " + name + " requires 1 argument"); + } + System.out.print(args[0] == null ? args[0] : args[0].toString()); + return Void.class; + case println: + case PRINTLN: + if (args.length != 1) { + throw new Exception("Function " + name + " requires 1 argument"); + } + System.out.println(args[0] == null ? args[0] : args[0].toString()); + return Void.class; + case atan2: + case ATAN2: + if (args.length != 2) { + throw new Exception("Function " + name + " requires 2 arguments"); + } + return Math.atan2(((Number) args[0]).doubleValue(), ((Number) args[1]).doubleValue()); + case cosh: + case COSH: + if (args.length != 1) { + throw new Exception("Function " + name + " requires 1 argument"); + } + return Math.cosh(((Number) args[0]).doubleValue()); + case abs: + case ABS: + if (args.length != 1) { + throw new Exception("Function " + name + " requires 1 argument"); + } + return Math.abs(((Number) args[0]).doubleValue()); + case cbrt: + case CBRT: + if (args.length != 1) { + throw new Exception("Function " + name + " requires 1 argument"); + } + return Math.cbrt(((Number) args[0]).doubleValue()); + case ceil: + case CEIL: + if (args.length != 1) { + throw new Exception("Function " + name + " requires 1 argument"); + } + return Math.ceil(((Number) args[0]).doubleValue()); + case exp: + case EXP: + if (args.length != 1) { + throw new Exception("Function " + name + " requires 1 argument"); + } + return Math.exp(((Number) args[0]).doubleValue()); + case expm1: + case EXPM1: + if (args.length != 1) { + throw new Exception("Function " + name + " requires 1 argument"); + } + return Math.expm1(((Number) args[0]).doubleValue()); + case sqrt: + case SQRT: + if (args.length != 1) { + throw new Exception("Function " + name + " requires 1 argument"); + } + return Math.sqrt(((Number) args[0]).doubleValue()); + case sin: + case SIN: + if (args.length != 1) { + throw new Exception("Function " + name + " requires 1 argument"); + } + if (expressionParser.isInRadians()) { + return Math.sin(((Number) args[0]).doubleValue()); + } else { + return Math.sin(((Number) args[0]).doubleValue() * DEGREES_TO_RADIANS); + } + case cos: + case COS: + if (args.length != 1) { + throw new Exception("Function " + name + " requires 1 argument"); + } + if (expressionParser.isInRadians()) { + return Math.cos(((Number) args[0]).doubleValue()); + } else { + return Math.cos(((Number) args[0]).doubleValue() * DEGREES_TO_RADIANS); + } + case tan: + case TAN: + if (args.length != 1) { + throw new Exception("Function " + name + " requires 1 argument"); + } + return Math.tan(((Number) args[0]).doubleValue()); + + case asin: + case ASIN: + if (args.length != 1) { + throw new Exception("Function " + name + " requires 1 argument"); + } + return Math.asin(((Number) args[0]).doubleValue()); + + case acos: + case ACOS: + if (args.length != 1) { + throw new Exception("Function " + name + " requires 1 argument"); + } + return Math.acos(((Number) args[0]).doubleValue()); + + case atan: + case ATAN: + if (args.length != 1) { + throw new Exception("Function " + name + " requires 1 argument"); + } + return Math.atan(((Number) args[0]).doubleValue()); + + case log: + case LOG: + if (args.length != 1) { + throw new Exception("Function " + name + " requires 1 argument"); + } + return Math.log(((Number) args[0]).doubleValue()); + + } + throw new Exception("Unknown error"); + } + + public String fiGetName() { + return name; + } + + public void fiSetName(String name) { + type = INBUILT_FUNCTION.valueOf(name); + this.name = name; + } + + public void fiSetExpressionParser(ExpressionParser expressionParser) { + this.expressionParser = expressionParser; + } +} diff --git a/src/main/java/cct/math/expparser/OPERATION.java b/src/main/java/cct/math/expparser/OPERATION.java new file mode 100644 index 0000000..b3c223e --- /dev/null +++ b/src/main/java/cct/math/expparser/OPERATION.java @@ -0,0 +1,23 @@ +package cct.math.expparser; + +/** + * + * @author vvv900 + */ +public enum OPERATION { + + Unary_logical_negation, // Precedence = 13 + MULTIPLY, DEVIDE, POWER, MODULUS, // Precedence = 12 + ADD, SUBSTRACT, // Precedence = 11 + Bitwise_left_shift, Bitwise_right_shift_with_sign_extension, // Precedence = 10 + Bitwise_right_shift_with_zero_extension, // Precedence = 10 + Relational_less_than, Relational_less_than_or_equal, Relational_greater_than, // Precedence = 9 + Relational_greater_than_or_equal, Type_comparison, // Precedence = 9 + Relational_is_equal_to, Relational_is_not_equal_to, // Precedence = 8 + Bitwise_AND, // Precedence = 7 + Bitwise_exclusive_OR, // Precedence = 6 + Bitwise_inclusive_OR, // Precedence = 5 + Logical_AND, // Precedence = 4 + Logical_OR, // Precedence = 3 + Ternary_conditional // Precedence = 2 +} diff --git a/src/main/java/cct/math/expparser/PARANTHESIS.java b/src/main/java/cct/math/expparser/PARANTHESIS.java new file mode 100644 index 0000000..6711f16 --- /dev/null +++ b/src/main/java/cct/math/expparser/PARANTHESIS.java @@ -0,0 +1,15 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.math.expparser; + +/** + * + * @author vvv900 + */ +public enum PARANTHESIS { + + LEFT, RIGHT +} diff --git a/src/main/java/cct/math/expparser/SYMBOL_TYPE.java b/src/main/java/cct/math/expparser/SYMBOL_TYPE.java new file mode 100644 index 0000000..801a8af --- /dev/null +++ b/src/main/java/cct/math/expparser/SYMBOL_TYPE.java @@ -0,0 +1,20 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.math.expparser; + +/** + * + * @author vvv900 + */ +public enum SYMBOL_TYPE { + + VARIABLE, CLASS, LOCAL_VARIABLE, FUNCTION, OPERATION_ADD, OPERATION_SUB, OPERATION_MUL, OPERATION_DIV, OPERATION_POWER, + LEFT_PARANTHESIS, RIGHT_PARANTHESIS, + COMMA, + Bitwise_left_shift, Bitwise_right_shift_with_sign_extension, Bitwise_right_shift_with_zero_extension, + Relational_less_than, + LEFT_SQUARE_BRACKET, RIGHT_SQUARE_BRACKET +} diff --git a/src/main/java/cct/math/expparser/Variable.java b/src/main/java/cct/math/expparser/Variable.java new file mode 100644 index 0000000..92a7c1a --- /dev/null +++ b/src/main/java/cct/math/expparser/Variable.java @@ -0,0 +1,182 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.math.expparser; + +/** + * + * @author vvv900 + */ +public class Variable { + + private SYMBOL_TYPE type; + private OPERATION operation; + private PARANTHESIS paranthesis; + private String name; + private double number; + private boolean is_number = false; + private boolean constant = false; + + private Object value; + + public Variable(double value) { + //this.name = String.valueOf(value); + this.type = SYMBOL_TYPE.VARIABLE; + try { + setValue(value); + } catch (Exception ex) { + } + } + + public Variable(double value, boolean constant) { + //this.name = String.valueOf(value); + this.type = SYMBOL_TYPE.VARIABLE; + try { + setValue(value); + } catch (Exception ex) { + } + this.constant = constant; + } + + public Variable(Object value) { + this.type = SYMBOL_TYPE.VARIABLE; + try { + this.setValue(value); + } catch (Exception ex) { + } + } + + public Variable(String name, Object value, boolean constant) { + this.name = name; + this.type = SYMBOL_TYPE.VARIABLE; + try { + this.setValue(value); + } catch (Exception ex) { + } + this.constant = constant; + } + + public Variable(Object value, boolean constant) { + this.type = SYMBOL_TYPE.VARIABLE; + try { + this.setValue(value); + } catch (Exception ex) { + } + this.constant = constant; + } + + public Variable(String name, SYMBOL_TYPE type) { + this.name = name; + this.type = type; + } + + public Variable(OPERATION op, SYMBOL_TYPE type) { + operation = op; + this.type = type; + } + + public Variable(PARANTHESIS par, SYMBOL_TYPE type) { + paranthesis = par; + this.type = type; + } + + public Variable(SYMBOL_TYPE type) throws Exception { + if (type != SYMBOL_TYPE.COMMA) { + throw new Exception("INTERNAL ERROR: Not comma"); + } + this.type = type; + } + + public void setValue(double value) throws Exception { + if (constant) { + throw new Exception(name + " is a Constant and its value cannot be changed"); + } + number = value; + this.value = new Double(value); + is_number = true; + } + + public void setValue(Object value) throws Exception { + if (constant) { + throw new Exception(name + " is a Constant and its value cannot be changed"); + } + this.value = value; + if (value instanceof Number) { + is_number = true; + number = ((Number) value).doubleValue(); + } else { + is_number = false; + } + } + + public Object getValue() { + return value; + } + + public double getValueAsDouble() throws Exception { + if (value instanceof Number) { + return ((Number) value).doubleValue(); + } + throw new Exception("Variable " + name + " cannot be converted into a double value. Got: " + value.getClass().getName()); + } + + public String getName() { + return name; + } + + public SYMBOL_TYPE getType() { + return type; + } + + public void setType(SYMBOL_TYPE type) { + this.type = type; + } + + public boolean isNumber() { + return is_number; + } + + public boolean isString() { + if (value == null) { + return true; + } + return value instanceof String; + } + + public boolean isConstant() { + return constant; + } +} diff --git a/src/main/java/cct/math/polyg/.DS_Store b/src/main/java/cct/math/polyg/.DS_Store new file mode 100644 index 0000000..245b008 Binary files /dev/null and b/src/main/java/cct/math/polyg/.DS_Store differ diff --git a/src/main/java/cct/math/polyg/._.DS_Store b/src/main/java/cct/math/polyg/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/cct/math/polyg/._.DS_Store differ diff --git a/src/main/java/cct/math/polyg/GLvector.java b/src/main/java/cct/math/polyg/GLvector.java new file mode 100644 index 0000000..80aaa02 --- /dev/null +++ b/src/main/java/cct/math/polyg/GLvector.java @@ -0,0 +1,64 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.math.polyg; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class GLvector { + public float fX = 0; + public float fY = 0; + public float fZ = 0; + + public GLvector() {} + + public GLvector(float x, float y, float z) { + fX = x; + fY = y; + fZ = z; + } +} diff --git a/src/main/java/cct/math/polyg/Polygonizer.java b/src/main/java/cct/math/polyg/Polygonizer.java new file mode 100644 index 0000000..50d0c11 --- /dev/null +++ b/src/main/java/cct/math/polyg/Polygonizer.java @@ -0,0 +1,1485 @@ +package cct.math.polyg; + +import java.util.ArrayList; +import java.util.List; + +import cct.interfaces.ImplicitFunctionInterface; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class Polygonizer { + + // For any edge, if one vertex is inside of the surface and the other is outside of the surface + // then the edge intersects the surface + // For each of the 8 vertices of the cube can be two possible states : either inside or outside of the surface + // For any cube the are 2^8=256 possible sets of vertex states + // This table lists the edges intersected by the surface for all 256 possible vertex states + // There are 12 edges. For each entry in the table, if edge #n is intersected, then bit #n is set to 1 + + static final int aiCubeEdgeFlags[] = { // 256 values + 0x000, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, + 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, + 0x190, 0x099, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, + 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, + 0x230, 0x339, 0x033, 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, + 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, + 0x3a0, 0x2a9, 0x1a3, 0x0aa, 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, + 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, + 0x460, 0x569, 0x663, 0x76a, 0x066, 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, + 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, + 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0x0ff, 0x3f5, 0x2fc, 0xdfc, 0xcf5, + 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, + 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x055, 0x15c, 0xe5c, 0xf55, + 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, + 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0x0cc, 0xfcc, 0xec5, + 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, + 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0x0cc, 0x1c5, + 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, + 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x055, + 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, + 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, + 0x0ff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, + 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, + 0x16f, 0x066, 0x76a, 0x663, 0x569, 0x460, + 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, + 0x6af, 0x7a6, 0x0aa, 0x1a3, 0x2a9, 0x3a0, + 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, + 0x73f, 0x636, 0x13a, 0x033, 0x339, 0x230, + 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, + 0x49f, 0x596, 0x29a, 0x393, 0x099, 0x190, + 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, + 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x000 + }; + + // For each of the possible vertex states listed in aiCubeEdgeFlags there is a specific triangulation +// of the edge intersection points. a2iTriangleConnectionTable lists all of them in the form of +// 0-5 edge triples with the list terminated by the invalid value -1. +// For example: a2iTriangleConnectionTable[3] list the 2 triangles formed when corner[0] +// and corner[1] are inside of the surface, but the rest of the cube is not. +// +// I found this table in an example program someone wrote long ago. It was probably generated by hand + + static final int a2iTriangleConnectionTable[][] = { // 256x16 + { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1}, { + 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1}, { + 3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1}, { + 3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1}, { + 9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1}, { + 1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1}, { + 9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, { + 2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1}, { + 8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1}, { + 9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, { + 4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1}, { + 3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1}, { + 1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1}, { + 4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1}, { + 4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1}, { + 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1}, { + 1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, { + 5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1}, { + 2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1}, { + 9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, { + 0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, { + 2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1}, { + 10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1}, { + 4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1}, { + 5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1}, { + 5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1}, { + 9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1}, { + 0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1}, { + 1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1}, { + 10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1}, { + 8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1}, { + 2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1}, { + 7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1}, { + 9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1}, { + 2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1}, { + 11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1}, { + 9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1}, { + 5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1}, { + 11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1}, { + 11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, { + 1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1}, { + 9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1}, { + 5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1}, { + 2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, { + 0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, { + 5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1}, { + 6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1}, { + 0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1}, { + 3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1}, { + 6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1}, { + 5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1}, { + 1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, { + 10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1}, { + 6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1}, { + 1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1}, { + 8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1}, { + 7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1}, { + 3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, { + 5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1}, { + 0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1}, { + 9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1}, { + 8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1}, { + 5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1}, { + 0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1}, { + 6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1}, { + 10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1}, { + 10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1}, { + 8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1}, { + 1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1}, { + 3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1}, { + 0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1}, { + 10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1}, { + 0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1}, { + 3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1}, { + 6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1}, { + 9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1}, { + 8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1}, { + 3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1}, { + 6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1}, { + 0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1}, { + 10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1}, { + 10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1}, { + 1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1}, { + 2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1}, { + 7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1}, { + 7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1}, { + 2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1}, { + 1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1}, { + 11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1}, { + 8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1}, { + 0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1}, { + 7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, { + 10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, { + 2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, { + 6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1}, { + 7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1}, { + 2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1}, { + 1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1}, { + 10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1}, { + 10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1}, { + 0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1}, { + 7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1}, { + 6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1}, { + 8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1}, { + 9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1}, { + 6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1}, { + 1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1}, { + 4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1}, { + 10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1}, { + 8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1}, { + 0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1}, { + 1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1}, { + 8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1}, { + 10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1}, { + 4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1}, { + 10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, { + 5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, { + 11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1}, { + 9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, { + 6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1}, { + 7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1}, { + 3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1}, { + 7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1}, { + 9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1}, { + 3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1}, { + 6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1}, { + 9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1}, { + 1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1}, { + 4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1}, { + 7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1}, { + 6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1}, { + 3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1}, { + 0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1}, { + 6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1}, { + 1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1}, { + 0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1}, { + 11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1}, { + 6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1}, { + 5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1}, { + 9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1}, { + 1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1}, { + 1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1}, { + 10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1}, { + 0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1}, { + 5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1}, { + 10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1}, { + 11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1}, { + 0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1}, { + 9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1}, { + 7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1}, { + 2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1}, { + 8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1}, { + 9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1}, { + 9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1}, { + 1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1}, { + 9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1}, { + 9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1}, { + 5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1}, { + 0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1}, { + 10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1}, { + 2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1}, { + 0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1}, { + 0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1}, { + 9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1}, { + 5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1}, { + 3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1}, { + 5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1}, { + 8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1}, { + 0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1}, { + 9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1}, { + 0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1}, { + 1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1}, { + 3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1}, { + 4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1}, { + 9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1}, { + 11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1}, { + 11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1}, { + 2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1}, { + 9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1}, { + 3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1}, { + 1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1}, { + 4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1}, { + 4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1}, { + 0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1}, { + 3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1}, { + 3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1}, { + 0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1}, { + 9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1}, { + 1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + 0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1} + }; + + //a2fVertexOffset lists the positions, relative to vertex0, of each of the 8 vertices of a cube + static final float a2fVertexOffset[][] = { // 8x3 + { + 0.0f, 0.0f, 0.0f}, { + 1.0f, 0.0f, 0.0f}, { + 1.0f, 1.0f, 0.0f}, { + 0.0f, 1.0f, 0.0f}, { + 0.0f, 0.0f, 1.0f}, { + 1.0f, 0.0f, 1.0f}, { + 1.0f, 1.0f, 1.0f}, { + 0.0f, 1.0f, 1.0f} + }; + + //a2iEdgeConnection lists the index of the endpoint vertices for each of the 12 edges of the cube + static final int a2iEdgeConnection[][] = { // 12x12 + { + 0, 1}, { + 1, 2}, { + 2, 3}, { + 3, 0}, { + 4, 5}, { + 5, 6}, { + 6, 7}, { + 7, 4}, { + 0, 4}, { + 1, 5}, { + 2, 6}, { + 3, 7} + }; + + //a2fEdgeDirection lists the direction vector (vertex1-vertex0) for each edge in the cube + static final float a2fEdgeDirection[][] = { // 12x3 + { + 1.0f, 0.0f, 0.0f}, { + 0.0f, 1.0f, 0.0f}, { + -1.0f, 0.0f, 0.0f}, { + 0.0f, -1.0f, 0.0f}, { + 1.0f, 0.0f, 0.0f}, { + 0.0f, 1.0f, 0.0f}, { + -1.0f, 0.0f, 0.0f}, { + 0.0f, -1.0f, 0.0f}, { + 0.0f, 0.0f, 1.0f}, { + 0.0f, 0.0f, 1.0f}, { + 0.0f, 0.0f, 1.0f}, { + 0.0f, 0.0f, 1.0f} + }; + + //a2iTetrahedronEdgeConnection lists the index of the endpoint vertices for each of the 6 edges of the tetrahedron + static final int a2iTetrahedronEdgeConnection[][] = { // 6x2 + { + 0, 1}, { + 1, 2}, { + 2, 0}, { + 0, 3}, { + 1, 3}, { + 2, 3} + }; + + //a2iTetrahedronEdgeConnection lists the index of verticies from a cube + // that made up each of the six tetrahedrons within the cube + static final int a2iTetrahedronsInACube[][] = { // 6x4 + { + 0, 5, 1, 6}, { + 0, 1, 2, 6}, { + 0, 2, 3, 6}, { + 0, 3, 7, 6}, { + 0, 7, 4, 6}, { + 0, 4, 5, 6}, + }; + + // For any edge, if one vertex is inside of the surface and the other is outside of the surface + // then the edge intersects the surface + // For each of the 4 vertices of the tetrahedron can be two possible states : either inside or outside of the surface + // For any tetrahedron the are 2^4=16 possible sets of vertex states + // This table lists the edges intersected by the surface for all 16 possible vertex states + // There are 6 edges. For each entry in the table, if edge #n is intersected, then bit #n is set to 1 + int aiTetrahedronEdgeFlags[] = { // 16 + 0x00, 0x0d, 0x13, 0x1e, 0x26, 0x2b, 0x35, 0x38, 0x38, 0x35, 0x2b, 0x26, + 0x1e, 0x13, 0x0d, 0x00, + }; + + // For each of the possible vertex states listed in aiTetrahedronEdgeFlags there is a specific triangulation + // of the edge intersection points. a2iTetrahedronTriangles lists all of them in the form of + // 0-2 edge triples with the list terminated by the invalid value -1. + + int a2iTetrahedronTriangles[][] = { // 16x7 + { + -1, -1, -1, -1, -1, -1, -1}, { + 0, 3, 2, -1, -1, -1, -1}, { + 0, 1, 4, -1, -1, -1, -1}, { + 1, 4, 2, 2, 4, 3, -1}, + + { + 1, 2, 5, -1, -1, -1, -1}, { + 0, 3, 5, 0, 5, 1, -1}, { + 0, 2, 5, 0, 5, 4, -1}, { + 5, 4, 3, -1, -1, -1, -1}, + + { + 3, 4, 5, -1, -1, -1, -1}, { + 4, 5, 0, 5, 2, 0, -1}, { + 1, 5, 0, 5, 3, 0, -1}, { + 5, 2, 1, -1, -1, -1, -1}, + + { + 3, 4, 2, 2, 4, 1, -1}, { + 4, 1, 0, -1, -1, -1, -1}, { + 2, 3, 0, -1, -1, -1, -1}, { + -1, -1, -1, -1, -1, -1, -1}, + }; + + protected int[] iDataSetSize = { + 20, 20, 20}; + protected float[] dataOrigin = { + 0, 0, 0}; + + private float[] xyzMax = new float[3]; + + protected float fStepSize = 0.1f; + protected float fTargetValue = 1; + protected ImplicitFunctionInterface function = null; + + protected List Normals = new ArrayList(); + protected List Vertices = new ArrayList(); + protected List Triangles = new ArrayList(); + + public Polygonizer() { + function = new defaultFunction(); + } + + public Polygonizer(float origin[], int dataSetSize[], float stepSize, + float isovalue, ImplicitFunctionInterface fun) { + dataOrigin = origin; + iDataSetSize = dataSetSize; + fStepSize = stepSize; + fTargetValue = isovalue; + function = fun; + + for (int i = 0; i < 3; i++) { + xyzMax[i] = dataOrigin[i] + iDataSetSize[i] * stepSize; + } + } + + public int noTriangles() { + if (Triangles == null) { + return 0; + } + return Triangles.size(); + } + + public List getVertices() { + return Vertices; + } + + public List getNormals() { + return Normals; + } + + public static void main(String[] args) { + Polygonizer polygonizer = new Polygonizer(); + } + + //vMarchingCubes iterates over the entire dataset, calling vMarchCube on each cube + public void marchingCubes() { + int iX, iY, iZ; + for (iX = 0; iX < iDataSetSize[0]; iX++) { + for (iY = 0; iY < iDataSetSize[1]; iY++) { + for (iZ = 0; iZ < iDataSetSize[2]; iZ++) { + marchCube(dataOrigin[0] + iX * fStepSize, + dataOrigin[1] + iY * fStepSize, + dataOrigin[2] + iZ * fStepSize, fStepSize); + } + } + } + } + + public void marchingTetrahedrons() { + int iX, iY, iZ; + for (iX = 0; iX < iDataSetSize[0]; iX++) { + for (iY = 0; iY < iDataSetSize[1]; iY++) { + for (iZ = 0; iZ < iDataSetSize[2]; iZ++) { + marchTetrahedrons(dataOrigin[0] + iX * fStepSize, + dataOrigin[1] + iY * fStepSize, + dataOrigin[2] + iZ * fStepSize, fStepSize); + } + } + } + } + + //vMarchCube1 performs the Marching Cubes algorithm on a single cube + void marchCube(float fX, float fY, float fZ, float fScale) { + + int iCorner, iVertex, iVertexTest, iEdge, iTriangle, iFlagIndex, + iEdgeFlags; + float fOffset; + GLvector sColor = new GLvector(); + float[] afCubeValue = new float[8]; + GLvector[] asEdgeVertex = new GLvector[12]; + GLvector[] asEdgeNorm = new GLvector[12]; + + for (int i = 0; i < 12; i++) { + asEdgeVertex[i] = new GLvector(); + asEdgeNorm[i] = new GLvector(); + } + + //Make a local copy of the values at the cube's corners + for (iVertex = 0; iVertex < 8; iVertex++) { + afCubeValue[iVertex] = (float) function.eval(fX + + a2fVertexOffset[iVertex][0] * fScale, + fY + + a2fVertexOffset[iVertex][1] * fScale, + fZ + + a2fVertexOffset[iVertex][2] * fScale); + } + + //Find which vertices are inside of the surface and which are outside + iFlagIndex = 0; + for (iVertexTest = 0; iVertexTest < 8; iVertexTest++) { + if (afCubeValue[iVertexTest] <= fTargetValue) { + iFlagIndex |= 1 << iVertexTest; + } + } + + //Find which edges are intersected by the surface + iEdgeFlags = aiCubeEdgeFlags[iFlagIndex]; + + //If the cube is entirely inside or outside of the surface, then there will be no intersections + if (iEdgeFlags == 0) { + return; + } + + //Find the point of intersection of the surface with each edge + //Then find the normal to the surface at those points + for (iEdge = 0; iEdge < 12; iEdge++) { + //if there is an intersection on this edge + if ( (iEdgeFlags & (1 << iEdge)) != 0) { + fOffset = fGetOffset(afCubeValue[a2iEdgeConnection[iEdge][0]], + afCubeValue[a2iEdgeConnection[iEdge][1]], + fTargetValue); + + asEdgeVertex[iEdge].fX = fX + + (a2fVertexOffset[a2iEdgeConnection[iEdge][0]][0] + + fOffset * a2fEdgeDirection[iEdge][0]) * fScale; + asEdgeVertex[iEdge].fY = fY + + (a2fVertexOffset[a2iEdgeConnection[iEdge][0]][1] + + fOffset * a2fEdgeDirection[iEdge][1]) * fScale; + asEdgeVertex[iEdge].fZ = fZ + + (a2fVertexOffset[a2iEdgeConnection[iEdge][0]][2] + + fOffset * a2fEdgeDirection[iEdge][2]) * fScale; + + getNormal(asEdgeNorm[iEdge], asEdgeVertex[iEdge].fX, + asEdgeVertex[iEdge].fY, asEdgeVertex[iEdge].fZ); + } + } + + //Draw the triangles that were found. There can be up to five per cube + for (iTriangle = 0; iTriangle < 5; iTriangle++) { + if (a2iTriangleConnectionTable[iFlagIndex][3 * iTriangle] < 0) { + break; + } + + Triangle triangle = new Triangle(); + + for (iCorner = 0; iCorner < 3; iCorner++) { + iVertex = a2iTriangleConnectionTable[iFlagIndex][3 * iTriangle + + iCorner]; + + //vGetColor(sColor, asEdgeVertex[iVertex], asEdgeNorm[iVertex]); + //glColor3f(sColor.fX, sColor.fY, sColor.fZ); + + //glNormal3f(asEdgeNorm[iVertex].fX, asEdgeNorm[iVertex].fY, + // asEdgeNorm[iVertex].fZ); + GLvector normal = new GLvector(asEdgeNorm[iVertex].fX, + asEdgeNorm[iVertex].fY, + asEdgeNorm[iVertex].fZ); + Normals.add(normal); + + //glVertex3f(asEdgeVertex[iVertex].fX, asEdgeVertex[iVertex].fY, + // asEdgeVertex[iVertex].fZ); + + GLvector vertex = new GLvector(asEdgeVertex[iVertex].fX, + asEdgeVertex[iVertex].fY, + asEdgeVertex[iVertex].fZ); + Vertices.add(vertex); + + triangle.addVertex(vertex, normal); + } + + Triangles.add(triangle); + } + } + + //vMarchingCubes iterates over the entire dataset, calling vMarchCube on each cube + public void marchingCubes2() { + int iX, iY, iZ; + Cube[][] slab_0 = new Cube[iDataSetSize[0]][iDataSetSize[1]]; + Cube[][] slab_1 = new Cube[iDataSetSize[0]][iDataSetSize[1]]; + + for (iX = 0; iX < iDataSetSize[0]; iX++) { + for (iY = 0; iY < iDataSetSize[1]; iY++) { + slab_0[iX][iY] = new Cube(); + slab_0[iX][iY].setStep(fStepSize); + slab_1[iX][iY] = new Cube(); + slab_1[iX][iY].setStep(fStepSize); + } + } + + for (iZ = 0; iZ < iDataSetSize[2]; iZ++) { + float fZ = dataOrigin[2] + iZ * fStepSize; + + for (iX = 0; iX < iDataSetSize[0]; iX++) { + float fX = dataOrigin[0] + iX * fStepSize; + for (iY = 0; iY < iDataSetSize[1]; iY++) { + float fY = dataOrigin[1] + iY * fStepSize; + + Cube cube = slab_1[iX][iY]; + cube.setOrigin(fX, fY, fZ); + + setupCube(slab_0, slab_1, iX, iY, iZ); + + } + } + // --- Switch slabs + Cube[][] temp = slab_0; + slab_0 = slab_1; + slab_1 = temp; + } + } + + void setupCube(Cube[][] slab_0, Cube[][] slab_1, int iX, int iY, int iZ) { + + // --- Set function values + + Cube cube = slab_1[iX][iY]; + + for (int iVertex = 0; iVertex < 8; iVertex++) { + cube.afCubeValue[iVertex] = (float) function.eval(cube.originX + + a2fVertexOffset[iVertex][0] * cube.step, + cube.originY + + a2fVertexOffset[iVertex][1] * cube.step, + cube.originZ + + a2fVertexOffset[iVertex][2] * cube.step); + } + + if (true) { + + if (iX == 0 && iY == 0) { + // --- Set 4,5, 6, 7th vertices + cube.afCubeValue[4] = (float) function.eval(cube.originX + a2fVertexOffset[4][0] * cube.step, + cube.originY + a2fVertexOffset[4][1] * cube.step, + cube.originZ + a2fVertexOffset[4][2] * cube.step); + cube.afCubeValue[5] = (float) function.eval(cube.originX + a2fVertexOffset[5][0] * cube.step, + cube.originY + a2fVertexOffset[5][1] * cube.step, + cube.originZ + a2fVertexOffset[5][2] * cube.step); + cube.afCubeValue[6] = (float) function.eval(cube.originX + a2fVertexOffset[6][0] * cube.step, + cube.originY + a2fVertexOffset[6][1] * cube.step, + cube.originZ + a2fVertexOffset[6][2] * cube.step); + cube.afCubeValue[7] = (float) function.eval(cube.originX + a2fVertexOffset[7][0] * cube.step, + cube.originY + a2fVertexOffset[7][1] * cube.step, + cube.originZ + a2fVertexOffset[7][2] * cube.step); + } + else if (iX == 0) { + + Cube cube_0 = slab_1[iX][iY - 1]; + cube.afCubeValue[4] = cube_0.afCubeValue[7]; + cube.afCubeValue[5] = cube_0.afCubeValue[6]; + cube.afCubeValue[6] = (float) function.eval(cube.originX + a2fVertexOffset[6][0] * fStepSize, + cube.originY + a2fVertexOffset[6][1] * fStepSize, + cube.originZ + a2fVertexOffset[6][2] * fStepSize); + cube.afCubeValue[7] = (float) function.eval(cube.originX + a2fVertexOffset[7][0] * fStepSize, + cube.originY + a2fVertexOffset[7][1] * fStepSize, + cube.originZ + a2fVertexOffset[7][2] * fStepSize); + } + else if (iY == 0) { + + Cube cube_0 = slab_1[iX - 1][iY]; + cube.afCubeValue[4] = cube_0.afCubeValue[5]; + cube.afCubeValue[7] = cube_0.afCubeValue[6]; + cube.afCubeValue[5] = (float) function.eval(cube.originX + a2fVertexOffset[5][0] * fStepSize, + cube.originY + a2fVertexOffset[5][1] * fStepSize, + cube.originZ + a2fVertexOffset[5][2] * fStepSize); + cube.afCubeValue[6] = (float) function.eval(cube.originX + a2fVertexOffset[6][0] * fStepSize, + cube.originY + a2fVertexOffset[6][1] * fStepSize, + cube.originZ + a2fVertexOffset[6][2] * fStepSize); + } + else { + + Cube cube_0 = slab_1[iX][iY - 1]; + cube.afCubeValue[4] = cube_0.afCubeValue[7]; + cube.afCubeValue[5] = cube_0.afCubeValue[6]; + cube_0 = slab_1[iX - 1][iY]; + cube.afCubeValue[7] = cube_0.afCubeValue[6]; + cube.afCubeValue[6] = (float) function.eval(cube.originX + a2fVertexOffset[6][0] * fStepSize, + cube.originY + a2fVertexOffset[6][1] * fStepSize, + cube.originZ + a2fVertexOffset[6][2] * fStepSize); + } + + // --- Process slab + if (iZ == 0) { + if (iX == 0 && iY == 0) { + // --- Set 4,5, 6, 7th vertices + cube.afCubeValue[0] = (float) function.eval(cube.originX + a2fVertexOffset[0][0] * fStepSize, + cube.originY + a2fVertexOffset[0][1] * fStepSize, + cube.originZ + a2fVertexOffset[0][2] * fStepSize); + cube.afCubeValue[1] = (float) function.eval(cube.originX + a2fVertexOffset[1][0] * fStepSize, + cube.originY + a2fVertexOffset[1][1] * fStepSize, + cube.originZ + a2fVertexOffset[1][2] * fStepSize); + cube.afCubeValue[2] = (float) function.eval(cube.originX + a2fVertexOffset[2][0] * fStepSize, + cube.originY + a2fVertexOffset[2][1] * fStepSize, + cube.originZ + a2fVertexOffset[2][2] * fStepSize); + cube.afCubeValue[3] = (float) function.eval(cube.originX + a2fVertexOffset[3][0] * fStepSize, + cube.originY + a2fVertexOffset[3][1] * fStepSize, + cube.originZ + a2fVertexOffset[3][2] * fStepSize); + } + else if (iX == 0) { + Cube cube_0 = slab_1[iX][iY - 1]; + cube.afCubeValue[0] = cube_0.afCubeValue[3]; + cube.afCubeValue[1] = cube_0.afCubeValue[2]; + cube.afCubeValue[2] = (float) function.eval(cube.originX + a2fVertexOffset[2][0] * fStepSize, + cube.originY + a2fVertexOffset[2][1] * fStepSize, + cube.originZ + a2fVertexOffset[2][2] * fStepSize); + cube.afCubeValue[3] = (float) function.eval(cube.originX + a2fVertexOffset[3][0] * fStepSize, + cube.originY + a2fVertexOffset[3][1] * fStepSize, + cube.originZ + a2fVertexOffset[3][2] * fStepSize); + } + else if (iY == 0) { + Cube cube_0 = slab_1[iX - 1][iY]; + cube.afCubeValue[0] = cube_0.afCubeValue[1]; + cube.afCubeValue[3] = cube_0.afCubeValue[2]; + cube.afCubeValue[1] = (float) function.eval(cube.originX + a2fVertexOffset[1][0] * fStepSize, + cube.originY + a2fVertexOffset[1][1] * fStepSize, + cube.originZ + a2fVertexOffset[1][2] * fStepSize); + cube.afCubeValue[2] = (float) function.eval(cube.originX + a2fVertexOffset[2][0] * fStepSize, + cube.originY + a2fVertexOffset[2][1] * fStepSize, + cube.originZ + a2fVertexOffset[2][2] * fStepSize); + } + else { + Cube cube_0 = slab_1[iX][iY - 1]; + cube.afCubeValue[0] = cube_0.afCubeValue[3]; + cube.afCubeValue[1] = cube_0.afCubeValue[2]; + cube_0 = slab_1[iX - 1][iY]; + cube.afCubeValue[3] = cube_0.afCubeValue[2]; + cube.afCubeValue[2] = (float) function.eval(cube.originX + a2fVertexOffset[2][0] * fStepSize, + cube.originY + a2fVertexOffset[2][1] * fStepSize, + cube.originZ + a2fVertexOffset[2][2] * fStepSize); + } + + } + + else { + Cube cube_0 = slab_0[iX][iY]; + cube.afCubeValue[0] = cube_0.afCubeValue[4]; + cube.afCubeValue[1] = cube_0.afCubeValue[5]; + cube.afCubeValue[2] = cube_0.afCubeValue[6]; + cube.afCubeValue[3] = cube_0.afCubeValue[7]; + } + } + + //Find which vertices are inside of the surface and which are outside + int iEdgeFlags = cube.getEdgeFlags(fTargetValue); + + //If the cube is entirely inside or outside of the surface, then there will be no intersections + if (iEdgeFlags == 0) { + return; + } + + //Find the point of intersection of the surface with each edge + //Then find the normal to the surface at those points + + for (int iEdge = 0; iEdge < 12; iEdge++) { + + //if there is an intersection on this edge + if ( (iEdgeFlags & (1 << iEdge)) != 0) { + float fOffset = fGetOffset(cube.afCubeValue[a2iEdgeConnection[iEdge][0]], + cube.afCubeValue[a2iEdgeConnection[iEdge][1]], + fTargetValue); + + cube.asEdgeVertex[iEdge].fX = cube.originX + (a2fVertexOffset[a2iEdgeConnection[iEdge][0]][0] + + fOffset * a2fEdgeDirection[iEdge][0]) * fStepSize; + cube.asEdgeVertex[iEdge].fY = cube.originY + (a2fVertexOffset[a2iEdgeConnection[iEdge][0]][1] + + fOffset * a2fEdgeDirection[iEdge][1]) * fStepSize; + cube.asEdgeVertex[iEdge].fZ = cube.originZ + (a2fVertexOffset[a2iEdgeConnection[iEdge][0]][2] + + fOffset * a2fEdgeDirection[iEdge][2]) * fStepSize; + + getNormal(cube.asEdgeNorm[iEdge], cube.asEdgeVertex[iEdge].fX, + cube.asEdgeVertex[iEdge].fY, cube.asEdgeVertex[iEdge].fZ); + } + } + + if (false) { + // More smart stuff, if any + + if (iX == 0 && iY == 0) { + if ( (iEdgeFlags & (1 << 4)) != 0) { + setupEdge(cube, 4); + } + if ( (iEdgeFlags & (1 << 5)) != 0) { + setupEdge(cube, 5); + } + if ( (iEdgeFlags & (1 << 6)) != 0) { + setupEdge(cube, 6); + } + if ( (iEdgeFlags & (1 << 7)) != 0) { + setupEdge(cube, 7); + } + if ( (iEdgeFlags & (1 << 8)) != 0) { + setupEdge(cube, 8); + } + if ( (iEdgeFlags & (1 << 9)) != 0) { + setupEdge(cube, 9); + } + if ( (iEdgeFlags & (1 << 10)) != 0) { + setupEdge(cube, 10); + } + if ( (iEdgeFlags & (1 << 11)) != 0) { + setupEdge(cube, 11); + } + } + + else if (iX == 0) { + + if ( (iEdgeFlags & (1 << 5)) != 0) { + setupEdge(cube, 5); + } + if ( (iEdgeFlags & (1 << 6)) != 0) { + setupEdge(cube, 6); + } + if ( (iEdgeFlags & (1 << 7)) != 0) { + setupEdge(cube, 7); + } + if ( (iEdgeFlags & (1 << 10)) != 0) { + setupEdge(cube, 10); + } + if ( (iEdgeFlags & (1 << 11)) != 0) { + setupEdge(cube, 11); + } + + Cube cube_0 = slab_1[iX][iY - 1]; + + if ( (iEdgeFlags & (1 << 4)) != 0) { + setupEdge(cube, 4, cube_0, 6); + } + if ( (iEdgeFlags & (1 << 8)) != 0) { + setupEdge(cube, 8, cube_0, 11); + } + if ( (iEdgeFlags & (1 << 9)) != 0) { + setupEdge(cube, 9, cube_0, 10); + } + } + + else if (iY == 0) { + + if ( (iEdgeFlags & (1 << 4)) != 0) { + setupEdge(cube, 4); + } + if ( (iEdgeFlags & (1 << 5)) != 0) { + setupEdge(cube, 5); + } + if ( (iEdgeFlags & (1 << 6)) != 0) { + setupEdge(cube, 6); + } + if ( (iEdgeFlags & (1 << 9)) != 0) { + setupEdge(cube, 9); + } + if ( (iEdgeFlags & (1 << 10)) != 0) { + setupEdge(cube, 10); + } + + Cube cube_0 = slab_1[iX - 1][iY]; + + if ( (iEdgeFlags & (1 << 7)) != 0) { + setupEdge(cube, 7, cube_0, 5); + } + if ( (iEdgeFlags & (1 << 8)) != 0) { + setupEdge(cube, 8, cube_0, 9); + } + if ( (iEdgeFlags & (1 << 11)) != 0) { + setupEdge(cube, 11, cube_0, 10); + } + } + + else { + if ( (iEdgeFlags & (1 << 5)) != 0) { + setupEdge(cube, 5); + } + if ( (iEdgeFlags & (1 << 6)) != 0) { + setupEdge(cube, 6); + } + if ( (iEdgeFlags & (1 << 10)) != 0) { + setupEdge(cube, 10); + } + + Cube cube_0 = slab_1[iX][iY - 1]; + + if ( (iEdgeFlags & (1 << 4)) != 0) { + setupEdge(cube, 4, cube_0, 6); + } + if ( (iEdgeFlags & (1 << 8)) != 0) { + setupEdge(cube, 8, cube_0, 11); + } + if ( (iEdgeFlags & (1 << 9)) != 0) { + setupEdge(cube, 9, cube_0, 10); + } + + cube_0 = slab_1[iX - 1][iY]; + + if ( (iEdgeFlags & (1 << 7)) != 0) { + setupEdge(cube, 7, cube_0, 5); + } + if ( (iEdgeFlags & (1 << 11)) != 0) { + setupEdge(cube, 11, cube_0, 10); + } + } + + // --- Process slab + if (iZ == 0) { + if (iX == 0 && iY == 0) { + + if ( (iEdgeFlags & (1 << 0)) != 0) { + setupEdge(cube, 0); + } + if ( (iEdgeFlags & (1 << 1)) != 0) { + setupEdge(cube, 1); + } + if ( (iEdgeFlags & (1 << 2)) != 0) { + setupEdge(cube, 2); + } + if ( (iEdgeFlags & (1 << 3)) != 0) { + setupEdge(cube, 3); + } + } + + else if (iX == 0) { + + if ( (iEdgeFlags & (1 << 1)) != 0) { + setupEdge(cube, 1); + } + if ( (iEdgeFlags & (1 << 2)) != 0) { + setupEdge(cube, 2); + } + if ( (iEdgeFlags & (1 << 3)) != 0) { + setupEdge(cube, 3); + } + + Cube cube_0 = slab_0[iX][iY - 1]; + + if ( (iEdgeFlags & (1 << 0)) != 0) { + setupEdge(cube, 0, cube_0, 2); + } + + } + else if (iY == 0) { + + if ( (iEdgeFlags & (1 << 0)) != 0) { + setupEdge(cube, 0); + } + if ( (iEdgeFlags & (1 << 1)) != 0) { + setupEdge(cube, 1); + } + if ( (iEdgeFlags & (1 << 2)) != 0) { + setupEdge(cube, 2); + } + + Cube cube_0 = slab_0[iX - 1][iY]; + + if ( (iEdgeFlags & (1 << 3)) != 0) { + setupEdge(cube, 3, cube_0, 1); + } + } + + else { + if ( (iEdgeFlags & (1 << 1)) != 0) { + setupEdge(cube, 1); + } + if ( (iEdgeFlags & (1 << 2)) != 0) { + setupEdge(cube, 2); + } + + Cube cube_0 = slab_0[iX][iY - 1]; + + if ( (iEdgeFlags & (1 << 0)) != 0) { + setupEdge(cube, 0, cube_0, 2); + } + + cube_0 = slab_0[iX - 1][iY]; + + if ( (iEdgeFlags & (1 << 3)) != 0) { + setupEdge(cube, 3, cube_0, 1); + } + } + } + + else { + Cube cube_0 = slab_0[iX][iY]; + if ( (iEdgeFlags & (1 << 0)) != 0) { + setupEdge(cube, 0, cube_0, 4); + } + if ( (iEdgeFlags & (1 << 1)) != 0) { + setupEdge(cube, 1, cube_0, 5); + } + if ( (iEdgeFlags & (1 << 2)) != 0) { + setupEdge(cube, 2, cube_0, 6); + } + if ( (iEdgeFlags & (1 << 3)) != 0) { + setupEdge(cube, 3, cube_0, 7); + } + + } + } + //Draw the triangles that were found. There can be up to five per cube + int iFlagIndex = cube.getFlagIndex(fTargetValue); + for (int iTriangle = 0; iTriangle < 5; iTriangle++) { + if (a2iTriangleConnectionTable[iFlagIndex][3 * iTriangle] < 0) { + break; + } + + Triangle triangle = new Triangle(); + + for (int iCorner = 0; iCorner < 3; iCorner++) { + int iVertex = a2iTriangleConnectionTable[iFlagIndex][3 * iTriangle + iCorner]; + + GLvector normal = new GLvector(cube.asEdgeNorm[iVertex].fX, + cube.asEdgeNorm[iVertex].fY, + cube.asEdgeNorm[iVertex].fZ); + Normals.add(normal); + + GLvector vertex = new GLvector(cube.asEdgeVertex[iVertex].fX, + cube.asEdgeVertex[iVertex].fY, + cube.asEdgeVertex[iVertex].fZ); + Vertices.add(vertex); + + triangle.addVertex(vertex, normal); + } + + Triangles.add(triangle); + } + + } + + void setupEdge(Cube cube, int iEdge) { + float fOffset = fGetOffset(cube.afCubeValue[a2iEdgeConnection[iEdge][0]], cube.afCubeValue[a2iEdgeConnection[iEdge][1]], + fTargetValue); + + cube.asEdgeVertex[iEdge].fX = cube.originX + (a2fVertexOffset[a2iEdgeConnection[iEdge][0]][0] + + fOffset * a2fEdgeDirection[iEdge][0]) * fStepSize; + cube.asEdgeVertex[iEdge].fY = cube.originY + (a2fVertexOffset[a2iEdgeConnection[iEdge][0]][1] + + fOffset * a2fEdgeDirection[iEdge][1]) * fStepSize; + cube.asEdgeVertex[iEdge].fZ = cube.originZ + (a2fVertexOffset[a2iEdgeConnection[iEdge][0]][2] + + fOffset * a2fEdgeDirection[iEdge][2]) * fStepSize; + + getNormal(cube.asEdgeNorm[iEdge], cube.asEdgeVertex[iEdge].fX, cube.asEdgeVertex[iEdge].fY, cube.asEdgeVertex[iEdge].fZ); + } + + void setupEdge(Cube cube, int iEdge, Cube cube_2, int iEdge_2) { + cube.asEdgeVertex[iEdge].fX = cube_2.asEdgeVertex[iEdge_2].fX; + cube.asEdgeVertex[iEdge].fY = cube_2.asEdgeVertex[iEdge_2].fY; + cube.asEdgeVertex[iEdge].fZ = cube_2.asEdgeVertex[iEdge_2].fZ; + + cube.asEdgeNorm[iEdge].fX = cube_2.asEdgeNorm[iEdge_2].fX; + cube.asEdgeNorm[iEdge].fY = cube_2.asEdgeNorm[iEdge_2].fY; + cube.asEdgeNorm[iEdge].fZ = cube_2.asEdgeNorm[iEdge_2].fZ; + } + + void marchCube2(Cube cube, float fX, float fY, float fZ, float fScale) { + + int iCorner, iVertex, iVertexTest, iEdge, iTriangle, iFlagIndex, iEdgeFlags; + float fOffset; + GLvector sColor = new GLvector(); + float[] afCubeValue = new float[8]; + GLvector[] asEdgeVertex = new GLvector[12]; + GLvector[] asEdgeNorm = new GLvector[12]; + + for (int i = 0; i < 12; i++) { + asEdgeVertex[i] = new GLvector(); + asEdgeNorm[i] = new GLvector(); + } + + //Make a local copy of the values at the cube's corners + /* + 0 0.0f, 0.0f, 0.0f}, { + 1 1.0f, 0.0f, 0.0f}, { + 2 1.0f, 1.0f, 0.0f}, { + 3 0.0f, 1.0f, 0.0f}, { + 4 0.0f, 0.0f, 1.0f}, { + 5 1.0f, 0.0f, 1.0f}, { + 6 1.0f, 1.0f, 1.0f}, { + 7 0.0f, 1.0f, 1.0f} + */ + for (iVertex = 0; iVertex < 8; iVertex++) { + afCubeValue[iVertex] = (float) function.eval(fX + + a2fVertexOffset[iVertex][0] * fScale, + fY + + a2fVertexOffset[iVertex][1] * fScale, + fZ + + a2fVertexOffset[iVertex][2] * fScale); + } + + //Find which vertices are inside of the surface and which are outside + iFlagIndex = 0; + for (iVertexTest = 0; iVertexTest < 8; iVertexTest++) { + if (afCubeValue[iVertexTest] <= fTargetValue) { + iFlagIndex |= 1 << iVertexTest; + } + } + + //Find which edges are intersected by the surface + iEdgeFlags = aiCubeEdgeFlags[iFlagIndex]; + + //If the cube is entirely inside or outside of the surface, then there will be no intersections + if (iEdgeFlags == 0) { + return; + } + + //Find the point of intersection of the surface with each edge + //Then find the normal to the surface at those points + for (iEdge = 0; iEdge < 12; iEdge++) { + //if there is an intersection on this edge + if ( (iEdgeFlags & (1 << iEdge)) != 0) { + fOffset = fGetOffset(afCubeValue[a2iEdgeConnection[iEdge][0]], + afCubeValue[a2iEdgeConnection[iEdge][1]], + fTargetValue); + + asEdgeVertex[iEdge].fX = fX + + (a2fVertexOffset[a2iEdgeConnection[iEdge][0]][0] + + fOffset * a2fEdgeDirection[iEdge][0]) * fScale; + asEdgeVertex[iEdge].fY = fY + + (a2fVertexOffset[a2iEdgeConnection[iEdge][0]][1] + + fOffset * a2fEdgeDirection[iEdge][1]) * fScale; + asEdgeVertex[iEdge].fZ = fZ + + (a2fVertexOffset[a2iEdgeConnection[iEdge][0]][2] + + fOffset * a2fEdgeDirection[iEdge][2]) * fScale; + + getNormal(asEdgeNorm[iEdge], asEdgeVertex[iEdge].fX, + asEdgeVertex[iEdge].fY, asEdgeVertex[iEdge].fZ); + } + } + + //Draw the triangles that were found. There can be up to five per cube + for (iTriangle = 0; iTriangle < 5; iTriangle++) { + if (a2iTriangleConnectionTable[iFlagIndex][3 * iTriangle] < 0) { + break; + } + + Triangle triangle = new Triangle(); + + for (iCorner = 0; iCorner < 3; iCorner++) { + iVertex = a2iTriangleConnectionTable[iFlagIndex][3 * iTriangle + + iCorner]; + + GLvector normal = new GLvector(asEdgeNorm[iVertex].fX, + asEdgeNorm[iVertex].fY, + asEdgeNorm[iVertex].fZ); + Normals.add(normal); + + GLvector vertex = new GLvector(asEdgeVertex[iVertex].fX, + asEdgeVertex[iVertex].fY, + asEdgeVertex[iVertex].fZ); + Vertices.add(vertex); + + triangle.addVertex(vertex, normal); + } + + Triangles.add(triangle); + } + } + +//vGetNormal() finds the gradient of the scalar field at a point +//This gradient can be used as a very accurate vertx normal for lighting calculations + void getNormal(GLvector rfNormal, float fX, float fY, float fZ) { + float delta = 0.01f; + + if (fX - delta < this.dataOrigin[0]) { + rfNormal.fX = (float) (function.eval(fX, fY, fZ) - function.eval(fX + delta, fY, fZ)) / delta; + } + else if (fX + delta > xyzMax[0]) { + rfNormal.fX = (float) (function.eval(fX - delta, fY, fZ) - function.eval(fX, fY, fZ)) / delta; + } + else { + rfNormal.fX = (float) (function.eval(fX - delta, fY, fZ) - function.eval(fX + delta, fY, fZ)) / (2 * delta); + } + + if (fY - delta < this.dataOrigin[1]) { + rfNormal.fY = (float) (function.eval(fX, fY, fZ) - function.eval(fX, fY + delta, fZ)) / delta; + } + else if (fY + delta > xyzMax[1]) { + rfNormal.fY = (float) (function.eval(fX, fY - delta, fZ) - function.eval(fX, fY, fZ)) / delta; + } + else { + rfNormal.fY = (float) (function.eval(fX, fY - delta, fZ) - function.eval(fX, fY + delta, fZ)) / (2 * delta); + } + + if (fZ - delta < this.dataOrigin[2]) { + rfNormal.fZ = (float) (function.eval(fX, fY, fZ) - function.eval(fX, fY, fZ + delta)) / delta; + } + else if (fZ + delta > xyzMax[2]) { + rfNormal.fZ = (float) (function.eval(fX, fY, fZ - delta) - function.eval(fX, fY, fZ)) / delta; + } + else { + rfNormal.fZ = (float) (function.eval(fX, fY, fZ - delta) - function.eval(fX, fY, fZ + delta)) / (2 * delta); + } + + /* + rfNormal.fX = function.eval(fX - 0.01f, fY, fZ) - function.eval(fX + 0.01f, fY, fZ); + rfNormal.fY = function.eval(fX, fY - 0.01f, fZ) - function.eval(fX, fY + 0.01f, fZ); + rfNormal.fZ = function.eval(fX, fY, fZ - 0.01f) - function.eval(fX, fY, fZ + 0.01f); + */ + + normalizeVector(rfNormal, rfNormal); + } + + void normalizeVector(GLvector rfVectorResult, GLvector rfVectorSource) { + float fOldLength; + float fScale; + + fOldLength = (float) Math.sqrt( (rfVectorSource.fX * rfVectorSource.fX) + + (rfVectorSource.fY * rfVectorSource.fY) + + (rfVectorSource.fZ * rfVectorSource.fZ)); + + if (fOldLength == 0.0) { + rfVectorResult.fX = rfVectorSource.fX; + rfVectorResult.fY = rfVectorSource.fY; + rfVectorResult.fZ = rfVectorSource.fZ; + } + else { + fScale = 1.0f / fOldLength; + rfVectorResult.fX = rfVectorSource.fX * fScale; + rfVectorResult.fY = rfVectorSource.fY * fScale; + rfVectorResult.fZ = rfVectorSource.fZ * fScale; + } + } + +//fGetOffset finds the approximate point of intersection of the surface +// between two points with the values fValue1 and fValue2 + float fGetOffset(float fValue1, float fValue2, float fValueDesired) { + //double fDelta = fValue2 - fValue1; + float fDelta = fValue2 - fValue1; + + if (fDelta == 0.0f) { + return 0.5f; + } + return (fValueDesired - fValue1) / fDelta; + } + +//vMarchCube2 performs the Marching Tetrahedrons algorithm on a single cube by making six calls to vMarchTetrahedron + public void marchTetrahedrons(float fX, float fY, float fZ, float fScale) { + int iVertex, iTetrahedron, iVertexInACube; + GLvector[] asCubePosition = new GLvector[8]; + float[] afCubeValue = new float[8]; + GLvector[] asTetrahedronPosition = new GLvector[4]; + float[] afTetrahedronValue = new float[4]; + + for (int i = 0; i < 8; i++) { + asCubePosition[i] = new GLvector(); + } + for (int i = 0; i < 4; i++) { + asTetrahedronPosition[i] = new GLvector(); + } + + //Make a local copy of the cube's corner positions + for (iVertex = 0; iVertex < 8; iVertex++) { + asCubePosition[iVertex].fX = fX + a2fVertexOffset[iVertex][0] * fScale; + asCubePosition[iVertex].fY = fY + a2fVertexOffset[iVertex][1] * fScale; + asCubePosition[iVertex].fZ = fZ + a2fVertexOffset[iVertex][2] * fScale; + } + + //Make a local copy of the cube's corner values + for (iVertex = 0; iVertex < 8; iVertex++) { + afCubeValue[iVertex] = (float) function.eval(asCubePosition[iVertex].fX, + asCubePosition[iVertex].fY, + asCubePosition[iVertex].fZ); + } + + for (iTetrahedron = 0; iTetrahedron < 6; iTetrahedron++) { + for (iVertex = 0; iVertex < 4; iVertex++) { + iVertexInACube = a2iTetrahedronsInACube[iTetrahedron][iVertex]; + asTetrahedronPosition[iVertex].fX = asCubePosition[iVertexInACube].fX; + asTetrahedronPosition[iVertex].fY = asCubePosition[iVertexInACube].fY; + asTetrahedronPosition[iVertex].fZ = asCubePosition[iVertexInACube].fZ; + afTetrahedronValue[iVertex] = afCubeValue[iVertexInACube]; + } + marchTetrahedron(asTetrahedronPosition, afTetrahedronValue); + } + } + +//marchTetrahedron performs the Marching Tetrahedrons algorithm on a single tetrahedron + void marchTetrahedron(GLvector pasTetrahedronPosition[], + float pafTetrahedronValue[]) { + //extern GLint aiTetrahedronEdgeFlags[16]; + //extern GLint a2iTetrahedronTriangles[16][7]; + + int iEdge, iVert0, iVert1, iEdgeFlags, iTriangle, iCorner, iVertex, + iFlagIndex = 0; + float fOffset, fInvOffset, fValue = 0.0f; + GLvector[] asEdgeVertex = new GLvector[6]; + GLvector[] asEdgeNorm = new GLvector[6]; + GLvector sColor; + + for (int i = 0; i < 6; i++) { + asEdgeVertex[i] = new GLvector(); + asEdgeNorm[i] = new GLvector(); + } + + //Find which vertices are inside of the surface and which are outside + for (iVertex = 0; iVertex < 4; iVertex++) { + if (pafTetrahedronValue[iVertex] <= fTargetValue) { + iFlagIndex |= 1 << iVertex; + } + } + + //Find which edges are intersected by the surface + iEdgeFlags = aiTetrahedronEdgeFlags[iFlagIndex]; + + //If the tetrahedron is entirely inside or outside of the surface, then there will be no intersections + if (iEdgeFlags == 0) { + return; + } + //Find the point of intersection of the surface with each edge + // Then find the normal to the surface at those points + for (iEdge = 0; iEdge < 6; iEdge++) { + //if there is an intersection on this edge + if ( (iEdgeFlags & (1 << iEdge)) != 0) { + iVert0 = a2iTetrahedronEdgeConnection[iEdge][0]; + iVert1 = a2iTetrahedronEdgeConnection[iEdge][1]; + fOffset = fGetOffset(pafTetrahedronValue[iVert0], + pafTetrahedronValue[iVert1], fTargetValue); + fInvOffset = 1.0f - fOffset; + + asEdgeVertex[iEdge].fX = fInvOffset * pasTetrahedronPosition[iVert0].fX + + fOffset * pasTetrahedronPosition[iVert1].fX; + asEdgeVertex[iEdge].fY = fInvOffset * pasTetrahedronPosition[iVert0].fY + + fOffset * pasTetrahedronPosition[iVert1].fY; + asEdgeVertex[iEdge].fZ = fInvOffset * pasTetrahedronPosition[iVert0].fZ + + fOffset * pasTetrahedronPosition[iVert1].fZ; + + getNormal(asEdgeNorm[iEdge], asEdgeVertex[iEdge].fX, + asEdgeVertex[iEdge].fY, asEdgeVertex[iEdge].fZ); + } + } + //Draw the triangles that were found. There can be up to 2 per tetrahedron + for (iTriangle = 0; iTriangle < 2; iTriangle++) { + if (a2iTetrahedronTriangles[iFlagIndex][3 * iTriangle] < 0) { + break; + } + + Triangle triangle = new Triangle(); + + for (iCorner = 0; iCorner < 3; iCorner++) { + iVertex = a2iTetrahedronTriangles[iFlagIndex][3 * iTriangle + iCorner]; + + //vGetColor(sColor, asEdgeVertex[iVertex], asEdgeNorm[iVertex]); + //glColor3f(sColor.fX, sColor.fY, sColor.fZ); + + //glNormal3f(asEdgeNorm[iVertex].fX, asEdgeNorm[iVertex].fY, + // asEdgeNorm[iVertex].fZ); + GLvector normal = new GLvector(asEdgeNorm[iVertex].fX, + asEdgeNorm[iVertex].fY, + asEdgeNorm[iVertex].fZ); + Normals.add(normal); + + //glVertex3f(asEdgeVertex[iVertex].fX, asEdgeVertex[iVertex].fY, + // asEdgeVertex[iVertex].fZ); + GLvector vertex = new GLvector(asEdgeVertex[iVertex].fX, + asEdgeVertex[iVertex].fY, + asEdgeVertex[iVertex].fZ); + Vertices.add(vertex); + + triangle.addVertex(vertex, normal); + + } + + Triangles.add(triangle); + } + } + + public void dispose() { + Normals.clear(); + Vertices.clear(); + Triangles.clear(); + Normals = null; + Vertices = null; + Triangles = null; + } + + private class Triangle { + GLvector[] vertices = new GLvector[3]; + GLvector[] normals = new GLvector[3]; + int index = 0; + + public void addVertex(GLvector vertex, GLvector normal) { + vertices[index] = vertex; + normals[index] = normal; + ++index; + } + } + + private class Cube { + float originX, originY, originZ, step; + float[] afCubeValue = new float[8]; + GLvector[] asEdgeVertex = new GLvector[12]; + GLvector[] asEdgeNorm = new GLvector[12]; + + public Cube() { + for (int i = 0; i < 12; i++) { + asEdgeVertex[i] = new GLvector(); + asEdgeNorm[i] = new GLvector(); + } + } + + public void setStep(float st) { + step = st; + } + + public void setOrigin(float x, float y, float z) { + originX = x; + originY = y; + originZ = z; + } + + public int getFlagIndex(float fTargetValue) { + //Find which vertices are inside of the surface and which are outside + int iFlagIndex = 0; + for (int iVertexTest = 0; iVertexTest < 8; iVertexTest++) { + if (afCubeValue[iVertexTest] <= fTargetValue) { + iFlagIndex |= 1 << iVertexTest; + } + } + return iFlagIndex; + } + + public int getEdgeFlags(float fTargetValue) { + //Find which vertices are inside of the surface and which are outside + int iFlagIndex = 0; + for (int iVertexTest = 0; iVertexTest < 8; iVertexTest++) { + if (afCubeValue[iVertexTest] <= fTargetValue) { + iFlagIndex |= 1 << iVertexTest; + } + } + + //Find which edges are intersected by the surface + int iEdgeFlags = aiCubeEdgeFlags[iFlagIndex]; + + //If the cube is entirely inside or outside of the surface, then there will be no intersections + return iEdgeFlags; + } + } + + private class defaultFunction + implements ImplicitFunctionInterface { + @Override + public double eval(float x, float y, float z) { + return (float) Math.sqrt( (x - 1) * (x - 1) + y * y + z * z); + } + } +} diff --git a/src/main/java/cct/math/polyg/java3d/j3dPolygonizer.java b/src/main/java/cct/math/polyg/java3d/j3dPolygonizer.java new file mode 100644 index 0000000..5fd9b99 --- /dev/null +++ b/src/main/java/cct/math/polyg/java3d/j3dPolygonizer.java @@ -0,0 +1,214 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.math.polyg.java3d; + +import java.util.logging.Logger; + +import org.scijava.java3d.Appearance; +import org.scijava.java3d.GeometryArray; +import org.scijava.java3d.Shape3D; +import org.scijava.java3d.TriangleArray; +import org.scijava.vecmath.Color3f; +import org.scijava.vecmath.Color4f; +import org.scijava.vecmath.Point3f; +import org.scijava.vecmath.Vector3f; + +import cct.interfaces.ImplicitFunctionInterface; +import cct.math.polyg.GLvector; +import cct.math.polyg.Polygonizer; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class j3dPolygonizer + extends Polygonizer { + + boolean marchingTetras = false; + static final Logger logger = Logger.getLogger(j3dPolygonizer.class.getCanonicalName()); + + public j3dPolygonizer() { + super(); + } + + public j3dPolygonizer(float origin[], int dataSetSize[], float stepSize, + float isovalue, ImplicitFunctionInterface fun) { + super(origin, dataSetSize, stepSize, isovalue, fun); + } + + public void setMarchingTatrahedrons(boolean enable) { + marchingTetras = enable; + } + + public Shape3D getSurface() { + + this.marchCubes(); + TriangleArray tetra2 = this.getTriangleArray(); + + Shape3D shape3d = new Shape3D(tetra2); + + shape3d.setAppearance(new Appearance()); + + return shape3d; + + } + + public void marchCubes() { + + if (marchingTetras) { + super.marchingTetrahedrons(); + } + else { + super.marchingCubes2(); + } + int nVertices = this.Vertices.size(); + + if (nVertices < 1) { + logger.info("No vertices"); + } + } + + public TriangleArray getTriangleArray() { + + boolean useColor4f = false; + + int nVertices = this.Vertices.size(); + + if (nVertices < 1) { + logger.info("No vertices"); + return null; + } + + java.awt.Color color; + + if (this.fTargetValue > 0) { + color = java.awt.Color.RED; + } + else if (this.fTargetValue < 0) { + color = java.awt.Color.BLUE; + } + else { + color = java.awt.Color.GRAY; + } + + logger.info("N of vertices " + nVertices); + + TriangleArray tetra2 = null; + + if (useColor4f) { + tetra2 = new TriangleArray(nVertices, GeometryArray.COORDINATES | GeometryArray.NORMALS | GeometryArray.COLOR_4); + } + else { + tetra2 = new TriangleArray(nVertices, GeometryArray.COORDINATES | GeometryArray.NORMALS | GeometryArray.COLOR_3); + } + + tetra2.setCapability(GeometryArray.ALLOW_COLOR_READ); + tetra2.setCapability(GeometryArray.ALLOW_COLOR_WRITE); + tetra2.setCapability(GeometryArray.ALLOW_COORDINATE_READ); + tetra2.setCapability(GeometryArray.ALLOW_COORDINATE_WRITE); + tetra2.setCapability(GeometryArray.ALLOW_COUNT_READ); + tetra2.setCapability(GeometryArray.ALLOW_COUNT_WRITE); + tetra2.setCapability(GeometryArray.ALLOW_FORMAT_READ); + tetra2.setCapability(GeometryArray.ALLOW_VERTEX_ATTR_READ); + tetra2.setCapability(GeometryArray.ALLOW_VERTEX_ATTR_WRITE); + tetra2.setCapability(GeometryArray.ALLOW_NORMAL_READ); + tetra2.setCapability(GeometryArray.ALLOW_NORMAL_WRITE); + + tetra2.setCapability(GeometryArray.ALLOW_REF_DATA_READ); + tetra2.setCapability(GeometryArray.ALLOW_REF_DATA_WRITE); + + Point3f[] coordinates = new Point3f[nVertices]; + Vector3f[] normals = new Vector3f[nVertices]; + Color4f[] colors_4f = null; + Color3f[] colors_3f = null; + + if (useColor4f) { + colors_4f = new Color4f[nVertices]; + } + else { + colors_3f = new Color3f[nVertices]; + } + + for (int i = 0; i < nVertices; ++i) { + GLvector coord = (GLvector) Vertices.get(i); + coordinates[i] = new Point3f(coord.fX, coord.fY, coord.fZ); + + float factor = 1.0f; + //if (delta > 0) { + // factor = -factor; + // } + + GLvector normal = (GLvector) Normals.get(i); + normals[i] = new Vector3f(factor * normal.fX, factor * normal.fY, factor * normal.fZ); + } + + if (useColor4f) { + for (int i = 0; i < nVertices; ++i) { + colors_4f[i] = new Color4f(color); + } + } + else { + for (int i = 0; i < nVertices; ++i) { + colors_3f[i] = new Color3f(color); + } + } + + tetra2.setCoordinates(0, coordinates); + tetra2.setNormals(0, normals); + if (useColor4f) { + tetra2.setColors(0, colors_4f); + } + else { + tetra2.setColors(0, colors_3f); + } + + return tetra2; + } + + public static void main(String[] args) { + j3dPolygonizer j3dpolygonizer = new j3dPolygonizer(); + } +} diff --git a/src/main/java/cct/mdl/MDLMol.java b/src/main/java/cct/mdl/MDLMol.java new file mode 100644 index 0000000..2f8a3ef --- /dev/null +++ b/src/main/java/cct/mdl/MDLMol.java @@ -0,0 +1,335 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.mdl; + +import java.io.BufferedReader; +import java.io.FileReader; + +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.ChemicalElements; +import cct.modelling.Molecule; +import cct.tools.IOUtils; +import java.awt.FileDialog; +import java.awt.Frame; +import java.io.File; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Set; + +/** + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2006

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class MDLMol { + + public MDLMol() { + } + + public MoleculeInterface parseFile(String filename, MoleculeInterface mol) throws Exception { + String line; + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(filename)); + } catch (Exception ex) { + throw new Exception("Error opening file " + filename + " : " + ex.getLocalizedMessage()); + } + return parseFile(in, mol); + } + + public MoleculeInterface parseFile(BufferedReader in, MoleculeInterface mol) throws Exception { + return parseFile((Object) in, mol); + + } + + public MoleculeInterface parseFile(File file, MoleculeInterface mol) throws Exception { + return parseFile(file.getAbsolutePath(), mol); + } + + public MoleculeInterface parseFile(Object in, MoleculeInterface mol) throws Exception { + String line; + try { + // --- Line 1 + // Molecule name. This line is unformatted, but like all other lines in a molfile + // may not extend beyond column 80. If no name is available, a blank line must be present. + if ((line = IOUtils.readLine(in)) == null) { + //IOUtils.close(in); + throw new Exception("parseMDLMolfile: ERROR: Unxpected End of file while reading Line 1"); + } + + mol.setName(line.trim()); + + // -- Line 2 - Ignored for now !!! + // This line has the format: + // IIPPPPPPPPMMDDYYHHmmddSSssssssssssEEEEEEEEEEEERRRRRR + //(FORTRAN: A2<--A8--><---A10-->A2I2<--F10.5-><---F12.5--><-I6-> ) + // User's first and last initials (l), program name (P), + // date/time (M/D/Y,H:m), dimensional codes (d), scaling factors (S, s), + // energy (E) if modeling program input, internal registry number (R) if input through MDL form. + // A blank line can be substituted for line 2. + if ((line = IOUtils.readLine(in)) == null) { + //IOUtils.close(in); + throw new Exception("parseMDLMolfile: ERROR: Unxpected End of file while reading Line 2"); + } + + // --- Line 3 - Ignored + // A line for comments. If no comment is entered, a blank line must be present. + if ((line = IOUtils.readLine(in)) == null) { + //IOUtils.close(in); + throw new Exception("parseMDLMolfile: ERROR: Unxpected End of file while reading Line 2"); + } + + // -- Counts line + // aaabbblllfffcccsssxxxrrrpppiiimmmvvvvvv + // Where: + // aaa = number of atoms (current max 255)* [Generic] + // bbb = number of bonds (current max 255)* [Generic] + // lll = number of atom lists (max 30)* [Query] + // fff = (obsolete) + // ccc = chiral flag: 0=not chiral, 1=chiral [Generic] + // sss = number of stext entries [MDL ISIS/Desktop] + // xxx = (obsolete) + // rrr = (obsolete) + // ppp = (obsolete) + // iii = (obsolete) + // mmm = number of lines of additional properties, including the M END line. + // No longer supported, the default is set to 999. [Generic] + // * These limits apply to MACCS-II, REACCS, and the MDL ISIS/Host Reaction Gateway, + // but not to the MDL ISIS/Host Molecule Gateway or MDL ISIS/Desktop. + if ((line = IOUtils.readLine(in)) == null) { + //IOUtils.close(in); + throw new Exception("parseMDLMolfile: ERROR: Unxpected End of file while reading Counts line"); + } + + int natoms = 0; + int nbonds = 0; + try { + natoms = Integer.parseInt(line.substring(0, 3).trim()); + } catch (Exception e) { + //IOUtils.close(in); + throw new Exception("parseMDLMolfile: ERROR: Error while parsing number of atoms: " + + e.getMessage()); + } + + try { + nbonds = Integer.parseInt(line.substring(3, 6).trim()); + } catch (Exception e) { + //IOUtils.close(in); + throw new Exception("parseMDLMolfile: ERROR: Error while parsing number of bonds: " + + e.getMessage()); + } + + // --- The atom block + // The Atom Block is made up of atom lines, one line per atom with the following format: + // xxxxx.xxxxyyyyy.yyyyzzzzz.zzzz aaaddcccssshhhbbbvvvHHHrrriiimmmnnneee + // where the values are described in the following table: + // x y z - atom coordinates [Generic] + // aaa - atom symbol - entry in periodic table or L for atom list, A, Q, + // * for unspecified atom, and LP for lone pair, or R# for Rgroup label - [Generic, Query, 3D, Rgroup] + // dd - mass difference - -3, -2, -1, 0, 1, 2, 3, 4 - (0 if value beyond these limits) + // [Generic] Difference from mass in periodic table. Wider range of values allowed by M ISO line, below. + // Retained for compatibility with older Ctabs, M ISO takes precedence. + // ccc - charge - 0 = uncharged or value other than these, 1 = +3, 2 = +2, 3 = +1, + // 4 = doublet radical, 5 = -1, 6 = -2, 7 = -3 [Generic] Wider range of values in M CHG and M RAD lines below. + // Retained for compatibility with older Ctabs, M CHG and M RAD lines take precedence. + // sss - atom stereo parity - 0 = not stereo, 1 = odd, 2 = even, 3 = either or unmarked stereo center + // [Generic] Ignored when read. + // hhh - hydrogen count + 1; 1 = H0, 2 = H1, 3 = H2, 4 = H3, 5 = H4 + // [Query] H0 means no H atoms allowed unless explicitly drawn. Hn means atom must have n or more Hs in excess of explicit H�s. + // bbb - stereo care box; 0 = ignore stereo configuration of this double bond atom, 1 = stereo configuration of double bond atom must match + // [Query] Double bond stereochemistry is considered during SSS only if both ends of the bond are marked with stereo care boxes. + // vvv - valence; 0 = no marking (default) (1 to 14) = (1 to 14) 15 = zero valence + // [Generic] Shows number of bonds to this atom, including bonds to implied H�s. + // HHH - H0 designator; 0 = not specified, 1 = no H atoms allowed + // [MDL ISIS/Desktop] Redundant with hydrogen count information. May be unsupported in future releases of Elsevier MDL software. + // rrr - Not used + // iii - Not used + // mmm - atom-atom mapping number; 1 - number of atoms; [Reaction] + // nnn - inversion/retention flag; 0 = property not applied; 1 = configuration is inverted, + // 2 = configuration is retained,; [Reaction] + // eee - exact change flag; 0 = property not applied, 1 = change on atom must be exactly as shown; [Reaction, Query] + // --- Reading atoms + for (int i = 0; i < natoms; i++) { + + if ((line = IOUtils.readLine(in)) == null) { + //IOUtils.close(in); + throw new Exception("parseMDLMolfile: ERROR: Unxpected End of file while reading atom " + (i + 1)); + } + + AtomInterface atom = mol.getNewAtomInstance(); + + // --- Getting x,y,z + float xyz; + try { + xyz = Float.parseFloat(line.substring(0, 10).trim()); + atom.setX(xyz); + xyz = Float.parseFloat(line.substring(10, 20).trim()); + atom.setY(xyz); + xyz = Float.parseFloat(line.substring(20, 30).trim()); + atom.setZ(xyz); + } catch (Exception ex) { + //IOUtils.close(in); + throw new Exception("parseMDLMolfile: ERROR: Error while parsing atom: " + + (i + 1) + " Cannot parse atom's coordinate(s): " + line); + } + + // --- Getting element + //String token = line.substring(31, 34).trim(); + String token = line.substring(31, Math.min(line.length(), 34)).trim(); + int element = ChemicalElements.getAtomicNumber(token); + atom.setAtomicNumber(element); + atom.setName(token); + + mol.addAtom(atom); + } + + // --- The Bond block + // The Bond Block is made up of bond lines, one line per bond, with the following format: + // 111222tttsssxxxrrrccc + // where + // 111 - first atom number; 1 - number of atoms; [Generic] + // 222 - second atom number; 1 - number of atoms; [Generic] + // ttt - bond type; 1 = Single, 2 = Double, 3 = Triple, 4 = Aromatic, 5 = Single or Double, + // 6 = Single or Aromatic, 7 = Double or Aromatic, 8 = Any [Query] Values 4 through 8 are for SSS queries only. + // sss - bond stereo; Single bonds: 0 = not stereo, 1 = Up, 4 = Either, 6 = Down, Double bonds: 0 = Use x-, y-, z-coords from atom block to determine cis or trans, + // 3 = Cis or trans (either) double bond; [Generic] The wedge (pointed) end of the stereo bond is at the first atom (Field 111 above) + // xxx - not used + // rrr - bond topology; 0 = Either, 1 = Ring, 2 = Chain; [Query] SSS queries only. + // ccc - reacting center status; 0 = unmarked, 1 = a center, -1 = not a center, + // Additional: 2 = no change, 4 = bond made/broken, 8 = bond order changes + // 12 = 4+8 (both made/broken and changes); 5 = (4 + 1), 9 = (8 + 1), and 13 = (12 + 1) are also possible; [Reaction, Query] + for (int i = 0; i < nbonds; i++) { + + if ((line = IOUtils.readLine(in)) == null) { + //IOUtils.close(in); + throw new Exception("parseMDLMolfile: ERROR: Unxpected End of file while reading bond " + (i + 1)); + } + + int a_i, a_j; + try { + a_i = Integer.parseInt(line.substring(0, 3).trim()) - 1; + a_j = Integer.parseInt(line.substring(3, 6).trim()) - 1; + } catch (Exception e) { + //IOUtils.close(in); + throw new Exception("parseMDLMolfile: ERROR: Error while parsing bond: " + + (i + 1) + " : " + e.getMessage()); + } + + BondInterface bond = mol.getNewBondInstance(mol.getAtomInterface( + a_i), mol.getAtomInterface(a_j)); + mol.addBond(bond); + } + + // -- now continue to read in properties, if any + Set props = new LinkedHashSet(); + String property = null; + boolean propStart = false; + while ((line = IOUtils.readLine(in)) != null && (!line.startsWith("$$$$"))) { + line = line.trim(); + if (line.startsWith("> <")) { + property = line.substring(line.indexOf("<") + 1); + property = property.substring(0, property.indexOf(">")); + propStart = true; + props.clear(); + continue; + } + if (!propStart) { + continue; + } + + // -- Read in the property + if (line.length() == 0) { // EMpty line - end of properties + propStart = false; + if (props.size() == 0) { + + } else if (props.size() == 1) { + mol.addProperty("SDF_" + property, props.iterator().next()); + } else { + mol.addProperty("SDF_" + property, props.toArray()); + } + continue; + } + + props.add(line); + + } + + //IOUtils.close(in); + } catch (Exception ex) { + if (in != null) { + //IOUtils.close(in); + } + throw new Exception("parseMDLMolfile: ERROR: " + ex.getMessage()); + } + + return mol; + } + + public static void main(String[] args) { + FileDialog fd = new FileDialog(new Frame(), "Open SDF File", FileDialog.LOAD); + fd.setFile("*.sdf"); + fd.setVisible(true); + if (fd.getFile() == null) { + System.exit(0); + } + String fileName = fd.getFile(); + String workingDirectory = fd.getDirectory(); + + MDLMol sdf = new MDLMol(); + + MoleculeInterface molec = new Molecule(); + try { + sdf.parseFile(workingDirectory + fileName, molec); + } catch (Exception ex) { + ex.printStackTrace(); + } + System.exit(0); + } +} diff --git a/src/main/java/cct/mdl/SDCompound.java b/src/main/java/cct/mdl/SDCompound.java new file mode 100644 index 0000000..e9d2228 --- /dev/null +++ b/src/main/java/cct/mdl/SDCompound.java @@ -0,0 +1,113 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.mdl; + +import cct.interfaces.MoleculeInterface; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.RandomAccessFile; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; + +/** + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class SDCompound { + + private String MoleculeName; + private MoleculeInterface Molecule = null; + private RandomAccessFile sdFile = null; + private long compoundPosition = 0; + private boolean loaded = false; + + public SDCompound(RandomAccessFile raf, long position, MoleculeInterface molec) { + sdFile = raf; + compoundPosition = position; + Molecule = molec; + } + + public void setMoleculename(String name) { + this.MoleculeName = name; + } + + public String getMoleculeName() { + return MoleculeName; + } + + public MoleculeInterface getMolecule() { + return Molecule; + } + + public long getCompoundPosition() { + return compoundPosition; + } + + public boolean isLoaded() { + return loaded; + } + + public MoleculeInterface loadCompound() throws Exception { + sdFile.seek(compoundPosition); + MDLMol sdf = new MDLMol(); + sdf.parseFile(sdFile, Molecule); + loaded = true; + return Molecule; + } + + public MoleculeInterface loadCompound(MoleculeInterface mol) throws Exception { + sdFile.seek(compoundPosition); + MDLMol sdf = new MDLMol(); + sdf.parseFile(sdFile, mol); + Molecule = mol; + return Molecule; + } + +} diff --git a/src/main/java/cct/mdl/SDF.java b/src/main/java/cct/mdl/SDF.java new file mode 100644 index 0000000..8d32659 --- /dev/null +++ b/src/main/java/cct/mdl/SDF.java @@ -0,0 +1,207 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.mdl; + +import java.awt.FileDialog; +import java.awt.Frame; +import java.io.RandomAccessFile; +import java.util.ArrayList; +import java.util.logging.Logger; + +import cct.interfaces.MoleculeInterface; +import cct.modelling.Molecule; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +/** + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class SDF { + + static final Logger logger = Logger.getLogger(SDF.class.getCanonicalName()); + private RandomAccessFile sdFile = null; + private java.util.List Compounds = null; + private MoleculeInterface molecule; + + public SDF() { + } + + public MoleculeInterface getMolecule() { + return molecule; + } + + public void setMolecule(MoleculeInterface molecule) { + this.molecule = molecule; + } + + public int getNumberCompounds() { + if (Compounds == null) { + return 0; + } + return Compounds.size(); + } + + public MoleculeInterface loadCompound(int index) throws Exception { + SDCompound sdc = Compounds.get(index); + if (sdc.isLoaded()) { + return sdc.getMolecule(); + } + + sdc.loadCompound(); + return sdc.getMolecule(); + } + + public MoleculeInterface loadCompound(int index, MoleculeInterface mol) throws Exception { + SDCompound sdc = Compounds.get(index); + if (sdc.isLoaded()) { + return sdc.getMolecule(); + } + + sdc.loadCompound(mol); + return sdc.getMolecule(); + } + + public void parseSDFile(String file_name, MoleculeInterface molec) throws Exception { + + // ---- Open file + try { + sdFile = new RandomAccessFile(file_name, "r"); + } catch (Exception ex) { + throw new Exception("Cannot open file " + file_name + " : " + ex.getMessage()); + } + + // --- Start to read file + String line; + long fileSize = sdFile.getChannel().size(); + int estimatedComps = (int) (fileSize / 3072l) + 1; + Compounds = new ArrayList(); + if (Compounds instanceof ArrayList) { + ((ArrayList) Compounds).ensureCapacity(estimatedComps); + } + logger.info("Allocated memory for estimated " + estimatedComps + " compounds"); + + try { + boolean newCompound = false; + long position = sdFile.getFilePointer(); + if ((line = sdFile.readLine()) == null) { + throw new Exception("Unexpected end-of-file while reading the first compound.."); + } + SDCompound compound = new SDCompound(sdFile, position, molec != null ? molec.getInstance() : molec); + compound.setMoleculename(line.trim()); + Compounds.add(compound); + + while ((line = sdFile.readLine()) != null) { + if (line.equals("$$$$")) { + position = sdFile.getFilePointer(); + if ((line = sdFile.readLine()) == null) { + System.err.println("Unexpected end-of-file while reading the " + Compounds.size() + " compound. Ignoring..."); + break; + } + + compound = new SDCompound(sdFile, position, molec != null ? molec.getInstance() : molec); + compound.setMoleculename(line.trim()); + Compounds.add(compound); + if (Compounds.size() % 10000 == 0) { + double bytes_per_comp = (double) position / (double) Compounds.size(); + double estim_comps = (double) fileSize / bytes_per_comp; + System.out.println("..." + Compounds.size() + " ~" + + String.format("%6.2f", ((double) Compounds.size() / estim_comps * 100.0)) + "%"); + } + } + } + + logger.info("Found compounds " + Compounds.size()); + } catch (Exception ex) { + throw new Exception(" : " + ex.getMessage()); + } + + } + + public static void main(String[] args) { + FileDialog fd = new FileDialog(new Frame(), "Open SDF File", FileDialog.LOAD); + fd.setFile("*.sdf"); + fd.setVisible(true); + if (fd.getFile() == null) { + System.exit(0); + } + String fileName = fd.getFile(); + String workingDirectory = fd.getDirectory(); + + SDF sdf = new SDF(); + + MoleculeInterface molec = new Molecule(); + try { + sdf.parseSDFile(workingDirectory + fileName, molec); + for (int i = 0; i < sdf.getNumberCompounds(); i++) { + MoleculeInterface mol = sdf.loadCompound(i); + System.out.println("Loaded " + mol.getName() + " Numat: " + mol.getNumberOfAtoms()); + Map map = mol.getProperties(); + for (Object obj : map.keySet()) { + System.out.print(obj.toString() + ": "); + Object val = map.get(obj); + if (val instanceof Object[]) { + Object[] array = (Object[]) val; + + for (Object iter : array) { + System.out.print("\n ---> " + iter.toString() + " "); + } + System.out.println(); + } else { + System.out.println(val.toString()); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + System.exit(0); + } +} diff --git a/src/main/java/cct/modelling/.DS_Store b/src/main/java/cct/modelling/.DS_Store new file mode 100644 index 0000000..f9625a5 Binary files /dev/null and b/src/main/java/cct/modelling/.DS_Store differ diff --git a/src/main/java/cct/modelling/._.DS_Store b/src/main/java/cct/modelling/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/cct/modelling/._.DS_Store differ diff --git a/src/main/java/cct/modelling/AbstractDataParser.java b/src/main/java/cct/modelling/AbstractDataParser.java new file mode 100644 index 0000000..10958f3 --- /dev/null +++ b/src/main/java/cct/modelling/AbstractDataParser.java @@ -0,0 +1,232 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.modelling; + +import cct.tools.UncompressInputStream; +import org.itadaki.bzip2.BZip2InputStream; + +import java.io.*; +import java.net.JarURLConnection; +import java.net.URL; +import java.util.Enumeration; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.logging.Logger; +import java.util.zip.GZIPInputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +/** + * + * @author vvv900 + */ +abstract public class AbstractDataParser { + + private String name, description, extensions; + private boolean useDialog = false; + static final Logger logger = Logger.getLogger(AbstractDataParser.class.getCanonicalName()); + + /** + * Parses the data + * @param in + * @throws Exception + */ + abstract public void parseData(BufferedReader in) throws Exception; + + /** + * Tries to determine whether it's a valid format. + * @param in + * @return 0 - not at all, 10 - 100% + * @throws Exception + */ + + + public void parseData(File file) throws Exception { + + BufferedReader in = null; + if (file.getName().endsWith(".Z")) { + in = new BufferedReader(new InputStreamReader(new UncompressInputStream(new FileInputStream(file)))); + } else if (file.getName().endsWith(".gz")) { + GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(file)); + in = new BufferedReader(new InputStreamReader(gzip)); + } else if (file.getName().endsWith(".bz2")) { + BZip2InputStream bzip2 = new BZip2InputStream(new FileInputStream(file), false); + //CBZip2InputStream bzip2 = new CBZip2InputStream(new FileInputStream(filename)); + in = new BufferedReader(new InputStreamReader(bzip2)); + in.mark(5); + char[] buf = new char[3]; + if (in.read(buf, 0, 2) == -1) { + throw new Exception("Unexpected end of file"); + } + if (!(buf[0] == 'B' && buf[0] == 'Z')) { + in.reset(); + } + } else if (file.getName().endsWith(".zip")) { + ZipFile zipFile = new ZipFile(file); + if (zipFile.size() < 1) { + String msg = "Zip file " + file.getName() + " has no entries"; + logger.warning(msg); + throw new Exception(msg); + } else if (zipFile.size() > 1) { + logger.warning("Zip file has " + zipFile.size() + " entries. Only the first will be used"); + } + Enumeration e = zipFile.entries(); + ZipEntry zipEntry = (ZipEntry) e.nextElement(); + in = new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry))); + } else if (file.getName().endsWith(".jar")) { + JarFile jarFile = new JarFile(file); + if (jarFile.size() < 1) { + String msg = "Jar file " + file.getName() + " has no entries"; + logger.warning(msg); + throw new Exception(msg); + } else if (jarFile.size() > 1) { + logger.warning("Jar file has " + jarFile.size() + " entries. Only the first will be used"); + } + JarEntry jarEntry = null; + Enumeration e = jarFile.entries(); + while (e.hasMoreElements()) { + JarEntry entry = (JarEntry) e.nextElement(); + if (entry.isDirectory() || entry.getName().equals("META-INF/MANIFEST.MF")) { + continue; + } + System.out.println(entry.getName() + " " + entry.getSize() + " " + entry.getExtra() + " " + entry.getComment()); + jarEntry = entry; + break; + } + + if (jarEntry == null) { + throw new Exception("Didn't find data file in jar"); + } + + in = new BufferedReader(new InputStreamReader(jarFile.getInputStream(jarEntry))); + } else { + in = new BufferedReader(new FileReader(file)); + } + parseData(in); + } + + public void parseData(String filename) throws Exception { + File file = new File(filename); + parseData(file); + } + + public void parseDataAsString(String data) throws Exception { + BufferedReader in = new BufferedReader(new StringReader(data)); + parseData(in); + } + + public void parseDataAsURL(String urlString) throws Exception { + URL url = new URL(urlString); + parseDataAsURL(url); + } + + public void parseDataAsURL(URL url) throws Exception { + + BufferedReader in = null; + if (url.getFile().endsWith(".Z")) { + in = new BufferedReader(new InputStreamReader(new UncompressInputStream(url.openStream()))); + } else if (url.getFile().endsWith(".gz")) { + GZIPInputStream gzip = new GZIPInputStream(url.openStream()); + in = new BufferedReader(new InputStreamReader(gzip)); + } else if (url.getFile().endsWith(".bz2")) { + BZip2InputStream bzip2 = new BZip2InputStream(url.openStream(), false); + //CBZip2InputStream bzip2 = new CBZip2InputStream(new FileInputStream(filename)); + in = new BufferedReader(new InputStreamReader(bzip2)); + in.mark(5); + char[] buf = new char[3]; + if (in.read(buf, 0, 2) == -1) { + throw new Exception("Unexpected end of file"); + } + if (!(buf[0] == 'B' && buf[0] == 'Z')) { + in.reset(); + } + } /* + else if (url.getFile().endsWith(".zip")) { + ZipFile zipFile = new ZipFile(file); + if (zipFile.size() < 1) { + String msg = "Zip file " + url.getFile() + " has no entries"; + logger.warning(msg); + throw new Exception(msg); + } else if (zipFile.size() > 1) { + logger.warning("Zip file has " + zipFile.size() + " entries. Only the first will be used"); + } + Enumeration e = zipFile.entries(); + ZipEntry zipEntry = (ZipEntry) e.nextElement(); + in = new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry))); + + } + */ else if (url.getFile().endsWith(".jar")) { + //local archive + // url=new URL("jar:file:/C:/Program%20Files/Java/jdk1.5.0/jre/lib/jsse.jar!/"); + //remote archive + //url=new URL("jar:http://.../archive.jar!/"); + JarURLConnection jarURL = (JarURLConnection) url.openConnection(); + JarFile jarFile = jarURL.getJarFile(); + if (jarFile.size() < 1) { + String msg = "Jar file " + url.getFile() + " has no entries"; + logger.warning(msg); + throw new Exception(msg); + } else if (jarFile.size() > 1) { + logger.warning("Jar file has " + jarFile.size() + " entries. Only the first will be used"); + } + JarEntry jarEntry = null; + Enumeration e = jarFile.entries(); + while (e.hasMoreElements()) { + JarEntry entry = (JarEntry) e.nextElement(); + if (entry.isDirectory() || entry.getName().equals("META-INF/MANIFEST.MF")) { + continue; + } + System.out.println(entry.getName() + " " + entry.getSize() + " " + entry.getExtra() + " " + entry.getComment()); + jarEntry = entry; + break; + } + + if (jarEntry == null) { + throw new Exception("Didn't find data file in jar"); + } + + in = new BufferedReader(new InputStreamReader(jarFile.getInputStream(jarEntry))); + } else { + in = new BufferedReader(new InputStreamReader(url.openStream())); + } + parseData(in); + } + + public AbstractDataParser getParserObject() { + return this; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getExtensions() { + return extensions; + } + + public void setExtensions(String extensions) { + this.extensions = extensions; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public boolean isUseDialog() { + return useDialog; + } + + public void setUseDialog(boolean useDialog) { + this.useDialog = useDialog; + } +} diff --git a/src/main/java/cct/modelling/AngleBend.java b/src/main/java/cct/modelling/AngleBend.java new file mode 100644 index 0000000..710a2a4 --- /dev/null +++ b/src/main/java/cct/modelling/AngleBend.java @@ -0,0 +1,84 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class AngleBend { + int ijk[] = new int[3]; + float Fk, Theta; + + public AngleBend(int i, int j, int k, float fk, float theta) { + ijk[0] = i; + ijk[1] = j; + ijk[2] = k; + Fk = fk; + Theta = theta; + } + + public int getI() { + return ijk[0]; + } + + public int getJ() { + return ijk[1]; + } + + public int getK() { + return ijk[2]; + } + + public void setFk(float fk) { + Fk = fk; + } + + public void setTheta(float theta) { + Theta = theta; + } + +} diff --git a/src/main/java/cct/modelling/AngleBendEnergy.java b/src/main/java/cct/modelling/AngleBendEnergy.java new file mode 100644 index 0000000..1264d6f --- /dev/null +++ b/src/main/java/cct/modelling/AngleBendEnergy.java @@ -0,0 +1,264 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.modelling; + +import java.util.List; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.vecmath.Point3f; + +/** + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2006

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class AngleBendEnergy { + + static final Logger logger = Logger.getLogger(AngleBendEnergy.class.getCanonicalName()); + + private AngleBendEnergy() { + } + + public static double angleBendEnergy(MoleculeInterface molec, + Object AngleBendInteractions[]) { + return angleBendEnergy(molec, AngleBendInteractions, null); + } + + public static double angleBendEnergy(MoleculeInterface molec, Object AngleBendInteractions[], + Point3f[] Gradients) { + double energy = 0; + + Integer intType = (Integer) AngleBendInteractions[0]; + + // --- Harmonic angle bend energy without gradients + if (intType == FFMolecule.HARMONIC_BOND_TERM && Gradients == null) { + AngleBendsArray angles = (AngleBendsArray) AngleBendInteractions[1]; + + energy += HarmonicBendEnergy(molec, angles); + } // --- Harmonic bond stretch energy with gradients + else if (intType == FFMolecule.HARMONIC_BOND_TERM) { + AngleBendsArray angles = (AngleBendsArray) AngleBendInteractions[1]; + + energy += HarmonicStretchEnergy(molec, angles, Gradients); + } + + return energy; + } + + /** + * Calculates harmonic angle bend energy + * + * @param molec MoleculeInterface + * @param angles AngleBendsArray + * @return double + */ + public static double HarmonicBendEnergy(MoleculeInterface molec, AngleBendsArray angles) { + double energy = 0; + + List triples = angles.getAngleBends(); + + for (int i = 0; i < triples.size(); i++) { + AngleBend ab = (AngleBend) triples.get(i); + AtomInterface a1 = molec.getAtomInterface(ab.getI()); + AtomInterface a2 = molec.getAtomInterface(ab.getJ()); + AtomInterface a3 = molec.getAtomInterface(ab.getK()); + + double dif = Point3f.angleBetween(a1, a2, a3) - ab.Theta; + energy += ab.Fk * dif * dif; + } + + return 0.5 * energy; + } + + public static double HarmonicBendEnergyAnalysis(MoleculeInterface molec, + AngleBendsArray angles, float threshold) { + double energy = 0; + + List triples = angles.getAngleBends(); + + for (int i = 0; i < triples.size(); i++) { + AngleBend ab = (AngleBend) triples.get(i); + AtomInterface a1 = molec.getAtomInterface(ab.getI()); + AtomInterface a2 = molec.getAtomInterface(ab.getJ()); + AtomInterface a3 = molec.getAtomInterface(ab.getK()); + + double dif = Point3f.angleBetween(a1, a2, a3) - ab.Theta; + double en = 0.5 * ab.Fk * dif * dif; + if (en >= threshold) { + logger.info(a1.getName() + "(" + (ab.getI() + 1) + ")-" + + a2.getName() + "(" + (ab.getJ() + 1) + ")-" + + a3.getName() + "(" + (ab.getK() + 1) + + ") Energy: " + + en + " R=" + + Point3f.angleBetween(a1, a2, a3) + * Point3f.RADIANS_TO_DEGREES); + + } + energy += en; + } + + return 0.5 * energy; + } + + /** + * Calculates Bond stretch energy with gradients + * + * @param molec MoleculeInterface + * @param bondPairs BondStretchPairs + * @param Gradients Point3f[] - Final gradients + * @return double + */ + public static double HarmonicStretchEnergy(MoleculeInterface molec, AngleBendsArray angles, Point3f[] Gradients) { + double energy = 0; + + List triples = angles.getAngleBends(); + + for (int i = 0; i < triples.size(); i++) { + AngleBend ab = (AngleBend) triples.get(i); + AtomInterface a1 = molec.getAtomInterface(ab.getI()); + AtomInterface a2 = molec.getAtomInterface(ab.getJ()); + AtomInterface a3 = molec.getAtomInterface(ab.getK()); + + /* + xyzvector a, b, c1, c2; + a = v1 - v2; + asq = a.normsq(); + anorm = sqrt(asq); + + b = v3 - v2; + bsq = b.normsq(); + bnorm = sqrt(bsq); + + ab = a * b; + + c1 = RAD2DEG * (a * ab - b * asq).normalize() / anorm; + c2 = RAD2DEG * (b * ab - a * bsq).normalize() / bnorm; + + g1 = c1; + g2 = -(c1 + c2); + g3 = c2; + + return ( RAD2DEG * acos( ab / (a.norm() * b.norm()) ) ); + } + + */ + float v1_x = a1.getX() - a2.getX(); + float v1_y = a1.getY() - a2.getY(); + float v1_z = a1.getZ() - a2.getZ(); + + float v2_x = a3.getX() - a2.getX(); + float v2_y = a3.getY() - a2.getY(); + float v2_z = a3.getZ() - a2.getZ(); + + float v12 = v1_x * v2_x + v1_y * v2_y + v1_z * v2_z; + + float v1_normsq = v1_x * v1_x + v1_y * v1_y + v1_z * v1_z; + float v1_norm = (float) Math.sqrt(v1_normsq); + + float v2_normsq = v2_x * v2_x + v2_y * v2_y + v2_z * v2_z; + float v2_norm = (float) Math.sqrt(v2_normsq); + + float c1_x = v1_x * v12 - v2_x * v1_normsq; + float c1_y = v1_y * v12 - v2_y * v1_normsq; + float c1_z = v1_z * v12 - v2_z * v1_normsq; + float c1_norm = (float) Math.sqrt(c1_x * c1_x + c1_y * c1_y + + c1_z * c1_z); + + float factor = 1 / (c1_norm * v1_norm); + c1_x *= factor; + c1_y *= factor; + c1_z *= factor; + + float c2_x = v2_x * v12 - v1_x * v2_normsq; + float c2_y = v2_y * v12 - v1_y * v2_normsq; + float c2_z = v2_z * v12 - v1_z * v2_normsq; + float c2_norm = (float) Math.sqrt(c2_x * c2_x + c2_y * c2_y + + c2_z * c2_z); + + factor = 1 / (c2_norm * v2_norm); + c2_x *= factor; + c2_y *= factor; + c2_z *= factor; + + double cosa = ((double) (v1_x * v2_x + v1_y * v2_y + v1_z * v2_z) + / (v1_norm * v2_norm)); + + float angle = 0; + if (cosa > 1.0) { + angle = 0; + } else if (cosa < -1.0) { + angle = Point3f.PI_FLOAT; + } else { + angle = (float) Math.acos(cosa); + } + + float dif = angle - ab.Theta; + float fac = ab.Fk * dif; + + energy += ab.Fk * dif * dif; + + Gradients[ab.getI()].add(fac * c1_x, fac * c1_y, fac * c1_z); + Gradients[ab.getJ()].add(-fac * (c1_x + c2_x), -fac * (c1_y + c2_y), + -fac * (c1_z + c2_z)); + Gradients[ab.getK()].add(fac * c2_x, fac * c2_y, fac * c2_z); + + /* + fac = p->keq * dif; + atom[p->i].grad += fac * dphidri; + atom[p->j].grad += fac * dphidrj; + atom[p->k].grad += fac * dphidrk; + + */ + } + + return 0.5 * energy; + } + +} diff --git a/src/main/java/cct/modelling/AngleBendsArray.java b/src/main/java/cct/modelling/AngleBendsArray.java new file mode 100644 index 0000000..661806d --- /dev/null +++ b/src/main/java/cct/modelling/AngleBendsArray.java @@ -0,0 +1,87 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +import java.util.ArrayList; +import java.util.List; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class AngleBendsArray { + + protected List angleBends = null; + + public AngleBendsArray() { + angleBends = new ArrayList(); + } + + public AngleBendsArray(int nb) { + angleBends = new ArrayList(nb); + } + + public void addAngleBend(AngleBend ab) { + angleBends.add(ab); + } + + public List getAngleBends() { + return angleBends; + } + + public int getSize() { + return angleBends.size(); + } + + public AngleBend getAngleBend(int n) { + try { + return (AngleBend) angleBends.get(n); + } + catch (Exception ex) { + return null; + } + } +} diff --git a/src/main/java/cct/modelling/Atom.java b/src/main/java/cct/modelling/Atom.java new file mode 100644 index 0000000..f0c04d5 --- /dev/null +++ b/src/main/java/cct/modelling/Atom.java @@ -0,0 +1,482 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.modelling; + +import java.util.Map; + +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; +import cct.vecmath.Point3f; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2006

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Atom + extends Point3f implements AtomInterface { + + protected int element; + protected float mass; + protected String name = ""; + protected int monomer_id = 0; + protected boolean selected = false; + protected boolean dynamic = true; // Whether it's allowed to be optimized + protected Map properties = new HashMap(); + protected List bondedToAtoms = new ArrayList(); + protected List bondsIndex = new ArrayList(); + protected int[] ijk = new int[3]; // Used for definition of Z-matrix + protected double[] zmat = new double[3]; + + public Atom() { + super(); + element = -1; + } + + public AtomInterface getNewAtom() { + return new Atom(); + } + + @Override + public AtomInterface getNewAtomInstance() { + return new Atom(); + } + + @Override + public AtomInterface getNewAtomInstance(AtomInterface a) { + return new Atom(a); + } + + Atom(Atom a) { + super(); + element = a.getAtomicNumber(); + name = a.getName(); + mass = a.getAtomicMass(); + monomer_id = a.getSubstructureNumber(); + selected = a.isSelected(); + dynamic = a.isDynamic(); + x = a.getX(); + y = a.getY(); + z = a.getZ(); + properties.putAll(a.getProperties()); + if (a == null) { + a = new Atom(); + } + } + + Atom(AtomInterface atom) { + super(); + element = atom.getAtomicNumber(); + mass = atom.getAtomicMass(); + name = atom.getName(); + monomer_id = atom.getSubstructureNumber(); + selected = atom.isSelected(); + dynamic = atom.isDynamic(); + x = atom.getX(); + y = atom.getY(); + z = atom.getZ(); + properties.putAll(atom.getProperties()); + + } + + public Atom(int element, float x, float y, float z) { + super(); + this.x = x; + this.y = y; + this.z = z; + this.element = element; + mass = ChemicalElements.getAtomicWeight(element); + } + + public float distanceTo(Atom a) { + float x = this.x - a.getX(); + float y = this.y - a.getY(); + float z = this.z - a.getZ(); + return (float) Math.sqrt((x * x + y * y + z * z)); + } + +// public String getProperty( String key ) { return (String)properties.get( key); } + public Map getAtomProperties() { + return properties; + } + + public int getNA() { + return ijk[0]; + } + + public int getNB() { + return ijk[1]; + } + + public int getNC() { + return ijk[2]; + } + + public int[] getNX() { + return ijk; + } + + public int[] getIJK() { + return ijk; + } + + public void setNA(int na) { + ijk[0] = na; + } + + public void setNB(int nb) { + ijk[1] = nb; + } + + public void setNC(int nc) { + ijk[2] = nc; + } + + public void setNX(int[] nx) { + ijk[0] = nx[0]; + ijk[1] = nx[1]; + ijk[2] = nx[2]; + } + + public void setIJK(int[] nx) { + ijk[0] = nx[0]; + ijk[1] = nx[1]; + ijk[2] = nx[2]; + } + + public double getBond() { + return zmat[0]; + } + + public double getAngle() { + return zmat[1]; + } + + public double getDihedralAngle() { + return zmat[2]; + } + + public double[] getZmatrix() { + return zmat; + } + + public void setBond(double bond) { + zmat[0] = bond; + } + + public void setAngle(double angle) { + zmat[1] = angle; + } + + public void setDihedralAngle(double dihedral) { + zmat[2] = dihedral; + } + + public void setZmatrix(double[] z) { + zmat[0] = z[0]; + zmat[1] = z[1]; + zmat[2] = z[2]; + } + + @Override + public float getX() { + return super.getX(); + } + + @Override + public float getY() { + return super.getY(); + } + + @Override + public float getZ() { + return super.getZ(); + } + + public float[] getCoordinates() { + float xyz[] = { + getX(), getY(), getZ()}; + return xyz; + } + + public boolean IsSelected() { + return selected; + } + + /* + * @Override public void setXYZ(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } + * + * @Override public void setXYZ(Point3f xyz) { this.x = xyz.x; this.y = xyz.y; this.z = xyz.z; } + * + * + * @Override public void setX(double x) { this.x = (float)x; } + * + * @Override public void setY( double x) { this.y = (float)x; } + * + * @Override public void setZ(double x) { this.z = (float)x; } + */ + @Override + public float vectorNorm() { + return vectorNorm(); + } + + public float[] getDirectionTo(Point3f a) { + float dir[] = { + 0, 0, 0}; //new float[3]; + float dist = distanceTo(a); + if (dist == 0) { + return dir; + } + dir[0] = (a.getX() - getX()) / dist; + dir[1] = (a.getY() - getY()) / dist; + dir[2] = (a.getZ() - getZ()) / dist; + return dir; + } + + public void translateAtom(float dir[], float increment) { + setX(getX() + dir[0] * increment); + setY(getY() + dir[1] * increment); + setZ(getZ() + dir[2] * increment); + } + + public void translateAtom(Point3f dir, float increment) { + setX(getX() + dir.x * increment); + setY(getY() + dir.y * increment); + setZ(getZ() + dir.z * increment); + } + + @Override + public Atom clone() { + return new Atom(this); + } + + //*********************************************** + @Override + public boolean isSelected() { + return selected; + } + + @Override + public boolean isDynamic() { + return dynamic; + } + + @Override + public boolean isBondedTo(AtomInterface a) { + return bondedToAtoms.contains( a ); + } + + @Override + public void setName(String aName) { + //if (name != null) { + //properties.put(AtomProperties.NAME, name); + //} + this.name = aName; + } + + @Override + public void setSubstructureNumber(int n) { + monomer_id = n; + } + + @Override + public void setSelected(boolean select) { + selected = select; + } + + @Override + public int getSubstructureNumber() { + return monomer_id; + } + + public float distanceTo(Point3f a) { + float x = this.x - a.x; + float y = this.y - a.y; + float z = this.z - a.z; + return (float) Math.sqrt((x * x + y * y + z * z)); + } + + public float distanceTo(AtomInterface a) { + float x = this.x - a.getX(); + float y = this.y - a.getY(); + float z = this.z - a.getZ(); + return (float) Math.sqrt((x * x + y * y + z * z)); + } + + @Override + public List getBondedToAtoms() { + return bondedToAtoms; + } + + @Override + public int getNumberOfBondedAtoms() { + return bondedToAtoms.size(); + } + + /** + * Used internally !!! + * + * @param bond BondInterface + * @return BondInterface + */ + @Override + public boolean removeBond(BondInterface bond) { + if (!bondsIndex.contains(bond)) { + return false; + } + return bondsIndex.remove(bond); + } + + @Override + public List getBondIndex() { + return bondsIndex; + } + + @Override + public BondInterface getBondToAtom(AtomInterface a) { + if (!bondedToAtoms.contains(a)) { + return null; // not bonded to it + } + try { + return (BondInterface) bondsIndex.get(bondedToAtoms.indexOf(a)); + } catch (IndexOutOfBoundsException e) { + System.err.println("getBondtoAtom: IndexOutOfBoundsException: " + e.getMessage()); + return null; + } + } + + public void setBondedTo(AtomInterface a) { + bondedToAtoms.add(a); + } + + // !!! Function to delete !!! + @Override + public void setBondedTo(AtomInterface a, boolean set_bond) { + if (set_bond) { + if (!bondedToAtoms.contains(a)) { + bondedToAtoms.add(a); + } + } else { + if (!bondedToAtoms.contains(a)) { + return; + } + int index = bondedToAtoms.indexOf(a); + bondedToAtoms.remove(index); + bondsIndex.remove(index); + } + } + + public void setUnbondedTo(AtomInterface a) { + if (!bondedToAtoms.contains(a)) { + return; + } + int index = bondedToAtoms.indexOf(a); + bondedToAtoms.remove(index); + bondsIndex.remove(index); + } + + @Override + public void setBondIndex(BondInterface a) { + bondsIndex.add(a); + } + + @Override + public int getAtomicNumber() { + return element; + } + + @Override + public void setAtomicNumber(int anumber) { + element = anumber; + mass = ChemicalElements.getAtomicWeight(element); + } + + @Override + public String getName() { + //return (String) properties.get(AtomProperties.NAME); + return name; + } + + @Override + public void setAtomicMass(float mass) { + this.mass = mass; + } + + @Override + public void setProperty(Object prop, Object value) { + if (value == null) { + properties.remove(prop); + return; + } + properties.put(prop, value); + } + + @Override + public Object getProperty(String key) { + return properties.get(key); + } + + @Override + public Map getProperties() { + return properties; + } + + @Override + public float getAtomicMass() { + return mass; + } + + public String toString() { + return this.getClass().getCanonicalName() + ": Element: " + String.valueOf(element) + + " X: " + String.valueOf(this.getX()) + " Y: " + String.valueOf(this.getY()) + " Z: " + String.valueOf(this.getZ()); + } +} diff --git a/src/main/java/cct/modelling/AtomGenerator.java b/src/main/java/cct/modelling/AtomGenerator.java new file mode 100644 index 0000000..67e9918 --- /dev/null +++ b/src/main/java/cct/modelling/AtomGenerator.java @@ -0,0 +1,640 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; +import cct.interfaces.MoleculeInterface; +import cct.interfaces.Point3fInterface; +import cct.vecmath.Point3f; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class AtomGenerator { + + static final double RIGHT_ANGLE = 90.0 * Math.PI / 180.0; + static final double TETRAHEDRAL_ANGLE = 109.47 * Math.PI / 180.0; + static final float TABULATED_35_3_COS = (float) Math.cos(RIGHT_ANGLE - TETRAHEDRAL_ANGLE / 2.0); + + static final float HALF_TETRAHEDRAL_ANGLE_COS = (float) Math.cos(TETRAHEDRAL_ANGLE / 2.0); + + static final double TRIGONAL_ANGLE = 120.0 * Math.PI / 180.0; + static double Factor = 0.7; + static final Logger logger = Logger.getLogger(AtomGenerator.class.getCanonicalName()); + + public AtomGenerator() { + } + + public static Map fillEmptyValences(MoleculeInterface molecule, AtomInterface atom, String atomTypeKey, Map atomTypes) throws + Exception { + + String refAtomType = (String) atom.getProperty(atomTypeKey); + if (refAtomType == null) { + throw new Exception("Atom type of reference atom is not set"); + } + CCTAtomTypes refType = (CCTAtomTypes) atomTypes.get(refAtomType); + if (refType.getCoordinationNumber() == 0 || + refType.getMaxSingleBonds() == 0) { + throw new Exception("Atom type of reference atom either does not have single bonds or it's coordination number is 0"); + } + float refCovRad = refType.getCovalentRadius(); + logger.info("Ref Atom: " + atom.getAtomicNumber() + " covRad: " + refCovRad); + + Map result = new HashMap(); + List newAtoms = new ArrayList(); + List newBonds = new ArrayList(); + + // Temporary array + Point3fInterface p1 = new Point3f(); + Point3fInterface p2 = new Point3f(); + Point3fInterface p3 = new Point3f(); + Point3fInterface p4 = new Point3f(); + Point3fInterface p5 = new Point3f(); + + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface a = molecule.getAtomInterface(i); + logger.info("Atom: " + i + " type: " + + a.getProperty(atomTypeKey) + " selected: " + + a.isSelected()); + + if (!a.isSelected()) { + continue; + } + + String atomType = (String) a.getProperty(atomTypeKey); + if (atomType == null) { + continue; // Does not have atom type + } + + if (!atomTypes.containsKey(atomType)) { // No such atom type in the list + System.err.println("Warning: No such atom type " + atomType + + " in the atom types list. Ignored..."); + continue; + } + + CCTAtomTypes type = (CCTAtomTypes) atomTypes.get(atomType); + + logger.info(" Number of bonds: " + a.getNumberOfBondedAtoms() + + " max number singlebonds: " + + type.getMaxSingleBonds()); + int nb = type.getMaxSingleBonds(); + if (nb < 1) { + continue; + } + + int nb_curr = a.getNumberOfBondedAtoms(); + //if (nb_curr nb ) { + // continue; + // } + + int atomsToAdd = 0; + + /* + if (nb_curr < type.getCoordinationNumber() - nb) { + atomsToAdd = nb; + } + else { + atomsToAdd = nb - nb_curr - (type.getCoordinationNumber() - nb); + } + */ + + atomsToAdd = type.getCoordinationNumber() - nb_curr; + if (atomsToAdd > nb) { + atomsToAdd = nb; + } + + logger.info(" Atoms to add: " + atomsToAdd); + if (atomsToAdd < 1) { + continue; + } + + float covRadius = type.getCovalentRadius(); + + logger.info("Atoms to add: " + atomsToAdd + " geometry: " + + type.getGeometry() + " covRadius: " + covRadius); + + // --- Assume that atom can have only two ligands + if (type.getGeometry() == AtomGeometry.LINEAR) { + if (nb_curr == 0) { + // --- Choose arbitrary direction for the first atom + float dx = (refCovRad + covRadius) * (float) Factor, dy = 0, + dz = 0; + AtomInterface newAtom = atom.getNewAtomInstance(atom); + newAtom.setX(a.getX() + dx); + newAtom.setY(a.getY() + dy); + newAtom.setZ(a.getZ() + dz); + newAtom.setSubstructureNumber(a.getSubstructureNumber()); + newAtoms.add(newAtom); + BondInterface bond = molecule.getNewBondInstance(a, newAtom); + newBonds.add(bond); + //molecule.addBond(bond); + --atomsToAdd; + ++nb_curr; + } + + if (type.getCoordinationNumber() == nb_curr) { + continue; + } + + List ligands = a.getBondedToAtoms(); + if (ligands.size() != 1) { + throw new Exception( + "Linear: Unexpected error: ligands.size() != 1 : " + + ligands.size()); + } + AtomInterface a2 = (AtomInterface) ligands.get(0); + float dist = (float) a.distanceTo(a2); + float dx = (a.getX() - a2.getX()) / dist; + float dy = (a.getY() - a2.getY()) / dist; + float dz = (a.getZ() - a2.getZ()) / dist; + AtomInterface newAtom = atom.getNewAtomInstance(atom); + newAtom.setX(a.getX() + dx); + newAtom.setY(a.getY() + dy); + newAtom.setZ(a.getZ() + dz); + newAtom.setSubstructureNumber(a.getSubstructureNumber()); + newAtoms.add(newAtom); + BondInterface bond = molecule.getNewBondInstance(a, newAtom); + newBonds.add(bond); + //molecule.addBond(bond); + } + + // --- Assume that atom can have only three ligands + else if (type.getGeometry() == AtomGeometry.TRIGONAL) { + + if (nb_curr == 0) { + logger.info("Case TRIGONAL & nb_curr == 0"); + // --- Choose arbitrary direction for the first atom + float dx = (refCovRad + covRadius) * (float) Factor, dy = 0, + dz = 0; + AtomInterface newAtom = atom.getNewAtomInstance(atom); + newAtom.setX(a.getX() + dx); + newAtom.setY(a.getY() + dy); + newAtom.setZ(a.getZ() + dz); + newAtom.setSubstructureNumber(a.getSubstructureNumber()); + newAtoms.add(newAtom); + BondInterface bond = molecule.getNewBondInstance(a, newAtom); + newBonds.add(bond); + //molecule.addBond(bond); + --atomsToAdd; + ++nb_curr; + } + + if (type.getCoordinationNumber() == nb_curr) { + continue; + } + + if (nb_curr == 1) { + logger.info("Case TRIGONAL & nb_curr == 1"); + // --- Choose arbitrary direction for the second atom + List ligands = a.getBondedToAtoms(); + if (ligands.size() != 1) { + throw new Exception( + "Trigonal: Unexpected error: ligands.size() != 1 : " + + ligands.size()); + } + + AtomInterface a2 = (AtomInterface) ligands.get(0); + + List ligs = a2.getBondedToAtoms(); + + if (ligs.size() == 1) { // General case + float dist = (float) a.distanceTo(a2); + float length = (refCovRad + covRadius) * (float) Factor; + + p1.setXYZ( (a2.getX() - a.getX()) / dist, + (a2.getY() - a.getY()) / dist, + (a2.getZ() - a.getZ()) / dist); + + generateAtom(p1, (float) TRIGONAL_ANGLE, length, p2); + + AtomInterface newAtom = atom.getNewAtomInstance(atom); + newAtom.setX(a.getX() + p2.getX()); + newAtom.setY(a.getY() + p2.getY()); + newAtom.setZ(a.getZ() + p2.getZ()); + newAtom.setSubstructureNumber(a.getSubstructureNumber()); + newAtoms.add(newAtom); + BondInterface bond = molecule.getNewBondInstance(a, newAtom); + newBonds.add(bond); + //molecule.addBond(bond); + --atomsToAdd; + ++nb_curr; + + } + else { + AtomInterface a3 = (AtomInterface) ligs.get(0); + if (a3 == a) { + a3 = (AtomInterface) ligs.get(1); + } + // Place new atom in trans position to a3 in the direction a3->a2 + float dist = (float) a2.distanceTo(a3); + float v1_x = (a2.getX() - a3.getX()) / dist; + float v1_y = (a2.getY() - a3.getY()) / dist; + float v1_z = (a2.getZ() - a3.getZ()) / dist; + + float length = (refCovRad + covRadius) * (float) Factor; + + AtomInterface newAtom = atom.getNewAtomInstance(atom); + newAtom.setX(a.getX() + v1_x * length); + newAtom.setY(a.getY() + v1_y * length); + newAtom.setZ(a.getZ() + v1_z * length); + newAtom.setSubstructureNumber(a.getSubstructureNumber()); + newAtoms.add(newAtom); + BondInterface bond = molecule.getNewBondInstance(a, newAtom); + newBonds.add(bond); + --atomsToAdd; + ++nb_curr; + + } + + } + + if (type.getCoordinationNumber() == nb_curr) { + continue; + } + + if (nb_curr == 2) { + logger.info("Case TRIGONAL & nb_curr == 2"); + List ligands = a.getBondedToAtoms(); + if (ligands.size() != 2) { + throw new Exception( + "Tetragonal: Unexpected error: ligands.size() != 2 : " + + ligands.size()); + } + + AtomInterface a2 = (AtomInterface) ligands.get(0); + AtomInterface a3 = (AtomInterface) ligands.get(1); + + p2.setXYZ(a.getX() - a2.getX(), a.getY() - a2.getY(), a.getZ() - a2.getZ()); + Point3f.normalize(p2); + p3.setXYZ(a.getX() - a3.getX(), a.getY() - a3.getY(), a.getZ() - a3.getZ()); + Point3f.normalize(p3); + + float length = (refCovRad + covRadius) * (float) Factor; + //p1.setX(2.0f * a.getX() - a2.getX() - a3.getX()); + //p1.setY(2.0f * a.getY() - a2.getY() - a3.getY()); + //p1.setZ(2.0f * a.getZ() - a2.getZ() - a3.getZ()); + p1.setX(p2.getX() + p3.getX()); + p1.setY(p2.getY() + p3.getY()); + p1.setZ(p2.getZ() + p3.getZ()); + + Point3f.normalize(p1); + + AtomInterface newAtom = atom.getNewAtomInstance(atom); + newAtom.setX(a.getX() + p1.getX() * length); + newAtom.setY(a.getY() + p1.getY() * length); + newAtom.setZ(a.getZ() + p1.getZ() * length); + newAtom.setSubstructureNumber(a.getSubstructureNumber()); + newAtoms.add(newAtom); + BondInterface bond = molecule.getNewBondInstance(a, newAtom); + newBonds.add(bond); + --atomsToAdd; + ++nb_curr; + } + + } + + // --- Assume that atom can have only four ligands + else if (type.getGeometry() == AtomGeometry.TETRAHEDRAL) { + //if (atomsToAdd == 4) { + if (nb_curr == 0) { + logger.info("Case TETRAHEDRAL & nb_curr == 0"); + // --- Choose arbitrary direction for the first atom + float dx = (refCovRad + covRadius) * (float) Factor, dy = 0, + dz = 0; + AtomInterface newAtom = atom.getNewAtomInstance(atom); + newAtom.setX(a.getX() + dx); + newAtom.setY(a.getY() + dy); + newAtom.setZ(a.getZ() + dz); + newAtom.setSubstructureNumber(a.getSubstructureNumber()); + newAtoms.add(newAtom); + BondInterface bond = molecule.getNewBondInstance(a, newAtom); + newBonds.add(bond); + //molecule.addBond(bond); + --atomsToAdd; + ++nb_curr; + } + + if (type.getCoordinationNumber() == nb_curr) { + continue; + } + + //if (atomsToAdd == 3) { + if (nb_curr == 1) { + logger.info("Case TETRAHEDRAL & nb_curr == 1"); + // --- Choose arbitrary direction for the second atom + List ligands = a.getBondedToAtoms(); + if (ligands.size() != 1) { + throw new Exception( + "Tetrahedral: Unexpected error: ligands.size() != 1 : " + + ligands.size()); + } + AtomInterface a2 = (AtomInterface) ligands.get(0); + float dist = (float) a.distanceTo(a2); + float length = (refCovRad + covRadius) * (float) Factor; + + p1.setXYZ( (a2.getX() - a.getX()) / dist, + (a2.getY() - a.getY()) / dist, + (a2.getZ() - a.getZ()) / dist); + + generateAtom(p1, (float) TETRAHEDRAL_ANGLE, length, p2); + + AtomInterface newAtom = atom.getNewAtomInstance(atom); + newAtom.setX(a.getX() + p2.getX()); + newAtom.setY(a.getY() + p2.getY()); + newAtom.setZ(a.getZ() + p2.getZ()); + newAtom.setSubstructureNumber(a.getSubstructureNumber()); + newAtoms.add(newAtom); + BondInterface bond = molecule.getNewBondInstance(a, newAtom); + newBonds.add(bond); + //molecule.addBond(bond); + --atomsToAdd; + ++nb_curr; + } + + if (type.getCoordinationNumber() == nb_curr) { + continue; + } + + //if (atomsToAdd == 2) { + if (nb_curr == 2) { + logger.info("Case TETRAHEDRAL & nb_curr == 2"); + // --- Choose direction for the atom using a sum of three vector + List ligands = a.getBondedToAtoms(); + if (ligands.size() != 2) { + throw new Exception( + "Tetrahedral: Unexpected error: ligands.size() != 2 : " + + ligands.size()); + } + AtomInterface a1 = (AtomInterface) ligands.get(0); + AtomInterface a2 = (AtomInterface) ligands.get(1); + /* + p1.setXYZ(a1.getX() - a.getX(), a1.getY() - a.getY(), + a1.getZ() - a.getZ()); + p2.setXYZ(a2.getX() - a.getX(), a2.getY() - a.getY(), + a2.getZ() - a.getZ()); + Point3f.crossProduct(p1, p2, p3); + Point3f.normalize(p3); + float factor2 = length * (float) Math.sin(TETRAHEDRAL_ANGLE / 2); + logger.info("factor2: " + factor2 + " p3" + p3.getX() + + " " + p3.getY() + " " + p3.getZ()); + + float dx = 0, dy = 0, dz = 0; + + dx -= a1.getX() + a2.getX() - 2.0f * a.getX(); + dy -= a1.getY() + a2.getY() - 2.0f * a.getY(); + dz -= a1.getZ() + a2.getZ() - 2.0f * a.getZ(); + double scale = Math.sqrt( (double) (dx * dx + dy * dy + dz * dz)); + float factor = length * (float) Math.cos(TETRAHEDRAL_ANGLE / 2); + dx /= scale; + dy /= scale; + dz /= scale; + + logger.info("dx, dy, dz, factor: " + dx + " " + dy + " " + + dz + " " + factor); + */ + + p1.setXYZ(a1.getX() - a.getX(), a1.getY() - a.getY(), + a1.getZ() - a.getZ()); + Point3f.normalize(p1); + p2.setXYZ(a2.getX() - a.getX(), a2.getY() - a.getY(), + a2.getZ() - a.getZ()); + Point3f.normalize(p2); + Point3f.crossProduct(p1, p2, p3); + Point3f.normalize(p3); + + p3.setXYZ(p3.getX() * TABULATED_35_3_COS, + p3.getY() * TABULATED_35_3_COS, + p3.getZ() * TABULATED_35_3_COS); + + p4.setXYZ( -p1.getX() - p2.getX(), -p1.getY() - p2.getY(), + -p1.getZ() - p2.getZ()); + Point3f.normalize(p4); + p4.setXYZ(p4.getX() * HALF_TETRAHEDRAL_ANGLE_COS, + p4.getY() * HALF_TETRAHEDRAL_ANGLE_COS, + p4.getZ() * HALF_TETRAHEDRAL_ANGLE_COS); + + p5.setXYZ(p3.getX() + p4.getX(), p3.getY() + p4.getY(), + p3.getZ() + p4.getZ()); + Point3f.normalize(p5); + + AtomInterface newAtom = atom.getNewAtomInstance(atom); + //newAtom.setX(a.getX() + dx * factor + p3.getX() * factor2); + //newAtom.setY(a.getY() + dy * factor + p3.getY() * factor2); + //newAtom.setZ(a.getZ() + dz * factor + p3.getZ() * factor2); + newAtom.setX(a.getX() + p5.getX()); + newAtom.setY(a.getY() + p5.getY()); + newAtom.setZ(a.getZ() + p5.getZ()); + + newAtom.setSubstructureNumber(a.getSubstructureNumber()); + newAtoms.add(newAtom); + BondInterface bond = molecule.getNewBondInstance(a, newAtom); + newBonds.add(bond); + //molecule.addBond(bond); + --atomsToAdd; + ++nb_curr; + } + if (type.getCoordinationNumber() == nb_curr) { + continue; + } + + //if (atomsToAdd == 1) { + if (nb_curr == 3) { + logger.info("Case TETRAHEDRAL & nb_curr == 3"); + // --- Choose direction for the atom using a sum of three vector + List ligands = a.getBondedToAtoms(); + if (ligands.size() != 3) { + throw new Exception( + "Tetrahedral: Unexpected error: ligands.size() != 3 : " + + ligands.size()); + } + AtomInterface a1 = (AtomInterface) ligands.get(0); + AtomInterface a2 = (AtomInterface) ligands.get(1); + AtomInterface a3 = (AtomInterface) ligands.get(2); + + p1.setXYZ(a1.getX() - a.getX(), a1.getY() - a.getY(), + a1.getZ() - a.getZ()); + Point3f.normalize(p1); + p2.setXYZ(a2.getX() - a.getX(), a2.getY() - a.getY(), + a2.getZ() - a.getZ()); + Point3f.normalize(p2); + p3.setXYZ(a3.getX() - a.getX(), a3.getY() - a.getY(), + a3.getZ() - a.getZ()); + Point3f.normalize(p3); + + p4.setXYZ( -p1.getX() - p2.getX() - p3.getX(), + -p1.getY() - p2.getY() - p3.getY(), + -p1.getZ() - p2.getZ() - p3.getZ()); + Point3f.normalize(p4); + /* + float dx = 0, dy = 0, dz = 0; + + dx -= a1.getX() + a2.getX() + a3.getX() - 3.0f * a.getX(); + dy -= a1.getY() + a2.getY() + a3.getY() - 3.0f * a.getY(); + dz -= a1.getZ() + a2.getZ() + a3.getZ() - 3.0f * a.getZ(); + // !!! Add test for dx, dy & dz = 0 !!! + + double scale = Math.sqrt(dx * dx + dy * dy + dz * dz); + dx /= scale; + dy /= scale; + dz /= scale; + */ + float length = (refCovRad + covRadius) * (float) Factor; + + AtomInterface newAtom = atom.getNewAtomInstance(atom); + //newAtom.setX(a.getX() + dx * length); + //newAtom.setY(a.getY() + dy * length); + //newAtom.setZ(a.getZ() + dz * length); + newAtom.setX(a.getX() + p4.getX() * length); + newAtom.setY(a.getY() + p4.getY() * length); + newAtom.setZ(a.getZ() + p4.getZ() * length); + + newAtom.setSubstructureNumber(a.getSubstructureNumber()); + newAtoms.add(newAtom); + BondInterface bond = molecule.getNewBondInstance(a, newAtom); + newBonds.add(bond); + //molecule.addBond(bond); + --atomsToAdd; + ++nb_curr; + } + if (type.getCoordinationNumber() == nb_curr) { + continue; + } + + } + + } + + logger.info("Atoms generated: " + newAtoms.size()); + //for (int i = 0; i < newAtoms.size(); i++) { + // molecule.addAtom( (AtomInterface) newAtoms.get(i)); + //} + result.put("atoms", newAtoms); + result.put("bonds", newBonds); + //return newAtoms.size(); + return result; + } + + public static void generateAtom(Point3fInterface dir, float theta, + float length, Point3fInterface atom) throws + Exception { + + float projection = length * (float) Math.cos(theta); + + float v1_x = dir.getX() * projection; + float v1_y = dir.getY() * projection; + float v1_z = dir.getZ() * projection; + + float v_normal_length = (float) Math.sqrt( (length * + length - projection * projection)); + float vx_normal, vy_normal, vz_normal; + // --- Choose arbitrary direction for vx + + // x & y != 0 + if (Math.abs(v1_x) > 0.0001 && Math.abs(v1_y) > 0.0001) { + vx_normal = -v1_y / v1_x; + vy_normal = 1; + vz_normal = 0; + } + // x & z != 0 + else if (Math.abs(v1_x) > 0.0001 && Math.abs(v1_z) > 0.0001) { + vx_normal = -v1_z / v1_x; + vy_normal = 0; + vz_normal = 1; + } + // y & z != 0 + else if (Math.abs(v1_y) > 0.0001 && Math.abs(v1_z) > 0.0001) { + vx_normal = 0; + vy_normal = -v1_z / v1_y; + vz_normal = 1; + } + else if (Math.abs(v1_x) > 0.0001) { + vx_normal = 0; + vy_normal = 0; + vz_normal = 1; + } + else if (Math.abs(v1_y) > 0.0001) { + vx_normal = 0; + vy_normal = 0; + vz_normal = 1; + } + else if (Math.abs(v1_z) > 0.0001) { + vx_normal = 1; + vy_normal = 0; + vz_normal = 0; + } + + else { + throw new Exception( + "Unexpected error: x, y & z are all zero:" + + v1_x + " " + v1_y + " " + v1_z); + } + + // --- Form (arbitrary) vector perpendicular to v1 + + double scale = Math.sqrt( (vx_normal * vx_normal + + vy_normal * vy_normal + + vz_normal * vz_normal)); + vx_normal /= scale; + vy_normal /= scale; + vz_normal /= scale; + + atom.setX(v1_x + vx_normal * v_normal_length); + atom.setY(v1_y + vy_normal * v_normal_length); + atom.setZ(v1_z + vz_normal * v_normal_length); + } + + public static void main(String[] args) { + AtomGenerator atomgenerator = new AtomGenerator(); + } +} diff --git a/src/main/java/cct/modelling/AtomGeometry.java b/src/main/java/cct/modelling/AtomGeometry.java new file mode 100644 index 0000000..395fbec --- /dev/null +++ b/src/main/java/cct/modelling/AtomGeometry.java @@ -0,0 +1,439 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +import cct.resources.images.ImageResources; + +import javax.swing.*; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +/* + # Element Fragment Table + # Fragment Format: index pixmap fragment hotx hoty name + # Indexes = 0 ... n-1 + Fragment nItems = 20 + 0 atom.xpm atom.frg 24 18 "%1 Atom" + 1 sing.xpm sing.frg 24 24 "%1 Terminal (S)" + 2 dit.xpm dit.frg 24 24 "%1 Terminal (T)" + 3 lin.xpm lin.frg 24 24 "%1 Linear (S-S)" + 4 dist.xpm dist.frg 24 24 "%1 Divalent (S-T)" + 5 didd.xpm didd.frg 24 24 "%1 Divalent (D-D)" + 6 trid.xpm trid.frg 24 24 "%1 Trivalent (D-LP-LP)" + 7 trisd.xpm trisd.frg 24 24 "%1 Trivalent (S-D-LP)" + 8 triaa.xpm triaa.frg 24 24 "%1 Trivalent (A-A-LP)" + 9 tripla.xpm tripla.frg 24 24 "%1 Trigonal Planar" + 10 tshap.xpm tshap.frg 24 24 "%1 T-shaped" + 11 trissd.xpm trissd.frg 24 24 "%1 Trivalent (S-S-D)" + 12 trisaa.xpm trisaa.frg 24 24 "%1 Trivalent (S-A-A)" + 13 bent.xpm bent.frg 24 24 "%1 Tetravalent (S-S-LP-LP)" + 14 tetsss.xpm tetsss.frg 24 24 "%1 Tetravalent (S-S-S-LP)" + 15 tet.xpm tet.frg 24 24 "%1 Tetrahedral" + 16 sqpla.xpm sqpla.frg 24 24 "%1 Square Planar" + 17 seesaw.xpm seesaw.frg 24 24 "%1 Seesaw" + 18 tribipyr.xpm tribipyr.frg 24 24 "%1 Trigonal Bipyramid" + 19 oct.xpm oct.frg 24 24 "%1 Octahedral" + # Fragment Format: atnum def_index frag_index0 frag_index1 ... + Element nItems = 111 + 1 1 0 1 + 2 19 0 19 + 3 1 0 1 + 4 3 0 3 + 5 9 0 9 + 6 15 0 4 5 11 12 15 + 7 14 0 2 7 8 14 + 8 13 0 6 13 + 9 1 0 1 + 10 19 0 19 + 11 1 0 1 + 12 3 0 3 + 13 9 0 9 + 14 15 0 4 5 11 12 15 18 + 15 14 0 7 9 14 15 18 19 + 16 13 0 6 11 13 15 18 19 + 17 1 0 1 3 9 15 18 19 + 18 19 0 19 + 19 1 0 1 + 20 3 0 3 + 21 19 0 3 9 10 15 16 17 18 19 + 22 19 0 3 9 10 15 16 17 18 19 + 23 19 0 3 9 10 15 16 17 18 19 + 24 19 0 3 9 10 15 16 17 18 19 + 25 19 0 3 9 10 15 16 17 18 19 + 26 19 0 3 9 10 15 16 17 18 19 + 27 19 0 3 9 10 15 16 17 18 19 + 28 19 0 3 9 10 15 16 17 18 19 + 29 19 0 3 9 10 15 16 17 18 19 + 30 19 0 3 9 10 15 16 17 18 19 + 31 19 0 3 9 10 15 16 17 18 19 + 32 19 0 3 9 10 15 16 17 18 19 + 33 19 0 3 9 10 15 16 17 18 19 + 34 19 0 3 9 10 15 16 17 18 19 + 35 1 0 1 3 9 15 16 17 18 19 + 36 19 0 19 + 37 1 0 1 + 38 3 0 3 + 39 19 0 3 9 10 15 16 17 18 19 + 40 19 0 3 9 10 15 16 17 18 19 + 41 19 0 3 9 10 15 16 17 18 19 + 42 19 0 3 9 10 15 16 17 18 19 + 43 19 0 3 9 10 15 16 17 18 19 + 44 19 0 3 9 10 15 16 17 18 19 + 45 19 0 3 9 10 15 16 17 18 19 + 46 19 0 3 9 10 15 16 17 18 19 + 47 19 0 3 9 10 15 16 17 18 19 + 48 19 0 3 9 10 15 16 17 18 19 + 49 19 0 3 9 10 15 16 17 18 19 + 50 19 0 3 9 10 15 16 17 18 19 + 51 19 0 3 9 10 15 16 17 18 19 + 52 19 0 3 9 10 15 16 17 18 19 + 53 19 0 1 3 9 15 16 17 18 19 + 54 19 0 19 + 55 1 0 1 + 56 3 0 3 + 57 19 0 3 9 10 15 16 17 18 19 + 58 19 0 3 9 10 15 16 17 18 19 + 59 19 0 3 9 10 15 16 17 18 19 + 60 19 0 3 9 10 15 16 17 18 19 + 61 19 0 3 9 10 15 16 17 18 19 + 62 19 0 3 9 10 15 16 17 18 19 + 63 19 0 3 9 10 15 16 17 18 19 + 64 19 0 3 9 10 15 16 17 18 19 + 65 19 0 3 9 10 15 16 17 18 19 + 66 19 0 3 9 10 15 16 17 18 19 + 67 19 0 3 9 10 15 16 17 18 19 + 68 19 0 3 9 10 15 16 17 18 19 + 69 19 0 3 9 10 15 16 17 18 19 + 70 19 0 3 9 10 15 16 17 18 19 + 71 19 0 3 9 10 15 16 17 18 19 + 72 19 0 3 9 10 15 16 17 18 19 + 73 19 0 3 9 10 15 16 17 18 19 + 74 19 0 3 9 10 15 16 17 18 19 + 75 19 0 3 9 10 15 16 17 18 19 + 76 19 0 3 9 10 15 16 17 18 19 + 77 19 0 3 9 10 15 16 17 18 19 + 78 19 0 3 9 10 15 16 17 18 19 + 79 19 0 3 9 10 15 16 17 18 19 + 80 19 0 3 9 10 15 16 17 18 19 + 81 19 0 3 9 10 15 16 17 18 19 + 82 19 0 3 9 10 15 16 17 18 19 + 83 19 0 3 9 10 15 16 17 18 19 + 84 19 0 3 9 10 15 16 17 18 19 + 85 19 0 1 3 9 15 16 17 18 19 + 86 19 0 19 + 87 1 0 1 + 88 3 0 3 + 89 19 0 3 9 10 15 16 17 18 19 + 90 19 0 3 9 10 15 16 17 18 19 + 91 19 0 3 9 10 15 16 17 18 19 + 92 19 0 3 9 10 15 16 17 18 19 + 93 19 0 3 9 10 15 16 17 18 19 + 94 19 0 3 9 10 15 16 17 18 19 + 95 19 0 3 9 10 15 16 17 18 19 + 96 19 0 3 9 10 15 16 17 18 19 + 97 19 0 3 9 10 15 16 17 18 19 + 98 19 0 3 9 10 15 16 17 18 19 + 99 19 0 3 9 10 15 16 17 18 19 + 100 19 0 3 9 10 15 16 17 18 19 + 101 19 0 3 9 10 15 16 17 18 19 + 102 19 0 3 9 10 15 16 17 18 19 + 103 19 0 3 9 10 15 16 17 18 19 + 104 19 0 3 9 10 15 16 17 18 19 + 105 19 0 3 9 10 15 16 17 18 19 + 106 19 0 3 9 10 15 16 17 18 19 + 107 19 0 3 9 10 15 16 17 18 19 + 108 19 0 3 9 10 15 16 17 18 19 + 109 19 0 3 9 10 15 16 17 18 19 + 110 1 0 1 + 111 1 0 1 + */ +public class AtomGeometry { + + public static final int LINEAR = 0; + public static final int TRIGONAL = 1; + public static final int SQUARE = 2; + public static final int TETRAHEDRAL = 3; + public static final int TRIGONAL_BIPYRAMID = 4; + public static final int OCTAHEDRAL = 5; + + static final String ATOM = "Atom"; + + static final String TERMINAL_SINGLE_ATOM = "Terminal single"; + static final String TERMINAL_DOUBLE_ATOM = "Terminal double"; + static final String TERMINAL_TRIPLE_ATOM = "Terminal triple"; + + static final String LINEAR_SINGLE_SINGLE_ATOM = "Linear Single-Single"; + static final String LINEAR_DOUBLE_DOUBLE_ATOM = "Linear Double-Double"; + static final String LINEAR_SINGLE_TRIPLE_ATOM = "Linear Single-Triple"; + + static final String BENDED_SINGLE_DOUBLE_ATOM = "Bended Single-Double"; + + static final String TRIGONAL_PLANAR_SSS_ATOM = "Trigonal Planar (SSS)"; + static final String TRIGONAL_PLANAR_DSS_ATOM = "Trigonal Planar (DSS)"; + static final String TRIGONAL_PLANAR_SAA_ATOM = "Trigonal Planar (SAA)"; + + static final String T_SHAPED_ATOM = "T-shaped"; + + static final String SEESAW_SHAPED_ATOM = "Seesaw"; + + static final String TETRAHEDRAL_SSSS_ATOM = "Tetrahedral (SSSS)"; + static final String TETRAHEDRAL_SSS_ATOM = "Tetrahedral (SSSLp)"; + static final String TETRAHEDRAL_SS_ATOM = "Tetrahedral (SSLpLp)"; + static final String TETRAHEDRAL_SSSD_ATOM = "Tetrahedral (SSSD)"; // H3PO4 + static final String TETRAHEDRAL_SSDD_ATOM = "Tetrahedral (SSDD)"; // H2SO4 + + static final String SQUARE_PLANAR_ATOM = "Square planar"; + + static final String TRIGONAL_BIPYRAMID_ATOM = "Trigonal bipyramid"; + + static final String OCTAHEDRAL_ATOM = "Octahedral"; + + // --- icons + + public static ImageIcon ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/emptyTransparent.png")); + static ImageIcon TERMINAL_SINGLE_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/terminal_single_atom.png")); + + static ImageIcon TERMINAL_DOUBLE_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/terminal_double_atom.png")); + + static ImageIcon TERMINAL_TRIPLE_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/terminal_triple_atom.png")); + + static ImageIcon LINEAR_SINGLE_SINGLE_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/linear_single_single_atom.png")); + + static ImageIcon LINEAR_SINGLE_TRIPLE_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/linear_single_triple_atom.png")); + + static ImageIcon LINEAR_DOUBLE_DOUBLE_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/linear_double_double_atom.png")); + + static ImageIcon BENDED_SINGLE_DOUBLE_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/bended_single_double_atom.png")); + + static ImageIcon TRIGONAL_PLANAR_SSS_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/trigonal-3.png")); + + static ImageIcon TRIGONAL_PLANAR_DSS_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/trigonal_planar_dss_atom.png")); + + static ImageIcon TRIGONAL_PLANAR_SAA_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/trigonal_planar_saa_atom.png")); + + static ImageIcon TRIGONAL_BIPYRAMID_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/trigonal_bipyramid_atom.png")); + + static ImageIcon T_SHAPED_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/t_shaped_atom.png")); + + static ImageIcon SQUARE_PLANAR_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/square_planar_atom.png")); + + static ImageIcon SEESAW_SHAPED_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/seesaw_shaped_atom.png")); + + static ImageIcon OCTAHEDRAL_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/octahedral_atom.png")); + + static ImageIcon TETRAHEDRAL_SSSS_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/tetrahedral-4.png")); + + static ImageIcon TETRAHEDRAL_SSS_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/tetrahedral-3.png")); + + static ImageIcon TETRAHEDRAL_SS_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/tetrahedral-2.png")); + + static ImageIcon TETRAHEDRAL_SSSD_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/tetrahedral_sssd_atom.png")); + + static ImageIcon TETRAHEDRAL_SSDD_ATOM_ICON = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/tetrahedral_ssdd_atom.png")); + + static Map atomTypes = new LinkedHashMap (); + + static { + atomTypes.put(ATOM, + new AtomGeometry(ATOM, 0, 0, 0, 0, 0, LINEAR, ATOM_ICON)); + atomTypes.put(TERMINAL_SINGLE_ATOM, + new AtomGeometry(TERMINAL_SINGLE_ATOM, 1, 1, 0, 0, 0, + LINEAR, TERMINAL_SINGLE_ATOM_ICON)); + atomTypes.put(TERMINAL_DOUBLE_ATOM, + new AtomGeometry(TERMINAL_DOUBLE_ATOM, 1, 0, 1, 0, 0, + LINEAR, TERMINAL_DOUBLE_ATOM_ICON)); + atomTypes.put(TERMINAL_TRIPLE_ATOM, + new AtomGeometry(TERMINAL_TRIPLE_ATOM, 1, 0, 0, 0, 1, + LINEAR, TERMINAL_TRIPLE_ATOM_ICON)); + atomTypes.put(LINEAR_SINGLE_SINGLE_ATOM, + new AtomGeometry(LINEAR_SINGLE_SINGLE_ATOM, 2, 2, 0, 0, 0, + LINEAR, LINEAR_SINGLE_SINGLE_ATOM_ICON)); + atomTypes.put(LINEAR_DOUBLE_DOUBLE_ATOM, + new AtomGeometry(LINEAR_DOUBLE_DOUBLE_ATOM, 2, 0, 2, 0, 0, + LINEAR, LINEAR_DOUBLE_DOUBLE_ATOM_ICON)); + atomTypes.put(LINEAR_SINGLE_TRIPLE_ATOM, + new AtomGeometry(LINEAR_SINGLE_TRIPLE_ATOM, 2, 1, 0, 0, 1, + LINEAR, LINEAR_SINGLE_TRIPLE_ATOM_ICON)); + atomTypes.put(BENDED_SINGLE_DOUBLE_ATOM, + new AtomGeometry(BENDED_SINGLE_DOUBLE_ATOM, 2, 1, 1, 0, 0, + TRIGONAL, BENDED_SINGLE_DOUBLE_ATOM_ICON)); + atomTypes.put(TRIGONAL_PLANAR_SSS_ATOM, + new AtomGeometry(TRIGONAL_PLANAR_SSS_ATOM, 3, 3, 0, 0, 0, + TRIGONAL, TRIGONAL_PLANAR_SSS_ATOM_ICON)); + atomTypes.put(TRIGONAL_PLANAR_DSS_ATOM, + new AtomGeometry(TRIGONAL_PLANAR_DSS_ATOM, 3, 2, 1, 0, 0, + TRIGONAL, TRIGONAL_PLANAR_DSS_ATOM_ICON)); + atomTypes.put(TRIGONAL_PLANAR_SAA_ATOM, + new AtomGeometry(TRIGONAL_PLANAR_SAA_ATOM, 3, 1, 0, 2, 0, + TRIGONAL, TRIGONAL_PLANAR_SAA_ATOM_ICON)); + atomTypes.put(T_SHAPED_ATOM, + new AtomGeometry(T_SHAPED_ATOM, 3, 3, 0, 0, 0, + SQUARE, T_SHAPED_ATOM_ICON)); + atomTypes.put(SEESAW_SHAPED_ATOM, + new AtomGeometry(SEESAW_SHAPED_ATOM, 4, 4, 0, 0, 0, + SQUARE, SEESAW_SHAPED_ATOM_ICON)); + atomTypes.put(TETRAHEDRAL_SSSS_ATOM, + new AtomGeometry(TETRAHEDRAL_SSSS_ATOM, 4, 4, 0, 0, 0, + TETRAHEDRAL, TETRAHEDRAL_SSSS_ATOM_ICON)); + atomTypes.put(TETRAHEDRAL_SSS_ATOM, + new AtomGeometry(TETRAHEDRAL_SSS_ATOM, 3, 3, 0, 0, 0, + TETRAHEDRAL, TETRAHEDRAL_SSS_ATOM_ICON)); + atomTypes.put(TETRAHEDRAL_SS_ATOM, + new AtomGeometry(TETRAHEDRAL_SS_ATOM, 2, 2, 0, 0, 0, + TETRAHEDRAL, TETRAHEDRAL_SS_ATOM_ICON)); + atomTypes.put(TETRAHEDRAL_SSSD_ATOM, + new AtomGeometry(TETRAHEDRAL_SSSD_ATOM, 4, 3, 1, 0, 0, + TETRAHEDRAL, TETRAHEDRAL_SSSD_ATOM_ICON)); + atomTypes.put(TETRAHEDRAL_SSDD_ATOM, + new AtomGeometry(TETRAHEDRAL_SSDD_ATOM, 4, 2, 2, 0, 0, + TETRAHEDRAL, TETRAHEDRAL_SSDD_ATOM_ICON)); + atomTypes.put(SQUARE_PLANAR_ATOM, + new AtomGeometry(SQUARE_PLANAR_ATOM, 4, 4, 0, 0, 0, + SQUARE, SQUARE_PLANAR_ATOM_ICON)); + atomTypes.put(TRIGONAL_BIPYRAMID_ATOM, + new AtomGeometry(TRIGONAL_BIPYRAMID_ATOM, 5, 5, 0, 0, 0, + TRIGONAL_BIPYRAMID, + TRIGONAL_BIPYRAMID_ATOM_ICON)); + atomTypes.put(OCTAHEDRAL_ATOM, + new AtomGeometry(OCTAHEDRAL_ATOM, 6, 6, 0, 0, 0, + OCTAHEDRAL, OCTAHEDRAL_ATOM_ICON)); + } + + private static AtomGeometry dummy = new AtomGeometry(null, 0, 0, 0, 0, 0, 0, null); + + protected String type = null; + protected int geometry = LINEAR; + protected int coordNumber = 0; + protected int singleBonds = 0; + protected int doubleBonds = 0; + protected int aromaticBonds = 0; + protected int tripleBonds = 0; + protected ImageIcon icon = null; + + public AtomGeometry() {} + + public AtomGeometry(String _type, int coordnum, int singles, int doubles, + int aromatics, int triples, int geom, ImageIcon _icon) { + type = _type; + geometry = geom; + coordNumber = coordnum; + singleBonds = singles; + doubleBonds = doubles; + aromaticBonds = aromatics; + tripleBonds = triples; + icon = _icon; + } + + public AtomGeometry(AtomGeometry aType) { + setAtomGeometry(aType); + } + + public ImageIcon getIcon() { + return icon; + } + + public void setAtomGeometry(AtomGeometry aType) { + type = aType.type; + geometry = aType.geometry; + coordNumber = aType.coordNumber; + singleBonds = aType.singleBonds; + doubleBonds = aType.doubleBonds; + aromaticBonds = aType.aromaticBonds; + tripleBonds = aType.tripleBonds; + icon = aType.icon; + + } + + public int getGeometry() { + return geometry; + } + + public static AtomGeometry getAtomGeometry(String gName) { + return atomTypes.get(gName); + } + + public void setCoordinationNumber(int n) { + coordNumber = n; + } + + public int getCoordinationNumber() { + return coordNumber; + } + + public int getMaxSingleBonds() { + return singleBonds; + } + + public void setMaxSingleBonds(int maxH) { + singleBonds = maxH; + } + +} diff --git a/src/main/java/cct/modelling/AtomProperties.java b/src/main/java/cct/modelling/AtomProperties.java new file mode 100644 index 0000000..6dc8bcc --- /dev/null +++ b/src/main/java/cct/modelling/AtomProperties.java @@ -0,0 +1,60 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public interface AtomProperties { + + int GEOMETRY_LINEAR = 1; + int GEOMETRY_TRIGONAL = 2; + int GEOMETRY_TETRAHEDRAL = 3; + +// public void setStyle(int style); + +} diff --git a/src/main/java/cct/modelling/AtomSelection.java b/src/main/java/cct/modelling/AtomSelection.java new file mode 100644 index 0000000..4a443a5 --- /dev/null +++ b/src/main/java/cct/modelling/AtomSelection.java @@ -0,0 +1,206 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.modelling; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.interfaces.MonomerInterface; +import cct.tools.ui.JobProgressInterface; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + * @author Vlad + */ +public class AtomSelection { + + static final Logger logger = Logger.getLogger(AtomSelection.class.getCanonicalName()); + + static public void applySelectionMask(MoleculeInterface molecule, boolean selectedAtoms[], SELECTION_TYPE selectionType, + SELECTION_RULE selectionRule, JobProgressInterface progress) throws Exception { + + // --- Error check + if (molecule == null) { + throw new Exception("INTERNAL ERROR: makeSelection: molecule == null"); + } + + int natoms = molecule.getNumberOfAtoms(); + + if (natoms != selectedAtoms.length) { + throw new Exception("INTERNAL ERROR: makeSelection: molecule.getNumberOfAtoms() != selectedAtoms.length"); + } + + // --- Make selection + switch (selectionRule) { + case UNION: + for (int i = 0; i < natoms; i++) { + if (!selectedAtoms[i]) { + continue; + } + AtomInterface atom = molecule.getAtomInterface(i); + atom.setSelected(true); + } + break; + //***************************************************** + case DIFFERENCE: + for (int i = 0; i < natoms; i++) { + if (!selectedAtoms[i]) { + continue; + } + AtomInterface atom = molecule.getAtomInterface(i); + + if (atom.isSelected()) { + atom.setSelected(false); + } + } + break; + //********************************************************** + case INTERSECTION: + for (int i = 0; i < natoms; i++) { + AtomInterface atom = molecule.getAtomInterface(i); + if (selectedAtoms[i] && atom.isSelected()) { + continue; + } + atom.setSelected(false); + } + break; + } + } + + static public boolean[] selectAtomsWithinSphere(MoleculeInterface molecule, double radius, SELECTION_TYPE selectionType, + JobProgressInterface progress) throws Exception { + + int natoms = molecule.getNumberOfAtoms(); + AtomInterface atom; + StringBuilder sb = null; + if (logger.isLoggable(Level.INFO) && selectionType == SELECTION_TYPE.MONOMERS) { + sb = new StringBuilder(); + } + + boolean selectedAtoms[] = new boolean[natoms]; + int nsel = 0; + for (int i = 0; i < selectedAtoms.length; i++) { + selectedAtoms[i] = molecule.getAtomInterface(i).isSelected(); + ++nsel; + } + + if (nsel < 1) { + return selectedAtoms; + } + + switch (selectionType) { + case ATOMS: + + for (int i = 0; i < natoms; i++) { + AtomInterface at = molecule.getAtomInterface(i); + if (!at.isSelected()) { + continue; + } + + for (int j = 0; j < natoms; j++) { + atom = molecule.getAtomInterface(j); + if (atom.isSelected()) { + continue; + } + if (atom.distanceTo(at) <= radius) { + selectedAtoms[j] = true; + } + } + } + + break; + //####################################################################### + case MONOMERS: + + int nmonomers = molecule.getNumberOfMonomers(); + boolean[] alreadySelected = null; + if (nmonomers > 0) { + alreadySelected = new boolean[nmonomers]; + } + + for (int i = 0; i < natoms; i++) { + AtomInterface at = molecule.getAtomInterface(i); + if (!at.isSelected()) { + continue; + } + + for (int j = 0; j < molecule.getNumberOfMonomers(); j++) { + if (alreadySelected[j]) { + continue; + } + + MonomerInterface mono = molecule.getMonomerInterface(j); + for (int k = 0; k < mono.getNumberOfAtoms(); k++) { + atom = mono.getAtom(k); + if (atom.distanceTo(at) <= radius) { + alreadySelected[j] = true; + if (logger.isLoggable(Level.INFO) && selectionType == SELECTION_TYPE.MONOMERS) { + sb.append(mono.getName() + String.valueOf(j + 1) + "\n"); + } + for (int kk = 0; kk < mono.getNumberOfAtoms(); kk++) { + atom = mono.getAtom(kk); + int n = molecule.getAtomIndex(atom); + selectedAtoms[n] = true; + } + break; + } + } + } + } + + if (logger.isLoggable(Level.INFO) && selectionType == SELECTION_TYPE.MONOMERS) { + logger.log(Level.INFO, "Selected monomers:\n" + sb.toString()); + } + break; + //####################################################################### + case MOLECULES: + + int nmols; + List> mols = Molecule.getMolecules(molecule); + if (mols == null || (nmols = mols.size()) < 1) { + break; + } + alreadySelected = null; + if (nmols > 0) { + alreadySelected = new boolean[nmols]; + } + + for (int i = 0; i < natoms; i++) { + AtomInterface at = molecule.getAtomInterface(i); + if (!at.isSelected()) { + continue; + } + + for (int j = 0; j < nmols; j++) { + if (alreadySelected[j]) { + continue; + } + + List mol = mols.get(j); + + for (int k = 0; k < mol.size(); k++) { + atom = mol.get(k); + if (atom.distanceTo(at) <= radius) { + alreadySelected[j] = true; + for (int kk = 0; kk < mol.size(); kk++) { + atom = mol.get(kk); + int n = molecule.getAtomIndex(atom); + selectedAtoms[n] = true; + } + break; + } + } + } + } + break; + default: + throw new Exception("Selection type " + selectionType.name() + " is not implemented"); + } + + return selectedAtoms; + } +} diff --git a/src/main/java/cct/modelling/AtomSurfaceEntity.java b/src/main/java/cct/modelling/AtomSurfaceEntity.java new file mode 100644 index 0000000..29c8d57 --- /dev/null +++ b/src/main/java/cct/modelling/AtomSurfaceEntity.java @@ -0,0 +1,47 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.modelling; + +import cct.interfaces.AtomInterface; + +/** + * + * @author Vlad + */ +public class AtomSurfaceEntity { + + private AtomInterface atom; + private double C = 0, A = 0; + + public AtomSurfaceEntity(AtomInterface atom, double A, double C) { + this.atom = atom; + this.A = A; + this.C = C; + } + + public double getA() { + return A; + } + + public void setA(double A) { + this.A = A; + } + + public double getC() { + return C; + } + + public void setC(double C) { + this.C = C; + } + + public AtomInterface getAtom() { + return atom; + } + + public void setAtom(AtomInterface atom) { + this.atom = atom; + } +} diff --git a/src/main/java/cct/modelling/AtomTypeDef.java b/src/main/java/cct/modelling/AtomTypeDef.java new file mode 100644 index 0000000..c870139 --- /dev/null +++ b/src/main/java/cct/modelling/AtomTypeDef.java @@ -0,0 +1,133 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +import java.awt.Color; + +import javax.swing.JFrame; +import javax.swing.JOptionPane; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description:

+ * Defines atom type + * + *

Copyright: Copyright (c) 2005

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class AtomTypeDef + implements AtomProperties { + protected String Name = null; + protected int Element = 0; + protected int Valence = 0; + protected int Geometry = 0; + + // --- Optional + + Color atomColor = null; + float Weight = -1.0f; + float covalentRadius = -1.0f; + String Description = null; + + public AtomTypeDef(String name, String element, int valence, int geometry) { + int elem = ChemicalElements.getAtomicNumber(element); + Init(name, elem, valence, geometry); + } + + public AtomTypeDef(String name, int element, int valence, int geometry) { + Init(name, element, valence, geometry); + } + + public void Init(String name, int element, int valence, int geometry) { + Name = name; + if (element < 0 || element > ChemicalElements.getNumberOfElements()) { + JOptionPane.showMessageDialog(new JFrame(), + "Internal ERROR: AtomType: Wrong element number: " + + element, + "Error", + JOptionPane.ERROR_MESSAGE); + element = 0; + } + Element = element; + + // !!! ERROR CHECK !!! + Valence = valence; + + Geometry = geometry; + } + + /** + * Get name (mnemonic) of atom type + * @return String + */ + public String getName() { + return Name; + } + + /** + * Set atomic weight + * @param weight float + * @return boolean "false" if atomic weight was wrong, "true" otherwise + */ + public boolean setWeight(float weight) { + if (weight < 0) { + JOptionPane.showMessageDialog(new JFrame(), + "Internal ERROR: setWeight: Wrong atomic weight: " + + weight, + "Error", + JOptionPane.ERROR_MESSAGE); + Weight = 0; + return false; + } + Weight = weight; + return true; + } + + /** + * Sets description for this atom type + * @param descr String + */ + public void setDescription(String descr) { + Description = descr; + } +} diff --git a/src/main/java/cct/modelling/AtomTypes.java b/src/main/java/cct/modelling/AtomTypes.java new file mode 100644 index 0000000..8de85f3 --- /dev/null +++ b/src/main/java/cct/modelling/AtomTypes.java @@ -0,0 +1,105 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +import java.util.HashMap; +import java.util.Map; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class AtomTypes + implements AtomProperties { + + static final Map defaultAtomTypes = new HashMap(); + Map atomTypes; + + public AtomTypes() { + atomTypes = new HashMap(defaultAtomTypes); + } + + static { + AtomTypeDef temp; + defaultAtomTypes.put("H", new AtomTypeDef("H", "H", 1, GEOMETRY_LINEAR)); + defaultAtomTypes.put("LI", new AtomTypeDef("LI", "LI", 1, GEOMETRY_LINEAR)); + defaultAtomTypes.put("BE", new AtomTypeDef("BE", "BE", 2, GEOMETRY_LINEAR)); + defaultAtomTypes.put("B", new AtomTypeDef("B", "B", 3, GEOMETRY_TRIGONAL)); + temp = new AtomTypeDef("C.4", "C", 4, GEOMETRY_TETRAHEDRAL); + defaultAtomTypes.put("C.4", temp); + defaultAtomTypes.put("C.3", new AtomTypeDef("C.3", "C", 3, GEOMETRY_TRIGONAL)); + defaultAtomTypes.put("C.2", new AtomTypeDef("C.2", "C", 2, GEOMETRY_TRIGONAL)); + + // --- Nitrogen atom types + + temp = new AtomTypeDef("N.4", "N", 4, GEOMETRY_TETRAHEDRAL); + temp.setDescription("Positively charged sp3 Nitrogen (S-S-S-S)"); + defaultAtomTypes.put(temp.getName(), temp); + + temp = new AtomTypeDef("N.3", "N", 3, GEOMETRY_TETRAHEDRAL); + temp.setDescription("Sp3 Nitrogen (S-S-S-Lp"); + defaultAtomTypes.put(temp.getName(), temp); + + temp = new AtomTypeDef("N.P3", "N", 3, GEOMETRY_TRIGONAL); + temp.setDescription("Trigonal planar Nitrogen"); + defaultAtomTypes.put(temp.getName(), temp); + + temp = new AtomTypeDef("N.2", "N", 2, GEOMETRY_LINEAR); + temp.setDescription("Nitrogen sp"); + defaultAtomTypes.put(temp.getName(), temp); + + // --- Oxygen atom types + + temp = new AtomTypeDef("O.4", "O", 2, GEOMETRY_TETRAHEDRAL); + temp.setDescription("Oxygen sp3"); + defaultAtomTypes.put(temp.getName(), temp); + + temp = new AtomTypeDef("O.2", "O", 1, GEOMETRY_LINEAR); + temp.setDescription("Oxygen sp2"); + defaultAtomTypes.put(temp.getName(), temp); + + } +} diff --git a/src/main/java/cct/modelling/AtomicSet.java b/src/main/java/cct/modelling/AtomicSet.java new file mode 100644 index 0000000..5961a73 --- /dev/null +++ b/src/main/java/cct/modelling/AtomicSet.java @@ -0,0 +1,38 @@ +package cct.modelling; + +import java.util.ArrayList; + +import cct.interfaces.AtomInterface; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class AtomicSet + extends ArrayList { + private String name = "NO_NAME"; + + public AtomicSet() { + } + + public AtomicSet(String name) { + this.name = name; + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + +} diff --git a/src/main/java/cct/modelling/AtomicSets.java b/src/main/java/cct/modelling/AtomicSets.java new file mode 100644 index 0000000..52c22a9 --- /dev/null +++ b/src/main/java/cct/modelling/AtomicSets.java @@ -0,0 +1,21 @@ +package cct.modelling; + +import java.util.HashMap; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class AtomicSets + extends HashMap { + public AtomicSets() { + } +} diff --git a/src/main/java/cct/modelling/AtomsArray.java b/src/main/java/cct/modelling/AtomsArray.java new file mode 100644 index 0000000..9a15848 --- /dev/null +++ b/src/main/java/cct/modelling/AtomsArray.java @@ -0,0 +1,414 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +//import java.util.Vector; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.NoSuchElementException; +import java.util.Set; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; + +/** + * + *

Title: AtomsArray

+ * + *

Description: This class keeps track about atoms/residues addition

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class AtomsArray { +//public class AtomsArray extends ArrayList { + protected ArrayList Atoms = new ArrayList(); + protected ArrayList Residues = new ArrayList(); + static final Logger logger = Logger.getLogger(AtomsArray.class.getCanonicalName()); + /** + * Creates a new atom array. + */ + public AtomsArray() { + super(); + } + + public void addMonomer(String monomer_name) { + Monomer last_monomer = new Monomer(monomer_name); + Residues.add(last_monomer); + } + + /** Copy constructor */ + public AtomsArray(AtomsArray av) { + // super( av.size(), av.size() ); + Atoms = (ArrayList) av.Atoms.clone(); + Residues = (ArrayList) av.Residues.clone(); + /* + for (int i = 0; i < av.size(); i++) { + Atom a = new Atom(av.getAtom(i)); + append(a); + } + */ + } + + /** + * Adds atom to the last residue in the list + * @param a Atom + */ + //public void addAtom(Atom a) { + public void addAtom(AtomInterface a) { + Monomer last_monomer; + int n; + if (Residues.isEmpty()) { + last_monomer = new Monomer(); + Residues.add(last_monomer); + n = 0; + } + else { + n = Residues.size() - 1; // Index of the last element + last_monomer = (Monomer) Residues.get(n); + } + a.setSubstructureNumber(n); + Atoms.add(a); + last_monomer.addAtom(a); + } + + /** + * Adds a new monomer and adds an atom to the monomer + * @param a Atom Atom to be added + * @param monomer_name String Name of new monomer to be added + */ + public void addAtom(AtomInterface a, String monomer_name) { + Monomer last_monomer = new Monomer(monomer_name); + Residues.add(last_monomer); + addAtom(a); + } + + /** + * Adds atom to the existing nth monomer. + * @param a Atom Atom to be added + * @param n int Monomer number + */ + /* + public void addAtom(Atom a, int n) { + if ( n < 0 || n>= Residues.size() ) { + logger.info( + "INTERNAL ERROR: addAtom: n < 0 || n>= Residues.size()"); + addAtom(a); // Just add the atom to the last residue + return; + } + Monomer n_monomer = (Monomer) Residues.get(n); + a.setSubstructureNumber(n); + Atoms.add(a); + n_monomer.addAtom(a); + } + */ + public void addAtom(AtomInterface a, int n) { + if (n < 0 || n >= Residues.size()) { + if (! (Residues.size() == 0 && n == 0)) { + System.err.println("Warning: addAtom: n < 0 || n>= Residues.size(" + Residues.size() + "): " + n); + } + addAtom(a); // Just add the atom to the last residue + return; + } + Monomer n_monomer = (Monomer) Residues.get(n); + a.setSubstructureNumber(n); + Atoms.add(a); + n_monomer.addAtom(a); + } + + /** + * + * @param a Atom + * @param n int + * @param name String + */ + public void addAtom(AtomInterface a, int n, String name) { + if (n < 0) { + System.err.println( + "INTERNAL ERROR: addAtom: n < 0 for residue " + name); + addAtom(a); // Just add the atom to the last residue + return; + } + + if (name == null) { + System.err.println( + "INTERNAL ERROR: addAtom: name ==null, put name to XXX"); + name = "XXX"; + } + + Monomer n_monomer = null; + + if (n < Residues.size()) { // Error check for existing residue + n_monomer = (Monomer) Residues.get(n); + String res_name = n_monomer.getName(); + if (res_name == null) { + n_monomer.setName(name); + } + else if (!res_name.equals(name)) { + System.err.println( + "ERROR: addAtom: residue already has name " + res_name + "; new name " + name + " is ignored"); + } + addAtom(a, n); + return; + } + else { // Allocate memory for new residue(s) + for (int i = Residues.size(); i <= n; i++) { + n_monomer = new Monomer(); + Residues.add(n_monomer); + } + } + + n_monomer.name = name; + addAtom(a, n); + } + + /** + * Returns ith atom + * @exception ArrayIndexOutOfBoundsException if index >= capacity() + */ + public AtomInterface getAtom(int i) throws + ArrayIndexOutOfBoundsException { +// return (Atom)elementAt( i ); + return (AtomInterface) Atoms.get(i); + } + + public AtomInterface getAtomInterface(int i) throws + ArrayIndexOutOfBoundsException { +// return (Atom)elementAt( i ); + return (AtomInterface) Atoms.get(i); + } + + /** + * Returns atom number in the list. + * @param a Atom Atom in question + * @return int Atom number. -1 if no such atom in the list. + */ + public int getAtomIndex(AtomInterface a) { + return Atoms.indexOf(a); + } + + /** + * Returns nth monomer from the list. + * @param n int - Monomer number + * @return Monomer - Returns nth monomer or null if n is out of bounds + */ + public Monomer getMonomer(int n) { + if (n < 0 || n >= Residues.size()) { + logger.info( + "INTERNAL ERROR: getMonomer: n < 0 || n>= Residues.size(): " + n); + return null; + } + return (Monomer) Residues.get(n); + } + + /** + * Returns number of monomers + * @return int Returns number of monomers + */ + public int getNumberOfMonomers() { + return Residues.size(); + } + + /** + * Set an atom at specified index; atom at index is replaced + */ + public void replace(Atom a, int i) { +// setElementAt( a, i ); + Atoms.set(i, a); + } + + /** + * Insert an atom at specified index; other atoms are shifted over + */ + public void insert(Atom a, int i) { +// insertElementAt( a, i ); + Atoms.add(i, a); + } + + /** + * Removes atom from the list + * @param a Atom - Atom to be removed + * @return boolean Returns "true" in the case of success, "false" otherwise + */ + public boolean removeAtom(AtomInterface a) { + if (Atoms.indexOf(a) == -1) { + logger.info( + "INTERNAL ERROR: AtomArray: removeAtom: No such atom in list"); + return false; + } + int nres = a.getSubstructureNumber(); + + if (nres < 0 || nres >= Residues.size()) { + logger.info( + "INTERNAL ERROR: AtomArray: removeAtom: Wrong residue number"); + return false; + } + + Monomer monomer = (Monomer) Residues.get(nres); + + if (monomer.indexOf(a) == -1) { + logger.info( + "INTERNAL ERROR: AtomArray: removeAtom: No such atom in specified monomer"); + return false; + } + + if (!Atoms.remove(a) || !monomer.remove(a)) { + logger.info( + "INTERNAL ERROR: AtomArray: removeAtom: !Atoms.remove(a) || !monomer.remove(a)"); + return false; + } + + if (monomer.size() == 0) { // No more atoms in residue, i.e. delete monomer as well + Residues.remove(monomer); + // Re-arrange residues and update atom information + for (int i = 0; i < Residues.size(); i++) { + monomer = (Monomer) Residues.get(i); + for (int j = 0; j < monomer.size(); j++) { + AtomInterface atom = monomer.getAtom(j); + atom.setSubstructureNumber(i); + } + } + } + return true; + } + + /** + * Remove atom at specified index; other atoms are shifted down + * @param i index of atom + * @exception ArrayIndexOutOfBoundsException if index >= capacity() + */ + public Atom removeAtom(int i) throws ArrayIndexOutOfBoundsException { +// removeElementAt( i ); + return remove(i); + } + + /** + * Remove all atoms + * @param i index of atom + * @exception ArrayIndexOutOfBoundsException if index >= capacity() + */ + public void removeAllAtoms() throws ArrayIndexOutOfBoundsException { + //removeAllElements(); + Atoms.clear(); + } + + /** + * Returns first atom in AtomVector + * @exception NoSuchElementException if size() == 0 + */ + public Atom firstAtom() throws NoSuchElementException { + //return (Atom)firstElement(); + if (size() <= 0) { + return null; + } + + return (Atom) Atoms.get(0); + } + + /** + * Returns last atom in AtomVector + * @exception NoSuchElementException if size() == 0 + */ + public Atom lastAtom() throws NoSuchElementException { + //return (Atom)lastElement(); + int dim = size(); + if (size() <= 0) { + return null; + } + + return (Atom) Atoms.get(dim - 1); + } + + /** + * Compares this AtomArray with another + * @param av AtomVector to compare with + * @return true if they are equal, else false + */ + public boolean equals(AtomsArray av) { + if (av == null) { + return false; + } + + if (size() != av.size()) { + return false; + } + + for (int i = 0; i < size(); i++) { + AtomInterface a1 = getAtom(i); + AtomInterface a2 = av.getAtom(i); + if (!a1.equals(a2)) { + return false; + } + } + + return true; + } + + Atom remove(int i) throws ArrayIndexOutOfBoundsException { + return (Atom) Atoms.remove(i); + } + + void set(Atom a, int i) { + Atoms.set(i, a); + } + + int size() { + return Atoms.size(); + } + + public boolean hasAtom(Atom atom) { + return Atoms.contains(atom); + } + + public Set getUniqueMonomersInMolecule() { + Set monomers = new HashSet (); + for (int i = 0; i < getNumberOfMonomers(); i++) { + Monomer m = this.getMonomer(i); + String monomer_name = m.getName(); + if (!monomers.contains(monomer_name)) { + monomers.add(monomer_name); + } + } + return monomers; + } + +} diff --git a/src/main/java/cct/modelling/BackgroundMinimizer.java b/src/main/java/cct/modelling/BackgroundMinimizer.java new file mode 100644 index 0000000..9006902 --- /dev/null +++ b/src/main/java/cct/modelling/BackgroundMinimizer.java @@ -0,0 +1,193 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.modelling; + +import java.awt.Component; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import javax.swing.JOptionPane; + +import cct.interfaces.MinimizeProgressInterface; +import cct.interfaces.MoleculeInterface; +import cct.interfaces.ParentInterface; +import cct.j3d.Java3dUniverse; +import cct.modelling.ui.MinimizationProgressDialog; +import cct.tools.ui.JShowText; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class BackgroundMinimizer + extends cct.tools.SwingWorker implements MinimizeProgressInterface { + + ParentInterface parentProcess = null; + MinimizeStructure mS = null; + Object ID; + MinimizationProgressDialog dial = null; + Component component = null; + Frame parentFrame = null; + boolean minimizationCancelled = false; + int frequencyUpdate_for_variables = 1; + Java3dUniverse visualizer = null; + + public BackgroundMinimizer(Object id, ParentInterface parent, MinimizeStructure ms) { + super(); + parentProcess = parent; + component = parent.getComponent(); + parentFrame = parent.getParentFrame(); + if (parentFrame == null) { + parentFrame = new Frame(); + } + if (component == null) { + component = parentFrame; + } + mS = ms; + ID = id; + dial = new MinimizationProgressDialog(parentFrame, "Optimization Progress...", false); + dial.getCancelButton().addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + cancelMinimization(); + } + }); + dial.setLocationByPlatform(true); + } + + @Override + public Object construct() { + try { + mS.minimize(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(parentFrame, ex.getMessage(), + "Error minimizing Energy", + JOptionPane.ERROR_MESSAGE); + return ex.getMessage(); + } + + dial.setVisible(false); + + JShowText show = new JShowText("Minimization Info"); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + PrintStream store = System.out; + System.setOut(new PrintStream(out)); + mS.printMinimizationSummary(); + show.setText(out); + show.setSize(500, 300); + //show.setLocationRelativeTo(this); + show.setLocationByPlatform(true); + show.setVisible(true); + System.setOut(store); + + parentProcess.childFinished(ID); + return this; + } + + public void setVisualizer(Java3dUniverse v) { + visualizer = v; + } + + public MoleculeInterface getMolecule() { + if (mS == null) { + return null; + } + return mS.getMolecule(); + } + + public void cancelMinimization() { + minimizationCancelled = true; + //parentProcess.childFinished(ID); + //dial.setVisible(false); + //interrupt(); + } + + @Override + public void minimizationStarted(String _started) { + dial.setProgress(_started); + dial.validate(); + dial.pack(); + dial.setVisible(true); + } + + @Override + public boolean isMinimizationCancelled() { + return minimizationCancelled; + } + + @Override + public void minimizationProgressed(String _progress) { + dial.setProgress(_progress); + dial.validate(); + dial.pack(); + } + + @Override + public void minimizationCompleted() { + dial.setVisible(false); + } + + @Override + public int getVariablesFrequencyUpdate() { + return frequencyUpdate_for_variables; + } + + @Override + public void setVariablesFrequencyUpdate(int n) { + frequencyUpdate_for_variables = n; + } + + @Override + public void updateVariables(int n, float x[]) { + if (visualizer == null) { + return; + } + visualizer.updateMolecularGeometry(); + //float[][] coords = mS.getCoordinates(n,x); + } +} diff --git a/src/main/java/cct/modelling/BasicFragment.java b/src/main/java/cct/modelling/BasicFragment.java new file mode 100644 index 0000000..7eadb21 --- /dev/null +++ b/src/main/java/cct/modelling/BasicFragment.java @@ -0,0 +1,139 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +import java.util.HashMap; +import java.util.Map; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ + +// Ordinal-based typesafe enum +public class BasicFragment + implements Comparable { + private final String name = ""; + // Ordinal of next suit to be created + private static int nextOrdinal = 0; + // Assign an ordinal to this suit + private final int ordinal = nextOrdinal++; + + private static Map Fragments = new HashMap(); + + private BasicFragment() { + + MoleculeInterface molecule = Molecule.getNewInstance(); + AtomInterface atom = molecule.getNewAtomInstance(); + + molecule.setName("Methyl"); + + atom.setAtomicNumber(6); + atom.setXYZ(0, 0, 0); + molecule.addAtom(atom); + + atom.setAtomicNumber(1); + atom.setXYZ(0.624883f, 0.624883f, 0.624883f); + molecule.addAtom(atom); + + atom.setAtomicNumber(1); + atom.setXYZ( -0.624883f, -0.624883f, 0.624883f); + molecule.addAtom(atom); + + atom.setAtomicNumber(1); + atom.setXYZ( -0.624883f, 0.624883f, -0.624883f); + molecule.addAtom(atom); + + atom.setAtomicNumber(1); + atom.setXYZ(0.624883f, -0.624883f, -0.624883f); + molecule.addAtom(atom); + + Fragments.put(molecule.getName(), molecule); + + } + + @Override + public String toString() { + return name; + } + + @Override + public int compareTo(Object o) { + return ordinal - ( (BasicFragment) o).ordinal; + } + + public int compareTo(String str) { + return this.toString().compareTo(str); + } + + public int compareToIgnoreCase(String str) { + return this.toString().compareToIgnoreCase(str); + } + + public boolean equalsIgnoreCase(String str) { + return this.toString().equalsIgnoreCase(str); + } + + public int getEnum() { + return ordinal; + } + + // CCT Tags + + + + class CarbonDivalentStr { + MoleculeInterface mol = Molecule.getNewInstance(); + + public MoleculeInterface getMolecule() { + return mol; + } + } + +} diff --git a/src/main/java/cct/modelling/Bond.java b/src/main/java/cct/modelling/Bond.java new file mode 100644 index 0000000..0d0bb74 --- /dev/null +++ b/src/main/java/cct/modelling/Bond.java @@ -0,0 +1,148 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +import java.util.HashMap; +import java.util.Map; + +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class Bond + implements BondInterface { + + protected AtomInterface a1, a2; + Map properties = new HashMap (); + + public Bond() { + a1 = a2 = null; + } + + @Override + public BondInterface getNewBondInstance() { + return new Bond(); + } + + public Bond(AtomInterface a1, AtomInterface a2) { + this.a1 = a1; + this.a2 = a2; + + a1.setBondedTo(a2, true); + a2.setBondedTo(a1, true); + + a1.setBondIndex(this); + a2.setBondIndex(this); + } + + @Override + public BondInterface getNewBondInstance(AtomInterface a_i, AtomInterface a_j) { + return new Bond(a_i, a_j); + } + + @Override + public BondInterface getNewBondInstance(BondInterface bond) { + return new Bond(bond); + } + + public Bond(Bond b) { + a1 = b.a1; + a2 = b.a2; + } + + public Bond(BondInterface b) { + a1 = b.getIAtomInterface(); + a2 = b.getJAtomInterface(); + } + + @Override + public float bondLength() { + return (float) Math.sqrt( ( + (a1.getX() - a2.getX()) * (a1.getX() - a2.getX()) + + (a1.getY() - a2.getY()) * (a1.getY() - a2.getY()) + + (a1.getZ() - a2.getZ()) * (a1.getZ() - a2.getZ()))); + } + + public Bond getBond() { + return this; + } + + public AtomInterface getI() { + return a1; + } + + public AtomInterface getJ() { + return a2; + } + + @Override + public AtomInterface getIAtomInterface() { + return a1; + } + + @Override + public AtomInterface getJAtomInterface() { + return a2; + } + + @Override + public Map getProperties() { + return properties; + } + + @Override + public Object getProperty(String key) { + return properties.get(key); + } + + @Override + public void setProperty(String prop, Object value) { + properties.put(prop, value); + } +} diff --git a/src/main/java/cct/modelling/BondStretchEnergy.java b/src/main/java/cct/modelling/BondStretchEnergy.java new file mode 100644 index 0000000..c24abfe --- /dev/null +++ b/src/main/java/cct/modelling/BondStretchEnergy.java @@ -0,0 +1,177 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +import java.util.List; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.vecmath.Point3f; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class BondStretchEnergy { + static final Logger logger = Logger.getLogger(BondStretchEnergy.class.getCanonicalName()); + + private BondStretchEnergy() { + } + + public static double bondStretchEnergy(MoleculeInterface molec, + Object BondStretchInteractions[]) { + return bondStretchEnergy(molec, BondStretchInteractions, null); + } + + public static double bondStretchEnergy(MoleculeInterface molec, + Object BondStretchInteractions[], + Point3f[] Gradients) { + double energy = 0; + + Integer intType = (Integer) BondStretchInteractions[0]; + + // --- Harmonic bond stretch energy without gradients + if (intType == FFMolecule.HARMONIC_BOND_TERM && Gradients == null) { + BondStretchPairs bondPairs = (BondStretchPairs) + BondStretchInteractions[1]; + + energy += HarmonicStretchEnergy(molec, bondPairs); + } + + // --- Harmonic bond stretch energy with gradients + else if (intType == FFMolecule.HARMONIC_BOND_TERM) { + BondStretchPairs bondPairs = (BondStretchPairs) + BondStretchInteractions[1]; + + energy += HarmonicStretchEnergy(molec, bondPairs, Gradients); + } + + return energy; + } + + /** + * Calculates Bond stretch energy without gradients + * @param molec MoleculeInterface - molecule + * @param bondPairs BondStretchPairs - bond stretch parameters + * @return double - Energy + */ + public static double HarmonicStretchEnergy(MoleculeInterface molec, + BondStretchPairs bondPairs) { + double energy = 0; + + List pairs = bondPairs.getBondStretchPairs(); + + for (int i = 0; i < pairs.size(); i++) { + HarmonicBondStretch hbs = (HarmonicBondStretch) pairs.get(i); + AtomInterface a1 = molec.getAtomInterface(hbs.i); + AtomInterface a2 = molec.getAtomInterface(hbs.j); + + double dif = Point3f.distance(a1, a2) - hbs.R0; + energy += hbs.Fk * dif * dif; + } + + return 0.5 * energy; + } + + public static double HarmonicStretchEnergyAnalysis(MoleculeInterface molec, + BondStretchPairs bondPairs, float threshold) { + double energy = 0; + + List pairs = bondPairs.getBondStretchPairs(); + + for (int i = 0; i < pairs.size(); i++) { + HarmonicBondStretch hbs = (HarmonicBondStretch) pairs.get(i); + AtomInterface a1 = molec.getAtomInterface(hbs.i); + AtomInterface a2 = molec.getAtomInterface(hbs.j); + + double dif = Point3f.distance(a1, a2) - hbs.R0; + double en = 0.5 * hbs.Fk * dif * dif; + if (en >= threshold) { + logger.info(a1.getName() + "(" + (hbs.i + 1) + ")-" + + a2.getName() + "(" + (hbs.j + 1) + ") Energy: " + + en + " R=" + Point3f.distance(a1, a2)); + } + energy += en; + } + + return 0.5 * energy; + } + + /** + * Calculates Bond stretch energy with gradients + * @param molec MoleculeInterface + * @param bondPairs BondStretchPairs + * @param Gradients Point3f[] - Final gradients + * @return double + */ + public static double HarmonicStretchEnergy(MoleculeInterface molec, + BondStretchPairs bondPairs, + Point3f[] Gradients) { + double energy = 0; + + List pairs = bondPairs.getBondStretchPairs(); + Point3f rijvec = new Point3f(); + + for (int i = 0; i < pairs.size(); i++) { + HarmonicBondStretch hbs = (HarmonicBondStretch) pairs.get(i); + AtomInterface a1 = molec.getAtomInterface(hbs.i); + AtomInterface a2 = molec.getAtomInterface(hbs.j); + + rijvec.subtract(a1, a2); + double r = rijvec.vectorNorm(); + double dif = r - hbs.R0; + energy += hbs.Fk * dif * dif; + + rijvec.multiply(hbs.Fk * dif / r); + Gradients[hbs.i].add(rijvec); + Gradients[hbs.j].substract(rijvec); + } + + return 0.5 * energy; + } + +} diff --git a/src/main/java/cct/modelling/BondStretchPairs.java b/src/main/java/cct/modelling/BondStretchPairs.java new file mode 100644 index 0000000..609cea4 --- /dev/null +++ b/src/main/java/cct/modelling/BondStretchPairs.java @@ -0,0 +1,81 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +import java.util.ArrayList; +import java.util.List; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class BondStretchPairs { + protected List Pairs; + public BondStretchPairs() { + Pairs = new ArrayList(); + } + + public BondStretchPairs(int nb) { + Pairs = new ArrayList(nb); + } + + public void addBondPair(Object bt) { + Pairs.add(bt); + } + + public int getSize() { + return Pairs.size(); + } + + public List getBondStretchPairs() { + return Pairs; + } + + public Object[] getBondStretchPairsAsArray() { + return Pairs.toArray(); + } + +} diff --git a/src/main/java/cct/modelling/BondsArray.java b/src/main/java/cct/modelling/BondsArray.java new file mode 100644 index 0000000..f95ed52 --- /dev/null +++ b/src/main/java/cct/modelling/BondsArray.java @@ -0,0 +1,192 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +//import java.util.Vector; +import java.util.ArrayList; +import java.util.NoSuchElementException; + +import cct.interfaces.BondInterface; + +/** + * + *

Title: BondsArray

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class BondsArray + extends ArrayList { + public BondsArray() { + super(); + } + + /** Copy constructor */ + public BondsArray(BondsArray ab) { + // super( av.size(), av.size() ); + + for (int i = 0; i < ab.size(); i++) { + BondInterface bond = ab.getBond(i); + //Bond b = new Bond( ab.getBond(i) ); + BondInterface b = bond.getNewBondInstance(bond); + add(b); + } + } + + /** + * Append an atom to the end of vector + */ + + public void append(BondInterface b) { + //addElement( a ); + add(b); + } + + /** + * Returns atom at specified index + * @exception ArrayIndexOutOfBoundsException if index >= capacity() + */ + public BondInterface getBond(int i) throws + ArrayIndexOutOfBoundsException { +// return (gAtom)elementAt( i ); + return (BondInterface) get(i); + } + + /** + * Set an atom at specified index; atom at index is replaced + */ + public void replace(BondInterface a, int i) { +// setElementAt( a, i ); + set(i, a); + } + + /** + * Insert an atom at specified index; other atoms are shifted over + */ + public void insert(BondInterface a, int i) { +// insertElementAt( a, i ); + add(i, a); + } + + /** + * Remove an atom; other atoms are shifted down + */ + public boolean removeBond(BondInterface a) { +// return removeElement( a ); + return remove(a); + } + + /** + * Remove atom at specified index; other atoms are shifted down + * @param i index of atom + * @exception ArrayIndexOutOfBoundsException if index >= capacity() + */ + public BondInterface removeBond(int i) throws ArrayIndexOutOfBoundsException { +// removeElementAt( i ); + return (BondInterface) remove(i); + } + + /** + * Remove all atoms + * @param i index of atom + * @exception ArrayIndexOutOfBoundsException if index >= capacity() + */ + public void removeAllBonds() throws ArrayIndexOutOfBoundsException { + //removeAllElements(); + clear(); + } + + /** + * Returns first atom in AtomVector + * @exception NoSuchElementException if size() == 0 + */ + public BondInterface firstBond() throws NoSuchElementException { + //return (gAtom)firstElement(); + if (size() <= 0) { + return null; + } + + return (BondInterface) get(0); + } + + /** + * Returns last atom in AtomVector + * @exception NoSuchElementException if size() == 0 + */ + public BondInterface lastBond() throws NoSuchElementException { + //return (gAtom)lastElement(); + int dim = size(); + if (size() <= 0) { + return null; + } + + return (BondInterface) get(dim - 1); + } + + /** + * Compares this AtomVector with another + * @param av AtomVector to compare with + * @return true if they are equal, else false + */ + public boolean equals(BondsArray av) { + if (av == null) { + return false; + } + + if (size() != av.size()) { + return false; + } + + for (int i = 0; i < size(); i++) { + BondInterface a1 = getBond(i); + BondInterface a2 = av.getBond(i); + if (!a1.equals(a2)) { + return false; + } + } + + return true; + } + +} diff --git a/src/main/java/cct/modelling/CCTAtomTypes.java b/src/main/java/cct/modelling/CCTAtomTypes.java new file mode 100644 index 0000000..d2d5905 --- /dev/null +++ b/src/main/java/cct/modelling/CCTAtomTypes.java @@ -0,0 +1,771 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +import cct.resources.images.ImageResources; + +import javax.swing.*; +import java.util.*; +import java.util.logging.Logger; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class CCTAtomTypes + extends AtomGeometry implements Comparator { + + public static final String LINEAR_GEOMETRY = "linear"; + public static final String TETRAHEDRAL_GEOMETRY = "tetrahedral"; + public static final String TRIGONAL_GEOMETRY = "trigonal"; + + static final String BASE_ELEMENT_KEY = "BASEELEMENT"; + static final String DEFAULT_TYPE_KEY = "DEFAULT"; + static final String COORDINATION_NUMBER_KEY = "COORDNUMBER"; + static final String GEOMETRY_KEY = "GEOMETRY"; + static final String MAX_SINGLE_BONDS_KEY = "MAXSINGLES"; + static final String VDW_DI_KEY = "DI"; + static final String VDW_RI_KEY = "RI"; + + static Set atomProperties = new HashSet(); + static final Logger logger = Logger.getLogger(CCTAtomTypes.class.getCanonicalName()); + + static final float unsetDiValue = -10000.0f; + + static private boolean debug = false; + private String typeName; + private int chemicalElement; + private float weight; + //private int coordNumber = 4; + //private int maxHNumber = coordNumber; + //private int geometry = TETRAHEDRAL; + private float covalentRadius = 0.0f; + private float vdwWellDepth = unsetDiValue; + private float vdwDistance = unsetDiValue; + private boolean defaultType = false; + + static String defaultProperiesFile = "cct.CCTAtomTypes"; + private static ResourceBundle resources; + // Ordinal of next suit to be created + private static int nextOrdinal = 0; + // Assign an ordinal to this suit + private final int ordinal = nextOrdinal++; + + private static Map allTypes = new LinkedHashMap (); + private static Map elementMapping = new LinkedHashMap(); + + static ImageIcon emptyIcon = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/emptyTransparent.png")); + static ImageIcon tetrahedral_4_Icon = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/tetrahedral-4.png")); + + static ImageIcon tetrahedral_3_Icon = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/tetrahedral-3.png")); + + static ImageIcon tetrahedral_2_Icon = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/tetrahedral-2.png")); + + static ImageIcon trigonal_3_Icon = new ImageIcon(ImageResources.class.getResource( + "/cct/images/icons48x48/trigonal-3.png")); + + static { + atomProperties.add(BASE_ELEMENT_KEY); + atomProperties.add(COORDINATION_NUMBER_KEY); + atomProperties.add(GEOMETRY_KEY); + atomProperties.add(MAX_SINGLE_BONDS_KEY); + atomProperties.add(VDW_DI_KEY); + atomProperties.add(VDW_RI_KEY); + atomProperties.add(DEFAULT_TYPE_KEY); + } + + static CCTAtomTypes defValues = new CCTAtomTypes(defaultProperiesFile); + + /* + static { + + try { + type001 = new CCTAtomTypes("H", ChemicalElements.getAtomicNumber("H"), + 1, LINEAR, 1); + + type002 = new CCTAtomTypes("C.4", ChemicalElements.getAtomicNumber("C"), + 4, TETRAHEDRAL, 4); + type003 = new CCTAtomTypes("C.3", ChemicalElements.getAtomicNumber("C"), + 3, TRIGONAL, 2); + type004 = new CCTAtomTypes("C.2", ChemicalElements.getAtomicNumber("C"), + 2, LINEAR, 1); + + type005 = new CCTAtomTypes("N.4", ChemicalElements.getAtomicNumber("N"), + 4, TETRAHEDRAL, 4); + type006 = new CCTAtomTypes("N.3", ChemicalElements.getAtomicNumber("N"), + 3, TETRAHEDRAL, 3); + type007 = new CCTAtomTypes("N.2", ChemicalElements.getAtomicNumber("N"), + 3, TRIGONAL, 2); + + type008 = new CCTAtomTypes("O.4", ChemicalElements.getAtomicNumber("O"), + 2, TETRAHEDRAL, 2); + type009 = new CCTAtomTypes("O.2", ChemicalElements.getAtomicNumber("O"), + 1, LINEAR, 0); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + */ + public CCTAtomTypes() {} + + public CCTAtomTypes(String propertiesName) { + try { + resources = ResourceBundle.getBundle(propertiesName); + } + catch (Exception ex) { + System.err.println(ex.getMessage()); + if (resources == null) { + System.err.println("Resources " + propertiesName + + " are not found"); + return; + } + } + + // --- Read data for each atom type + //H:baseElement=H + //H:coordNumber=1 + //H:geometry=linear + //H:maxH=1 + + CCTAtomTypes newType = null; + String typesStr = ""; + Enumeration en = resources.getKeys(); + while (en.hasMoreElements()) { + String key = en.nextElement(); + + // --- Divide atom type and properties + int index = key.indexOf("*"); + if (index == -1 || (index + 1) >= key.length()) { + System.err.println("Error in atom types file: " + key); + continue; + } + + String atomType = key.substring(0, index); + String propType = key.substring(index + 1); + + /* + logger.info("Size: "+atomProperties.size()); + Iterator iter = atomProperties.iterator(); + boolean valid = false; + while(iter.hasNext()) { + String prop = (String)iter.next(); + if ( prop.equalsIgnoreCase(propType) ) { + valid = true; + break; + } + } + */ + if (!atomProperties.contains(propType.toUpperCase())) { + //if (!valid) { + System.err.println( + "Error in atom types file: no such atom property: " + propType); + continue; + } + + if (allTypes.containsKey(atomType)) { + newType = allTypes.get(atomType); + } + else { + try { + newType = new CCTAtomTypes(atomType, 1); + allTypes.put(atomType, newType); + } + catch (Exception ex) { + System.err.println("CCTAtomTypes: program error: " + + ex.getMessage()); + } + } + + // Getting base element + + if (propType.equalsIgnoreCase(BASE_ELEMENT_KEY)) { + try { + typesStr = resources.getString(key); + int el = ChemicalElements.getAtomicNumber(typesStr); + if (el == 0) { + System.err.println("Warning: suspicious element: " + typesStr + + " for atom type " + atomType); + } + newType.setElement(el); + newType.setCovalentRadius(ChemicalElements.getCovalentRadius(el)); + } + catch (Exception ex) { + System.err.println("Parsing atom type: " + atomType + " : " + + ex.getMessage() + + "\n Setting element to dummy"); + newType.setElement(0); + newType.setCovalentRadius(ChemicalElements.getCovalentRadius(0)); + } + } + + // --- Getting default type + + else if (propType.equalsIgnoreCase(CCTAtomTypes.DEFAULT_TYPE_KEY)) { + try { + typesStr = resources.getString(key); + newType.setDefaultType(Boolean.parseBoolean(typesStr)); + } + catch (Exception ex) { + System.err.println("Parsing atom type: " + atomType + " : " + + ex.getMessage() + + "\n Trying to parse 'default' option (should be 'true' or 'false'). Got: " + + typesStr + "\nSet to 'false'"); + } + } + + // --- Getting coordination number + + else if (propType.equalsIgnoreCase(CCTAtomTypes.COORDINATION_NUMBER_KEY)) { + int coordN = 0; + try { + typesStr = resources.getString(key); + + try { + coordN = Integer.parseInt(typesStr); + } + catch (NumberFormatException ex) { + System.err.println( + "Warning: suspicious coordination number : " + + typesStr + + " for atom type " + atomType + "\nSet to 0"); + coordN = 0; + } + if (coordN < 0) { + System.err.println( + "Warning: suspicious coordination number : " + + coordN + + " for atom type " + atomType + "\nSet to 0"); + } + newType.setCoordinationNumber(coordN); + } + catch (Exception ex) { + System.err.println("Parsing atom type: " + atomType + " : " + + ex.getMessage() + + "\n Setting coordination number to 0"); + newType.setCoordinationNumber(0); + } + } + + // --- Getting geometry + + else if (propType.equalsIgnoreCase(CCTAtomTypes.GEOMETRY_KEY)) { + try { + typesStr = resources.getString(key); + + AtomGeometry geom = AtomGeometry.getAtomGeometry(typesStr); + if (geom == null) { + System.err.println("Unknown geometry: " + typesStr); + } + else { + newType.setAtomGeometry(geom); + } + /* + if (typesStr.equalsIgnoreCase(LINEAR_GEOMETRY)) { + newType.setGeometry(LINEAR); + } + else if (typesStr.equalsIgnoreCase(TETRAHEDRAL_GEOMETRY)) { + newType.setGeometry(TETRAHEDRAL); + } + else if (typesStr.equalsIgnoreCase(TRIGONAL_GEOMETRY)) { + newType.setGeometry(TRIGONAL); + } + else { + int coordN = newType.getCoordinationNumber(); + System.err.println("Warning: wrong geometry : " + typesStr + + " for atom type " + atomType); + if (coordN <= 1) { + System.err.println("Set to " + LINEAR_GEOMETRY); + newType.setGeometry(LINEAR); + } + else if (coordN <= 2) { + System.err.println("Set to " + LINEAR_GEOMETRY); + newType.setGeometry(LINEAR); + } + else if (coordN <= 3) { + System.err.println("Set to " + TRIGONAL_GEOMETRY); + newType.setGeometry(TRIGONAL); + } + else { + System.err.println("Set to " + TETRAHEDRAL_GEOMETRY); + newType.setGeometry(TETRAHEDRAL); + } + } + */ + } + catch (Exception ex) { + System.err.println("Parsing atom type: " + atomType + " : " + + ex.getMessage()); + /* + int coordN = newType.getCoordinationNumber(); + if (coordN <= 1) { + System.err.println("Set to " + LINEAR_GEOMETRY); + newType.setGeometry(LINEAR); + } + else if (coordN <= 2) { + System.err.println("Set to " + LINEAR_GEOMETRY); + newType.setGeometry(LINEAR); + } + else if (coordN <= 3) { + System.err.println("Set to " + TRIGONAL_GEOMETRY); + newType.setGeometry(TRIGONAL); + } + else { + System.err.println("Set to " + TETRAHEDRAL_GEOMETRY); + newType.setGeometry(TETRAHEDRAL); + } + */ + } + } + + // --- Getting max number of Hydrogens + /* + else if (propType.equalsIgnoreCase(this.MAX_SINGLE_BONDS_KEY)) { + int maxH = 0; + try { + typesStr = resources.getString(key); + + try { + maxH = Integer.parseInt(typesStr); + } + catch (NumberFormatException ex) { + System.err.println("Warning: suspicious max H's number : " + + typesStr + + " for atom type " + atomType + + "\nSet to 0"); + maxH = 0; + } + if (maxH < 0) { + System.err.println("Warning: suspicious max H's number : " + + maxH + + " for atom type " + atomType + + "\nSet to 0"); + } + newType.setMaxHNumber(maxH); + } + catch (Exception ex) { + System.err.println("Parsing atom type: " + atomType + " : " + + ex.getMessage() + + "\n Setting max H's number to 0"); + newType.setMaxHNumber(0); + } + } + */ + // --- Getting vdw well depth + + else if (propType.equalsIgnoreCase(CCTAtomTypes.VDW_DI_KEY)) { + float Dij = 0; // = ChemicalElements.getUFFWellDepth(el); + + try { + typesStr = resources.getString(key); + try { + Dij = Float.parseFloat(typesStr); + } + catch (NumberFormatException ex) { + int el = newType.getElement(); + Dij = ChemicalElements.getUFFWellDepth(el); + System.err.println( + "Warning: suspicious van-der-Waals well depth : " + + typesStr + + " for atom type " + atomType + "\nSet to " + Dij + + " for corresponding element"); + } + } + catch (Exception ex) { + + } + + newType.setVDWWellDepth(Dij); + } + + // --- Getting vdw distance + + else if (propType.equalsIgnoreCase(CCTAtomTypes.VDW_RI_KEY)) { + float Dij = 0; // = ChemicalElements.getUFFRadius(el); + + try { + typesStr = resources.getString(key); + + try { + Dij = Float.parseFloat(typesStr); + } + catch (NumberFormatException ex) { + int el = newType.getElement(); + Dij = ChemicalElements.getUFFRadius(el); + System.err.println( + "Warning: suspicious van-der-Waals distance : " + + typesStr + + " for atom type " + atomType + "\nSet to " + Dij + + " for corresponding element"); + } + } + catch (Exception ex) { + + } + + newType.setVDWDIstance(Dij); + } + + else { + System.err.println( + "Program error: should not be here for property: " + propType); + } + + } + + // --- Do element mapping and set default values + + Set set = allTypes.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String Key = me.getKey().toString(); + newType = (CCTAtomTypes) me.getValue(); + + String elem = ChemicalElements.getElementSymbol(newType.getElement()); + + if (newType.getVDWWellDepth() <= unsetDiValue) { + float Dij = ChemicalElements.getUFFWellDepth(newType.getElement()); + newType.setVDWWellDepth(Dij); + } + if (newType.getVDWDIstance() <= unsetDiValue) { + float Dij = ChemicalElements.getUFFRadius(newType.getElement()); + newType.setVDWDIstance(Dij); + } + + if (elementMapping.containsKey(elem)) { + Map map = (Map) elementMapping.get(elem); + map.put(Key, newType); + elementMapping.put(elem, map); + } + else { + Map map = new LinkedHashMap(); + map.put(Key, newType); + elementMapping.put(elem, map); + } + + } + + // ---Stupid thing... Sort atom types... + + set = elementMapping.entrySet(); + iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String Key = me.getKey().toString(); + Map map = (Map) me.getValue(); + Object toSort[] = new Object[map.size()]; + if (debug) { + System.out.print("Element: " + Key + ": atom types:"); + } + Set set2 = map.entrySet(); + Iterator iter2 = set2.iterator(); + int count = 0; + while (iter2.hasNext()) { + Map.Entry me2 = (Map.Entry) iter2.next(); + if (debug) { + System.out.print(" " + me2.getKey().toString()); + } + toSort[count++] = me2.getValue(); + } + if (debug) { + System.out.print("\n"); + } + if (count == 0) { + continue; + } + + Arrays.sort(toSort, this); + Map newMap = new LinkedHashMap(toSort.length); + for (int i = 0; i < toSort.length; i++) { + CCTAtomTypes type = (CCTAtomTypes) toSort[i]; + newMap.put(type.getAtomTypeName(), type); + } + elementMapping.put(Key, newMap); + } + + } + + public boolean isDefaultType() { + return this.defaultType; + } + + public void setDefaultType(boolean enable) { + defaultType = enable; + } + + public static ImageIcon getImageIcon(CCTAtomTypes atomType) { + return atomType.getIcon(); + //return getImageIcon(atomType.getGeometry(), atomType.getMaxSingleBonds()); + } + + /* + public static ImageIcon getImageIcon(int geometry, int maxSingle) { + if (geometry == TETRAHEDRAL && maxSingle == 4) { + return tetrahedral_4_Icon; + } + else if (geometry == TETRAHEDRAL && maxSingle == 3) { + return tetrahedral_3_Icon; + } + else if (geometry == TETRAHEDRAL && maxSingle == 2) { + return tetrahedral_2_Icon; + } + + + else if (geometry == TRIGONAL && maxSingle == 3) { + return trigonal_3_Icon; + } + + else if (geometry == TRIGONAL && maxSingle == 2) { + return trigonal_3_Icon; + } + + return emptyIcon; + } + */ + + public static int getAtomTypesCount() { + return allTypes.size(); + } + + public static boolean isValidCCTType(String type) { + if (allTypes == null) { + return false; + } + return allTypes.containsKey(type); + } + + public static CCTAtomTypes getAtomTypeInfo(String type) { + if (allTypes == null) { + return null; + } + if (allTypes.containsKey(type)) { + CCTAtomTypes info = allTypes.get(type); + return info; + } + return null; + } + + public static CCTAtomTypes[] getAtomTypesForElement(int elem) { + return getAtomTypesForElement(ChemicalElements.getElementSymbol(elem)); + } + + public static CCTAtomTypes[] getAtomTypesForElement(String elem) { + if (!elementMapping.containsKey(elem)) { + return null; + } + Map map = (Map) elementMapping.get(elem); + if (map.size() == 0) { + return null; + } + CCTAtomTypes[] types = new CCTAtomTypes[map.size()]; + Set set = map.entrySet(); + Iterator iter = set.iterator(); + int count = 0; + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + types[count] = (CCTAtomTypes) me.getValue(); + ++count; + } + return types; + } + + public void setElement(int elem) { + chemicalElement = elem; + } + + public int getElement() { + return chemicalElement; + } + + public static Map getElementMapping() { + return elementMapping; + } + + public static Map getAtomTypes() { + return allTypes; + } + + //public int getGeometry() { + // return geometry; + //} + + //public void setGeometry(int n) { + // geometry = n; + //} + + + + public float getCovalentRadius() { + return covalentRadius; + } + + public void setCovalentRadius(float radius) { + covalentRadius = radius; + } + + public void setVDWWellDepth(float d) { + vdwWellDepth = d; + } + + public float getVDWWellDepth() { + return vdwWellDepth; + } + + public void setVDWDIstance(float d) { + vdwDistance = d; + } + + public float getVDWDIstance() { + return vdwDistance; + } + + public String getAtomTypeName() { + return typeName; + } + + private CCTAtomTypes(String name, int element) throws Exception { + if (allTypes.containsKey(name)) { + throw new Exception("Atom type " + name + " is already in the table"); + } + this.typeName = name; + this.chemicalElement = element; + this.weight = ChemicalElements.getAtomicWeight(element); + //allTypes.put(typeName, this); + } + + private CCTAtomTypes(String name, int element, int coordNumber // int geometry, + ) throws Exception { + if (allTypes.containsKey(name)) { + throw new Exception("Atom type " + name + " is already in the table"); + } + //else if (geometry != LINEAR && geometry != TETRAHEDRAL && + // geometry != TRIGONAL) { + // throw new Exception("Atom type: " + name + " : wrong geometry"); + //} + + this.typeName = name; + this.chemicalElement = element; + this.weight = ChemicalElements.getAtomicWeight(element); + //this.coordNumber = coordNumber; + //this.geometry = geometry; + //this.maxHNumber = maxHNumber; + allTypes.put(typeName, this); + } + + public static Map getPictureMapping(int element) { + String currentType = "Atom"; + Map atomTypes = new LinkedHashMap(); + //atomTypes.put(currentType, CCTAtomTypes.getImageIcon(0, 0)); + atomTypes.put(currentType, AtomGeometry.ATOM_ICON); + + Map mapping = getElementMapping(); + Map map = (Map) mapping.get(ChemicalElements.getElementSymbol(element)); + + if (map != null) { + int count = 0; + Set set = map.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String Key = me.getKey().toString(); + CCTAtomTypes Type = (CCTAtomTypes) me.getValue(); + + atomTypes.put(Key, CCTAtomTypes.getImageIcon(Type)); + + ++count; + } + } + return atomTypes; + } + +//public static final CCTParserEnum CCT_TAG = new CCTParserEnum("cct"); + + public static void main(String[] args) { + //CCTAtomTypes cctatomtypes = new CCTAtomTypes(); + logger.info("Number of atom types: " + + CCTAtomTypes.getAtomTypesCount()); + Integer count[] = { + 0, 1}; + logger.info("Class: " + count.getClass().getCanonicalName() + " " + + count.getClass().getSimpleName() + " " + + count.getClass().getInterfaces()); + List a = new ArrayList(); + logger.info("Class: " + a.getClass().getCanonicalName() + " " + + a.getClass().getSimpleName()); + Class in[] = a.getClass().getInterfaces(); + for (int i = 0; i < in.length; i++) { + logger.info("Interface: " + i + " : " + in[i].getCanonicalName()); + } + } + + @Override + public int compare(Object o1, Object o2) throws ClassCastException { + if (o1 instanceof CCTAtomTypes && o2 instanceof CCTAtomTypes) { + CCTAtomTypes a1 = (CCTAtomTypes) o1; + CCTAtomTypes a2 = (CCTAtomTypes) o2; + if (a1.getGeometry() != a2.getGeometry()) { + return a1.getGeometry() - a2.getGeometry(); + } + + if (a1.getCoordinationNumber() != a2.getCoordinationNumber()) { + return a1.getCoordinationNumber() - a2.getCoordinationNumber(); + } + + return a1.getMaxSingleBonds() - a2.getMaxSingleBonds(); + } + throw new ClassCastException("CCTAtomTypes: Class Cast Exception"); + } + + @Override + public boolean equals(Object obj) { + return this == obj; + } +} diff --git a/src/main/java/cct/modelling/CELL_PARAMETER.java b/src/main/java/cct/modelling/CELL_PARAMETER.java new file mode 100644 index 0000000..f6b3b03 --- /dev/null +++ b/src/main/java/cct/modelling/CELL_PARAMETER.java @@ -0,0 +1,17 @@ +package cct.modelling; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public enum CELL_PARAMETER { + A, B, C, ALPHA, BETHA, GAMMA +} diff --git a/src/main/java/cct/modelling/CHEMISTRY_FILE_FORMAT.java b/src/main/java/cct/modelling/CHEMISTRY_FILE_FORMAT.java new file mode 100644 index 0000000..e961cf5 --- /dev/null +++ b/src/main/java/cct/modelling/CHEMISTRY_FILE_FORMAT.java @@ -0,0 +1,21 @@ +package cct.modelling; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ + + +public enum CHEMISTRY_FILE_FORMAT { + ALL_FORMATS, ADF_INPUT, ADF_OUTPUT, G03_GJF, G03_OUTPUT, G03_CUBE, G03_FRAGMENT, G03_TRAJECTORY, G03_FORM_CHECKPOINT, GAMESS_INPUT, GAMESS_OUTPUT, + MOPAC_INPUT, MOPAC_OUTPUT, MOPAC2002_LOG, PDB, MOL2, CCT, XMOL_XYZ, MDL_MOLFILE, GROMACS_GRO, QCHEM_INPUT, QCHEM_OUTPUT, + AMBER_PRMTOP, AMBER_CRD, AMBER_PREP, AMBER_LIB, POVRAY, VASP_POSCAR, VASP_VASPRUN, GULP_INPUT, SIESTA_INPUT, CPMD_OUTPUT, CPMD_TRAJECTORY +} diff --git a/src/main/java/cct/modelling/ChemicalElements.java b/src/main/java/cct/modelling/ChemicalElements.java new file mode 100644 index 0000000..e979cc9 --- /dev/null +++ b/src/main/java/cct/modelling/ChemicalElements.java @@ -0,0 +1,1059 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.modelling; + +import java.util.HashMap; +import java.util.Map; + +/** + * + *

+ * Title: ChemicalElements

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2006

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class ChemicalElements { + + static final int numberOfElements = 110; + static final String elementSymbol[] = new String[numberOfElements]; + static final String elementName[] = new String[numberOfElements]; + static final float covalentRadii[] = new float[numberOfElements]; + static final float atomicWeight[] = new float[numberOfElements]; + static final float vanderwaalsRadii[] = new float[numberOfElements]; + static final float uffVDWRadii[] = new float[numberOfElements]; + static final float uffD[] = new float[numberOfElements]; + static final private Map elementSymbolToAtomicNumber = new HashMap(numberOfElements); + static final private Map elementSymbolToCovalentRadius = new HashMap(numberOfElements); + + protected ChemicalElements() { + + } + + static { + + elementSymbol[0] = "Du"; + elementSymbol[1] = "H"; + elementSymbol[2] = "He"; + elementSymbol[3] = "Li"; + elementSymbol[4] = "Be"; + elementSymbol[5] = "B"; + elementSymbol[6] = "C"; + elementSymbol[7] = "N"; + elementSymbol[8] = "O"; + elementSymbol[9] = "F"; + elementSymbol[10] = "Ne"; + elementSymbol[11] = "Na"; + elementSymbol[12] = "Mg"; + elementSymbol[13] = "Al"; + elementSymbol[14] = "Si"; + elementSymbol[15] = "P"; + elementSymbol[16] = "S"; + elementSymbol[17] = "Cl"; + elementSymbol[18] = "Ar"; + elementSymbol[19] = "K"; + elementSymbol[20] = "Ca"; + elementSymbol[21] = "Sc"; + elementSymbol[22] = "Ti"; + elementSymbol[23] = "V"; + elementSymbol[24] = "Cr"; + elementSymbol[25] = "Mn"; + elementSymbol[26] = "Fe"; + elementSymbol[27] = "Co"; + elementSymbol[28] = "Ni"; + elementSymbol[29] = "Cu"; + elementSymbol[30] = "Zn"; + elementSymbol[31] = "Ga"; + elementSymbol[32] = "Ge"; + elementSymbol[33] = "As"; + elementSymbol[34] = "Se"; + elementSymbol[35] = "Br"; + elementSymbol[36] = "Kr"; + elementSymbol[37] = "Rb"; + elementSymbol[38] = "Sr"; + elementSymbol[39] = "Y"; + elementSymbol[40] = "Zr"; + elementSymbol[41] = "Nb"; + elementSymbol[42] = "Mo"; + elementSymbol[43] = "Tc"; + elementSymbol[44] = "Ru"; + elementSymbol[45] = "Rh"; + elementSymbol[46] = "Pd"; + elementSymbol[47] = "Ag"; + elementSymbol[48] = "Cd"; + elementSymbol[49] = "In"; + elementSymbol[50] = "Sn"; + elementSymbol[51] = "Sb"; + elementSymbol[52] = "Te"; + elementSymbol[53] = "I"; + elementSymbol[54] = "Xe"; + elementSymbol[55] = "Cs"; + elementSymbol[56] = "Ba"; + elementSymbol[57] = "La"; + elementSymbol[58] = "Ce"; + elementSymbol[59] = "Pr"; + elementSymbol[60] = "Nd"; + elementSymbol[61] = "Pm"; + elementSymbol[62] = "Sm"; + elementSymbol[63] = "Eu"; + elementSymbol[64] = "Gd"; + elementSymbol[65] = "Tb"; + elementSymbol[66] = "Dy"; + elementSymbol[67] = "Ho"; + elementSymbol[68] = "Er"; + elementSymbol[69] = "Tm"; + elementSymbol[70] = "Yb"; + elementSymbol[71] = "Lu"; + elementSymbol[72] = "Hf"; + elementSymbol[73] = "Ta"; + elementSymbol[74] = "W"; + elementSymbol[75] = "Re"; + elementSymbol[76] = "Os"; + elementSymbol[77] = "Ir"; + elementSymbol[78] = "Pt"; + elementSymbol[79] = "Au"; + elementSymbol[80] = "Hg"; + elementSymbol[81] = "Tl"; + elementSymbol[82] = "Pb"; + elementSymbol[83] = "Bi"; + elementSymbol[84] = "Po"; + elementSymbol[85] = "At"; + elementSymbol[86] = "Rn"; + elementSymbol[87] = "Fr"; + elementSymbol[88] = "Ra"; + elementSymbol[89] = "Ac"; + elementSymbol[90] = "Th"; + elementSymbol[91] = "Pa"; + elementSymbol[92] = "U"; + elementSymbol[93] = "Np"; + elementSymbol[94] = "Pu"; + elementSymbol[95] = "Am"; + elementSymbol[96] = "Cm"; + elementSymbol[97] = "Bk"; + elementSymbol[98] = "Cf"; + elementSymbol[99] = "Es"; + elementSymbol[100] = "Fm"; + elementSymbol[101] = "Md"; + elementSymbol[102] = "No"; + elementSymbol[103] = "Lr"; + elementSymbol[104] = "Rf"; + elementSymbol[105] = "Db"; + elementSymbol[106] = "Sg"; + elementSymbol[107] = "Bh"; + elementSymbol[108] = "Hn"; + elementSymbol[109] = "Mt"; + + elementName[0] = "Dummy"; + elementName[1] = "Hydrogen"; + elementName[2] = "Helium"; + elementName[3] = "Lithium"; + elementName[4] = "Beryllium"; + elementName[5] = "Boron"; + elementName[6] = "Carbon"; + elementName[7] = "Nitrogen"; + elementName[8] = "Oxygen"; + elementName[9] = "Fluorine"; + elementName[10] = "Neon"; + elementName[11] = "Sodium"; + elementName[12] = "Magnesium"; + elementName[13] = "Aluminum"; + elementName[14] = "Silicon"; + elementName[15] = "Phosphorus"; + elementName[16] = "Sulfur"; + elementName[17] = "Chlorine"; + elementName[18] = "Argon"; + elementName[19] = "Potassium"; + elementName[20] = "Calcium"; + elementName[21] = "Scandium"; + elementName[22] = "Titanium"; + elementName[23] = "Vanadium"; + elementName[24] = "Chromium"; + elementName[25] = "Manganese"; + elementName[26] = "Iron"; + elementName[27] = "Cobalt"; + elementName[28] = "Nickel"; + elementName[29] = "Copper"; + elementName[30] = "Zinc"; + elementName[31] = "Gallium"; + elementName[32] = "Germanium"; + elementName[33] = "Arsenic"; + elementName[34] = "Selenium"; + elementName[35] = "Bromine"; + elementName[36] = "Krypton"; + elementName[37] = "Rubidium"; + elementName[38] = "Strontium"; + elementName[39] = "Yttrium"; + elementName[40] = "Zirconium"; + elementName[41] = "Niobium"; + elementName[42] = "Molybdenum"; + elementName[43] = "Technetium"; + elementName[44] = "Ruthenium"; + elementName[45] = "Rhodium"; + elementName[46] = "Palladium"; + elementName[47] = "Silver"; + elementName[48] = "Cadmium"; + elementName[49] = "Indium"; + elementName[50] = "Tin"; + elementName[51] = "Antimony"; + elementName[52] = "Tellurium"; + elementName[53] = "Iodine"; + elementName[54] = "Xenon"; + elementName[55] = "Cesium"; + elementName[56] = "Barium"; + elementName[57] = "Lanthanum"; + elementName[58] = "Cerium"; + elementName[59] = "Praseodymium"; + elementName[60] = "Neodymium"; + elementName[61] = "Promethium"; + elementName[62] = "Samarium"; + elementName[63] = "Europium"; + elementName[64] = "Gadolinium"; + elementName[65] = "Terbium"; + elementName[66] = "Dysprosium"; + elementName[67] = "Holmium"; + elementName[68] = "Erbium"; + elementName[69] = "Thulium"; + elementName[70] = "Ytterbium"; + elementName[71] = "Lutetium"; + elementName[72] = "Hafnium"; + elementName[73] = "Tantalum"; + elementName[74] = "Tungsten"; + elementName[75] = "Rhenium"; + elementName[76] = "Osmium"; + elementName[77] = "Iridium"; + elementName[78] = "Platinum"; + elementName[79] = "Gold"; + elementName[80] = "Mercury"; + elementName[81] = "Thallium"; + elementName[82] = "Lead"; + elementName[83] = "Bismuth"; + elementName[84] = "Polonium"; + elementName[85] = "Astatine"; + elementName[86] = "Radon"; + elementName[87] = "Francium"; + elementName[88] = "Radium"; + elementName[89] = "Actinium"; + elementName[90] = "Thorium"; + elementName[91] = "Protactinium"; + elementName[92] = "Uranium"; + elementName[93] = "Neptunium"; + elementName[94] = "Plutonium"; + elementName[95] = "Americium"; + elementName[96] = "Curium"; + elementName[97] = "Berkelium"; + elementName[98] = "Californium"; + elementName[99] = "Einsteinium"; + elementName[100] = "Fermium"; + elementName[101] = "Mendelevium"; + elementName[102] = "Nobelium"; + elementName[103] = "Lawrencium"; + elementName[104] = "Rutherfordium"; + elementName[105] = "Dubnium"; + elementName[106] = "Seaborgium"; + elementName[107] = "Bohrium"; + elementName[108] = "Hahnium"; + elementName[109] = "Meitnerium"; + + covalentRadii[0] = 0.0f; + covalentRadii[1] = 0.55f; // H + covalentRadii[2] = 1.00f; // He + covalentRadii[3] = 1.56f; // Li + covalentRadii[4] = 1.13f; // Be + covalentRadii[5] = 0.95f; // B + covalentRadii[6] = 0.86f; // C + covalentRadii[7] = 0.80f; // N + covalentRadii[8] = 0.66f; // O + covalentRadii[9] = 0.64f; // F + covalentRadii[10] = 1.00f; // Ne + covalentRadii[11] = 1.91f; // Na + covalentRadii[12] = 1.60f; // Mg - Original value 1.6 + covalentRadii[13] = 1.43f; // Al + covalentRadii[14] = 1.34f; // Si + covalentRadii[15] = 1.30f; // P + covalentRadii[16] = 1.3f; // S - original: 1.04f + covalentRadii[17] = 1.62f; // Cl + covalentRadii[18] = 1.00f; // Ar + covalentRadii[19] = 1.9f; // K - Original value 2.34 + covalentRadii[20] = 1.97f; // Ca + covalentRadii[21] = 1.64f; // Sc + covalentRadii[22] = 1.45f; // Ti + covalentRadii[23] = 1.35f; // V + covalentRadii[24] = 1.27f; // Cr + covalentRadii[25] = 1.32f; // Mn + covalentRadii[26] = 1.27f; // Fe - original value 1.27f + covalentRadii[27] = 1.26f; // Co + covalentRadii[28] = 1.24f; // Ni + covalentRadii[29] = 1.28f; // Cu + covalentRadii[30] = 1.39f; // Zn + covalentRadii[31] = 1.40f; // Ga + covalentRadii[32] = 1.40f; // Ge + covalentRadii[33] = 1.50f; // As + covalentRadii[34] = 1.60f; // Se + covalentRadii[35] = 1.11f; // Br + covalentRadii[36] = 2.34f; // Kr + covalentRadii[37] = 2.50f; // Rb + covalentRadii[38] = 2.15f; // Sr + covalentRadii[39] = 1.80f; // Y + covalentRadii[40] = 1.60f; // Zr + covalentRadii[41] = 1.48f; // Nb + covalentRadii[42] = 1.40f; // Mo + covalentRadii[43] = 1.35f; // Tc + covalentRadii[44] = 1.32f; // Ru + covalentRadii[45] = 1.34f; // Rh + covalentRadii[46] = 1.37f; // Pd + covalentRadii[47] = 1.44f; // Ag + covalentRadii[48] = 1.57f; // Cd + covalentRadii[49] = 1.66f; // In + covalentRadii[50] = 1.58f; // Sn + covalentRadii[51] = 1.60f; // Sb + covalentRadii[52] = 1.70f; // Te + covalentRadii[53] = 1.95f; // I + covalentRadii[54] = 0.00f; // Xe + covalentRadii[55] = 2.71f; // Cs + covalentRadii[56] = 2.24f; // Ba + covalentRadii[57] = 1.87f; // La + covalentRadii[58] = 1.82f; // Ce + covalentRadii[59] = 1.83f; // Pr + covalentRadii[60] = 1.82f; // Nd + covalentRadii[61] = 0.00f; // Pm + covalentRadii[62] = 1.80f; // Sm + covalentRadii[63] = 2.04f; // Eu + covalentRadii[64] = 1.80f; // Gd + covalentRadii[65] = 1.78f; // Tb + covalentRadii[66] = 1.77f; // Dy + covalentRadii[67] = 1.77f; // Ho + covalentRadii[68] = 1.76f; // Er + covalentRadii[69] = 1.75f; // Tm + covalentRadii[70] = 1.94f; // Yb + covalentRadii[71] = 1.73f; // Lu + covalentRadii[72] = 1.59f; // Hf + covalentRadii[73] = 1.48f; // Ta + covalentRadii[74] = 1.41f; // W + covalentRadii[75] = 1.46f; // Re + covalentRadii[76] = 1.34f; // Os + covalentRadii[77] = 1.36f; // Ir + covalentRadii[78] = 1.39f; // Pt + covalentRadii[79] = 1.44f; // Au + covalentRadii[80] = 1.62f; // Hg + covalentRadii[81] = 1.73f; // Tl + covalentRadii[82] = 1.75f; // Pb + covalentRadii[83] = 1.70f; // Bi + covalentRadii[84] = 1.70f; // Po + covalentRadii[85] = 0.00f; // At + covalentRadii[86] = 0.00f; // Rn + covalentRadii[87] = 0.00f; // Fr + covalentRadii[88] = 0.00f; // Ra + covalentRadii[89] = 1.88f; // Ac + covalentRadii[90] = 1.80f; // Th + covalentRadii[91] = 1.61f; // Pa + covalentRadii[92] = 1.55f; // U + covalentRadii[93] = 1.58f; // Np + covalentRadii[94] = 1.64f; // Pu + covalentRadii[95] = 1.73f; // Am + covalentRadii[96] = 0.00f; // Cm + covalentRadii[97] = 0.00f; // Bk + covalentRadii[98] = 0.00f; // Cf + covalentRadii[99] = 0.00f; // Es + covalentRadii[100] = 0.00f; // Fm + covalentRadii[101] = 0.00f; // Md + covalentRadii[102] = 0.00f; // No + covalentRadii[103] = 0.00f; // Lr + covalentRadii[104] = 0.00f; // Db + covalentRadii[105] = 0.00f; // Jl + covalentRadii[106] = 0.00f; // Rf + covalentRadii[107] = 0.00f; // Bh + covalentRadii[108] = 0.00f; // Hn + covalentRadii[109] = 0.00f; // Mt + + // --- Taken from Bondi, J.Phys.Chem., 68, 441, 1964. Other elements are assigned van der Waals radii of 2.0A. + vanderwaalsRadii[0] = 0.0f; + vanderwaalsRadii[1] = 1.2f; // H + vanderwaalsRadii[2] = 1.4f; // He + vanderwaalsRadii[3] = 1.82f; // Li + vanderwaalsRadii[4] = 2.f; // Be + vanderwaalsRadii[5] = 2.f; // B + vanderwaalsRadii[6] = 1.7f; // C + vanderwaalsRadii[7] = 1.55f; // N + vanderwaalsRadii[8] = 1.52f; // O + vanderwaalsRadii[9] = 1.47f; // F + vanderwaalsRadii[10] = 1.54f; // Ne + vanderwaalsRadii[11] = 2.27f; // Na + vanderwaalsRadii[12] = 1.73f; // Mg + vanderwaalsRadii[13] = 2.f; // Al + vanderwaalsRadii[14] = 2.1f; // Si + vanderwaalsRadii[15] = 1.8f; // P + vanderwaalsRadii[16] = 1.8f; // S + vanderwaalsRadii[17] = 1.75f; // Cl + vanderwaalsRadii[18] = 1.88f; // Ar + vanderwaalsRadii[19] = 2.75f; // K + vanderwaalsRadii[20] = 2.f; // Ca + vanderwaalsRadii[21] = 2.f; // Sc + vanderwaalsRadii[22] = 2.f; // Ti + vanderwaalsRadii[23] = 2.f; // V + vanderwaalsRadii[24] = 2.f; // Cr + vanderwaalsRadii[25] = 2.f; // Mn + vanderwaalsRadii[26] = 2.f; // Fe + vanderwaalsRadii[27] = 2.f; // Co + vanderwaalsRadii[28] = 1.63f; // Ni + vanderwaalsRadii[29] = 1.40f; // Cu + vanderwaalsRadii[30] = 1.49f; // Zn + vanderwaalsRadii[31] = 1.87f; // Ga + vanderwaalsRadii[32] = 2.f; // Ge + vanderwaalsRadii[33] = 1.85f; // As + vanderwaalsRadii[34] = 1.9f; // Se + vanderwaalsRadii[35] = 1.85f; // Br + vanderwaalsRadii[36] = 2.02f; // Kr + vanderwaalsRadii[37] = 2.f; // Rb + vanderwaalsRadii[38] = 2.f; // Sr + vanderwaalsRadii[39] = 2.f; // Y + vanderwaalsRadii[40] = 2.f; // Zr + vanderwaalsRadii[41] = 2.f; // Nb + vanderwaalsRadii[42] = 2.0f; // Mo + vanderwaalsRadii[43] = 2.f; // Tc + vanderwaalsRadii[44] = 2.f; // Ru + vanderwaalsRadii[45] = 2.f; // Rh + vanderwaalsRadii[46] = 1.63f; // Pd + vanderwaalsRadii[47] = 1.72f; // Ag + vanderwaalsRadii[48] = 1.58f; // Cd + vanderwaalsRadii[49] = 1.93f; // In + vanderwaalsRadii[50] = 2.17f; // Sn + vanderwaalsRadii[51] = 2.f; // Sb + vanderwaalsRadii[52] = 2.06f; // Te + vanderwaalsRadii[53] = 1.98f; // I + vanderwaalsRadii[54] = 2.16f; // Xe + vanderwaalsRadii[55] = 2.f; // Cs + vanderwaalsRadii[56] = 2.f; // Ba + vanderwaalsRadii[57] = 2.f; // La + vanderwaalsRadii[58] = 2.f; // Ce + vanderwaalsRadii[59] = 2.f; // Pr + vanderwaalsRadii[60] = 2.f; // Nd + vanderwaalsRadii[61] = 2.00f; // Pm + vanderwaalsRadii[62] = 2.0f; // Sm + vanderwaalsRadii[63] = 2.f; // Eu + vanderwaalsRadii[64] = 2.0f; // Gd + vanderwaalsRadii[65] = 2.f; // Tb + vanderwaalsRadii[66] = 2.f; // Dy + vanderwaalsRadii[67] = 2.f; // Ho + vanderwaalsRadii[68] = 2.f; // Er + vanderwaalsRadii[69] = 2.f; // Tm + vanderwaalsRadii[70] = 2.f; // Yb + vanderwaalsRadii[71] = 2.f; // Lu + vanderwaalsRadii[72] = 2.f; // Hf + vanderwaalsRadii[73] = 2.f; // Ta + vanderwaalsRadii[74] = 2.f; // W + vanderwaalsRadii[75] = 2.f; // Re + vanderwaalsRadii[76] = 2.f; // Os + vanderwaalsRadii[77] = 2.f; // Ir + vanderwaalsRadii[78] = 1.72f; // Pt + vanderwaalsRadii[79] = 1.66f; // Au + vanderwaalsRadii[80] = 1.55f; // Hg + vanderwaalsRadii[81] = 1.96f; // Tl + vanderwaalsRadii[82] = 2.02f; // Pb + vanderwaalsRadii[83] = 2.0f; // Bi + vanderwaalsRadii[84] = 2.0f; // Po + vanderwaalsRadii[85] = 2.00f; // At + vanderwaalsRadii[86] = 2.00f; // Rn + vanderwaalsRadii[87] = 2.00f; // Fr + vanderwaalsRadii[88] = 2.00f; // Ra + vanderwaalsRadii[89] = 2.f; // Ac + vanderwaalsRadii[90] = 2.0f; // Th + vanderwaalsRadii[91] = 2.f; // Pa + vanderwaalsRadii[92] = 1.86f; // U + vanderwaalsRadii[93] = 2.f; // Np + vanderwaalsRadii[94] = 2.f; // Pu + vanderwaalsRadii[95] = 2.f; // Am + vanderwaalsRadii[96] = 2.00f; // Cm + vanderwaalsRadii[97] = 2.00f; // Bk + vanderwaalsRadii[98] = 2.00f; // Cf + vanderwaalsRadii[99] = 2.00f; // Es + vanderwaalsRadii[100] = 2.00f; // Fm + vanderwaalsRadii[101] = 2.00f; // Md + vanderwaalsRadii[102] = 2.00f; // No + vanderwaalsRadii[103] = 2.00f; // Lr + vanderwaalsRadii[104] = 2.00f; // Db + vanderwaalsRadii[105] = 2.00f; // Jl + vanderwaalsRadii[106] = 2.00f; // Rf + vanderwaalsRadii[107] = 2.00f; // Bh + vanderwaalsRadii[108] = 2.00f; // Hn + vanderwaalsRadii[109] = 2.00f; // Mt + + atomicWeight[0] = 0.0f; + atomicWeight[1] = 1.00079f; // H + atomicWeight[2] = 4.00260f; // He + atomicWeight[3] = 6.94f; // Li + atomicWeight[4] = 9.01218f; // Be + atomicWeight[5] = 10.81f; // B + atomicWeight[6] = 12.011f; // C + atomicWeight[7] = 14.0067f; // N + atomicWeight[8] = 15.9994f; // O + atomicWeight[9] = 18.998403f; // F + atomicWeight[10] = 20.179f; // Ne + atomicWeight[11] = 22.98977f; // Na + atomicWeight[12] = 24.305f; // Mg + atomicWeight[13] = 26.98154f; // Al + atomicWeight[14] = 28.0855f; // Si + atomicWeight[15] = 30.97376f; // P + atomicWeight[16] = 32.06f; // S + atomicWeight[17] = 35.453f; // Cl + atomicWeight[18] = 39.948f; // Ar + atomicWeight[19] = 39.0983f; // K + atomicWeight[20] = 40.08f; // Ca + atomicWeight[21] = 44.9559f; // Sc + atomicWeight[22] = 47.90f; // Ti + atomicWeight[23] = 50.9415f; // V + atomicWeight[24] = 51.996f; // Cr + atomicWeight[25] = 54.9380f; // Mn + atomicWeight[26] = 55.847f; // Fe + atomicWeight[27] = 58.9332f; // Co + atomicWeight[28] = 58.71f; // Ni + atomicWeight[29] = 63.546f; // Cu + atomicWeight[30] = 65.38f; // Zn + atomicWeight[31] = 65.735f; // Ga + atomicWeight[32] = 72.59f; // Ge + atomicWeight[33] = 74.9216f; // As + atomicWeight[34] = 78.96f; // Se + atomicWeight[35] = 79.904f; // Br + atomicWeight[36] = 83.80f; // Kr + atomicWeight[37] = 85.467f; // Rb + atomicWeight[38] = 87.62f; // Sr + atomicWeight[39] = 88.9059f; // Y + atomicWeight[40] = 91.22f; // Zr + atomicWeight[41] = 92.9064f; // Nb + atomicWeight[42] = 95.94f; // Mo + atomicWeight[43] = 98.9062f; // Tc + atomicWeight[44] = 101.07f; // Ru + atomicWeight[45] = 102.9055f; // Rh + atomicWeight[46] = 106.4f; // Pd + atomicWeight[47] = 107.868f; // Ag + atomicWeight[48] = 112.41f; // Cd + atomicWeight[49] = 114.82f; // In + atomicWeight[50] = 118.69f; // Sn + atomicWeight[51] = 121.75f; // Sb + atomicWeight[52] = 127.60f; // Te + atomicWeight[53] = 126.9045f; // I + atomicWeight[54] = 131.30f; // Xe + atomicWeight[55] = 132.9054f; // Cs + atomicWeight[56] = 137.33f; // Ba + atomicWeight[57] = 138.9055f; // La + atomicWeight[58] = 140.12f; // Ce + atomicWeight[59] = 140.9077f; // Pr + atomicWeight[60] = 144.24f; // Nd + atomicWeight[61] = 145.00f; // Pm + atomicWeight[62] = 150.4f; // Sm + atomicWeight[63] = 151.96f; // Eu + atomicWeight[64] = 157.25f; // Gd + atomicWeight[65] = 158.9254f; // Tb + atomicWeight[66] = 162.50f; // Dy + atomicWeight[67] = 164.9304f; // Ho + atomicWeight[68] = 167.26f; // Er + atomicWeight[69] = 168.9342f; // Tm + atomicWeight[70] = 173.04f; // Yb + atomicWeight[71] = 174.967f; // Lu + atomicWeight[72] = 178.49f; // Hf + atomicWeight[73] = 180.9479f; // Ta + atomicWeight[74] = 183.85f; // W + atomicWeight[75] = 186.207f; // Re + atomicWeight[76] = 190.2f; // Os + atomicWeight[77] = 192.22f; // Ir + atomicWeight[78] = 195.09f; // Pt + atomicWeight[79] = 196.9665f; // Au + atomicWeight[80] = 200.59f; // Hg + atomicWeight[81] = 204.37f; // Tl + atomicWeight[82] = 207.2f; // Pb + atomicWeight[83] = 208.9804f; // Bi + atomicWeight[84] = 209.0f; // Po + atomicWeight[85] = 210.0f; // At + atomicWeight[86] = 222.0f; // Rn + atomicWeight[87] = 223.0f; // Fr + atomicWeight[88] = 226.0254f; // Ra + atomicWeight[89] = 227.0f; // Ac + atomicWeight[90] = 232.0381f; // Th + atomicWeight[91] = 231.0359f; // Pa + atomicWeight[92] = 238.029f; // U + atomicWeight[93] = 237.0482f; // Np + atomicWeight[94] = 244.0f; // Pu + atomicWeight[95] = 243.0f; // Am + atomicWeight[96] = 247.0f; // Cm + atomicWeight[97] = 247.0f; // Bk + atomicWeight[98] = 251.0f; // Cf + atomicWeight[99] = 254.0f; // Es + atomicWeight[100] = 257.0f; // Fm + atomicWeight[101] = 258.0f; // Md + atomicWeight[102] = 259.0f; // No + atomicWeight[103] = 260.0f; // Lr + atomicWeight[104] = 260.0f; // Db + atomicWeight[105] = 260.0f; // Jl + atomicWeight[106] = 266f; // Rf + atomicWeight[107] = 261f; // Bh + atomicWeight[108] = 264f; // Hn + atomicWeight[109] = 266f; // Mt + + // --- Taken from JACS, 114(1992), 10026 + uffVDWRadii[0] = 0.0f; + uffVDWRadii[1] = 2.886f; // H + uffVDWRadii[2] = 2.362f; // He + uffVDWRadii[3] = 2.454f; // Li + uffVDWRadii[4] = 2.745f; // Be + uffVDWRadii[5] = 4.083f; // B + uffVDWRadii[6] = 3.851f; // C + uffVDWRadii[7] = 3.66f; // N + uffVDWRadii[8] = 3.5f; // O + uffVDWRadii[9] = 3.364f; // F + uffVDWRadii[10] = 3.243f; // Ne + uffVDWRadii[11] = 2.983f; // Na + uffVDWRadii[12] = 3.021f; // Mg + uffVDWRadii[13] = 4.499f; // Al + uffVDWRadii[14] = 4.295f; // Si + uffVDWRadii[15] = 4.147f; // P + uffVDWRadii[16] = 4.035f; // S + uffVDWRadii[17] = 3.947f; // Cl + uffVDWRadii[18] = 3.868f; // Ar + uffVDWRadii[19] = 3.812f; // K + uffVDWRadii[20] = 3.399f; // Ca + uffVDWRadii[21] = 3.295f; // Sc + uffVDWRadii[22] = 3.175f; // Ti + uffVDWRadii[23] = 3.144f; // V + uffVDWRadii[24] = 3.023f; // Cr + uffVDWRadii[25] = 2.961f; // Mn + uffVDWRadii[26] = 2.912f; // Fe + uffVDWRadii[27] = 2.872f; // Co + uffVDWRadii[28] = 2.834f; // Ni + uffVDWRadii[29] = 3.495f; // Cu + uffVDWRadii[30] = 2.763f; // Zn + uffVDWRadii[31] = 4.383f; // Ga + uffVDWRadii[32] = 4.280f; // Ge + uffVDWRadii[33] = 4.230f; // As + uffVDWRadii[34] = 4.205f; // Se + uffVDWRadii[35] = 4.189f; // Br + uffVDWRadii[36] = 4.141f; // Kr + uffVDWRadii[37] = 4.114f; // Rb + uffVDWRadii[38] = 3.641f; // Sr + uffVDWRadii[39] = 3.345f; // Y + uffVDWRadii[40] = 3.124f; // Zr + uffVDWRadii[41] = 3.165f; // Nb + uffVDWRadii[42] = 3.052f; // Mo + uffVDWRadii[43] = 2.998f; // Tc + uffVDWRadii[44] = 2.963f; // Ru + uffVDWRadii[45] = 2.929f; // Rh + uffVDWRadii[46] = 2.899f; // Pd + uffVDWRadii[47] = 3.148f; // Ag + uffVDWRadii[48] = 2.848f; // Cd + uffVDWRadii[49] = 4.463f; // In + uffVDWRadii[50] = 4.392f; // Sn + uffVDWRadii[51] = 4.420f; // Sb + uffVDWRadii[52] = 4.470f; // Te + uffVDWRadii[53] = 4.500f; // I + uffVDWRadii[54] = 4.404f; // Xe + uffVDWRadii[55] = 4.517f; // Cs + uffVDWRadii[56] = 3.703f; // Ba + uffVDWRadii[57] = 3.522f; // La + uffVDWRadii[58] = 3.556f; // Ce + uffVDWRadii[59] = 3.606f; // Pr + uffVDWRadii[60] = 3.575f; // Nd + uffVDWRadii[61] = 3.547f; // Pm + uffVDWRadii[62] = 3.520f; // Sm + uffVDWRadii[63] = 3.493f; // Eu + uffVDWRadii[64] = 3.368f; // Gd + uffVDWRadii[65] = 3.451f; // Tb + uffVDWRadii[66] = 3.428f; // Dy + uffVDWRadii[67] = 3.409f; // Ho + uffVDWRadii[68] = 3.391f; // Er + uffVDWRadii[69] = 3.374f; // Tm + uffVDWRadii[70] = 3.355f; // Yb + uffVDWRadii[71] = 3.640f; // Lu + uffVDWRadii[72] = 3.141f; // Hf + uffVDWRadii[73] = 3.170f; // Ta + uffVDWRadii[74] = 3.069f; // W + uffVDWRadii[75] = 2.954f; // Re + uffVDWRadii[76] = 3.120f; // Os + uffVDWRadii[77] = 2.840f; // Ir + uffVDWRadii[78] = 2.754f; // Pt + uffVDWRadii[79] = 3.293f; // Au + uffVDWRadii[80] = 2.705f; // Hg + uffVDWRadii[81] = 4.347f; // Tl + uffVDWRadii[82] = 4.297f; // Pb + uffVDWRadii[83] = 4.370f; // Bi + uffVDWRadii[84] = 4.709f; // Po + uffVDWRadii[85] = 4.750f; // At + uffVDWRadii[86] = 4.765f; // Rn + uffVDWRadii[87] = 4.900f; // Fr + uffVDWRadii[88] = 3.677f; // Ra + uffVDWRadii[89] = 3.478f; // Ac + uffVDWRadii[90] = 3.396f; // Th + uffVDWRadii[91] = 3.424f; // Pa + uffVDWRadii[92] = 3.395f; // U + uffVDWRadii[93] = 3.424f; // Np + uffVDWRadii[94] = 3.424f; // Pu + uffVDWRadii[95] = 3.381f; // Am + uffVDWRadii[96] = 3.326f; // Cm + uffVDWRadii[97] = 3.339f; // Bk + uffVDWRadii[98] = 3.313f; // Cf + uffVDWRadii[99] = 3.299f; // Es + uffVDWRadii[100] = 3.286f; // Fm + uffVDWRadii[101] = 3.274f; // Md + uffVDWRadii[102] = 3.248f; // No + uffVDWRadii[103] = 3.236f; // Lr --- Original table is up to here... + uffVDWRadii[104] = 2.00f; // Db + uffVDWRadii[105] = 2.00f; // Jl + uffVDWRadii[106] = 2.00f; // Rf + uffVDWRadii[107] = 2.00f; // Bh + uffVDWRadii[108] = 2.00f; // Hn + uffVDWRadii[109] = 2.00f; // Mt + + // --- Taken from JACS, 114(1992), 10026. In the case of several values the first was taken + uffD[0] = 0.0f; + uffD[1] = 0.044f; // H + uffD[2] = 0.056f; // He + uffD[3] = 0.025f; // Li + uffD[4] = 0.085f; // Be + uffD[5] = 0.180f; // B + uffD[6] = 0.105f; // C + uffD[7] = 0.069f; // N + uffD[8] = 0.060f; // O + uffD[9] = 0.050f; // F + uffD[10] = 0.042f; // Ne + uffD[11] = 0.030f; // Na + uffD[12] = 0.111f; // Mg + uffD[13] = 0.505f; // Al + uffD[14] = 0.402f; // Si + uffD[15] = 0.305f; // P + uffD[16] = 0.274f; // S + uffD[17] = 0.227f; // Cl + uffD[18] = 0.185f; // Ar + uffD[19] = 0.035f; // K + uffD[20] = 0.238f; // Ca + uffD[21] = 0.019f; // Sc + uffD[22] = 0.017f; // Ti + uffD[23] = 0.016f; // V + uffD[24] = 0.015f; // Cr + uffD[25] = 0.013f; // Mn + uffD[26] = 0.013f; // Fe + uffD[27] = 0.014f; // Co + uffD[28] = 0.015f; // Ni + uffD[29] = 0.005f; // Cu + uffD[30] = 0.124f; // Zn + uffD[31] = 0.405f; // Ga + uffD[32] = 0.379f; // Ge + uffD[33] = 0.309f; // As + uffD[34] = 0.291f; // Se + uffD[35] = 0.251f; // Br + uffD[36] = 0.220f; // Kr + uffD[37] = 0.040f; // Rb + uffD[38] = 0.235f; // Sr + uffD[39] = 0.072f; // Y + uffD[40] = 0.069f; // Zr + uffD[41] = 0.059f; // Nb + uffD[42] = 0.056f; // Mo + uffD[43] = 0.048f; // Tc + uffD[44] = 0.056f; // Ru + uffD[45] = 0.053f; // Rh + uffD[46] = 0.048f; // Pd + uffD[47] = 0.036f; // Ag + uffD[48] = 0.228f; // Cd + uffD[49] = 0.599f; // In + uffD[50] = 0.567f; // Sn + uffD[51] = 0.449f; // Sb + uffD[52] = 0.398f; // Te + uffD[53] = 0.339f; // I + uffD[54] = 0.332f; // Xe + uffD[55] = 0.045f; // Cs + uffD[56] = 0.364f; // Ba + uffD[57] = 0.017f; // La + uffD[58] = 0.013f; // Ce + uffD[59] = 0.010f; // Pr + uffD[60] = 0.010f; // Nd + uffD[61] = 0.009f; // Pm + uffD[62] = 0.008f; // Sm + uffD[63] = 0.008f; // Eu + uffD[64] = 0.009f; // Gd + uffD[65] = 0.007f; // Tb + uffD[66] = 0.007f; // Dy + uffD[67] = 0.007f; // Ho + uffD[68] = 0.007f; // Er + uffD[69] = 0.006f; // Tm + uffD[70] = 0.228f; // Yb + uffD[71] = 0.041f; // Lu + uffD[72] = 0.072f; // Hf + uffD[73] = 0.081f; // Ta + uffD[74] = 0.067f; // W + uffD[75] = 0.066f; // Re + uffD[76] = 0.037f; // Os + uffD[77] = 0.073f; // Ir + uffD[78] = 0.080f; // Pt + uffD[79] = 0.039f; // Au + uffD[80] = 0.385f; // Hg + uffD[81] = 0.680f; // Tl + uffD[82] = 0.663f; // Pb + uffD[83] = 0.518f; // Bi + uffD[84] = 0.325f; // Po + uffD[85] = 0.284f; // At + uffD[86] = 0.248f; // Rn + uffD[87] = 0.050f; // Fr + uffD[88] = 0.404f; // Ra + uffD[89] = 0.033f; // Ac + uffD[90] = 0.026f; // Th + uffD[91] = 0.022f; // Pa + uffD[92] = 0.022f; // U + uffD[93] = 0.019f; // Np + uffD[94] = 0.016f; // Pu + uffD[95] = 0.014f; // Am + uffD[96] = 0.013f; // Cm + uffD[97] = 0.013f; // Bk + uffD[98] = 0.013f; // Cf + uffD[99] = 0.012f; // Es + uffD[100] = 0.012f; // Fm + uffD[101] = 0.011f; // Md + uffD[102] = 0.011f; // No + uffD[103] = 0.011f; // Lr --- Original table is up to here... + uffD[104] = 0.011f; // Db + uffD[105] = 0.011f; // Jl + uffD[106] = 0.011f; // Rf + uffD[107] = 0.011f; // Bh + uffD[108] = 0.011f; // Hn + uffD[109] = 0.011f; // Mt + + for (int i = 0; i < numberOfElements; i++) { + elementSymbolToAtomicNumber.put(elementSymbol[i].toUpperCase(), i); + elementSymbolToCovalentRadius.put(elementSymbol[i].toUpperCase(), covalentRadii[i]); + } + } + + // Methods + public static int getAtomicNumber(String elem) { + if (elem.length() == 0) { + return 0; + } + Integer atn = elementSymbolToAtomicNumber.get(elem.toUpperCase()); + if (atn == null) { + return 0; + } + return atn; + //for (int i = 1; i < elementSymbol.length; i++) { /// !!! To do more elegant + // if (elem.compareToIgnoreCase(elementSymbol[i]) == 0) { + // return i; + // } + //} + //return 0; + } + + public static int checkAtomicSymbol(String elem) throws IllegalArgumentException { + if (elem.length() == 0) { + throw new IllegalArgumentException("checkAtomicSymbol: atom symbol is empty"); + } + Integer anumber = elementSymbolToAtomicNumber.get(elem.toUpperCase()); + if (anumber == null) { + throw new IllegalArgumentException("Unknown atom symbol: " + elem); + } + return anumber; + //for (int i = 1; i < elementSymbol.length; i++) { + // if (elem.compareToIgnoreCase(elementSymbol[i]) == 0) { + // return i; + // } + //} + //throw new IllegalArgumentException("Unknown atom symbol: " + elem); + } + + /** + * + * @param elem String + * @return float + */ + public static float getAtomicWeight(String elem) { + if (elem.length() == 0) { + return 0; + } + Integer anumber = elementSymbolToAtomicNumber.get(elem.toUpperCase()); + if (anumber == null) { + return 0.0f; + } + //for (int i = 1; i < elementSymbol.length; i++) { /// !!! To do more elegant + // if (elem.compareToIgnoreCase(elementSymbol[i]) == 0) { + // return atomicWeight[i]; + // } + //} + return atomicWeight[anumber]; + } + + /** + * + * @param element int + * @return float + */ + public static float getAtomicWeight(int element) { + if (element < 1 || element >= elementSymbol.length) { + return 0; + } else { + return atomicWeight[element]; + } + } + + public static String getElementSymbol(int element) { + if (element < 1 || element >= elementSymbol.length) { + return elementSymbol[0]; + } else { + return elementSymbol[element]; + } + } + + public static String getElementName(int element) { + if (element < 1 || element >= elementName.length) { + return elementName[0]; + } else { + return elementName[element]; + } + } + + public static float getCovalentRadius(int elem) { + if (elem < 0 || elem > covalentRadii.length - 1) { + return 0.0f; + } + return covalentRadii[elem]; + } + + /** + * Returns van-der-Waals radius of element (from Bondi, J.Phys.Chem., 68, 441, 1964) + * + * @param elem int + * @return float + */ + public static float getVanDerWaalsRadius(int elem) { + if (elem < 0 || elem > vanderwaalsRadii.length - 1) { + return 0.0f; + } + return vanderwaalsRadii[elem]; + } + + public static float getCovalentRadius(String elem) { + if (elem.length() == 0) { + return 0.0f; + } + elem = elem.toUpperCase(); + Float radius = elementSymbolToCovalentRadius.get(elem); + if (radius == null) { + return 0.0f; + } + //for (int i = 1; i < elementSymbol.length; i++) { /// !!! To do more elegant + // if (elem.compareToIgnoreCase(elementSymbol[i]) == 0) { + // return covalentRadii[i]; + // } + //} + return radius; + } + + /** + * Returns van-der-Waals radius of element (from Bondi, J.Phys.Chem., 68, 441, 1964) + * + * @param elem String + * @return float + */ + public static float getVanDerWaalsRadius(String elem) { + if (elem.length() == 0) { + return 0.0f; + } + Integer anumber = elementSymbolToAtomicNumber.get(elem.toUpperCase()); + if (anumber == null) { + return 0.0f; + } + //for (int i = 1; i < elementSymbol.length; i++) { /// !!! To do more elegant + // if (elem.compareToIgnoreCase(elementSymbol[i]) == 0) { + // return vanderwaalsRadii[i]; + // } + //} + return vanderwaalsRadii[anumber]; + } + + public static float getVDWWellDepth(String elem) { + if (elem.length() == 0) { + return 0.0f; + } + Integer anumber = elementSymbolToAtomicNumber.get(elem.toUpperCase()); + if (anumber == null) { + return 0.0f; + } + //for (int i = 1; i < elementSymbol.length; i++) { /// !!! To do more elegant + // if (elem.compareToIgnoreCase(elementSymbol[i]) == 0) { + // return uffD[i]; + // } + //} + return uffD[anumber]; + } + + public static float getUFFWellDepth(int elem) { + if (elem < 0 || elem > uffD.length - 1) { + return 0.0f; + } + return uffD[elem]; + } + + public static float getUFFRadius(int elem) { + if (elem < 0 || elem > uffVDWRadii.length - 1) { + return 0.0f; + } + return uffVDWRadii[elem]; + } + + public static String[] getAllElements() { + return elementSymbol; + } + + public static int getNumberOfElements() { + return numberOfElements; + } + + public static float guessCovalentBondLength(int elem1, int elem2) { + if (elem1 < 1 || elem2 < 1) { + return 0; + } + return (float) Math.sqrt(getCovalentRadius(elem1) * getCovalentRadius(elem2)); + } + + public static void main(String args[]) { + for (int i = 0; i < elementSymbol.length; i++) { + System.out.println("('" + elementName[i] + "','" + elementSymbol[i] + "'," + (i) + "," + atomicWeight[i] + "),"); + } + + } +} diff --git a/src/main/java/cct/modelling/CoordBuilder.java b/src/main/java/cct/modelling/CoordBuilder.java new file mode 100644 index 0000000..309edb3 --- /dev/null +++ b/src/main/java/cct/modelling/CoordBuilder.java @@ -0,0 +1,23 @@ +package cct.modelling; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class CoordBuilder { + String name, description; + Object builder; + public CoordBuilder(String name, String description, Object builder) { + this.name = name; + this.description = description; + this.builder = builder; + } +} diff --git a/src/main/java/cct/modelling/CoordParser.java b/src/main/java/cct/modelling/CoordParser.java new file mode 100644 index 0000000..b61d4f3 --- /dev/null +++ b/src/main/java/cct/modelling/CoordParser.java @@ -0,0 +1,23 @@ +package cct.modelling; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class CoordParser { + String name, description; + Object parser; + public CoordParser(String name, String description, Object parser) { + this.name = name; + this.description = description; + this.parser = parser; + } +} diff --git a/src/main/java/cct/modelling/DataParserInterface.java b/src/main/java/cct/modelling/DataParserInterface.java new file mode 100644 index 0000000..6168152 --- /dev/null +++ b/src/main/java/cct/modelling/DataParserInterface.java @@ -0,0 +1,20 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.modelling; + +import java.io.Reader; + +/** + * + * @author vvv900 + */ +public interface DataParserInterface { + + void parseData(Reader in) throws Exception; + + void parseData(String filename) throws Exception; + + void parseDataAsString(String data) throws Exception; +} diff --git a/src/main/java/cct/modelling/FFMolecule.java b/src/main/java/cct/modelling/FFMolecule.java new file mode 100644 index 0000000..d484a0f --- /dev/null +++ b/src/main/java/cct/modelling/FFMolecule.java @@ -0,0 +1,621 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.modelling; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; +import cct.interfaces.ForceFieldInterface; +import cct.interfaces.MoleculeInterface; +import cct.sff.BondParam; +import cct.sff.SimpleForceField; +import cct.vecmath.Point3f; +import java.io.StringWriter; +import java.util.Map; +import java.util.logging.Level; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class FFMolecule { + + static final Logger logger = Logger.getLogger(FFMolecule.class.getCanonicalName()); + static public final int HARMONIC_BOND_TERM = 0; + static public float defaultFk = 300.0f; + protected MoleculeInterface Molecule = null; + // --- Internal energy related variables + protected Object BondStretchInteractions[] = null; + protected Object AngleBendInteractions[] = null; + protected boolean Calculate_1_4 = true; + protected ForceFieldInterface forceField; + List Torsions = null; + List torsionInteractions = null; + List oneFourInteractions = null; + List nonbodedPairs = null; + List surfaces = null; + Nonbonded15Table nonbondedTable = null; + float SCNB = 1, SCEE = 1; + + private FFMolecule() { + } + + public FFMolecule(MoleculeInterface molec) { + Molecule = molec; + } + + public void applyForceField(ForceFieldInterface ff) { + forceField = ff; + SCNB = 1.0f / ff.get14NBScale(); + SCEE = 1.0f / ff.get14ElsScale(); + } + + public boolean isCalculate14() { + return Calculate_1_4; + } + + public List get14Interactions() { + return oneFourInteractions; + } + + public List getTorsionInteractions() { + return torsionInteractions; + } + + public List getNonbondInteractions() { + return nonbodedPairs; + } + + public Object[] getBondStretchInteractions() { + return BondStretchInteractions; + } + + public Object[] getAngleBendInteractions() { + return AngleBendInteractions; + } + + public MoleculeInterface getMolecule() { + return Molecule; + } + + public void formFFParameters() throws Exception { + long start = 0; + double secs; + + // --- Form Bond stretch parameters + try { + int n = 0; + n = formBondStretchInteractions(HARMONIC_BOND_TERM, MolecularEnergy.SFF_PARAMETERS); + } catch (Exception ex) { + throw ex; + } + + // --- Form angle bend parameters + + start = System.currentTimeMillis(); + AngleBendsArray angles = findDynamicAngles(Molecule); + secs = (System.currentTimeMillis() - start) / 1000.0; + logger.info("Number of angle bend interactions: " + angles.getSize() + " Elapsed time: " + + String.format("%10.4f secs", secs)); + start = System.currentTimeMillis(); + formAngleBendInteractions(MolecularEnergy.SFF_PARAMETERS, angles); + secs = (System.currentTimeMillis() - start) / 1000.0; + logger.info(" Elapsed time for forming angle bend parameters: " + String.format("%10.4f secs", secs)); + + // --- Form regular torsions + + start = System.currentTimeMillis(); + Torsions = findDynamicTorsions(Molecule); + secs = (System.currentTimeMillis() - start) / 1000.0; + logger.info("Number of torsions: " + Torsions.size() + " Elapsed time: " + + String.format("%10.4f secs", secs)); + + if (logger.isLoggable(Level.INFO)) { + StringWriter sr = new StringWriter(); + for (int i = 0; i < Torsions.size(); i++) { + Torsion torsion = (Torsion) Torsions.get(i); + sr.write(String.format("%3d - %3d - %3d - %3d\n", torsion.ijkl[0], torsion.ijkl[1], torsion.ijkl[2], torsion.ijkl[3])); + } + logger.info(sr.toString()); + sr = null; + } + + start = System.currentTimeMillis(); + torsionInteractions = formTorsionInteractions(MolecularEnergy.SFF_PARAMETERS, Torsions); + secs = (System.currentTimeMillis() - start) / 1000.0; + logger.info(" Elapsed time for assigning torsion parameters: " + String.format("%10.4f secs", secs)); + + // --- Form 1-4 pairs... + + if (Calculate_1_4) { + start = System.currentTimeMillis(); + oneFourInteractions = find14Interactions(Molecule, Torsions); + secs = (System.currentTimeMillis() - start) / 1000.0; + logger.info("Number of 1-4 interactions: " + oneFourInteractions.size() + " Elapsed time: " + + String.format("%10.4f secs", secs)); + start = System.currentTimeMillis(); + setupNonbondedInteractions(MolecularEnergy.SFF_PARAMETERS, oneFourInteractions); + secs = (System.currentTimeMillis() - start) / 1000.0; + logger.info(" Elapsed time for assigning 1-4 NB parameters: " + String.format("%10.4f secs", secs)); + } + + // --- Form 1>4 interactions + + start = System.currentTimeMillis(); + nonbondedTable = new Nonbonded15Table(Molecule.getNumberOfAtoms()); + + BondStretchPairs bondPairs = (BondStretchPairs) BondStretchInteractions[1]; + List bsp = bondPairs.getBondStretchPairs(); + for (int i = 0; i < bsp.size(); i++) { + HarmonicBondStretch hbs = (HarmonicBondStretch) bsp.get(i); + nonbondedTable.set15(hbs.i, hbs.j, false); + } + + for (int i = 0; i < angles.getSize(); i++) { + AngleBend ab = angles.getAngleBend(i); + nonbondedTable.set15(ab.getI(), ab.getK(), false); + } + + if (Calculate_1_4) { + for (int i = 0; i < oneFourInteractions.size(); i++) { + NonbondedPair nb = (NonbondedPair) oneFourInteractions.get(i); + nonbondedTable.set15(nb.ij[0], nb.ij[1], false); + } + } + + nonbodedPairs = findNonbondedPairs(Molecule, nonbondedTable); + secs = (System.currentTimeMillis() - start) / 1000.0; + logger.info("Number of nonbonded interactions: " + nonbodedPairs.size() + " Elapsed time: " + + String.format("%10.4f secs", secs)); + start = System.currentTimeMillis(); + setupNonbondedInteractions(MolecularEnergy.SFF_PARAMETERS, nonbodedPairs); + secs = (System.currentTimeMillis() - start) / 1000.0; + logger.info(" Elapsed time for assigning 1>4 NB parameters: " + String.format("%10.4f secs", secs)); + + // --- Surface parameters, if any + + Object s = Molecule.getProperty(MoleculeInterface.SurfacesProperty); + if (s != null) { + System.out.println("Molecule has surface property of a class " + s.getClass().getCanonicalName()); + surfaces = new ArrayList(); + try { + Map ss = (Map) s; + System.out.println("Number of surface(s): " + ss.size()); + for (Object key : ss.keySet()) { + String name = (String) key; + MolecularPlane plane = (MolecularPlane) ss.get(key); + System.out.println(" Surface " + name); + forceField.getSurfaceParam(plane); + System.out.println(" Surface Params " + plane.getSurfaceParameter().getR() + " & " + plane.getSurfaceParameter().getW()); + setupNonbondedInteractions(Molecule, plane); + surfaces.add(plane); + System.out.println("Plane " + name + ": " + plane); + } + } catch (Exception ex) { + logger.severe("Error Getting surface(s) from molecule: " + ex.getMessage()); + } + } + } + + /** + * + * @param paramType int + * @param intType int- type of bond stretch interactions: 0 - harmonic K*(r-r0) + * @return int - number of bond stretch interactions + * @throws Exception + */ + public int formBondStretchInteractions(int paramType, int intType) throws + Exception { + int n = 0; + if (Molecule == null) { + throw new Exception("Forming Bond Stretch Interactions: null pointer for molecule"); + } + + if (paramType != MolecularEnergy.SFF_PARAMETERS) { + throw new Exception("Forming Bond Stretch Interactions: unknown type of parameters"); + } + + if (intType != HARMONIC_BOND_TERM) { + throw new Exception("Forming Bond Stretch Interactions: unknown type of bond interactions"); + } + + // --- Go through all bonds + long start = System.currentTimeMillis(); + + if (BondStretchInteractions != null) { + BondStretchInteractions = null; + } + + BondStretchInteractions = new Object[2]; + + BondStretchPairs bondPairs = new BondStretchPairs(); + + if (intType == HARMONIC_BOND_TERM + && paramType == MolecularEnergy.SFF_PARAMETERS) { + BondStretchInteractions[0] = new Integer(HARMONIC_BOND_TERM); + for (int i = 0; i < Molecule.getNumberOfBonds(); i++) { + BondInterface bond = Molecule.getBondInterface(i); + AtomInterface a1 = bond.getIAtomInterface(); + AtomInterface a2 = bond.getJAtomInterface(); + if (a1.isDynamic() || a2.isDynamic()) { + + int index_1 = Molecule.getAtomIndex(a1); + int index_2 = Molecule.getAtomIndex(a2); + + String type_1 = (String) a1.getProperty(AtomInterface.CCT_ATOM_TYPE); + if (type_1 == null) { + type_1 = cct.modelling.Molecule.guessAtomType(a1, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } + + String type_2 = (String) a2.getProperty(AtomInterface.CCT_ATOM_TYPE); + if (type_2 == null) { + type_2 = cct.modelling.Molecule.guessAtomType(a2, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } + + if (type_1 == null || type_2 == null) { + float r0 = (float) Point3f.distance(a1, a2); + HarmonicBondStretch hbs = new HarmonicBondStretch(index_1, index_2, defaultFk, r0); + bondPairs.addBondPair(hbs); + } else { + BondParam bp = forceField.getBondStretchParam(type_1, type_2); + HarmonicBondStretch hbs = new HarmonicBondStretch(index_1, index_2, bp.Fk, bp.R0); + bondPairs.addBondPair(hbs); + } + } + } + + BondStretchInteractions[1] = bondPairs; + + float secs = (System.currentTimeMillis() - start) / 1000.0f; + logger.info("Number of bond stretch interactions: " + bondPairs.getSize() + " Elapsed time: " + secs + " secs"); + List pairs = bondPairs.getBondStretchPairs(); + + if (logger.isLoggable(Level.INFO)) { + StringWriter sr = new StringWriter(); + for (int i = 0; i < pairs.size(); i++) { + HarmonicBondStretch hbs = (HarmonicBondStretch) pairs.get(i); + sr.write((i + 1) + " : " + hbs.i + " " + hbs.j + " " + hbs.Fk + " " + hbs.R0 + "\n"); + } + logger.info(sr.toString()); + sr = null; + } + } + + return n; + } + + public void setupNonbondedInteractions(int paramType, List nonbonded) throws Exception { + + if (nonbonded == null) { + return; + } + + if (paramType != MolecularEnergy.SFF_PARAMETERS) { + throw new Exception("setupNonbondedInteractions: unknown type of parameters"); + } + + if (paramType == MolecularEnergy.SFF_PARAMETERS) { + SimpleForceField.setupNonbondedParams(Molecule, nonbonded); + } + + } + + public void setupNonbondedInteractions(MoleculeInterface mol, MolecularPlane plane) throws Exception { + + SimpleForceField.setupNonbondedParams(Molecule, plane); + } + + public int formAngleBendInteractions(int paramType, AngleBendsArray angles) throws + Exception { + if (Molecule == null) { + throw new Exception("formAngleBendInteractions: null pointer for molecule"); + } + + if (paramType != MolecularEnergy.SFF_PARAMETERS) { + throw new Exception("formAngleBendInteractions: unknown type of parameters"); + } + + if (AngleBendInteractions != null) { + AngleBendInteractions = null; + } + + AngleBendInteractions = new Object[2]; + + if (paramType == MolecularEnergy.SFF_PARAMETERS) { + + AngleBendInteractions[0] = new Integer(HARMONIC_BOND_TERM); + + forceField.getAngleBendParams(Molecule, angles); + + AngleBendInteractions[1] = angles; + + if (logger.isLoggable(Level.INFO)) { + StringWriter sr = new StringWriter(); + logger.info("Number of angle bend interactions: " + + angles.getSize() + "\nAngle Bend Parameters: "); + for (int i = 0; i < angles.getSize(); i++) { + AngleBend ab = angles.getAngleBend(i); + sr.write((i + 1) + " : " + ab.getI() + " " + ab.getJ() + + " " + ab.getK() + " " + + (ab.Fk / SimpleForceField.FK_GRAD_2_RAD_FACTOR) + + " " + + (ab.Theta * (float) Point3f.RADIANS_TO_DEGREES) + "\n"); + } + logger.info(sr.toString()); + sr = null; + } + } + + return angles.getSize(); + } + + public List formTorsionInteractions(int paramType, List torsions) throws + Exception { + + if (Molecule == null) { + throw new Exception("formTorsionInteractions: null pointer for molecule"); + } + + if (paramType != MolecularEnergy.SFF_PARAMETERS) { + throw new Exception("formTorsionInteractions: unknown type of parameters"); + } + + if (paramType == MolecularEnergy.SFF_PARAMETERS) { + + torsionInteractions = forceField.getTorsionParams(Molecule, Torsions); + + if (logger.isLoggable(Level.INFO)) { // 800 is for the INFO level + StringWriter sr = new StringWriter(); + sr.write("Number of torsion interactions: " + torsionInteractions.size() + + "\nTorsion Parameters: \n"); + for (int i = 0; i < torsionInteractions.size(); i++) { + TorsionParameter tp = (TorsionParameter) torsionInteractions.get(i); + sr.write((i + 1) + " : " + tp.getI() + " " + tp.getJ() + " " + tp.getK() + " " + tp.getL() + " "); + List serie = tp.getSerie(); + for (int j = 0; j < serie.size(); j++) { + TorsionTerm tt = (TorsionTerm) serie.get(j); + sr.write(tt.V + " " + tt.Periodicity + " " + (tt.Phase * (float) Point3f.RADIANS_TO_DEGREES)); + } + sr.write("\n"); + } + + logger.info(sr.toString()); + sr.close(); + sr = null; + } + + } + + return torsionInteractions; + } + + /** + * Finds all valent angles where at least one atom forming angle is dynamic + * + * @param molec MoleculeInterface - Molecule + * @return AngleBendsArray + */ + public static AngleBendsArray findDynamicAngles(MoleculeInterface molec) { + + AngleBendsArray aba = new AngleBendsArray(); + if (molec.getNumberOfAtoms() < 3) { + return aba; + } + + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface a1 = molec.getAtomInterface(i); + int index_1 = molec.getAtomIndex(a1); + List a1_list = a1.getBondedToAtoms(); + + for (int j = 0; j < a1_list.size(); j++) { + AtomInterface a2 = (AtomInterface) a1_list.get(j); + int index_2 = molec.getAtomIndex(a2); + List a2_list = a2.getBondedToAtoms(); + + for (int k = 0; k < a2_list.size(); k++) { + AtomInterface a3 = (AtomInterface) a2_list.get(k); + + if (a1.isDynamic() || a2.isDynamic() || a3.isDynamic()) { + + int index_3 = molec.getAtomIndex(a3); + + if (a1 == a3) { + continue; + } + + if (index_3 < index_1) { + continue; // always go in descending order + } + + // Check for 3-member ring + if (a1.getBondToAtom(a3) != null) { + continue; + } + + AngleBend ab = new AngleBend(index_1, index_2, index_3, -1, + -1); + aba.addAngleBend(ab); + } + } + } + } + + //logger.info("Number of angle bend interactions: " + aba.getSize()); + + if (logger.isLoggable(Level.INFO)) { + StringWriter sr = new StringWriter(); + for (int i = 0; i < aba.getSize(); i++) { + if (i == 0) { + sr.write("\nAngles: \n"); + } + AngleBend ab = aba.getAngleBend(i); + sr.write((i + 1) + " : " + ab.ijk[0] + " " + ab.ijk[1] + + " " + + ab.ijk[2] + " " + ab.Fk + " " + ab.Theta + "\n"); + } + logger.info(sr.toString()); + try { + sr.close(); + } catch (Exception ex) { + } + sr = null; + } + + return aba; + } + + /** + * Finds all regular torsions in molecule + * + * @param molec MoleculeInterface - Molecule + * @return ArrayList - array of class Torsion + */ + public static List findDynamicTorsions(MoleculeInterface molec) { + List torsions = new ArrayList(); + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + //at[0] = i; + AtomInterface a1 = molec.getAtomInterface(i); + int index_1 = molec.getAtomIndex(a1); + List a1_list = a1.getBondedToAtoms(); + + for (int j = 0; j < a1_list.size(); j++) { + //a2 = atom[i].br[j]; + AtomInterface a2 = (AtomInterface) a1_list.get(j); + int index_2 = molec.getAtomIndex(a2); + List a2_list = a2.getBondedToAtoms(); + + for (int k = 0; k < a2_list.size(); k++) { + //a3 = atom[a2].br[k]; + AtomInterface a3 = (AtomInterface) a2_list.get(k); + int index_3 = molec.getAtomIndex(a3); + List a3_list = a3.getBondedToAtoms(); + + //if (a3 == i) { + if (a3 == a1) { + continue; + } + + for (int l = 0; l < a3_list.size(); l++) { + //a4 = atom[a3].br[l]; + AtomInterface a4 = (AtomInterface) a3_list.get(l); + + if (a4 == a2 || a4 == a1) { + continue; + } + + if (!a1.isDynamic() && !a2.isDynamic() && !a3.isDynamic() + && !a4.isDynamic()) { + continue; + } + + // Check for 4-member ring + if (a1.getBondToAtom(a4) != null) { + continue; + } + + int index_4 = molec.getAtomIndex(a4); + + //if (a4 < i) { + if (index_4 < index_1) { + continue; // always go in descending order + } + + Torsion torsion = new Torsion(index_1, index_2, index_3, + index_4); + torsions.add(torsion); + //printf("\n%3d - %3d - %3d - %3d", at[0], at[1], at[2], at[3]); + } + } + } + } + + return torsions; + } + + public static List find14Interactions(MoleculeInterface molec, List torsions) { + List int14 = new ArrayList(); + for (int i = 0; i < torsions.size(); i++) { + Torsion tor = (Torsion) torsions.get(i); + AtomInterface a1 = molec.getAtomInterface(tor.ijkl[0]); + AtomInterface a4 = molec.getAtomInterface(tor.ijkl[3]); + if ((!a1.isDynamic()) && (!a4.isDynamic())) { + continue; + } + NonbondedPair nb = new NonbondedPair(tor.ijkl[0], tor.ijkl[3]); + int14.add(nb); + } + return int14; + } + + public static List findNonbondedPairs(MoleculeInterface molec, Nonbonded15Table nbTable) { + List nb = new ArrayList(); + + for (int i = 1; i < molec.getNumberOfAtoms(); i++) { + AtomInterface a1 = molec.getAtomInterface(i); + for (int j = 0; j < i; j++) { + AtomInterface a2 = molec.getAtomInterface(j); + if (!a1.isDynamic() && !a2.isDynamic()) { + continue; + } + if (nbTable.get15(i, j)) { + NonbondedPair nbp = new NonbondedPair(molec.getAtomIndex(a1), molec.getAtomIndex(a2)); + nb.add(nbp); + } + } + } + return nb; + } + + public static void main(String[] args) { + FFMolecule ffmolecule = new FFMolecule(); + } + + public List getSurfaces() { + return surfaces; + } +} diff --git a/src/main/java/cct/modelling/FormatManager.java b/src/main/java/cct/modelling/FormatManager.java new file mode 100644 index 0000000..c64f966 --- /dev/null +++ b/src/main/java/cct/modelling/FormatManager.java @@ -0,0 +1,577 @@ +package cct.modelling; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.StringReader; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import cct.GlobalSettings; +import cct.interfaces.CoordinateBuilderInterface; +import cct.interfaces.CoordinateParserInterface; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class FormatManager { + + public static final String SIMPLE_COORDINATE_BUILDERS_TAG = "simpleCoordinateBuilders"; + public static final String SIMPLE_COORDINATE_BUILDER_TAG = "simpleCoordinateBuilder"; + public static final String SIMPLE_COORDINATE_PARSER_TAG = "simpleCoordinateParser"; + public static final String SIMPLE_COORDINATE_NAME_TAG = "name"; + public static final String SIMPLE_COORDINATE_DESC_TAG = "desc"; + public static final String SIMPLE_COORDINATE_CLASS_TAG = "class"; + + public static boolean debug = true; + static final Logger logger = Logger.getLogger(FormatManager.class.getCanonicalName()); + + private static Map coordBuilders = null; + private static Map coordParsers = null; + + public FormatManager() { + } + + public static void main(String[] args) { + FormatManager formatmanager = new FormatManager(); + } + + public static CoordinateBuilderInterface getCoordinateBuilder(String builder) throws Exception { + if (coordBuilders == null || coordBuilders.size() < 1) { + try { + getSimpleCoordinateBuilders(); + } + catch (Exception ex) { + System.err.println("Encountered some errors while getting builder list: " + ex.getMessage()); + } + } + + if (coordBuilders == null || coordBuilders.size() < 1) { + throw new Exception("Cannot get list of coordinate builders"); + } + + if (!coordBuilders.containsKey(builder)) { + throw new Exception("No such coordinate builder: " + builder); + } + + CoordBuilder cBuilder = coordBuilders.get(builder); + CoordinateBuilderInterface cbi = (CoordinateBuilderInterface) cBuilder.builder; + return cbi; + } + + public static CoordinateParserInterface getCoordinateParser(String builder) throws Exception { + if (coordParsers == null || coordParsers.size() < 1) { + try { + getSimpleCoordinateParsers(); + } + catch (Exception ex) { + System.err.println("Encountered some errors while getting parsers list: " + ex.getMessage()); + } + } + + if (coordParsers == null || coordParsers.size() < 1) { + throw new Exception("Cannot get list of coordinate Parsers"); + } + + if (!coordParsers.containsKey(builder)) { + throw new Exception("No such coordinate parser: " + builder); + } + + CoordParser cParser = coordParsers.get(builder); + CoordinateParserInterface cpi = (CoordinateParserInterface) cParser.parser; + return cpi; + } + + public static String[] getCoordinateBuilders() { + if (coordBuilders == null || coordBuilders.size() < 1) { + try { + getSimpleCoordinateBuilders(); + } + catch (Exception ex) { + System.err.println("Encountered some errors while getting builder list: " + ex.getMessage()); + } + } + + if (coordBuilders == null || coordBuilders.size() < 1) { + return null; + } + String[] builders = new String[coordBuilders.size()]; + coordBuilders.keySet().toArray(builders); + return builders; + } + + public static String[] getCoordinateParsers() { + if (coordParsers == null || coordParsers.size() < 1) { + try { + getSimpleCoordinateParsers(); + } + catch (Exception ex) { + System.err.println("Encountered some errors while getting parser list: " + ex.getMessage()); + } + } + + if (coordParsers == null || coordParsers.size() < 1) { + return null; + } + String[] parsers = new String[coordParsers.size()]; + coordParsers.keySet().toArray(parsers); + return parsers; + } + + public static void getSimpleCoordinateBuilders() throws Exception { + getSimpleCoordinateBuilders(GlobalSettings.FORMATS_XML_FILE); + } + + public static void getSimpleCoordinateParsers() throws Exception { + getSimpleCoordinateParsers(GlobalSettings.FORMATS_XML_FILE); + } + + public static void getSimpleCoordinateBuilders(String file_name) throws Exception { + + if (coordBuilders == null) { + coordBuilders = new HashMap (); + } + + //URL builderURL = null; + InputStream is = null; + try { + ClassLoader cl = FormatManager.class.getClassLoader(); + //logger.info("Class loader: " + cl.toString()); + //builderURL = cl.getResource(file_name); + is = cl.getResourceAsStream(file_name); + } + catch (Exception ex) { + throw new Exception("getSimpleCoordinateBuilders: cannot get resource : " + file_name + " : " + ex.getMessage()); + } + + /* + File file = new File(builderURL.getFile()); + if (!file.exists()) { + throw new Exception("Error: file " + file_name + " with description of simple coordinate builders is not exists"); + } + */ + + /* + + + + + */ + // --- Using DOM + Document doc = null; + try { + // Create a factory + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + // Use the factory to create a builder + DocumentBuilder builder = factory.newDocumentBuilder(); + doc = builder.parse(is); + } + + catch (Exception ex) { + throw new Exception("Error parsing file " + file_name + " with description of simple coordinate builders: " + + ex.getMessage()); + } + + NodeList list = doc.getElementsByTagName(SIMPLE_COORDINATE_BUILDER_TAG); + for (int i = 0; i < list.getLength(); i++) { + + // Get element + Node node = list.item(i); + if (debug) { + logger.info(node.getNodeName() + " : " + node.getNodeValue()); + } + + NamedNodeMap attr = node.getAttributes(); + + if (attr == null || attr.getLength() < 1) { + continue; + } + + // --- Get Name + + Node nameN = attr.getNamedItem(SIMPLE_COORDINATE_NAME_TAG); + + if (nameN == null) { + System.err.println("getSimpleCoordinateBuilders: no name for builder. Ignored..."); + continue; + } + + if (nameN.getNodeType() != Node.ATTRIBUTE_NODE) { + System.err.println("getSimpleCoordinateBuilders: name is not attribute. Ignored..."); + continue; + } + + String name = ""; + try { + name = nameN.getNodeValue(); + } + catch (Exception ex) { + System.err.println("getSimpleCoordinateBuilders: error getting name: " + ex.getMessage() + " Ignored..."); + continue; + } + + if (coordBuilders.containsKey(name)) { + System.err.println("Coordinate Builder " + name + " is already in Table. Ignored..."); + continue; + } + + // --- Get Description + + String desc = ""; + Node descN = attr.getNamedItem(SIMPLE_COORDINATE_DESC_TAG); + + if (descN != null) { + if (descN.getNodeType() != Node.ATTRIBUTE_NODE) { + System.err.println("getSimpleCoordinateBuilders: description is not an attribute. Ignored..."); + } + else { + try { + desc = descN.getNodeValue(); + } + catch (Exception ex) { + System.err.println("getSimpleCoordinateBuilders: error getting description: " + ex.getMessage() + + " Ignored..."); + } + } + } + + // --- Get class + + Node classN = attr.getNamedItem(SIMPLE_COORDINATE_CLASS_TAG); + + if (classN == null) { + System.err.println("getSimpleCoordinateBuilders: no class for builder. Ignored..."); + continue; + } + + if (classN.getNodeType() != Node.ATTRIBUTE_NODE) { + System.err.println("getSimpleCoordinateBuilders: class is not attribute. Ignored..."); + continue; + } + + // -- Load class + + String className = ""; + try { + className = classN.getNodeValue(); + } + catch (Exception ex) { + System.err.println("getSimpleCoordinateBuilders: error getting class name: " + ex.getMessage() + " Ignored..."); + continue; + } + + if (debug) { + logger.info("Loading class " + className); + } + + Class builderClass = null; + ClassLoader loader = null; + try { + // Get the Class object associated with builder + builderClass = Class.forName(className); + + // Get the ClassLoader object associated with this Class. + loader = builderClass.getClassLoader(); + + if (loader == null) { + System.err.println("loader == null. Ignored..."); + continue; + } + else if (debug) { + // Verify that this ClassLoader is associated with the builder class. + Class loaderClass = loader.getClass(); + + logger.info("Class associated with ClassLoader: " + loaderClass.getName()); + } + } + catch (ClassNotFoundException ex) { + System.err.println("Cannot load class " + className + " : " + ex.getMessage() + " Ignored..."); + continue; + } + + Class cl = loader.loadClass(className); + Object obj = cl.newInstance(); + if (debug) { + logger.info("Classr " + className + " was loaded"); + } + + if (! (obj instanceof CoordinateBuilderInterface)) { + System.err.println("Class " + className + " does not implement " + CoordinateBuilderInterface.class.getName() + + " interface. Ignored..."); + continue; + } + + CoordBuilder cBuilder = new CoordBuilder(name, desc, obj); + coordBuilders.put(name, cBuilder); + } + + } + + public static void getSimpleCoordinateParsers(String file_name) throws Exception { + + if (coordParsers == null) { + coordParsers = new HashMap (); + } + + //URL builderURL = null; + InputStream is = null; + try { + ClassLoader cl = FormatManager.class.getClassLoader(); + //logger.info("Class loader: " + cl.toString()); + //builderURL = cl.getResource(file_name); + is = cl.getResourceAsStream(file_name); + } + catch (Exception ex) { + throw new Exception("getSimpleCoordinateParser: cannot get resource : " + file_name + " : " + ex.getMessage()); + } + + /* + File file = new File(builderURL.getFile()); + if (!file.exists()) { + throw new Exception("Error: file " + file_name + " with description of simple coordinate builders is not exists"); + } + */ + + /* + + + + + */ + // --- Using DOM + Document doc = null; + try { + // Create a factory + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + // Use the factory to create a builder + DocumentBuilder builder = factory.newDocumentBuilder(); + doc = builder.parse(is); + } + + catch (Exception ex) { + throw new Exception("Error parsing file " + file_name + " with description of simple coordinate parsers: " + + ex.getMessage()); + } + + NodeList list = doc.getElementsByTagName(SIMPLE_COORDINATE_PARSER_TAG); + for (int i = 0; i < list.getLength(); i++) { + + // Get element + Node node = list.item(i); + if (debug) { + logger.info(node.getNodeName() + " : " + node.getNodeValue()); + } + + NamedNodeMap attr = node.getAttributes(); + + if (attr == null || attr.getLength() < 1) { + continue; + } + + // --- Get Name + + Node nameN = attr.getNamedItem(SIMPLE_COORDINATE_NAME_TAG); + + if (nameN == null) { + System.err.println("getSimpleCoordinateParsers: no name for Parser. Ignored..."); + continue; + } + + if (nameN.getNodeType() != Node.ATTRIBUTE_NODE) { + System.err.println("getSimpleCoordinateParsers: name is not attribute. Ignored..."); + continue; + } + + String name = ""; + try { + name = nameN.getNodeValue(); + } + catch (Exception ex) { + System.err.println("getSimpleCoordinateParsers: error getting name: " + ex.getMessage() + " Ignored..."); + continue; + } + + if (coordParsers.containsKey(name)) { + System.err.println("Coordinate Parser " + name + " is already in Table. Ignored..."); + continue; + } + + // --- Get Description + + String desc = ""; + Node descN = attr.getNamedItem(SIMPLE_COORDINATE_DESC_TAG); + + if (descN != null) { + if (descN.getNodeType() != Node.ATTRIBUTE_NODE) { + System.err.println("getSimpleCoordinateParsers: description is not an attribute. Ignored..."); + } + else { + try { + desc = descN.getNodeValue(); + } + catch (Exception ex) { + System.err.println("getSimpleCoordinateParsers: error getting description: " + ex.getMessage() + + " Ignored..."); + } + } + } + + // --- Get class + + Node classN = attr.getNamedItem(SIMPLE_COORDINATE_CLASS_TAG); + + if (classN == null) { + System.err.println("getSimpleCoordinateParsers: no class for builder. Ignored..."); + continue; + } + + if (classN.getNodeType() != Node.ATTRIBUTE_NODE) { + System.err.println("getSimpleCoordinateBuilders: class is not attribute. Ignored..."); + continue; + } + + // -- Load class + + String className = ""; + try { + className = classN.getNodeValue(); + } + catch (Exception ex) { + System.err.println("getSimpleCoordinateParsers: error getting class name: " + ex.getMessage() + " Ignored..."); + continue; + } + + if (debug) { + logger.info("Loading class " + className); + } + + Class builderClass = null; + ClassLoader loader = null; + try { + // Get the Class object associated with builder + builderClass = Class.forName(className); + + // Get the ClassLoader object associated with this Class. + loader = builderClass.getClassLoader(); + + if (loader == null) { + System.err.println("loader == null. Ignored..."); + continue; + } + else if (debug) { + // Verify that this ClassLoader is associated with the builder class. + Class loaderClass = loader.getClass(); + + logger.info("Class associated with ClassLoader: " + loaderClass.getName()); + } + } + catch (ClassNotFoundException ex) { + System.err.println("Cannot load class " + className + " : " + ex.getMessage() + " Ignored..."); + continue; + } + + Class cl = loader.loadClass(className); + Object obj = cl.newInstance(); + if (debug) { + logger.info("Class " + className + " was loaded"); + } + + if (! (obj instanceof CoordinateParserInterface)) { + System.err.println("Class " + className + " does not implement " + CoordinateParserInterface.class.getName() + + " interface. Ignored..."); + continue; + } + + CoordParser cBuilder = new CoordParser(name, desc, obj); + coordParsers.put(name, cBuilder); + } + } + + public static String guessSimpleCoordinateParser(String coordinates) { + if (coordParsers == null || coordParsers.size() < 1) { + try { + getSimpleCoordinateParsers(); + } + catch (Exception ex) { + return null; + } + } + + if (coordParsers == null || coordParsers.size() < 1) { + return null; + } + + ParserScore[] parsers = new ParserScore[coordParsers.size()]; + Set set = coordParsers.entrySet(); + Iterator iter = set.iterator(); + int count = 0; + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + CoordParser parser = (CoordParser) me.getValue(); + BufferedReader in = new BufferedReader(new StringReader(coordinates)); + CoordinateParserInterface cpi = (CoordinateParserInterface) parser.parser; + double score = 0; + try { + score = cpi.evaluateCompliance(in); + } + catch (Exception ex) {} + + parsers[count] = new ParserScore(parser, score); + count++; + } + + Arrays.sort(parsers, new ParserComparator()); + + return parsers[0].parser.name; + } + + static class ParserScore { + CoordParser parser; + double score; + public ParserScore(CoordParser parser, double score) { + this.parser = parser; + this.score = score; + } + } + + static class ParserComparator + implements Comparator { + /** + * Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second + * @param o1 Object - ParserScore object + * @param o2 Object - ParserScore object + * @return int + */ + @Override + public int compare(Object o1, Object o2) { + if ( ( (ParserScore) o1).score == ( (ParserScore) o2).score) { + return 0; + } + if ( ( (ParserScore) o1).score < ( (ParserScore) o2).score) { + return 1; + } + return -1; + } + } +} diff --git a/src/main/java/cct/modelling/Frequencies.java b/src/main/java/cct/modelling/Frequencies.java new file mode 100644 index 0000000..9ae285f --- /dev/null +++ b/src/main/java/cct/modelling/Frequencies.java @@ -0,0 +1,102 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class Frequencies { + + private static double inc_freq = 100; + private static double fullWidth_at_HalfMaximum = 4; + + public Frequencies() { + } + + static public void makeCurve(double[] freqs, double[] values, double[] x, double[] y, int dim, VIBRATIONAL_SPECTRUM_CURVE curve_type) { + double start = freqs[0] - inc_freq; + double step = (freqs[freqs.length - 1] + inc_freq - start) / (dim - 1); + for (int i = 0; i < dim; i++) { + x[i] = start; + start += step; + y[i] = calculateIntensity(freqs, values, x[i], curve_type); + } + } + + /** + * Calculates intensity at point x + * @param freqs double[] + * @param values double[] + * @param x double + * @param curve_type VIBRATIONAL_SPECTRUM_CURVE + * @return double + */ + static public double calculateIntensity(double[] freqs, double[] values, double x, VIBRATIONAL_SPECTRUM_CURVE curve_type) { + double intensity = 0; + double half_max_sq = fullWidth_at_HalfMaximum * fullWidth_at_HalfMaximum; + for (int i = 0; i < freqs.length; i++) { + double displ = x - freqs[i]; + switch (curve_type) { + case GAUSSIAN: + intensity += values[i] * Math.exp( - (displ * displ) / (2.0 * half_max_sq)); + break; + case LORENTZ: + intensity += values[i] * fullWidth_at_HalfMaximum / (displ * displ + half_max_sq); + break; + case GAUSSIAN_LORENTZ: + case VOIGHT: + break; + + } + } + return intensity; + } + + public static void main(String[] args) { + Frequencies frequencies = new Frequencies(); + } +} diff --git a/src/main/java/cct/modelling/GeneralMolecularDataParser.java b/src/main/java/cct/modelling/GeneralMolecularDataParser.java new file mode 100644 index 0000000..5f1c0ba --- /dev/null +++ b/src/main/java/cct/modelling/GeneralMolecularDataParser.java @@ -0,0 +1,84 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.modelling; + +import cct.GlobalSettings; +import cct.interfaces.MoleculeInterface; +import cct.tools.Utils; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; + +/** + * + * @author vvv900 + */ +abstract public class GeneralMolecularDataParser extends AbstractDataParser { + + private static MoleculeInterface refMolecule = null; + private List molecules = new ArrayList(); + static final Logger logger = Logger.getLogger(GeneralMolecularDataParser.class.getCanonicalName()); + + public GeneralMolecularDataParser() { + if (refMolecule == null) { + String className = null; + try { + className = GlobalSettings.getProperty(GlobalSettings.MOLECULE_INTERFACE_CLASS); + } catch (Exception ex) { + logger.warning("Cannot get property " + GlobalSettings.MOLECULE_INTERFACE_CLASS); + } + try { + Object obj = Utils.loadClass(className); + if (obj instanceof MoleculeInterface) { + refMolecule = (MoleculeInterface) obj; + } else { + logger.warning("Class " + className + " is not an instance of MoleculeInterface"); + } + } catch (Exception ex) { + logger.warning("Cannot load class " + className); + } + } + } + + abstract public int validFormatScore(BufferedReader in) throws Exception; + + public MoleculeInterface getMolecule() { + if (molecules.size() == 0) { + return null; + } + return molecules.get(0); + } + + public List getMolecules() { + return molecules; + } + + public int getNumberMolecules() { + return molecules.size(); + } + + public void setMoleculeInterface(MoleculeInterface molecule) { + refMolecule = molecule.getInstance(); + } + + protected MoleculeInterface getMoleculeInterface() { + return refMolecule.getInstance(); + } + + protected void addMolecule(MoleculeInterface molecule) { + molecules.add(molecule); + } + + @Override + public GeneralMolecularDataParser getParserObject() { + return this; + } +} diff --git a/src/main/java/cct/modelling/HarmonicBondStretch.java b/src/main/java/cct/modelling/HarmonicBondStretch.java new file mode 100644 index 0000000..d6f1eea --- /dev/null +++ b/src/main/java/cct/modelling/HarmonicBondStretch.java @@ -0,0 +1,61 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class HarmonicBondStretch { + protected int i, j; + protected float Fk, R0; + public HarmonicBondStretch(int a1, int a2, float fk, float r0) { + i = a1; + j = a2; + Fk = fk; + R0 = r0; + } +} diff --git a/src/main/java/cct/modelling/JobControl.java b/src/main/java/cct/modelling/JobControl.java new file mode 100644 index 0000000..2e66e8f --- /dev/null +++ b/src/main/java/cct/modelling/JobControl.java @@ -0,0 +1,67 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +/** + * + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class JobControl { + protected boolean PeriodicBoundary = false; + protected float NonbondedCutoff = 8.0f; // Default for AMBER + protected int NonbondedListUpdates = 25; + protected int MaxSteps = 1000; + protected float TimeStep = 0.001f; // In ps + protected float ReferenceTemperature = 300.0f; // In K + protected float BathCouplingTime = 1.0f; // In ps + protected float ReferencePressure = 1.0f; // in bars + protected float Compressibility = 44.6f; // 1.0e-6/bar + protected float PressureRelaxationTime = 1.0f; // in ps + + public JobControl() { + } +} diff --git a/src/main/java/cct/modelling/MinimizeStructure.java b/src/main/java/cct/modelling/MinimizeStructure.java new file mode 100644 index 0000000..5432e42 --- /dev/null +++ b/src/main/java/cct/modelling/MinimizeStructure.java @@ -0,0 +1,248 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.ForceFieldInterface; +import cct.interfaces.MinimizeProgressInterface; +import cct.interfaces.MoleculeInterface; +import cct.math.DFPMin; +import cct.math.MinimizerInterface; +import cct.tools.Utils; +import cct.vecmath.VecmathTools; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class MinimizeStructure { + + static final int OPT_CARTESIAN_COORD = 0; + static final int OPT_INTERNAL_COORD = OPT_CARTESIAN_COORD + 1; + static final Logger logger = Logger.getLogger(MinimizeStructure.class.getCanonicalName()); + + protected FFMolecule ffMolecule = null; + protected MoleculeInterface Molec = null; + protected MinimizerInterface minimizer = null; + MolecularEnergy molEnergy = null; + int exitCode; + MinimizeProgressInterface progressInterface = null; + ForceFieldInterface forceField = null; + + float[] Gradients = null; + float[] Variables = null; + int[][] indexes = null; + int nVar = 0; + + public MinimizeStructure(MoleculeInterface mol) { + Molec = mol; + } + + public MoleculeInterface getMolecule() { + return Molec; + } + + public void setMinimizer(MinimizerInterface min) { + minimizer = min; + } + + public void setForceField(ForceFieldInterface ff) { + forceField = ff; + } + + public void setMinimizeProgressInterface(MinimizeProgressInterface mpi) { + this.progressInterface = mpi; + } + + public float[][] getCoordinates(int n, float vars[]) { + float[][] coords = molEnergy.getCoordinates(n, vars); + return coords; + } + + void setupMinimization() throws Exception { + ffMolecule = new FFMolecule(Molec); + if (forceField != null) { + ffMolecule.applyForceField(forceField); + } + ffMolecule.formFFParameters(); + + int dynamicAtoms = 0; + for (int i = 0; i < Molec.getNumberOfAtoms(); i++) { + AtomInterface atom = Molec.getAtomInterface(i); + if (atom.isDynamic()) { + ++dynamicAtoms; + } + } + + Gradients = new float[3 * dynamicAtoms]; + Variables = new float[3 * dynamicAtoms]; + indexes = new int[3 * dynamicAtoms][2]; + + dynamicAtoms = 0; + for (int i = 0; i < Molec.getNumberOfAtoms(); i++) { + AtomInterface atom = Molec.getAtomInterface(i); + if (atom.isDynamic()) { + + Variables[3 * dynamicAtoms] = atom.getX(); + Variables[3 * dynamicAtoms + 1] = atom.getY(); + Variables[3 * dynamicAtoms + 2] = atom.getZ(); + + indexes[3 * dynamicAtoms][0] = i; + indexes[3 * dynamicAtoms][1] = 0; + indexes[3 * dynamicAtoms + 1][0] = i; + indexes[3 * dynamicAtoms + 1][1] = 1; + indexes[3 * dynamicAtoms + 2][0] = i; + indexes[3 * dynamicAtoms + 2][1] = 2; + ++dynamicAtoms; + } + } + + nVar = 3 * dynamicAtoms; + + /* + for (int i = 0; i < nVar; i++) { + logger.info( (i + 1) + " " + Variables[i] + " Atom: " + + indexes[i][0] + " var: " + indexes[i][1]); + } + */ + + logger.info("Number of variables: " + nVar + " # of atoms: " + + Molec.getNumberOfAtoms()); + } + + public int minimize() throws Exception { + if (minimizer == null) { + throw new Exception("Minimizer is not set"); + } + + if (progressInterface != null) { + minimizer.setMinimizeProgressInterface(progressInterface); + } + + setupMinimization(); + + molEnergy = new MolecularEnergy(ffMolecule); + molEnergy.setIndexes(indexes); + + exitCode = minimizer.minimizeFunction(nVar, Variables, molEnergy); + printMinimizationSummary(); + return exitCode; + } + + public void printMinimizationSummary() { + logger.info(minimizer.getExitCodeDescription(exitCode)); + + logger.info("RMS of gradients : " + + VecmathTools.getRMS(minimizer.getGradients()) + + " Maximum gradient: " + + VecmathTools.getMaxAbsValue(minimizer.getGradients())); + molEnergy.printEnergyDecomposition(); + } + + public int minimize(int method) throws Exception { + + setupMinimization(); + + molEnergy = new MolecularEnergy(ffMolecule); + molEnergy.setIndexes(indexes); + + if (method == 1) { + DFPMin minimizer = new DFPMin(); + minimizer.setMaximumStep(0.5); + minimizer.setGTolerance(0.01f); + minimizer.minimizeFunction(nVar, Variables, molEnergy); + } + + /* + if ( method == 0 ) { + Amoeba simplex2 = new Amoeba(); + int cond = simplex2.amoeba(Variables, nVar, 0.01f, me); + } + */ + + + /* + Simplex simplex = new Simplex(nVar); + simplex.DownhillSimplex(Variables,nVar,0.01f,me,500, 0.1f); + */ + + logger.info("Minimum function value: " + + molEnergy.function(nVar, Variables)); + + if (method == 0) { + molEnergy.enable14Energy(true); + molEnergy.enable1NonbondEnergy(true); + molEnergy.enableBondStretchEnergy(false); + molEnergy.enableAngleBendEnergy(false); + molEnergy.enableTorsionEnergy(false); + + molEnergy.enableNumericalGradients(true); + molEnergy.function(nVar, Variables, Gradients); + molEnergy.enableNumericalGradients(false); + float g[] = new float[nVar]; + molEnergy.function(nVar, Variables, g); + Utils.printFloatVectors(nVar, Gradients, g); + + molEnergy.printEnergyDecomposition(); + + molEnergy.enable14Energy(true); + molEnergy.enable1NonbondEnergy(true); + molEnergy.enableAngleBendEnergy(true); + molEnergy.enableBondStretchEnergy(true); + molEnergy.enableTorsionEnergy(true); + } + + return 0; + } + + /* + public static void main(String[] args) { + MinimizeStructure minimizestructure = new MinimizeStructure(); + } + */ +} diff --git a/src/main/java/cct/modelling/MolecularDataParserInterface.java b/src/main/java/cct/modelling/MolecularDataParserInterface.java new file mode 100644 index 0000000..7e908ad --- /dev/null +++ b/src/main/java/cct/modelling/MolecularDataParserInterface.java @@ -0,0 +1,22 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.modelling; + +import cct.interfaces.MoleculeInterface; + +/** + * + * @author vvv900 + */ +public interface MolecularDataParserInterface extends DataParserInterface { + + MoleculeInterface getMolecule(); + + MoleculeInterface[] getMolecules(); + + int getNumberMolecules(); + + void setMoleculeInterface(MoleculeInterface molecule); +} diff --git a/src/main/java/cct/modelling/MolecularDataWizard.java b/src/main/java/cct/modelling/MolecularDataWizard.java new file mode 100644 index 0000000..448cbf8 --- /dev/null +++ b/src/main/java/cct/modelling/MolecularDataWizard.java @@ -0,0 +1,343 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + /* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.modelling; + +import cct.GlobalSettings; +import cct.config.FormatObject; +import cct.interfaces.MoleculeInterface; +import cct.tools.FileFilterImpl; +import java.awt.Component; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.prefs.Preferences; +import javax.swing.JFileChooser; +import javax.swing.JOptionPane; + +/** + * + * @author vvv900 + */ +public class MolecularDataWizard { + + private boolean useOpenFileDialog = true; + private Component parent; + private Object parserObject; + private JFileChooser chooser; + private FileFilterImpl filter; + private File currentWorkingDirectory = null; + static private Preferences prefs = null; + static final Logger logger = Logger.getLogger(MolecularDataWizard.class.getCanonicalName()); + private MoleculeInterface reference; + private List molecules = new ArrayList(); + private static Map parsers; + + public MolecularDataWizard(MoleculeInterface mol) { + this(); + reference = mol; + } + + public MolecularDataWizard() { + if (parsers == null) { + parsers = GlobalSettings.getParsers(); + } + if (prefs == null) { + try { + prefs = Preferences.userNodeForPackage(getClass()); + } catch (Exception ex) { + logger.warning("Cannot get Preferences: " + ex.getMessage()); + } + } + } + + private void reset() { + //molecule = reference.getInstance(); + molecules.clear(); + } + + /* + * public void parseMolecularData(CHEMISTRY_FILE_FORMAT format) throws Exception { if (!useOpenFileDialog) { throw new + * Exception("This method can be used only with setUseOpenFileDialog(true)"); } String filename = chooseFileDialog(format); + * BufferedReader in = new BufferedReader(new FileReader(filename)); parseMolecularData(format, in); } + * + * public void parseMolecularData(CHEMISTRY_FILE_FORMAT format, String filename) throws Exception { BufferedReader in = new + * BufferedReader(new FileReader(filename)); parseMolecularData(format, in); } + * + * + * public void parseMolecularData(CHEMISTRY_FILE_FORMAT format, BufferedReader in) throws Exception { reset(); + * + * switch (format) { + * + * case MOL2: TriposParser triposParser = new TriposParser(); parserObject = triposParser; triposParser.parseMol2File(in, + * molecule); break; + * + * default: throw new Exception("Format " + format.toString() + " is not implemented yet!"); } } + */ + public void parseMolecularData(String format) throws Exception { + reset(); + if (!useOpenFileDialog) { + throw new Exception("This method can be used only with setUseOpenFileDialog(true)"); + } + GeneralMolecularDataParser parser = this.getParser(format); + String filename = chooseFileDialog(parser); + parseMolecularData(parser, filename); + //BufferedReader in = new BufferedReader(new FileReader(filename)); + //parseMolecularData(format, in); + } + + public void parseMolecularData(File file) throws Exception { + List ps = GlobalSettings.getParsersForFile(file); + String format = ps.get(0).getName(); + //if (ps.size() > 1) { + // logger.warning("There are " + ps.size() + " parsers for file " + file.getName() + " Using the first one only..."); + //} + + //BufferedReader in = new BufferedReader(new FileReader(file)); + //if (!in.markSupported()) { + // System.err.println("A stream associated with " + file + " does not support marking"); + //} + //in.mark(65536); + int score = 0; + for (FormatObject parser : ps) { + + //in.reset(); + if (parser.getParser() instanceof GeneralMolecularDataParser) { + BufferedReader in = new BufferedReader(new FileReader(file)); + score = ((GeneralMolecularDataParser) parser.getParser()).validFormatScore(in); + in.close(); + System.out.println("Testing format: " + ((GeneralMolecularDataParser) parser.getParser()).getName() + " Score: " + score); + if (score == 10) { + format = ((GeneralMolecularDataParser) parser.getParser()).getName(); + break; + } + } else { + System.err.println("Parser of unknown class: " + + (parser.getParser() == null ? "null" : parser.getParser().getClass().getCanonicalName()) + + " Expected class: " + GeneralMolecularDataParser.class.getCanonicalName()); + } + } + + if (score == 0) { + throw new Exception("File " + file.getAbsolutePath() + " is not recognized as a valid or implemented format"); + } + + System.out.println("Guessed format: " + format); + BufferedReader in = new BufferedReader(new FileReader(file)); + parseMolecularData(format, in); + } + + public void parseMolecularData(String format, String filename) throws Exception { + reset(); + GeneralMolecularDataParser parser = this.getParser(format); + parseMolecularData(parser, filename); + //BufferedReader in = new BufferedReader(new FileReader(filename)); + //parseMolecularData(format, in); + } + + public void parseMolecularData(String format, BufferedReader in) throws Exception { + reset(); + parseMolecularData(getParser(format), in); + } + + public GeneralMolecularDataParser getParser(String format) throws Exception { + if (parsers == null || parsers.size() < 1) { + throw new Exception("No parsers"); + } + + if (!parsers.containsKey(format.toUpperCase())) { + throw new Exception("No parser for a format " + format); + } + + FormatObject obj = parsers.get(format.toUpperCase()); + + if (!(obj.getParser() instanceof GeneralMolecularDataParser)) { + throw new Exception("Parser for a format " + format + " is not an instanceof " + GeneralMolecularDataParser.class.getCanonicalName()); + } + + GeneralMolecularDataParser parser = null; + try { + parser = (GeneralMolecularDataParser) obj.newParserInstance(); + } catch (Exception ex) { + throw new Exception("Cannot get a new instance of " + obj.getClass().getCanonicalName() + " : " + ex.getMessage()); + } + + if (parser == null) { + throw new Exception("Uanble to get a new instance of " + obj.getClass().getCanonicalName()); + } + + //try { + // parser = (GeneralMolecularDataParser) obj; + //} catch (Exception ex) { + // throw new Exception("Cannot cast " + obj.getClass().getCanonicalName() + " to " + GeneralMolecularDataParser.class.getCanonicalName() + " : " + ex.getMessage()); + //} + return parser; + } + + public void parseMolecularData(GeneralMolecularDataParser parser, BufferedReader in) throws Exception { + parser.parseData(in); + parserObject = parser; + molecules.addAll(parser.getMolecules()); + } + + public void parseMolecularData(GeneralMolecularDataParser parser, String filename) throws Exception { + parser.parseData(filename); + parserObject = parser; + molecules.addAll(parser.getMolecules()); + } + + String chooseFileDialog(GeneralMolecularDataParser parser) { + if (chooser == null) { + chooser = new JFileChooser(); + chooser.setDialogTitle("Open File"); + } + filter = new FileFilterImpl(); + String extensions = parser.getExtensions(); + String temp[] = extensions.split(";"); + for (int i = 0; i < temp.length; i++) { + filter.addExtension(temp[i]); + } + filter.setDescription(parser.getDescription()); + chooser.setFileFilter(filter); + chooser.setDialogType(JFileChooser.OPEN_DIALOG); + + currentWorkingDirectory = GlobalSettings.getCurrentWorkingDirectory(); + if (currentWorkingDirectory != null) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } else if (prefs != null) { + String lastPWD = prefs.get(GlobalSettings.lastPWDKey, ""); + if (lastPWD.length() > 0) { + currentWorkingDirectory = new File(lastPWD); + if (currentWorkingDirectory.isDirectory() && currentWorkingDirectory.exists()) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } + } + } + + int returnVal = chooser.showOpenDialog(parent); + + if (returnVal == JFileChooser.APPROVE_OPTION) { + String fileName = chooser.getSelectedFile().getPath(); + currentWorkingDirectory = chooser.getCurrentDirectory(); + GlobalSettings.setCurrentWorkingDirectory(currentWorkingDirectory); + if (prefs != null) { + try { + prefs.put(GlobalSettings.lastPWDKey, currentWorkingDirectory.getAbsolutePath()); + } catch (Exception ex) { + System.err.println("Cannot save cwd: " + ex.getMessage() + " Ignored..."); + } + } + logger.info("You chose to open this file: " + fileName); + return fileName; + } + return null; + } + + public boolean isUseOpenFileDialog() { + return useOpenFileDialog; + } + + public void setUseOpenFileDialog(boolean useOpenFileDialog) { + this.useOpenFileDialog = useOpenFileDialog; + } + + public Component getParent() { + return parent; + } + + public void setParent(Component parent) { + this.parent = parent; + } + + public MoleculeInterface getMolecule() { + return molecules.get(0); + } + + public int getNumberMolecules() { + return molecules.size(); + } + + public Object getParserObject() { + return parserObject; + } + + public static void main(String[] args) { + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setMultiSelectionEnabled(false); + fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); + int result = fileChooser.showOpenDialog(null); + + if (result != JFileChooser.APPROVE_OPTION) { + return; + } + + //File[] files = fileChooser.getSelectedFiles(); + File file = fileChooser.getSelectedFile(); + if (file == null) { + System.err.println("No files selected"); + return; + } + + System.out.println("Selected file: " + file.getAbsolutePath()); + + //System.out.println(files.length + " files selected"); + //FilesComparator fc = new FilesComparator(); + //Arrays.sort(files, fc); + // + File currentDir = fileChooser.getCurrentDirectory(); + System.out.println("Current working directory: " + currentDir.getAbsolutePath()); + System.setProperty("user.dir", fileChooser.getCurrentDirectory().getAbsolutePath()); + + // --- + MoleculeInterface mol = new Molecule(); + MolecularDataWizard mdw = new MolecularDataWizard(mol); + try { + mdw.parseMolecularData(file); + } catch (Exception ex) { + Logger.getLogger(MolecularDataWizard.class.getName()).log(Level.SEVERE, null, ex); + } + } +} diff --git a/src/main/java/cct/modelling/MolecularEditor.java b/src/main/java/cct/modelling/MolecularEditor.java new file mode 100644 index 0000000..52cfee8 --- /dev/null +++ b/src/main/java/cct/modelling/MolecularEditor.java @@ -0,0 +1,213 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.modelling; + +import java.util.List; +import java.util.Set; +import java.util.logging.Logger; + +import javax.swing.JFrame; +import javax.swing.JOptionPane; + +import cct.amber.Sander8JobControl; +import cct.awtdialogs.ConnectSQLServer; +import cct.database.ChemistryDatabaseDialog; +import cct.database.SQLChemistryDatabase; +import cct.database.SQLDatabaseAccess; +import cct.database.new_ChemistryDatabaseDialog; +import cct.database.new_SQLChemistryDatabase; +import cct.dialogs.AtomSelectionDialog; +import cct.dialogs.JModifyTorsionDialog; +import cct.gaussian.Gaussian; +import cct.interfaces.HelperInterface; +import cct.interfaces.MoleculeInterface; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public abstract class MolecularEditor + implements OperationsOnAtoms { + + private HelperInterface helper = null; + protected MoleculeInterface molecule = null; + public Gaussian gaussianData = null; + public Sander8JobControl Sander_8_Controls = null; + public SQLDatabaseAccess databaseAccess = null; + public ConnectSQLServer sqlServerDialog = null; + protected boolean connectedToDB = false; + public SQLChemistryDatabase sqlChemistryDatabase = null; + public ChemistryDatabaseDialog chemistryDatabase = null; + protected AtomSelectionDialog jAtomSelectionDialog = null; + public JModifyTorsionDialog jModifyTorsionDialog = null; + public new_SQLChemistryDatabase new_sqlChemistryDatabase = null; + public new_ChemistryDatabaseDialog new_chemistryDatabase = null; + protected boolean HighlighSelectedAtoms = true; + //protected int selectionType = SELECT_ATOMS; + protected SELECTION_TYPE selectionType = SELECTION_TYPE.ATOMS; + //protected int selectionRule = RULE_UNION; + protected SELECTION_RULE selectionRule = SELECTION_RULE.UNION; + protected int processingSelected = SELECTED_NOTHING; + public int selectedMode = SELECTION_UNLIMITED; + public boolean selectAndProcessDialog = false; + static final Logger logger = Logger.getLogger(MolecularEditor.class.getCanonicalName()); + + // --- Abstract Functions + public abstract void cancelSelection(); + + public abstract void changeAngleBetweenSelectedAtoms(float new_angle, + int I_atom_status, + int J_atom_status, + int K_atom_status); + + public abstract void changeDihedralForSelectedAtoms(float new_angle, + int I_atom_status, + int L_atom_status); + + public abstract void clearSelection(); + + public abstract void confirmChanges(); + + public abstract void enableMousePicking(boolean enable); + + public abstract void endProcessingSelectedAtoms(); + + public abstract Set getAtomNamesInMolecule(); + + public abstract Set getElementsInMolecule(); + + public abstract boolean getMousePickingStatus(); + + public abstract void invertSelection(); + + public abstract void makeMonomersSelection(int monomers[]); + + public abstract void makeMonomersSelection(Object monomers[]); + + public abstract void makeSelection(boolean selectedAtoms[]); + + public abstract void makeSelection(Object elements[], Object atom_names[]); + + public abstract void processSelectedAtoms(); + + public abstract void resetGeometry(); + + public abstract void selectAll(); + + public abstract void undoLastSelection(); + + public abstract void highlighSelectedAtoms(boolean enable); + + // --- Real function + /** + * + * @return int + */ + public int getJobType() { + return this.processingSelected; + } + + public void setHelper(HelperInterface h) { + helper = h; + } + + public void setJobType(int type) { + processingSelected = type; + } + + public SELECTION_TYPE getSelectionType() { + return selectionType; + } + + public List getMolecularSubstructure() { + return molecule.getMolecularSubstructure(); + } + + public Set getUniqueMonomersInMolecule() { + //return molecule.getUniqueMonomersInMolecule(); + return Molecule.getUniqueMonomersInMolecule(molecule); + } + + /* + * @Deprecated public void openAtomSelectionDialog(Frame owner, int jobType) { + * + * // --- Common for all selections + * + * if (molecule == null) { JOptionPane.showMessageDialog(owner, "Load Molecule first!", "Warning", JOptionPane.WARNING_MESSAGE); + * return; } + * + * if (getMousePickingStatus()) { JOptionPane.showMessageDialog(owner, "Another Selection is already in progress!", "Error", + * JOptionPane.ERROR_MESSAGE); return; } + * + * if (jAtomSelectionDialog == null) { jAtomSelectionDialog = new AtomSelectionDialog(owner, "Atom Selection", false); + * jAtomSelectionDialog.setTargetClass(this); jAtomSelectionDialog.setLocationRelativeTo(owner); if (helper != null) { JButton h = + * jAtomSelectionDialog.getHelpButton(); h.setEnabled(true); helper.setHelpIDString(h, HelperInterface.JMD_SELECT_ATOMS_ID); + * helper.displayHelpFromSourceActionListener(h); } } enableMousePicking(true); selectedMode = SELECTION_UNLIMITED; + * processingSelected = jobType; selectAndProcessDialog = false; jAtomSelectionDialog.setVisible(true); } + */ + public void setSelectionType(SELECTION_TYPE type) { + //if (type != SELECT_ATOMS && type != SELECT_MONOMERS && type != SELECT_MOLECULES) { + // JOptionPane.showMessageDialog(new JFrame(), "INTERNAL ERROR: setSelectionType: wrong selection type!", + // "Error", JOptionPane.ERROR_MESSAGE); + // logger.info("INTERNAL ERROR: setSelectionType: wrong selection type!"); + // return; + //} + + selectionType = type; + } + + public void setSelectionRule(SELECTION_RULE type) { + //if (type != RULE_UNION && type != RULE_DIFFERENCE && type != RULE_INTERSECTION) { + // JOptionPane.showMessageDialog(new JFrame(), + // "INTERNAL ERROR: setSelectionRule: wrong selection rule!", + // "Error", JOptionPane.ERROR_MESSAGE); + // logger.info("INTERNAL ERROR: setSelectionRule: wrong selection rule!"); + // return; + + //} + + selectionRule = type; + } +} diff --git a/src/main/java/cct/modelling/MolecularEnergy.java b/src/main/java/cct/modelling/MolecularEnergy.java new file mode 100644 index 0000000..8d86118 --- /dev/null +++ b/src/main/java/cct/modelling/MolecularEnergy.java @@ -0,0 +1,469 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.modelling; + +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.math.MinimizedFunctionInterface; +import cct.vecmath.Point3f; +import java.util.List; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class MolecularEnergy + implements MinimizedFunctionInterface { + + static final public int SFF_PARAMETERS = 0; + static final Logger logger = Logger.getLogger(MolecularEnergy.class.getCanonicalName()); + protected boolean gradAllocated = false; + protected FFMolecule ffMolecule = null; + protected Point3f[] Gradients = null; + protected int dynamicAtoms = 0; + protected double totalEnergy = 0; + protected double bondStretchEnergy = 0; + protected double angleBendEnergy = 0; + protected double torsionEnergy = 0; + protected double nonbond_1_4_Energy = 0; + protected double nonbondEnergy = 0; + protected double surfaceAtomEnergy = 0; + protected boolean calculateBondStretchEnergy = true; + protected boolean calculateAngleBendEnergy = true; + protected boolean calculateTorsionEnergy = true; + protected boolean calculate14Energy = true; + protected boolean calculateNonbondEnergy = true; + protected boolean calculateAtomSurfaceEnergy = true; + boolean numericalGradients = false; + // Related to the MinimizedFunctionInterface interface + protected int indexes[][] = null; + + public MolecularEnergy(FFMolecule ffmol) { + ffMolecule = ffmol; + gradAllocated = false; + Point3f Gradients = null; + } + + public void enableNumericalGradients(boolean enable) { + numericalGradients = enable; + } + + public void enableBondStretchEnergy(boolean enable) { + calculateBondStretchEnergy = enable; + } + + public void enableAngleBendEnergy(boolean enable) { + calculateAngleBendEnergy = enable; + } + + public void enableTorsionEnergy(boolean enable) { + calculateTorsionEnergy = enable; + } + + public void enable14Energy(boolean enable) { + calculate14Energy = enable; + } + + public void enable1NonbondEnergy(boolean enable) { + calculateNonbondEnergy = enable; + } + + public Point3f[] getGradients() { + return Gradients; + } + + public void setIndexes(int[][] ind) { + indexes = ind; + } + + public double calculateEnergy(boolean andGrads) throws Exception { + + if (ffMolecule == null || ffMolecule.getMolecule() == null) { + throw new Exception("calculateEnergy: ffMolecule == null || ffMolecule.getMolecule() == null"); + } + + totalEnergy = 0; + + MoleculeInterface molec = ffMolecule.getMolecule(); + + // --- Allocate gradients (only once) + + if (andGrads && (!gradAllocated)) { + dynamicAtoms = 0; + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface atom = molec.getAtomInterface(i); + if (atom.isDynamic()) { + ++dynamicAtoms; + } + } + + if (dynamicAtoms < 1) { + throw new Exception("calculateEnergy: no dynamic atoms in molecule"); + } + + /* + * Gradients = new Point3f[dynamicAtoms]; for (int i = 0; i < dynamicAtoms; i++) { Gradients[i] = new Point3f(0, 0, 0); } + */ + + Gradients = new Point3f[molec.getNumberOfAtoms()]; + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + Gradients[i] = new Point3f(0, 0, 0); + } + + } + + // --- Clear up gradients (if needed) + + if (andGrads) { + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + Gradients[i].setXYZ(0, 0, 0); + } + } + + // --- Start to calculate energy (and gradients) + + // --- Bond stretch energy + bondStretchEnergy = 0; + if (calculateBondStretchEnergy) { + Object BondStretchInteractions[] = ffMolecule.getBondStretchInteractions(); + if (andGrads) { + bondStretchEnergy = + BondStretchEnergy.bondStretchEnergy(molec, + BondStretchInteractions, + Gradients); + } else { + bondStretchEnergy = + BondStretchEnergy.bondStretchEnergy(molec, + BondStretchInteractions); + } + + totalEnergy += bondStretchEnergy; + } + + // --- Angle bend energy + + angleBendEnergy = 0; + if (calculateAngleBendEnergy) { + Object AngleBendInteractions[] = ffMolecule.getAngleBendInteractions(); + if (andGrads) { + angleBendEnergy = + AngleBendEnergy.angleBendEnergy(molec, + AngleBendInteractions, + Gradients); + } else { + angleBendEnergy = + AngleBendEnergy.angleBendEnergy(molec, + AngleBendInteractions); + } + totalEnergy += angleBendEnergy; + } + + // --- Torsion energy + + torsionEnergy = 0; + if (calculateTorsionEnergy && ffMolecule.getTorsionInteractions() != null) { + if (andGrads) { + torsionEnergy = + TorsionEnergy.TorsionEnergy(molec, + ffMolecule.getTorsionInteractions(), + Gradients); + } else { + torsionEnergy = + TorsionEnergy.TorsionEnergy(molec, + ffMolecule.getTorsionInteractions()); + } + + totalEnergy += torsionEnergy; + } + + // --- 1-4 Nonbonded energy + + nonbond_1_4_Energy = 0; + if (calculate14Energy && ffMolecule.isCalculate14() + && ffMolecule.get14Interactions() != null) { + + if (andGrads) { + nonbond_1_4_Energy = NonbondedEnergy.LennardJonesEnergy(ffMolecule.getMolecule(), ffMolecule.get14Interactions(), ffMolecule.SCNB, + Gradients); + } else { + nonbond_1_4_Energy = NonbondedEnergy.LennardJonesEnergy(ffMolecule.getMolecule(), ffMolecule.get14Interactions(), ffMolecule.SCNB); + } + } + totalEnergy += nonbond_1_4_Energy; + + // --- Nonbonded energy + + nonbondEnergy = 0; + if (calculateNonbondEnergy && ffMolecule.getNonbondInteractions() != null) { + if (andGrads) { + nonbondEnergy = NonbondedEnergy.LennardJonesEnergy(ffMolecule.getMolecule(), ffMolecule.getNonbondInteractions(), 1.0, + Gradients); + } else { + nonbondEnergy = NonbondedEnergy.LennardJonesEnergy(ffMolecule.getMolecule(), ffMolecule.getNonbondInteractions(), 1.0); + } + } + totalEnergy += nonbondEnergy; + + // --- Atom-Surface Energy + + surfaceAtomEnergy = 0; + List surfaces = ffMolecule.getSurfaces(); + if (calculateAtomSurfaceEnergy && surfaces != null && surfaces.size() > 0) { + if (andGrads) { + surfaceAtomEnergy = NonbondedEnergy.LennardJonesSurfaceEnergy(ffMolecule.getMolecule(), surfaces, Gradients); + } else { + surfaceAtomEnergy = NonbondedEnergy.LennardJonesSurfaceEnergy(ffMolecule.getMolecule(), surfaces); + } + totalEnergy += surfaceAtomEnergy; + } + + return totalEnergy; + } + + public void printEnergyDecomposition() { + System.out.println("\nEnergy Decomposition:"); + /* + * printf("\n BOND ENERGY: %12.4lf",energy12); printf("\n ANGLE ENERGY: %12.4lf",energy13); printf("\n TORSION ENERGY: + * %12.4lf",etor); printf("\n IMPROPER TORSION ENERGY: %12.4lf",eimptor); if ( N_dist_constr ) printf("\n CONSTRAIN DISTANCE + * ENERGY: %12.4lf",DistConstrEnergy); if ( N_Space_Constr ) printf("\n SPACE CONSTRAIN ENERGY: %12.4lf",SpaceConstr_Energy); if + * ( N_TorsConstr) printf("\n CONSTRAIN TORSION ENERGY: %12.4lf",TorsConstrEnergy); if ( N_Range_Constr ) printf("\n RANGE + * CONSTRAIN ENERGY: %12.4lf",RangeConstr_Energy); printf("\n"); printf("\n NB VDW ENERGY: %12.4lf",vdw15); printf("\n NB EL/ST + * ENERGY: %12.4lf",elec15); printf("\n 1-4 NB VDW ENERGY: %12.4lf",vdw14); printf("\n 1-4 NB EL/ST ENERGY: %12.4lf",elec14); + * + */ + + if (calculateBondStretchEnergy) { + System.out.println(String.format( + " Bond Energy: %12.4f", + bondStretchEnergy)); + } + if (calculateAngleBendEnergy) { + System.out.println(String.format( + " Angle Energy: %12.4f", angleBendEnergy)); + } + + if (calculateTorsionEnergy) { + System.out.println(String.format( + " Torsion Energy: %12.4f", torsionEnergy)); + } + + if (ffMolecule.isCalculate14()) { + System.out.println(String.format( + " 1-4 NB VDW ENERGY: %12.4f", nonbond_1_4_Energy)); + } + + System.out.println(String.format( + " NB VDW ENERGY: %12.4f", nonbondEnergy)); + + + if (calculateAtomSurfaceEnergy) { + System.out.println(String.format( + " SURFACE ENERGY: %12.4f", this.surfaceAtomEnergy)); + } + +// --- And now the total energy + for (int i = 0; i < 8; i++) { + System.out.print("--------"); + } + System.out.print("\n"); + System.out.println(String.format( + "\n Total Energy: %12.4f", totalEnergy)); + + Object obj[] = ffMolecule.BondStretchInteractions; + BondStretchPairs bp = (BondStretchPairs) obj[1]; + BondStretchEnergy.HarmonicStretchEnergyAnalysis(ffMolecule.getMolecule(), + bp, 10); + + obj = ffMolecule.AngleBendInteractions; + AngleBendsArray at = (AngleBendsArray) obj[1]; + AngleBendEnergy.HarmonicBendEnergyAnalysis(ffMolecule.getMolecule(), at, + 10); + + } + + // --- Implementation of MinimizedFunctionInterface interface + @Override + public double function(int n, double[] X, double[] Grads) { + return 0; + } + + @Override + public float function(int n, float[] X, float[] Grads) { + + float energy = 0; + try { + // --- Numerical gradients + if (numericalGradients) { + float delta = 0.0001f; + energy = (float) calculateEnergy(false); + for (int i = 0; i < n; i++) { + float store = X[i]; + X[i] += delta; + setupCoordinates(n, X); + float energyDelta = (float) calculateEnergy(false); + Grads[i] = (energyDelta - energy) / delta; + if (energyDelta < energy) { + energy = energyDelta; + } else { + X[i] = store; + } + } + } // --- Analytical gradients + else { + energy = (float) calculateEnergy(true); + setupGradinents(n, Grads); + } + } catch (Exception ex) { + System.err.println(ex.getMessage()); + } + + return energy; + } + + @Override + public double function(int n, double[] X) { + return 0; + } + + @Override + public float function(int n, float[] X) { + + setupCoordinates(n, X); + float energy = 0; + try { + energy = (float) calculateEnergy(false); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + } + logger.info("function= " + energy); + return energy; + } + + void setupCoordinates(int n, float[] X) { + MoleculeInterface molec = ffMolecule.getMolecule(); + for (int i = 0; i < n; i++) { + int at_n = indexes[i][0]; + int var = indexes[i][1]; + + AtomInterface atom = molec.getAtomInterface(at_n); + switch (var) { + case 0: + atom.setX(X[i]); + break; + case 1: + atom.setY(X[i]); + break; + case 2: + atom.setZ(X[i]); + break; + } + } + } + + public float[][] getCoordinates(int n, float[] X) { + + MoleculeInterface molec = ffMolecule.getMolecule(); + float[][] coords = new float[molec.getNumberOfAtoms()][3]; + + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface atom = molec.getAtomInterface(i); + coords[i][0] = atom.getX(); + coords[i][1] = atom.getY(); + coords[i][2] = atom.getZ(); + } + + for (int i = 0; i < n; i++) { + int at_n = indexes[i][0]; + int var = indexes[i][1]; + + AtomInterface atom = molec.getAtomInterface(at_n); + switch (var) { + case 0: + coords[i][0] = X[i]; + break; + case 1: + coords[i][1] = X[i]; + break; + case 2: + coords[i][2] = X[i]; + break; + } + } + + return coords; + } + + void setupGradinents(int n, float[] Grads) { + MoleculeInterface molec = ffMolecule.getMolecule(); + for (int i = 0; i < n; i++) { + int at_n = indexes[i][0]; + int var = indexes[i][1]; + + AtomInterface atom = molec.getAtomInterface(at_n); + switch (var) { + case 0: + Grads[i] = Gradients[at_n].getX(); + break; + case 1: + Grads[i] = Gradients[at_n].getY(); + break; + case 2: + Grads[i] = Gradients[at_n].getZ(); + break; + } + } + + } + + public boolean isCalculateAtomSurfaceEnergy() { + return calculateAtomSurfaceEnergy; + } + + public void setCalculateAtomSurfaceEnergy(boolean calculateAtomSurfaceEnergy) { + this.calculateAtomSurfaceEnergy = calculateAtomSurfaceEnergy; + } +} diff --git a/src/main/java/cct/modelling/MolecularFileFormats.java b/src/main/java/cct/modelling/MolecularFileFormats.java new file mode 100644 index 0000000..9e8d8cb --- /dev/null +++ b/src/main/java/cct/modelling/MolecularFileFormats.java @@ -0,0 +1,601 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.modelling; + +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +import cct.tools.FileFilterImpl; +import java.util.HashMap; +import java.util.Properties; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class MolecularFileFormats { + + public static final String extension_All_Formats = "*"; + public static final String extension_ADF_Input = "in;inp;dat;run"; + public static final String extension_ADF_Output = "out;log"; + public static final String extension_G03_GJF = "gjf;com;inp;dat;in;g03"; + public static final String extension_G03_Output = "log;out"; + public static final String extension_G03_Cube = "cub;cube"; + public static final String extension_G03_Fragment = "frg"; + public static final String extension_G03_Trajectory = "trj;7;log;out"; + public static final String extension_G03_FormCheckpoint = "fchk;fch"; + public static final String extension_GAMESS_Input = "inp"; + public static final String extension_GAMESS_Output = "out;log"; + public static final String extension_MOPAC_Input = "dat;inp;mop"; + public static final String extension_MOPAC_Output = "out"; + public static final String extension_MOPAC_Log = "log"; + public static final String extension_PDB = "pdb;ent;Z"; + public static final String extension_Geom = "gf"; + public static final String extension_VRML = "wrl"; + public static final String extension_Mol2 = "mol2"; + public static final String extension_CCT = "cct"; + public static final String extension_XMol_XYZ = "xyz"; + public static final String extension_MDL_Molfile = "mol"; + public static final String extension_GRO = "gro"; + public static final String extension_Prmtop = "top;prmtop"; + public static final String extension_Prep = "in;prepin;prep"; + public static final String extension_AmberLib = "off;lib"; + public static final String extension_Ambercrd = "crd;rst;inpcrd"; + public static final String extension_AmberTraj = "crd;rst;mdcrd"; + public static final String extension_Povray = "pov"; + public static final String extension_VASP_POSCAR = "dat;inp;poscar"; + public static final String extension_VASP_Vasprun = "xml"; + public static final String extension_QChem_Input = "in"; + public static final String extension_QChem_Output = "out;log"; + public static final String extension_GULP_Input = "in;inp;gin;grs"; + public static final String extension_GULP_Trajectory = "trg;trj"; + public static final String extension_SIESTA_Input = "fdf;dat;inp;in"; + public static final String extension_CPMD_Output = "out"; + public static final String extension_CPMD_Trajectory = "xyz"; + public static final String allFormats = "All Chemistry Format Files"; + public static final String adfInput = "ADF Input"; + public static final String adfOutput = "ADF Output"; + public static final String gaussian03GJF = "Gaussian G03 Input"; + public static final String gaussian03Output = "Gaussian G03 Output"; + public static final String gaussian03Cube = "Geometry from G03 cube"; + public static final String gaussianFragment = "Gaussian G03 Fragment"; + public static final String gaussianTrajectory = "Gaussian G03 Trajectory"; + public static final String gaussianFormCheckpoint = "Gaussian G03 Formatted Checkpoint"; + public static final String gamessInput = "GAMESS Input"; + public static final String gamessOutput = "GAMESS Output"; + public static final String geomFormat = "Geom Format File"; + public static final String vrmlFormat = "VRML Format File"; + public static final String mopacInput = "Mopac Input File"; + public static final String mopacLog = "Mopac2002 Log File"; + public static final String mopacOutput = "Mopac Output File"; + public static final String pdbFile = "PDB"; + public static final String triposMol2 = "Tripos Mol2"; + public static final String cctFileFormat = "CCT File"; + public static final String xmolXYZFileFormat = "XMol XYZ File"; + public static final String mdlMolfileFormat = "MDL Molfile File"; + public static final String gromacsGROFormat = "Gromacs coordinate file"; + public static final String amberPrmtopFormat = "Amber prmtop file"; + public static final String amberPrepFormat = "Amber PREP file"; + public static final String amberLibFormat = "Amber Lib file"; + public static final String amberCoordFormat = "Amber coordinate/restart file"; + public static final String amberMdcrdFormat = "Amber trajectory file"; + public static final String povrayFormat = "Povray file"; + public static final String vaspPoscarFormat = "VASP Poscar file"; + public static final String vaspVasprunFormat = "VASP Vasprun file"; + public static final String qchemFormat = "QChem Input file"; + public static final String qchemOutputFormat = "QChem Output file"; + public static final String gulpInputFormat = "GULP Input file"; + public static final String gulpTrajectoryFormat = "GULP Trajectory file"; + public static final String siestaInputFormat = "SIESTA Input file (in development)"; + public static final String CPMDOutputFormat = "CPMD Output file (in development)"; + public static final String CPMDTrajectoryFormat = "CPMD MD Trajectory file (in development)"; + public static final int formatUnknown = 0; + public static final int formatG03_GJF = 1; + public static final int formatG03_Output = 2; + public static final int formatPDB = 3; + public static final int formatTripos_Mol2 = 4; + public static final int formatCCT = 5; + public static final int formatG03_Fragment = 6; + public static final int format_XMol_XYZ = 7; + public static final int format_MDL_Molfile = 8; + public static final int format_GRO = 9; + public static final int format_Prmtop = 10; + public static final int format_AmberCrd = 11; + public static final int format_GAMESS_Input = 12; + public static final int formatG03_Cube = 13; + public static final int format_GAMESS_Output = 14; + public static final int format_MOPAC_Log = 15; + public static final int format_MOPAC_Output = 16; + public static final int format_Povray = 17; + public static final int format_VASP_Poscar = 18; + public static final int format_QChem_Input = 19; + public static final int format_QChem_Output = 20; + public static final int format_MOPAC_Input = 21; + public static final int format_ADF_Input = 22; + public static final int format_G03_Trajectory = 23; + public static final int format_GULP_Input = 24; + public static final int format_GULP_Trajectory = 25; + public static final int format_VASP_Vasprun = 26; + public static final int format_ADF_Output = 27; + public static final int format_SIESTA_Input = 28; + public static final int format_G03_FormCheckpoint = 29; + public static final int format_CPMD_Output = 30; + public static final int format_CPMD_Trajectory = 31; + private static Map openFileExtensions = new LinkedHashMap(); + private static Map openFileFormats = new LinkedHashMap(); + public static final Map readFormats = new LinkedHashMap(); + public static final Map remoteReadFormats = new LinkedHashMap(); + public static final Map commonReadFormats = new LinkedHashMap(); + public static final Map remoteReadFormatDescription = new LinkedHashMap(); + private static Map commonFileFormatDescription = new HashMap(); + static final Map readFormatsTypes = new LinkedHashMap(); + static final Map saveFormats = new LinkedHashMap(); + static final Map updateCoordFormats = new LinkedHashMap(); + protected static final Map trajectoryReadFormats = new LinkedHashMap(); + protected static final Map trajectoryReadFormatDescription = new LinkedHashMap(); + // --- General case - all Molecular file formats + public static final String allMolecularFormats = "Molecular File Formats"; + public static final String allMolecularExtensions = + "gjf;log;out;pdb;ent;mol2;cct;mol"; + + static { + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.G03_GJF, extension_G03_GJF); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.G03_OUTPUT, extension_G03_Output); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.G03_CUBE, extension_G03_Cube); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.G03_FRAGMENT, extension_G03_Fragment); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.G03_TRAJECTORY, extension_G03_Trajectory); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.G03_FORM_CHECKPOINT, extension_G03_FormCheckpoint); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.GAMESS_INPUT, extension_GAMESS_Input); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.GAMESS_OUTPUT, extension_GAMESS_Output); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.MOPAC_INPUT, extension_MOPAC_Input); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.MOPAC_OUTPUT, extension_MOPAC_Output); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.MOPAC2002_LOG, extension_MOPAC_Log); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.ADF_INPUT, extension_ADF_Input); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.ADF_OUTPUT, extension_ADF_Output); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.PDB, extension_PDB); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.MOL2, extension_Mol2); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.CCT, extension_CCT); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.XMOL_XYZ, extension_XMol_XYZ); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.MDL_MOLFILE, extension_MDL_Molfile); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.GROMACS_GRO, extension_GRO); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.AMBER_PRMTOP, extension_Prmtop); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.AMBER_PREP, extension_Prep); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.AMBER_LIB, extension_AmberLib); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.SIESTA_INPUT, extension_SIESTA_Input); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.VASP_POSCAR, extension_VASP_POSCAR); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.VASP_VASPRUN, extension_VASP_Vasprun); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.QCHEM_INPUT, extension_QChem_Input); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.QCHEM_OUTPUT, extension_QChem_Output); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.GULP_INPUT, extension_GULP_Input); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.CPMD_OUTPUT, extension_CPMD_Output); + openFileExtensions.put(CHEMISTRY_FILE_FORMAT.CPMD_TRAJECTORY, extension_CPMD_Trajectory); + + + openFileFormats.put(CHEMISTRY_FILE_FORMAT.G03_GJF, extension_G03_GJF); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.G03_OUTPUT, extension_G03_Output); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.G03_CUBE, extension_G03_Cube); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.G03_FRAGMENT, extension_G03_Fragment); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.G03_TRAJECTORY, extension_G03_Trajectory); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.G03_FORM_CHECKPOINT, extension_G03_FormCheckpoint); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.GAMESS_INPUT, extension_GAMESS_Input); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.GAMESS_OUTPUT, extension_GAMESS_Output); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.MOPAC_INPUT, extension_MOPAC_Input); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.MOPAC_OUTPUT, extension_MOPAC_Output); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.MOPAC2002_LOG, extension_MOPAC_Log); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.ADF_INPUT, extension_ADF_Input); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.ADF_OUTPUT, extension_ADF_Output); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.PDB, extension_PDB); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.MOL2, extension_Mol2); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.CCT, extension_CCT); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.XMOL_XYZ, extension_XMol_XYZ); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.MDL_MOLFILE, extension_MDL_Molfile); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.GROMACS_GRO, extension_GRO); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.AMBER_PRMTOP, extension_Prmtop); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.AMBER_PREP, extension_Prep); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.AMBER_LIB, extension_AmberLib); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.SIESTA_INPUT, extension_SIESTA_Input); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.VASP_POSCAR, extension_VASP_POSCAR); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.VASP_VASPRUN, extension_VASP_Vasprun); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.QCHEM_INPUT, extension_QChem_Input); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.QCHEM_OUTPUT, extension_QChem_Output); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.GULP_INPUT, extension_GULP_Input); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.CPMD_OUTPUT, extension_CPMD_Output); + openFileFormats.put(CHEMISTRY_FILE_FORMAT.CPMD_TRAJECTORY, extension_CPMD_Trajectory); + } + + static { + readFormats.put(gaussian03GJF, extension_G03_GJF); + readFormats.put(gaussian03Output, extension_G03_Output); + readFormats.put(gaussian03Cube, extension_G03_Cube); + readFormats.put(gaussianFragment, extension_G03_Fragment); + readFormats.put(gaussianTrajectory, extension_G03_Trajectory); + readFormats.put(gaussianFormCheckpoint, extension_G03_FormCheckpoint); + readFormats.put(gamessInput, extension_GAMESS_Input); + readFormats.put(gamessOutput, extension_GAMESS_Output); + readFormats.put(mopacInput, extension_MOPAC_Input); + readFormats.put(mopacOutput, extension_MOPAC_Output); + readFormats.put(mopacLog, extension_MOPAC_Log); + readFormats.put(adfInput, extension_ADF_Input); + readFormats.put(adfOutput, extension_ADF_Output); + readFormats.put(pdbFile, extension_PDB); + readFormats.put(triposMol2, extension_Mol2); + readFormats.put(cctFileFormat, extension_CCT); + readFormats.put(xmolXYZFileFormat, extension_XMol_XYZ); + readFormats.put(mdlMolfileFormat, extension_MDL_Molfile); + readFormats.put(gromacsGROFormat, extension_GRO); + readFormats.put(amberPrmtopFormat, extension_Prmtop); + readFormats.put(amberPrepFormat, extension_Prep); + readFormats.put(amberLibFormat, extension_AmberLib); + readFormats.put(siestaInputFormat, extension_SIESTA_Input); + readFormats.put(vaspPoscarFormat, extension_VASP_POSCAR); + readFormats.put(vaspVasprunFormat, extension_VASP_Vasprun); + readFormats.put(qchemFormat, extension_QChem_Input); + readFormats.put(qchemOutputFormat, extension_QChem_Output); + readFormats.put(gulpInputFormat, extension_GULP_Input); + readFormats.put(CPMDOutputFormat, extension_CPMD_Output); + readFormats.put(CPMDTrajectoryFormat, extension_CPMD_Trajectory); + + //remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.ALL_FORMATS, extension_All_Formats); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.G03_GJF, extension_G03_GJF); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.G03_OUTPUT, extension_G03_Output); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.G03_CUBE, extension_G03_Cube); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.G03_TRAJECTORY, extension_G03_Trajectory); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.GAMESS_INPUT, extension_GAMESS_Input); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.GAMESS_OUTPUT, extension_GAMESS_Output); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.MOPAC_INPUT, extension_MOPAC_Input); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.MOPAC_OUTPUT, extension_MOPAC_Output); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.MOPAC2002_LOG, extension_MOPAC_Log); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.PDB, extension_PDB); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.MOL2, extension_Mol2); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.CCT, extension_CCT); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.XMOL_XYZ, extension_XMol_XYZ); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.MDL_MOLFILE, extension_MDL_Molfile); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.GROMACS_GRO, extension_GRO); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.QCHEM_INPUT, extension_QChem_Input); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.QCHEM_OUTPUT, extension_QChem_Output); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.GULP_INPUT, extension_GULP_Input); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.VASP_VASPRUN, extension_VASP_Vasprun); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.CPMD_OUTPUT, extension_CPMD_Output); + remoteReadFormats.put(CHEMISTRY_FILE_FORMAT.CPMD_TRAJECTORY, extension_CPMD_Trajectory); + + //remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.ALL_FORMATS, allFormats); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.G03_GJF, gaussian03GJF); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.G03_OUTPUT, gaussian03Output); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.G03_CUBE, gaussian03Cube); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.G03_TRAJECTORY, gaussianTrajectory); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.GAMESS_INPUT, gamessInput); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.GAMESS_OUTPUT, gamessOutput); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.MOPAC_INPUT, mopacInput); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.MOPAC_OUTPUT, mopacOutput); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.MOPAC2002_LOG, mopacLog); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.PDB, pdbFile); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.MOL2, triposMol2); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.CCT, cctFileFormat); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.XMOL_XYZ, xmolXYZFileFormat); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.MDL_MOLFILE, mdlMolfileFormat); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.GROMACS_GRO, gromacsGROFormat); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.QCHEM_INPUT, qchemFormat); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.QCHEM_OUTPUT, qchemOutputFormat); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.GULP_INPUT, gulpInputFormat); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.VASP_VASPRUN, vaspVasprunFormat); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.CPMD_OUTPUT, CPMDOutputFormat); + remoteReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.CPMD_TRAJECTORY, CPMDTrajectoryFormat); + + //commonReadFormats.put(CHEMISTRY_FILE_FORMAT.G03_GJF, extension_G03_GJF); + //commonReadFormats.put(CHEMISTRY_FILE_FORMAT.G03_OUTPUT, extension_G03_Output); + commonReadFormats.put(CHEMISTRY_FILE_FORMAT.G03_CUBE, extension_G03_Cube); + commonReadFormats.put(CHEMISTRY_FILE_FORMAT.G03_TRAJECTORY, extension_G03_Trajectory); + commonReadFormats.put(CHEMISTRY_FILE_FORMAT.GAMESS_INPUT, extension_GAMESS_Input); + commonReadFormats.put(CHEMISTRY_FILE_FORMAT.GAMESS_OUTPUT, extension_GAMESS_Output); + commonReadFormats.put(CHEMISTRY_FILE_FORMAT.MOPAC_INPUT, extension_MOPAC_Input); + commonReadFormats.put(CHEMISTRY_FILE_FORMAT.MOPAC_OUTPUT, extension_MOPAC_Output); + commonReadFormats.put(CHEMISTRY_FILE_FORMAT.MOPAC2002_LOG, extension_MOPAC_Log); + commonReadFormats.put(CHEMISTRY_FILE_FORMAT.PDB, extension_PDB); + commonReadFormats.put(CHEMISTRY_FILE_FORMAT.MOL2, extension_Mol2); + commonReadFormats.put(CHEMISTRY_FILE_FORMAT.CCT, extension_CCT); + commonReadFormats.put(CHEMISTRY_FILE_FORMAT.XMOL_XYZ, extension_XMol_XYZ); + commonReadFormats.put(CHEMISTRY_FILE_FORMAT.MDL_MOLFILE, extension_MDL_Molfile); + commonReadFormats.put(CHEMISTRY_FILE_FORMAT.GROMACS_GRO, extension_GRO); + commonReadFormats.put(CHEMISTRY_FILE_FORMAT.QCHEM_INPUT, extension_QChem_Input); + commonReadFormats.put(CHEMISTRY_FILE_FORMAT.QCHEM_OUTPUT, extension_QChem_Output); + commonReadFormats.put(CHEMISTRY_FILE_FORMAT.GULP_INPUT, extension_GULP_Input); + commonReadFormats.put(CHEMISTRY_FILE_FORMAT.CPMD_OUTPUT, extension_CPMD_Output); + commonReadFormats.put(CHEMISTRY_FILE_FORMAT.CPMD_TRAJECTORY, extension_CPMD_Trajectory); + + //commonReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.G03_GJF, gaussian03GJF); + //commonReadFormatDescription.put(CHEMISTRY_FILE_FORMAT.G03_OUTPUT, gaussian03Output); + commonFileFormatDescription.put(CHEMISTRY_FILE_FORMAT.G03_CUBE, gaussian03Cube); + commonFileFormatDescription.put(CHEMISTRY_FILE_FORMAT.G03_TRAJECTORY, gaussianTrajectory); + commonFileFormatDescription.put(CHEMISTRY_FILE_FORMAT.GAMESS_INPUT, gamessInput); + commonFileFormatDescription.put(CHEMISTRY_FILE_FORMAT.GAMESS_OUTPUT, gamessOutput); + commonFileFormatDescription.put(CHEMISTRY_FILE_FORMAT.MOPAC_INPUT, mopacInput); + commonFileFormatDescription.put(CHEMISTRY_FILE_FORMAT.MOPAC_OUTPUT, mopacOutput); + commonFileFormatDescription.put(CHEMISTRY_FILE_FORMAT.MOPAC2002_LOG, mopacLog); + commonFileFormatDescription.put(CHEMISTRY_FILE_FORMAT.PDB, pdbFile); + commonFileFormatDescription.put(CHEMISTRY_FILE_FORMAT.MOL2, triposMol2); + commonFileFormatDescription.put(CHEMISTRY_FILE_FORMAT.CCT, cctFileFormat); + commonFileFormatDescription.put(CHEMISTRY_FILE_FORMAT.XMOL_XYZ, xmolXYZFileFormat); + commonFileFormatDescription.put(CHEMISTRY_FILE_FORMAT.MDL_MOLFILE, mdlMolfileFormat); + commonFileFormatDescription.put(CHEMISTRY_FILE_FORMAT.GROMACS_GRO, gromacsGROFormat); + commonFileFormatDescription.put(CHEMISTRY_FILE_FORMAT.QCHEM_INPUT, qchemFormat); + commonFileFormatDescription.put(CHEMISTRY_FILE_FORMAT.QCHEM_OUTPUT, qchemOutputFormat); + commonFileFormatDescription.put(CHEMISTRY_FILE_FORMAT.GULP_INPUT, gulpInputFormat); + commonFileFormatDescription.put(CHEMISTRY_FILE_FORMAT.CPMD_OUTPUT, CPMDOutputFormat); + commonFileFormatDescription.put(CHEMISTRY_FILE_FORMAT.CPMD_TRAJECTORY, CPMDTrajectoryFormat); + + readFormatsTypes.put(adfInput, new Integer(format_ADF_Input)); + readFormatsTypes.put(adfOutput, new Integer(format_ADF_Output)); + readFormatsTypes.put(gaussian03GJF, new Integer(formatG03_GJF)); + readFormatsTypes.put(gaussian03Output, new Integer(formatG03_Output)); + readFormatsTypes.put(gaussian03Cube, new Integer(formatG03_Cube)); + readFormatsTypes.put(gaussianFragment, new Integer(formatG03_Fragment)); + readFormatsTypes.put(gaussianTrajectory, new Integer(format_G03_Trajectory)); + readFormatsTypes.put(gaussianFormCheckpoint, new Integer(format_G03_FormCheckpoint)); + readFormatsTypes.put(gamessInput, new Integer(format_GAMESS_Input)); + readFormatsTypes.put(gamessOutput, new Integer(format_GAMESS_Output)); + readFormatsTypes.put(mopacInput, new Integer(format_MOPAC_Input)); + readFormatsTypes.put(mopacOutput, new Integer(format_MOPAC_Output)); + readFormatsTypes.put(mopacLog, new Integer(format_MOPAC_Log)); + readFormatsTypes.put(pdbFile, new Integer(formatPDB)); + readFormatsTypes.put(triposMol2, new Integer(formatTripos_Mol2)); + readFormatsTypes.put(cctFileFormat, new Integer(formatCCT)); + readFormatsTypes.put(xmolXYZFileFormat, new Integer(format_XMol_XYZ)); + readFormatsTypes.put(mdlMolfileFormat, new Integer(format_MDL_Molfile)); + readFormatsTypes.put(gromacsGROFormat, new Integer(format_GRO)); + readFormatsTypes.put(amberPrmtopFormat, new Integer(format_Prmtop)); + readFormatsTypes.put(siestaInputFormat, new Integer(format_SIESTA_Input)); + readFormatsTypes.put(vaspPoscarFormat, new Integer(format_VASP_Poscar)); + readFormatsTypes.put(vaspVasprunFormat, new Integer(format_VASP_Vasprun)); + readFormatsTypes.put(qchemFormat, new Integer(format_QChem_Input)); + readFormatsTypes.put(qchemOutputFormat, new Integer(format_QChem_Output)); + readFormatsTypes.put(gulpInputFormat, new Integer(format_GULP_Input)); + readFormatsTypes.put(CPMDOutputFormat, new Integer(format_CPMD_Output)); + readFormatsTypes.put(CPMDTrajectoryFormat, new Integer(format_CPMD_Trajectory)); + + saveFormats.put(pdbFile, extension_PDB); + saveFormats.put(triposMol2, extension_Mol2); + saveFormats.put(xmolXYZFileFormat, extension_XMol_XYZ); + saveFormats.put(gaussian03GJF, extension_G03_GJF); + saveFormats.put(siestaInputFormat, extension_SIESTA_Input); + saveFormats.put(cctFileFormat, extension_CCT); + saveFormats.put(povrayFormat, extension_Povray); + saveFormats.put(geomFormat, extension_Geom); + saveFormats.put(vrmlFormat, extension_VRML); + + updateCoordFormats.put(amberCoordFormat, extension_Ambercrd); + updateCoordFormats.put(pdbFile, extension_PDB); + + // --- File descriptions for trajectory extensions + + trajectoryReadFormats.put(TRAJECTORY_FILE_FORMAT.AMBER, extension_AmberTraj); + trajectoryReadFormats.put(TRAJECTORY_FILE_FORMAT.G03_TRAJECTORY, extension_G03_Trajectory); + trajectoryReadFormats.put(TRAJECTORY_FILE_FORMAT.GULP_TRAJECTORY, extension_GULP_Trajectory); + + trajectoryReadFormatDescription.put(TRAJECTORY_FILE_FORMAT.AMBER, amberMdcrdFormat); + trajectoryReadFormatDescription.put(TRAJECTORY_FILE_FORMAT.G03_TRAJECTORY, gaussianTrajectory); + trajectoryReadFormatDescription.put(TRAJECTORY_FILE_FORMAT.GULP_TRAJECTORY, gulpTrajectoryFormat); + } + + private MolecularFileFormats() { + Properties cctProperties; + + } + + /** + * Currently very simple implementation for guessing molecular file format based on file extension + * @param fileName String + * @param Ext String + * @return int + */ + public static int guessMolecularFileFormat(String fileName, String Ext) { + + Set set = readFormats.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String description = me.getKey().toString(); + String ext = me.getValue().toString(); + + String temp[] = ext.split(";"); + for (int i = 0; i < temp.length; i++) { + if (Ext.equalsIgnoreCase(temp[i])) { + + if (!readFormatsTypes.containsKey(description)) { + System.err.println( + "INTERNAL ERROR: guessMolecularFileFormat: file type is not set" + + description); + return formatUnknown; + } + + Integer type = (Integer) readFormatsTypes.get(description); + return type.intValue(); + } + } + } + + if (extension_G03_GJF.contains(Ext)) { + return formatG03_GJF; + } else if (extension_G03_Output.contains(Ext)) { + return formatG03_Output; + } else if (extension_PDB.contains(Ext)) { + return formatPDB; + } else if (extension_Mol2.contains(Ext)) { + return formatTripos_Mol2; + } else if (extension_G03_Fragment.contains(Ext)) { + return formatG03_Fragment; + } else if (extension_CCT.contains(Ext)) { + return formatCCT; + } else if (extension_XMol_XYZ.contains(Ext)) { + return format_XMol_XYZ; + } else if (extension_MDL_Molfile.contains(Ext)) { + return format_MDL_Molfile; + } else if (extension_GRO.contains(Ext)) { + return format_GRO; + } else if (extension_Prmtop.contains(Ext)) { + return format_Prmtop; + } + + return formatUnknown; + } + + public static Map getUpdateCoordFormats() { + Map temp = new LinkedHashMap(updateCoordFormats); + return temp; + } + + @Deprecated + public static Map getReadCoordFormats() { + Map temp = new LinkedHashMap(readFormats); + //LinkedHashMap temp = (LinkedHashMap)readFormats.clone(); + return temp; + } + + public static Map getOpenFileFormats() { + Map temp = new LinkedHashMap(openFileExtensions); + //LinkedHashMap temp = (LinkedHashMap)readFormats.clone(); + return temp; + } + + public static Map getSaveCoordFormats() { + Map temp = new LinkedHashMap(saveFormats); + return temp; + } + + public static String getOpenFileExtensions(CHEMISTRY_FILE_FORMAT format) { + return openFileExtensions.get(format); + } + + public static String getFileFormatDescription(CHEMISTRY_FILE_FORMAT format) { + return commonFileFormatDescription.get(format); + } + + public static int getReadFileType(String description) { + if (readFormatsTypes.containsKey(description)) { + Integer type = (Integer) readFormatsTypes.get(description); + return type.intValue(); + } + return formatUnknown; + } + + public static Map getTrajectoryReadFormats() { + return new LinkedHashMap(trajectoryReadFormats); + } + + public static Map getTrajectoryReadFormatDescription() { + return new LinkedHashMap(trajectoryReadFormatDescription); + } + + public static FileFilterImpl[] formTrajectoryFileFilters() { + Map trReadFormats = MolecularFileFormats.getTrajectoryReadFormats(); + Map trReadFormatsDescr = MolecularFileFormats.getTrajectoryReadFormatDescription(); + int count = 0; + FileFilterImpl[] filter = new FileFilterImpl[trReadFormats.size()]; + + //filter[count] = new FileFilterImpl(); + //filter[count].setDescription("All files"); + //++count; + Set set = trReadFormats.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + TRAJECTORY_FILE_FORMAT format = (TRAJECTORY_FILE_FORMAT) me.getKey(); + String extensions = trReadFormats.get(format); + String temp[] = extensions.split(";"); + filter[count] = new FileFilterImpl(); + String descr = trReadFormatsDescr.get(format); + + for (int i = 0; i < temp.length; i++) { + if (i == 0) { + descr += " ("; + } else { + descr += ";"; + } + filter[count].addExtension(temp[i]); + descr += "*." + temp[i]; + if (i == temp.length - 1) { + descr += ")"; + } + } + filter[count].setDescription(descr); + ++count; + } + + return filter; + } + + public static Map formTrajectoryFileRef() { + Map trReadFormats = MolecularFileFormats.getTrajectoryReadFormats(); + Map trReadFormatsDescr = MolecularFileFormats.getTrajectoryReadFormatDescription(); + + Map reference = new LinkedHashMap(trReadFormats.size()); + + Set set = trReadFormats.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + TRAJECTORY_FILE_FORMAT format = (TRAJECTORY_FILE_FORMAT) me.getKey(); + String extensions = trReadFormats.get(format); + String temp[] = extensions.split(";"); + String descr = trReadFormatsDescr.get(format); + + for (int i = 0; i < temp.length; i++) { + if (i == 0) { + descr += " ("; + } else { + descr += ";"; + } + descr += "*." + temp[i]; + if (i == temp.length - 1) { + descr += ")"; + } + } + reference.put(descr, format); + } + + return reference; + } +} diff --git a/src/main/java/cct/modelling/MolecularGeometry.java b/src/main/java/cct/modelling/MolecularGeometry.java new file mode 100644 index 0000000..1f7cb53 --- /dev/null +++ b/src/main/java/cct/modelling/MolecularGeometry.java @@ -0,0 +1,103 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.modelling; + +import java.util.ArrayList; +import java.util.logging.Logger; + +import cct.vecmath.Point3f; + +/** + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2004

+ * + *

+ * Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class MolecularGeometry + extends ArrayList { + + String Name = "Geometry"; + String Remark = null; + static final Logger logger = Logger.getLogger(MolecularGeometry.class.getCanonicalName()); + + public MolecularGeometry() { + } + + public MolecularGeometry(float[][] coords) { + if (coords == null || coords.length < 1) { + return; + } + this.ensureCapacity(coords.length); + for (int i = 0; i < coords.length; i++) { + this.add(new Point3f(coords[i][0], coords[i][1], coords[i][2])); + } + } + + public boolean addCoordinates(Point3f coord) { + return add(coord); + } + + public void addRemark(String rem) { + Remark.concat(rem); + } + + public Point3f getCoordinates(int n) { + if (n < 0 || n >= size()) { + logger.info("getCoordinates: n < 0 || n>= size()"); + return null; + } + return get(n); + } + + public String getName() { + return Name; + } + + public void setName(String name) { + Name = name; + } +} diff --git a/src/main/java/cct/modelling/MolecularPlane.java b/src/main/java/cct/modelling/MolecularPlane.java new file mode 100644 index 0000000..435ac5d --- /dev/null +++ b/src/main/java/cct/modelling/MolecularPlane.java @@ -0,0 +1,59 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.modelling; + +import cct.interfaces.AtomInterface; +import cct.vecmath.Plane; +import java.util.ArrayList; +import java.util.List; + +/** + * + * @author Vlad + */ +public class MolecularPlane extends Plane { + + private String name; + private SurfaceParameter surfaceParameter; + private List atomList = new ArrayList(); + + public List getAtomList() { + return atomList; + } + + public MolecularPlane(String name) throws Exception { + super(0, 0, 1, 0); + setName(name); + } + + public MolecularPlane(double A, double B, double C, double D, String name) throws Exception { + super(A, B, C, D); + setName(name); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public SurfaceParameter getSurfaceParameter() { + return surfaceParameter; + } + + public void setSurfaceParameter(SurfaceParameter surfaceParameter) { + this.surfaceParameter = surfaceParameter; + } + + public void setSurfaceParameter(double R, double W) { + if (surfaceParameter == null) { + surfaceParameter = new SurfaceParameter(R, W); + } else { + surfaceParameter.set(R, W); + } + } +} diff --git a/src/main/java/cct/modelling/MolecularProperties.java b/src/main/java/cct/modelling/MolecularProperties.java new file mode 100644 index 0000000..7c075e9 --- /dev/null +++ b/src/main/java/cct/modelling/MolecularProperties.java @@ -0,0 +1,86 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +/** + *

Title:

+ * + *

Description:

+ * Property labels correspond to the labels in SQL database + * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public interface MolecularProperties { + /* + public static final String RenderingStyle = "RenderingStyle"; + + public static final String ChargeProperty = "Charge"; + public static final String MultiplicityProperty = "Multiplicity"; + public static final String SCFEnergyProperty = "SCF Energy"; + public static final String MP2EnergyProperty = "MP2 Energy"; + public static final String MP3EnergyProperty = "MP3 Energy"; + public static final String MP4DEnergyProperty = "MP4D Energy"; + public static final String MP4DQEnergyProperty = "MP4DQ Energy"; + public static final String MP4SDQEnergyProperty = "MP4SDQ Energy"; + public static final String CCSDEnergyProperty = "CCSD Energy"; + public static final String CCSDTEnergyProperty = "CCSDT Energy"; + public static final String DipoleMomentProperty = "Dipole"; + public static final String PolarizabilityProperty = "Polarizability"; + public static final String MullikenChargesProperty = "Mulliken charges"; + public static final String ESPChargesProperty = "ESP charges"; + public static final String FrameGroupProperty = "FrameGroup"; + public static final String S_SquaredProperty = "S**2"; + public static final String ZeroPointCorrProperty = "ZPCorr"; + public static final String EnergyThermCorrProperty = "EnergyTC"; + public static final String EnthalpyThermCorrProperty = "EnthalpyTC"; + public static final String GibbsThermCorrProperty = "GibbsTC"; + public static final String ImaginaryFreqsProperty = "ImaginaryFreqs"; + public static final String NotesProperty = "Notes"; + public static final String ProgramProperty = "Program"; + public static final String VersionProperty = "Version"; + public static final String PeriodicBox = "PeriodicBox"; +*/ + //public static final HashMap PropertiesDescription = new HashMap(); + + //PropertiesDescription.put( ChargeProperty, "Total Charge on molecule/ion, in a.u."); +} diff --git a/src/main/java/cct/modelling/Molecule.java b/src/main/java/cct/modelling/Molecule.java new file mode 100644 index 0000000..6432a82 --- /dev/null +++ b/src/main/java/cct/modelling/Molecule.java @@ -0,0 +1,2562 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.modelling; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import cct.Constants; +import cct.amber.AmberUtilities; +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; +import cct.interfaces.MoleculeInterface; +import cct.interfaces.MonomerInterface; +import cct.interfaces.Point3fInterface; +import cct.pdb.PDB; +import cct.vecmath.Geometry3d; +import cct.vecmath.Point3f; +import cct.vecmath.VecmathTools; + +/** + * + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2015 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class Molecule + implements AtomProperties, MoleculeInterface { + + protected String molName; + protected int number_of_Atoms; + protected AtomsArray Atoms; + protected BondsArray Bonds; + protected Monomer Residues; // Depreciated + protected Map Properties = null; + protected AtomInterface atomInterface = null; + protected BondInterface bondInterface = null; + protected boolean boundary_done = false; + protected float Xmin, Xmax, Ymin, Ymax, Zmin, Zmax; + static final Logger logger = Logger.getLogger(Molecule.class.getCanonicalName()); + + public Molecule() { + molName = "Unnamed Molecule"; + number_of_Atoms = 0; + Atoms = new AtomsArray(); + Bonds = new BondsArray(); + Residues = new Monomer(); + Properties = new HashMap(); + + // --- Set default atom & bond interfaces + setAtomInterface(new Atom()); + setBondInterface(new Bond()); + } + + public boolean IsAtomSelected(int n) { + if (n < 0 || n >= Atoms.size()) { + return false; + } + AtomInterface a = Atoms.getAtom(n); + return a.isSelected(); + } + + public void appendMolecule(MoleculeInterface mol) { + if (mol == null || mol.getNumberOfAtoms() == 0) { + System.err.println("Warning: appendMolecule: empty molecule to append"); + return; + } + + AtomInterface refAtom = getNewAtomInstance(); + int oldNumAtoms = this.getNumberOfAtoms(); + int oldNumMonomers = this.getNumberOfMonomers(); + for (int i = 0; i < mol.getNumberOfMonomers(); i++) { + MonomerInterface mono = mol.getMonomerInterface(i); + addMonomer(mono.getName()); + for (int j = 0; j < mono.getNumberOfAtoms(); j++) { + AtomInterface a1 = mono.getAtom(j); + AtomInterface atom = refAtom.getNewAtomInstance(a1); + addAtom(atom, oldNumMonomers + i); + } + } + + BondInterface refBond = this.getNewBondInstance(); + for (int i = 0; i < mol.getNumberOfBonds(); i++) { + BondInterface b = mol.getBondInterface(i); + AtomInterface a1 = b.getIAtomInterface(); + AtomInterface a2 = b.getJAtomInterface(); + int i_index = mol.getAtomIndex(a1); + int j_index = mol.getAtomIndex(a2); + + a1 = this.getAtomInterface(oldNumAtoms + i_index); + a2 = this.getAtomInterface(oldNumAtoms + j_index); + BondInterface bond = refBond.getNewBondInstance(a1, a2); + this.addBond(bond); + } + } + + /* + * public void addAtom(Atom a) { Atoms.addAtom(a); } + */ + public void addAtom(AtomInterface a) { + Atoms.addAtom(a); + } + + public void addAtom(AtomInterface a, int monomer_number) { + Atoms.addAtom(a, monomer_number); + } + + public void addAtom(AtomInterface a, String monomer_name) { + Atoms.addAtom(a, monomer_name); + } + + public void addAtom(AtomInterface a, int n, String name) { + Atoms.addAtom(a, n, name); + } + + public void addAtom(int element, float x, float y, float z) { + Atom a = new Atom(element, x, y, z); + Atoms.addAtom(a); + } + + public void addBond(Bond b) { + Bonds.add(b); + } + + public void addBond(BondInterface b) { + Bonds.add(b); + } + + public Bond addBondBetweenAtoms(int origin, int target) { + if (origin < 0 || origin >= getNumberOfAtoms() + || target < 0 || target >= getNumberOfAtoms()) { + return null; + } + + AtomInterface a_origin = getAtom(origin); + AtomInterface a_target = getAtom(target); + AtomInterface a_i = a_origin, a_j = a_target; + Bond b = null; + + // Check for existence of this bond + for (int i = 0; i < getNumberOfBonds(); i++) { + b = getBond(i); + a_i = b.getI(); + a_j = b.getJ(); + if ((a_origin == a_i && a_target == a_j) + || (a_origin == a_j && a_target == a_i)) { + return null; + } + } + + if (a_i == null || a_j == null) { + return null; + } + + // --- Create new bond + b = createNewBond(a_origin, a_target); + + return b; + } + + public void addMonomer(String name) { + Atoms.addMonomer(name); + } + + public static void addMonomer(MoleculeInterface molec, + MonomerInterface monomer) { + molec.addMonomer(monomer.getName()); + int n = molec.getNumberOfMonomers() - 1; + int oldAtoms = molec.getNumberOfAtoms(); + AtomInterface refAtom = molec.getNewAtomInstance(); + + // --- Adding atoms + for (int i = 0; i < monomer.getNumberOfAtoms(); i++) { + AtomInterface atom = refAtom.getNewAtomInstance(monomer.getAtom(i)); + molec.addAtom(atom, n); + } + + // --- Adding bonds + for (int i = 0; i < monomer.getNumberOfAtoms(); i++) { + AtomInterface atom = monomer.getAtom(i); + List bondedAtoms = monomer.getAtom(i).getBondedToAtoms(); + for (int j = 0; j < bondedAtoms.size(); j++) { + AtomInterface a2 = (AtomInterface) bondedAtoms.get(j); + int second_index = monomer.getAtomIndex(a2); + if (second_index == -1) { + continue; + } else if (second_index < j) { + continue; + } + + AtomInterface a_1 = molec.getAtomInterface(oldAtoms + i); + AtomInterface a_2 = molec.getAtomInterface(oldAtoms + second_index); + BondInterface bond = molec.getNewBondInstance(a_1, a_2); + molec.addBond(bond); + } + } + } + + public void addProperty(String propName, Object value) { + if (Properties.containsKey(propName)) { + Object obj = Properties.get(propName); + if (obj instanceof List) { + List props = (List) obj; + props.add(value); + } else { + List props = new ArrayList(); + props.add(obj); + props.add(value); + Properties.put(propName, props); + } + } else { // Add this property for the first time + Properties.put(propName, value); + } + } + + public void centerMolecule(float x, float y, float z) { + if (this.getNumberOfAtoms() < 1) { + return; + } + AtomInterface a = getAtom(0); + float x_center = a.getX(); + float y_center = a.getY(); + float z_center = a.getZ(); + for (int i = 1; i < getNumberOfAtoms(); i++) { + a = getAtom(i); + x_center += a.getX(); + y_center += a.getY(); + z_center += a.getZ(); + } + + x_center /= (float) getNumberOfAtoms(); + y_center /= (float) getNumberOfAtoms(); + z_center /= (float) getNumberOfAtoms(); + + for (int i = 0; i < getNumberOfAtoms(); i++) { + a = getAtom(i); + a.setX(a.getX() - x_center + x); + a.setY(a.getY() - y_center + y); + a.setZ(a.getZ() - z_center + z); + } + + } + + public static MoleculeInterface cloneMolecule(MoleculeInterface refMol) { + return duplicateMolecule(refMol); + } + + /** + * No error check!!! + * + * @param origin int + * @param target int + */ + Bond createNewBond(AtomInterface a_origin, AtomInterface a_target) { + Bond b = new Bond(a_origin, a_target); + Bonds.add(b); + return b; + } + + public AtomInterface deleteAtom(int n) { + AtomInterface atom = this.getAtomInterface(n); + List list = atom.getBondIndex(); + + //logger.info(" Number of bonds: "+list.size()+" Total number of bonds: "+this.getNumberOfBonds()); + // --- Delete all associated bonds + int i; + while (list.size() > 0) { + i = list.size() - 1; + BondInterface bond = (BondInterface) list.get(i); + if (deleteBond(bond) == null) { + System.err.println(" Cannot delete " + i + " bond"); + } else { + //logger.info(" "+i+" bond deleted Total number of bonds: "+this.getNumberOfBonds()); + } + + } + /* + * if (list != null && list.size() > 0) { for (int i = list.size() - 1; i > -1; i--) { BondInterface bond = (BondInterface) + * list.get(i); if (deleteBond(bond) == null) { System.err.println(" Cannot delete " + i + " bond"); } else { //logger.info(" + * "+i+" bond deleted Total number of bonds: "+this.getNumberOfBonds()); } } } + */ + Atoms.removeAtom(atom); + + return atom; + } + + /** + * Deletes bond between atoms and all related information + * + * @param bond_to_delete BondInterface - bond to delete + * @return BondInterface - Deleted bond or "null" if molecule does not have this bond + */ + public BondInterface deleteBond(BondInterface bond_to_delete) { + if (Bonds.indexOf(bond_to_delete) == -1) { + System.err.println("Cannot delete bond between: " + + this.getAtomIndex(bond_to_delete.getIAtomInterface()) + + " & " + + getAtomIndex(bond_to_delete.getJAtomInterface())); + return null; // Error + } + AtomInterface a_origin = bond_to_delete.getIAtomInterface(); + AtomInterface a_target = bond_to_delete.getJAtomInterface(); + + a_origin.setBondedTo(a_target, false); + a_origin.removeBond(bond_to_delete); + + a_target.setBondedTo(a_origin, false); + a_target.removeBond(bond_to_delete); + + if (!Bonds.removeBond(bond_to_delete)) { + System.err.println("Bonds.removeBond: Cannot delete bond"); + } + return bond_to_delete; + } + + public int deleteSelectedAtoms() { + return deleteSelectedAtoms(this); + } + + public static int deleteSelectedAtoms(MoleculeInterface molec) { + + int deleted = 0; + int nat = molec.getNumberOfAtoms(); + for (int i = nat - 1; i > -1; i--) { + AtomInterface atom = molec.getAtomInterface(i); + if (!atom.isSelected()) { + continue; // Atom is not selected + } + logger.info("Deleting atom: " + i); + molec.deleteAtom(i); + ++deleted; + } + + if (true) { + return deleted; + } + + // --- Delete atoms and associated bonds + for (int i = nat - 1; i > -1; i--) { + AtomInterface atom = molec.getAtomInterface(i); + if (!atom.isSelected()) { + continue; // Atom is not selected + } + AtomInterface at = molec.getAtomInterface(i); + List bi = at.getBondIndex(); + + // --- First, delete bonds associated with this atom + for (int j = 0; j < bi.size(); j++) { + BondInterface b = (BondInterface) bi.get(j); + if (molec.getBondIndex(b) == -1) { + continue; // --- Bond is already deleted + } + //Bonds.removeBond(b); + molec.deleteBond(b); + } + + ++deleted; + } + + // --- Final clean-up + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface at = molec.getAtomInterface(i); + List bi = at.getBondIndex(); + int nb = bi.size(); + // --- remove bond references to deleted bonds + for (int j = nb - 1; j > -1; j--) { + BondInterface b = (BondInterface) bi.get(j); + if (molec.getBondIndex(b) == -1) { + bi.remove(b); + } + } + // --- remove references to deleted atoms + bi = at.getBondedToAtoms(); + nb = bi.size(); + for (int j = nb - 1; j > -1; j--) { + Atom atom = (Atom) bi.get(j); + if (molec.getAtomIndex(atom) == -1) { + bi.remove(atom); + } + } + + } + + return deleted; + } + + public static String distancesAsString(MoleculeInterface molecule) { + if (molecule == null) { + return "Molecule is not allocated"; + } + + StringWriter sWriter = new StringWriter(); + sWriter.write("Interatomic distances for " + molecule.getName() + "\n\n"); + //double *A, + int NUMB = molecule.getNumberOfAtoms(); + int LIMIT = (NUMB * (NUMB + 1)) / 2; + int I, K, L = 0, LL, M, MA, N, NA = 1, n; + do { + LL = 0; + M = Math.min((NUMB + 1 - NA), 5); + MA = 3 * M + 1; + M = NA + M - 1; + sWriter.write("\n\n "); + + for (I = NA; I <= M; I++) { + sWriter.write(String.format(" %5d", I)); + } + sWriter.write("\n "); + for (I = NA; I <= M; I++) { + AtomInterface a_1 = molecule.getAtomInterface(I - 1); + n = Math.min(a_1.getName().length(), 5); + sWriter.write(String.format(" %5s", a_1.getName().substring(0, n))); + } + + sWriter.write("\n "); + for (I = 1; I <= MA; I++) { + sWriter.write("----"); + } + for (I = NA; I <= NUMB; I++) { + ++LL; + K = (I * (I - 1)) / 2; + L = Math.min((K + M), (K + I)); + K += NA; + sWriter.write(String.format("\n%4d ", I)); + AtomInterface a_1 = molecule.getAtomInterface(I - 1); + for (n = NA - 1, N = K; N <= L; N++, n++) { + AtomInterface a_2 = molecule.getAtomInterface(n); + sWriter.write(String.format("%12.4f", a_1.distanceTo(a_2))); + //sWriter.write(String.format("%12.4lf", A[N - 1])); + } + sWriter.write(" " + a_1.getName()); + } + NA = M + 1; + } while (L < LIMIT); + + return sWriter.toString(); + } + + public static MoleculeInterface divideIntoMolecules(MoleculeInterface molec) { + int nAtoms = molec.getNumberOfAtoms(); + if (nAtoms < 2) { + return molec; + } + + int atomsInMol = 0; + MoleculeInterface molecule = molec.getInstance(); + + // -- Copy all molecular properties + molecule.setName(molec.getName()); + + Map props = molec.getProperties(); + Set set = props.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + Object key = me.getKey(); + Object value = me.getValue(); + molecule.addProperty(key.toString(), value); + } + + // --- unselect all atoms first + List reference = new ArrayList(nAtoms); // Temporary array + if (reference instanceof ArrayList) { + ((ArrayList) reference).ensureCapacity(nAtoms); + } + for (int i = 0; i < nAtoms; i++) { + AtomInterface atom = molec.getAtomInterface(i); + atom.setSelected(false); + reference.add(null); + } + + int nRes = 0; + for (int i = 0; i < nAtoms; i++) { + AtomInterface atom = molec.getAtomInterface(i); + if (atom.isSelected()) { + continue; + } + List group = getMoleculeAtomBelongsTo(atom); + logger.info("Found molecule " + (nRes + 1) + + " number of atoms: " + group.size()); + atomsInMol += group.size(); + ++nRes; + String resName = "R" + nRes; + molecule.addMonomer(resName); + logger.info(" New number of monomers: " + + molecule.getNumberOfMonomers()); + for (int j = 0; j < group.size(); j++) { + atom = (AtomInterface) group.get(j); + int index = molec.getAtomIndex(atom); + AtomInterface a = atom.getNewAtomInstance(atom); + //reference.add(index, a); + reference.set(index, a); + //a.setSubstructureNumber(nRes-1); + molecule.addAtom(a); + atom.setSelected(true); + } + + if (atomsInMol == nAtoms) { + break; + } + } + + // --- now, reconstruct bonds + if (molec.getNumberOfBonds() > 0) { + BondInterface refB = molec.getBondInterface(0); + for (int i = 0; i < molec.getNumberOfBonds(); i++) { + BondInterface bond = molec.getBondInterface(i); + AtomInterface a_i = bond.getIAtomInterface(); + AtomInterface a_j = bond.getJAtomInterface(); + int i_index = molec.getAtomIndex(a_i); + int j_index = molec.getAtomIndex(a_j); + + a_i = (AtomInterface) reference.get(i_index); + a_j = (AtomInterface) reference.get(j_index); + bond = refB.getNewBondInstance(a_i, a_j); + molecule.addBond(bond); + } + } + + // --- free memory + reference = null; + + return molecule; + } + + public static MoleculeInterface duplicateMolecule(MoleculeInterface refMol) { + MoleculeInterface copy = refMol.getInstance(); + copy.appendMolecule(refMol); + return copy; + } + + private static void findAllBondedAtoms(AtomInterface target_atom, List group) { + if (group.contains(target_atom)) { + return; + } + group.add(target_atom); + List bonded = target_atom.getBondedToAtoms(); + for (int i = 0; i < bonded.size(); i++) { + AtomInterface a = bonded.get(i); + if (group.contains(a)) { + continue; + } + if (a.getNumberOfBondedAtoms() == 1) { + group.add(a); + continue; + } + findAllBondedAtoms(a, group); + } + } + + void findBoundaries() { + Xmin = Xmax = Ymin = Ymax = Zmin = Zmax = 0.0f; + if (Atoms.size() < 1) { + return; + } + AtomInterface a = Atoms.getAtom(0); + Xmin = Xmax = a.getX(); + Ymin = Ymax = a.getY(); + Zmin = Zmax = a.getZ(); + for (int i = 1; i < Atoms.size(); i++) { + a = Atoms.getAtom(i); + if (Xmin > a.getX()) { + Xmin = a.getX(); + } else if (Xmax < a.getX()) { + Xmax = a.getX(); + } + if (Ymin > a.getY()) { + Ymin = a.getY(); + } else if (Ymax < a.getY()) { + Ymax = a.getY(); + } + if (Zmin > a.getZ()) { + Zmin = a.getZ(); + } else if (Zmax < a.getZ()) { + Zmax = a.getZ(); + } + } + boundary_done = true; + } + + public boolean fromArchiveFormat(InputStream in) { + String bufer; + byte symbol[] = new byte[1]; + int natoms = 0; + + // -- Read number of atoms + bufer = ""; + try { + while (in.read(symbol) != -1 && symbol[0] != '\n') { + bufer += (char) symbol[0]; + } + natoms = Integer.parseInt(bufer); + logger.info("fromArchiveFormat: Number of atoms: " + natoms); + } catch (IOException e) { + logger.info( + "fromArchiveFormat: cannot read number of atoms\n"); + return false; + } + + // --- Read atoms + try { + for (int i = 0; i < natoms; i++) { + bufer = ""; + while (in.read(symbol) != -1 && symbol[0] != '\n') { + bufer += (char) symbol[0]; + } + StringTokenizer st = new StringTokenizer(bufer, ","); + //gAtom a = new Atom(); + AtomInterface a = this.getNewAtomInstance(); + a.setAtomicNumber(Integer.parseInt(st.nextToken())); + a.setProperty(AtomInterface.NAME, st.nextToken()); + a.setX(Float.parseFloat(st.nextToken())); + a.setY(Float.parseFloat(st.nextToken())); + a.setZ(Float.parseFloat(st.nextToken())); + addAtom(a); + } + } catch (IOException e) { + logger.info("fromArchiveFormat: cannot read atom's info"); + return false; + } + + // -- Read number of bonds if any + bufer = ""; + int nbonds; + try { + while (in.read(symbol) != -1 && symbol[0] != '\n') { + bufer += (char) symbol[0]; + } + nbonds = Integer.parseInt(bufer); + logger.info("fromArchiveFormat: Number of bonds: " + nbonds); + } catch (IOException e) { + logger.info( + "fromArchiveFormat: cannot read number of bonds\n"); + return false; + } + + // --- Read bonds + try { + for (int i = 0; i < nbonds; i++) { + bufer = ""; + while (in.read(symbol) != -1 && symbol[0] != '\n') { + bufer += (char) symbol[0]; + } + StringTokenizer st = new StringTokenizer(bufer, ","); + int at_i = Integer.parseInt(st.nextToken()); + int at_j = Integer.parseInt(st.nextToken()); + AtomInterface a_i = Atoms.getAtom(at_i); + AtomInterface a_j = Atoms.getAtom(at_j); + createNewBond(a_i, a_j); + //Bond b = new Bond( a_i, a_j); + //addBond( b ); + } + } catch (IOException e) { + logger.info("fromArchiveFormat: cannot read bonds info"); + return false; + } + + // --- Close + try { + in.close(); + } catch (IOException e) { + //logger.info( "toArchiveFormat: cannot write atom's info"); + //return false; + } + + return true; + } + + public boolean fromArchiveFormat(byte in[]) { + String bufer; + int offset = 0; + int natoms = 0; + + //bufer = in; + //logger.info("fromArchiveFormat: input string: " + bufer ); + // -- Read number of atoms + bufer = ""; + offset = -1; + //try { + while (in[++offset] != '\n' && offset < in.length) { + bufer += (char) in[offset]; + //++offset; + } + natoms = Integer.parseInt(bufer); + logger.info("fromArchiveFormat: Number of atoms: " + natoms); + //} catch ( IOException e ) { + // logger.info( "fromArchiveFormat: cannot read number of atoms\n"); + // return false; + //} + + // --- Read atoms + //try { + for (int i = 0; i < natoms; i++) { + bufer = ""; + while (in[++offset] != '\n' && offset < in.length) { + bufer += (char) in[offset]; + //++offset; + } + StringTokenizer st = new StringTokenizer(bufer, ","); + Atom a = new Atom(); + a.setAtomicNumber(Integer.parseInt(st.nextToken())); + a.setProperty(AtomInterface.NAME, st.nextToken()); + a.setX(Float.parseFloat(st.nextToken())); + a.setY(Float.parseFloat(st.nextToken())); + a.setZ(Float.parseFloat(st.nextToken())); + addAtom(a); + } + //} catch ( IOException e ) { + // logger.info( "fromArchiveFormat: cannot read atom's info"); + // return false; + //} + + // --- Close + //try { + // in.close(); + //} catch ( IOException e ) { + //logger.info( "toArchiveFormat: cannot write atom's info"); + //return false; + //} + return true; + } + + public static MoleculeInterface generateSolventShell(MoleculeInterface refMol, MoleculeInterface solvent, float radius, float closeness, + int solvationType) { + + // --- Error check + if (refMol.getNumberOfAtoms() < 1 || solvent.getNumberOfAtoms() < 1) { + System.err.println( + "generateSolventShell: reference molecule or/and solvent has no atoms: " + + refMol.getNumberOfAtoms() + " & " + solvent.getNumberOfAtoms()); + return null; + } + if (solvationType != OperationsOnAtoms.SELECTED_SOLVATE_CAP + && solvationType != OperationsOnAtoms.SELECTED_SOLVATE_SHELL) { + System.err.println( + "generateSolventShell: unknown solvation type: " + solvationType); + return null; + } + // --- Exit if no selected atoms + boolean no_selected = true; + for (int i = 0; i < refMol.getNumberOfAtoms(); i++) { + AtomInterface atom = refMol.getAtomInterface(i); + if (atom.isSelected()) { + no_selected = false; + break; + } + } + if (no_selected) { + System.err.println("generateSolventShell: no selected atoms in reference molecule"); + return null; + } + + // --- End of error check + MoleculeInterface shell = refMol.getInstance(); + + // -- Determine overall size of solvation box + float xStart = 0, yStart = 0, zStart = 0, xEnd = 0, yEnd = 0, zEnd = 0; + float x = 0, y = 0, z = 0; + Point3f point = null; + + if (solvationType == OperationsOnAtoms.SELECTED_SOLVATE_CAP) { + int n = 0; + for (int i = 0; i < refMol.getNumberOfAtoms(); i++) { + AtomInterface atom = refMol.getAtomInterface(i); + if (atom.isSelected()) { + ++n; + x += atom.getX(); + y += atom.getY(); + z += atom.getZ(); + } + } + x /= (float) n; + y /= (float) n; + z /= (float) n; + point = new Point3f(x, y, z); + + xStart = x - radius; + yStart = y - radius; + zStart = z - radius; + xEnd = x + radius; + yEnd = y + radius; + zEnd = z + radius; + + } else if (solvationType == OperationsOnAtoms.SELECTED_SOLVATE_SHELL) { + int n = 0; + for (int i = 0; i < refMol.getNumberOfAtoms(); i++) { + AtomInterface atom = refMol.getAtomInterface(i); + if (atom.isSelected() && n == 0) { + xStart = atom.getX() - radius; + yStart = atom.getY() - radius; + zStart = atom.getZ() - radius; + xEnd = atom.getX() + radius; + yEnd = atom.getY() + radius; + zEnd = atom.getZ() + radius; + ++n; + } else if (atom.isSelected()) { + if (xStart > atom.getX() - radius) { + xStart = atom.getX() - radius; + } + if (yStart > atom.getY() - radius) { + yStart = atom.getY() - radius; + } + if (zStart > atom.getZ() - radius) { + zStart = atom.getZ() - radius; + } + if (xEnd < atom.getX() + radius) { + xEnd = atom.getX() + radius; + } + if (yEnd < atom.getY() + radius) { + yEnd = atom.getY() + radius; + } + if (zEnd < atom.getZ() + radius) { + zEnd = atom.getZ() + radius; + } + } + } + } + + logger.info("Solvation box: \nX: " + xStart + " Xm:" + xEnd + + "\nY: " + yStart + " Ym:" + yEnd + "\nZ: " + zStart + + " Zm:" + zEnd); + + // -- Determine size of solvent + Float XYZ[] = (Float[]) refMol.getProperty(MoleculeInterface.PeriodicBox); + if (XYZ == null) { + XYZ = new Float[3]; + for (int i = 0; i < solvent.getNumberOfAtoms(); i++) { + AtomInterface atom = solvent.getAtomInterface(i); + if (i == 0) { + XYZ[0] = atom.getX(); + XYZ[1] = atom.getY(); + XYZ[2] = atom.getZ(); + } else { + if (XYZ[0] > atom.getX()) { + XYZ[0] = atom.getX(); + } + if (XYZ[1] > atom.getY()) { + XYZ[1] = atom.getY(); + } + if (XYZ[2] > atom.getZ()) { + XYZ[2] = atom.getZ(); + } + } + } + for (int i = 0; i < solvent.getNumberOfAtoms(); i++) { + AtomInterface atom = solvent.getAtomInterface(i); + atom.setX(atom.getX() - XYZ[0]); + atom.setY(atom.getY() - XYZ[1]); + atom.setZ(atom.getZ() - XYZ[2]); + } + + for (int i = 0; i < solvent.getNumberOfAtoms(); i++) { + AtomInterface atom = solvent.getAtomInterface(i); + if (i == 0) { + XYZ[0] = atom.getX(); + XYZ[1] = atom.getY(); + XYZ[2] = atom.getZ(); + } else { + if (XYZ[0] < atom.getX()) { + XYZ[0] = atom.getX(); + } + if (XYZ[1] < atom.getY()) { + XYZ[1] = atom.getY(); + } + if (XYZ[2] < atom.getZ()) { + XYZ[2] = atom.getZ(); + } + } + } + + } + + logger.info("Solvent size: X: " + XYZ[0] + " Y: " + XYZ[1] + + " Z: " + XYZ[2]); + + // --- Start solvation + if (solvationType == OperationsOnAtoms.SELECTED_SOLVATE_CAP) { + float xCount = xStart; + while (xCount < xEnd) { + float yCount = yStart; + while (yCount < yEnd) { + float zCount = zStart; + while (zCount < zEnd) { + // --- Translate original solvent box + MoleculeInterface box = refMol.getInstance(); + box.appendMolecule(solvent); + for (int i = 0; i < box.getNumberOfAtoms(); i++) { + AtomInterface atom = box.getAtomInterface(i); + atom.setX(atom.getX() + xCount); + atom.setY(atom.getY() + yCount); + atom.setZ(atom.getZ() + zCount); + } + + for (int i = 0; i < box.getNumberOfMonomers(); i++) { + MonomerInterface monomer = box.getMonomerInterface(i); + if (!isHeavyAtomsWithinRange(point, monomer, radius)) { + continue; + } + + if (isWithinWanDerWaalsRange(refMol, monomer, closeness)) { + continue; // Too close + } + + Molecule.addMonomer(shell, monomer); + } + + zCount += XYZ[2]; + } + yCount += XYZ[1]; + } + xCount += XYZ[0]; + } + } // --- Make shell solvation + else if (solvationType == OperationsOnAtoms.SELECTED_SOLVATE_SHELL) { + + // --- Prepare list of selected atoms + List atomList = new ArrayList(); + for (int i = 0; i < refMol.getNumberOfAtoms(); i++) { + AtomInterface atom = refMol.getAtomInterface(i); + if (!atom.isSelected()) { + continue; + } + atomList.add(atom); + } + + float xCount = xStart; + while (xCount < xEnd) { + float yCount = yStart; + while (yCount < yEnd) { + float zCount = zStart; + while (zCount < zEnd) { + // --- Translate original solvent box + MoleculeInterface box = refMol.getInstance(); + box.appendMolecule(solvent); + for (int i = 0; i < box.getNumberOfAtoms(); i++) { + AtomInterface atom = box.getAtomInterface(i); + atom.setX(atom.getX() + xCount); + atom.setY(atom.getY() + yCount); + atom.setZ(atom.getZ() + zCount); + } + + for (int i = 0; i < box.getNumberOfMonomers(); i++) { + MonomerInterface monomer = box.getMonomerInterface(i); + + // --- Go through the list of selected atoms + boolean NotWithinRange = true; + for (int j = 0; j < atomList.size(); j++) { + AtomInterface at = (AtomInterface) atomList.get(j); + if (isHeavyAtomsWithinRange(at, monomer, radius)) { + NotWithinRange = false; + break; + } + + } + if (NotWithinRange) { + continue; + } + + // --- Check closeness + if (isWithinWanDerWaalsRange(refMol, monomer, closeness)) { + continue; // Too close + } + + Molecule.addMonomer(shell, monomer); + } + + zCount += XYZ[2]; + } + yCount += XYZ[1]; + } + xCount += XYZ[0]; + } + + } else { + System.err.println("Uknown solvation type"); + return null; + } + + // --- Test + float x0 = 0, y0 = 0, z0 = 0, x1 = 0, y1 = 0, z1 = 0; + for (int i = 0; i < shell.getNumberOfAtoms(); i++) { + AtomInterface atom = shell.getAtomInterface(i); + if (i == 0) { + x0 = atom.getX(); + y0 = atom.getY(); + z0 = atom.getZ(); + x1 = atom.getX(); + y1 = atom.getY(); + z1 = atom.getZ(); + } else { + x0 = x0 > atom.getX() ? atom.getX() : x0; + y0 = y0 > atom.getY() ? atom.getY() : y0; + z0 = z0 > atom.getZ() ? atom.getZ() : z0; + x1 = x1 < atom.getX() ? atom.getX() : x1; + y1 = y1 < atom.getY() ? atom.getY() : y1; + z1 = z1 < atom.getZ() ? atom.getZ() : z1; + } + } + logger.info("Test: Shell min: X: " + x0 + " Y: " + + y0 + + " Z: " + z0 + " Max: X: " + x1 + " Y: " + + y1 + + " Z: " + z1); + // --- End Test + + return shell; + } + + public static String geometryAsString(MoleculeInterface molecule) { + if (molecule == null) { + return "Molecule is not allocated"; + } + + StringWriter sWriter = new StringWriter(); + sWriter.write(molecule.getName() + "\n\n"); + sWriter.write("Number of atoms: " + molecule.getNumberOfAtoms() + "\n\n"); + sWriter.write(" N Name X Y Z\n"); + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface atom = molecule.getAtomInterface(i); + sWriter.write(String.format(" %4d %6s %12.6f %12.6f %12.6f\n", (i + 1), atom.getName(), atom.getX(), atom.getY(), + atom.getZ())); + } + sWriter.write("\n"); + + sWriter.write("Number of bonds: " + molecule.getNumberOfBonds() + "\n\n"); + for (int i = 0; i < molecule.getNumberOfBonds(); i++) { + BondInterface bond = molecule.getBondInterface(i); + AtomInterface a_1 = bond.getIAtomInterface(); + AtomInterface a_2 = bond.getJAtomInterface(); + + sWriter.write(String.format(" %4d %4s(%d) - %4s(%d) %12.6f\n", (i + 1), a_1.getName(), molecule.getAtomIndex(a_1) + 1, + a_2.getName(), molecule.getAtomIndex(a_2) + 1, a_1.distanceTo(a_2))); + } + sWriter.write("\n"); + + AngleBendsArray angles = FFMolecule.findDynamicAngles(molecule); + sWriter.write("Number of covalent angles: " + angles.getSize() + "\n\n"); + + for (int i = 0; i < angles.getSize(); i++) { + AngleBend ab = angles.getAngleBend(i); + AtomInterface a1 = molecule.getAtomInterface(ab.getI()); + AtomInterface a2 = molecule.getAtomInterface(ab.getJ()); + AtomInterface a3 = molecule.getAtomInterface(ab.getK()); + sWriter.write(String.format(" %4d %4s(%d) - %4s(%d) - %4s(%d) %12.6f\n", (i + 1), a1.getName(), (ab.getI() + 1), + a2.getName(), (ab.getJ() + 1), a3.getName(), (ab.getK() + 1), + Point3f.angleBetween(a1, a2, a3) * Constants.RADIANS_TO_DEGREES)); + } + sWriter.write("\n"); + + List torsions = FFMolecule.findDynamicTorsions(molecule); + sWriter.write("Number of torsions: " + torsions.size() + "\n\n"); + for (int i = 0; i < torsions.size(); i++) { + Torsion torsion = (Torsion) torsions.get(i); + AtomInterface a1 = molecule.getAtomInterface(torsion.getI()); + AtomInterface a2 = molecule.getAtomInterface(torsion.getJ()); + AtomInterface a3 = molecule.getAtomInterface(torsion.getK()); + AtomInterface a4 = molecule.getAtomInterface(torsion.getL()); + sWriter.write(String.format(" %4d %4s(%d) - %4s(%d) - %4s(%d) - %4s(%d) %12.6f\n", (i + 1), a1.getName(), + (torsion.getI() + 1), + a2.getName(), (torsion.getJ() + 1), a3.getName(), (torsion.getK() + 1), a4.getName(), + (torsion.getL() + 1), + Point3f.dihedralAngle(a1, a2, a3, a4) * Constants.RADIANS_TO_DEGREES)); + + } + + return sWriter.toString(); + } + + public AtomInterface getAtom(int i) { + return Atoms.getAtom(i); + } + + public int getAtomIndex(AtomInterface a) { + return Atoms.getAtomIndex(a); + } + + public AtomInterface getAtomInterface(int i) { + return Atoms.getAtom(i); + } + + public Set getAtomListUsingAtomMaskSelection(String atomSelectionMask) throws Exception { + return getAtomListUsingAtomMaskSelection(this, atomSelectionMask); + } + + public static Set getAtomListUsingAtomMaskSelection(MoleculeInterface mol, String atomSelectionMask) throws Exception { + if (mol == null || mol.getNumberOfAtoms() < 1) { + logger.warning("mol == null || mol.getNumberOfAtoms() < 1"); + } else if (atomSelectionMask == null || atomSelectionMask.trim().length() < 1) { + logger.warning("atomSelectionMask == null || atomSelectionMask.trim().length() < 1"); + return null; + } + + Set set = new HashSet(); + String[] tokens = atomSelectionMask.split("\\s+"); + for (String mask : tokens) { + String[] atomic = mask.split(","); + for (String xxx : atomic) { + if (xxx.contains("-")) { // Atom range + String at1 = xxx.substring(0, xxx.indexOf("-")); + if (at1.length() < 1) { + throw new Exception("Wrong first atom range number description in a mask \"" + atomSelectionMask); + } else if (xxx.indexOf("-") + 1 == xxx.length()) { + throw new Exception("Absent the second atom in a range number description in a mask \"" + atomSelectionMask); + } + String at2 = xxx.substring(xxx.indexOf("-") + 1); + int a1, a2; + try { + a1 = Integer.parseInt(at1); + if (a1 < 1 || a1 > mol.getNumberOfAtoms()) { + throw new Exception("Wrong atom number \"" + a1 + "\" in mask \"" + atomSelectionMask + "\"\n" + + "Should be in range 1 - " + mol.getNumberOfAtoms()); + } + } catch (Exception ex) { + throw new Exception("Cannot parse atom number \"" + at1 + "\" in mask \"" + atomSelectionMask + "\""); + } + try { + a2 = Integer.parseInt(at2); + if (a2 < 1 || a2 > mol.getNumberOfAtoms()) { + throw new Exception("Wrong atom number \"" + a2 + "\" in mask \"" + atomSelectionMask + "\"\n" + + "Should be in range 1 - " + mol.getNumberOfAtoms()); + } else if (a2 < a1) { + throw new Exception("The second atom number \"" + a2 + "\" should be bigger than of the first one: " + a1); + } + for (int i = a1; i <= a2; i++) { + set.add(mol.getAtomInterface(i - 1)); + } + } catch (Exception ex) { + throw new Exception("Cannot parse atom number \"" + at1 + "\" in mask \"" + atomSelectionMask + "\""); + } + + } else { // Individual number + try { + int at = Integer.parseInt(xxx); + if (at < 1 || at > mol.getNumberOfAtoms()) { + throw new Exception("Wrong atom number \"" + at + "\" in mask \"" + atomSelectionMask + "\"\n" + + "Should be in range 1 - " + mol.getNumberOfAtoms()); + } + set.add(mol.getAtomInterface(at - 1)); + } catch (Exception ex) { + throw new Exception("Cannot parse atom number \"" + xxx + "\" in mask \"" + atomSelectionMask + "\""); + } + } + } + } + + return set; + } + + public Set getAtomNamesInMolecule() { + return getAtomNamesInMolecule(this); + } + + public static Set getAtomNamesInMolecule(MoleculeInterface molec) { + Set elements = new HashSet(); + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface a = molec.getAtomInterface(i); + String a_name = (String) a.getProperty(AtomInterface.NAME); + if (!elements.contains(a_name)) { + elements.add(a_name); + } + } + return elements; + } + + public static List getAvailableAtomicProperties(MoleculeInterface molec) { + List prop = new ArrayList(); + Map unique = new HashMap(); + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface atom = molec.getAtomInterface(i); + Map ap = atom.getProperties(); + //.getAtomProperties(); + Set set = ap.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String key = me.getKey().toString(); + if (key.startsWith("_")) { + continue; + } + if (!unique.containsKey(key)) { + prop.add(key); + unique.put(key, null); + } + } + } + return prop; + } + + public Bond getBond(int i) { + return (Bond) Bonds.get(i); + } + + public int getBond(BondInterface b) { + return Bonds.indexOf(b); + } + + public int getBondIndex(BondInterface b) { + return Bonds.indexOf(b); + } + + public BondInterface getBondInterface(int i) { + return (BondInterface) Bonds.get(i); + } + + public static AtomInterface getCenterOfMass(Set list) throws Exception { + AtomInterface centroid = new Atom(); + centroid.setAtomicNumber(0); + double mass = 0.0f; + for (AtomInterface atom : list) { + centroid.setXYZ(atom.getX() * atom.getAtomicMass() + centroid.getX(), + atom.getY() * atom.getAtomicMass() + centroid.getY(), + atom.getZ() * atom.getAtomicMass() + centroid.getZ()); + mass += atom.getAtomicMass(); + } + centroid.setAtomicMass((float) mass); + centroid.setXYZ(centroid.getX() / mass, centroid.getY() / mass, centroid.getZ() / mass); + return centroid; + } + + public AtomInterface getCenterOfMass() throws Exception { + return getCenterOfMass(this); + } + + public static AtomInterface getCenterOfMass(MoleculeInterface mol) throws Exception { + AtomInterface centroid = new Atom(); + centroid.setAtomicNumber(0); + double mass = 0.0f; + for (int i = 0; i < mol.getNumberOfAtoms(); i++) { + AtomInterface atom = mol.getAtomInterface(i); + centroid.setXYZ(atom.getX() * atom.getAtomicMass() + centroid.getX(), + atom.getY() * atom.getAtomicMass() + centroid.getY(), + atom.getZ() * atom.getAtomicMass() + centroid.getZ()); + mass += atom.getAtomicMass(); + } + centroid.setXYZ(centroid.getX() / mass, + centroid.getY() / mass, + centroid.getZ() / mass); + centroid.setAtomicMass((float) mass); + return centroid; + } + + public static AtomInterface getCentroid(Set list) throws Exception { + AtomInterface centroid = new Atom(); + centroid.setAtomicNumber(0); + for (AtomInterface atom : list) { + centroid.setXYZ(atom.getX() + centroid.getX(), atom.getY() + centroid.getY(), atom.getZ() + centroid.getZ()); + } + centroid.setXYZ(centroid.getX() / list.size(), centroid.getY() / list.size(), centroid.getZ() / list.size()); + return centroid; + } + + public AtomInterface getCentroid() throws Exception { + return getCentroid(this); + } + + public static AtomInterface getCentroid(MoleculeInterface mol) throws Exception { + AtomInterface centroid = new Atom(); + centroid.setAtomicNumber(0); + for (int i = 0; i < mol.getNumberOfAtoms(); i++) { + AtomInterface atom = mol.getAtomInterface(i); + centroid.setXYZ(atom.getX() + centroid.getX(), + atom.getY() + centroid.getY(), + atom.getZ() + centroid.getZ()); + } + centroid.setXYZ(centroid.getX() / mol.getNumberOfAtoms(), + centroid.getY() / mol.getNumberOfAtoms(), + centroid.getZ() / mol.getNumberOfAtoms()); + return centroid; + } + + public static String getChemicalFormula(MoleculeInterface molec) { + String formula = ""; + int count[] = new int[ChemicalElements.getNumberOfElements()]; + for (int i = 0; i < count.length; i++) { + count[i] = 0; + } + + // --- Counting atoms + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface atom = molec.getAtomInterface(i); + int element = atom.getAtomicNumber(); + count[element] += 1; + } + // --- Forming chemical formula + for (int i = 1; i < count.length; i++) { + if (count[i] > 0) { + formula += ChemicalElements.getElementSymbol(i); + } + if (count[i] > 1) { + formula += String.valueOf(count[i]); + } + } + formula = formula.toUpperCase(); + return formula; + } + + public static boolean getCoordinates(MoleculeInterface molec, Point3f coord[]) { + if (coord.length < molec.getNumberOfAtoms()) { + logger.info( + "INTERNAL ERROR: getCoordinates: coord.length < this.getNumberOfAtoms()"); + return false; + } + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface a = molec.getAtomInterface(i); + if (coord[i] == null) { + coord[i] = new Point3f(a); + } else { + coord[i].setXYZ(a); + } + } + return true; + } + + public static int[] getElementCount(MoleculeInterface molec) { + int count[] = new int[ChemicalElements.getNumberOfElements()]; + for (int i = 0; i < count.length; i++) { + count[i] = 0; + } + + // --- Counting atoms + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface atom = molec.getAtomInterface(i); + int element = atom.getAtomicNumber(); + count[element] += 1; + } + return count; + } + + /** + * Calculate number of each element in a molecule + * @param molec + * @return Map, i.e pairs, for example, {C,5}, {H,5} + */ + public static Map getElementCountAsMap(MoleculeInterface molec) { + Map els = new HashMap(molec.getNumberOfAtoms()); + + // --- Counting atoms + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface atom = molec.getAtomInterface(i); + String element = ChemicalElements.getElementSymbol(atom.getAtomicNumber()); + if (els.containsKey(element)) { + els.put(element, new Integer(els.get(element) + 1)); + } else { + els.put(element, new Integer(1)); + } + } + return els; + } + + public Set getElementsInMolecule() { + return getElementsInMolecule(this); + } + + public static Set getElementsInMolecule(MoleculeInterface molec) { + Set elements = new HashSet(); + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface a = molec.getAtomInterface(i); + int el = a.getAtomicNumber(); + String mnemonic = ChemicalElements.getElementSymbol(el); + if (!elements.contains(mnemonic)) { + elements.add(mnemonic); + } + } + return elements; + } + + public MoleculeInterface getInstance() { + return new Molecule(); + } + + public List getMolecularSubstructure() { + List monomers = new ArrayList(this.getNumberOfMonomers()); + for (int i = 0; i < getNumberOfMonomers(); i++) { + Monomer m = this.getMonomer(i); + String monomer_name = m.getName(); + monomers.add(monomer_name); + } + return monomers; + } + + public static float getMolecularWeight(MoleculeInterface molec) { + float weight = 0.0f; + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface atom = molec.getAtomInterface(i); + weight += ChemicalElements.getAtomicWeight(atom.getAtomicNumber()); + } + return weight; + } + + public List> getMolecules() { + return getMolecules(this); + } + + public static List> getMolecules(MoleculeInterface molecule) { + + int natoms; + if (molecule == null || (natoms = molecule.getNumberOfAtoms()) < 1) { + return null; + } + + List> molecules = new ArrayList>(); + HashSet track = new HashSet(natoms); // Temporary storage + + for (int i = 0; i < natoms; i++) { + AtomInterface atom = molecule.getAtomInterface(i); + if (track.contains(atom)) { + continue; + } + List list = getMoleculeAtomBelongsTo(atom); + molecules.add(list); + for (AtomInterface at : list) { // Track atoms + track.add(at); + } + } + + track.clear(); + track = null; + return molecules; + } + + public static List getMoleculeAtomBelongsTo(AtomInterface target_atom) { + List group = new ArrayList(); + + // --- Some special cases... + if (target_atom.getNumberOfBondedAtoms() == 0) { + group.add(target_atom); + return group; + } + + // --- General case + findAllBondedAtoms(target_atom, group); + + return group; + } + + public Monomer getMonomer(int n) { + return Atoms.getMonomer(n); + } + + public MonomerInterface getMonomerInterface(int n) { + return Atoms.getMonomer(n); + } + + public String getName() { + return molName; + } + + public AtomInterface getNewAtomInstance() throws NullPointerException { + if (atomInterface == null && this.getNumberOfAtoms() == 0) { + throw new NullPointerException("Atom Interface is not defined"); + } else if (atomInterface == null) { + AtomInterface a = this.getAtomInterface(0); + return a.getNewAtomInstance(); + } + return atomInterface.getNewAtomInstance(); + } + + public BondInterface getNewBondInstance() throws NullPointerException { + if (bondInterface == null && this.getNumberOfBonds() == 0) { + throw new NullPointerException("Bond Interface is not defined"); + } else if (bondInterface == null) { + BondInterface b = this.getBondInterface(0); + return b.getNewBondInstance(); + } + return bondInterface.getNewBondInstance(); + } + + public BondInterface getNewBondInstance(AtomInterface a, AtomInterface b) throws + NullPointerException { + if (bondInterface == null && this.getNumberOfBonds() == 0) { + throw new NullPointerException("Bond Interface is not defined"); + } else if (bondInterface == null) { + BondInterface bb = this.getBondInterface(0); + return bb.getNewBondInstance(a, b); + } + + return bondInterface.getNewBondInstance(a, b); + + } + + public static MoleculeInterface getNewInstance() { + return new Molecule(); + } + + public int getNumberOfAtoms() { + return Atoms.size(); + } + + public int getNumberOfBonds() { + return Bonds.size(); + } + + public int getNumberOfMonomers() { + return Atoms.getNumberOfMonomers(); + } + + public Map getProperties() { + return Properties; + } + + public Object getProperty(String key) { + return Properties.get(key); + } + + public Set getUniqueMonomersInMolecule() { + Set monomers = new HashSet(); + for (int i = 0; i < getNumberOfMonomers(); i++) { + Monomer m = this.getMonomer(i); + String monomer_name = m.getName(); + if (!monomers.contains(monomer_name)) { + monomers.add(monomer_name); + } + } + return monomers; + } + + public static Set getUniqueMonomersInMolecule(MoleculeInterface molec) { + Set monomers = new HashSet(); + for (int i = 0; i < molec.getNumberOfMonomers(); i++) { + MonomerInterface m = molec.getMonomerInterface(i); + String monomer_name = m.getName(); + if (!monomers.contains(monomer_name)) { + monomers.add(monomer_name); + } + } + return monomers; + } + + static public MoleculeInterface getWaterMolecule() { + MoleculeInterface m = new Molecule(); + AtomInterface a = m.getNewAtomInstance(); + a.setAtomicNumber(8); + a.setName("O"); + a.setXYZ(-0.213333f, -0.301699f, 0.000000f); + m.addAtom(a); + + a = m.getNewAtomInstance(); + a.setAtomicNumber(1); + a.setName("H1"); + a.setXYZ(0.746667f, -0.301699f, 0.000000f); + m.addAtom(a); + + a = m.getNewAtomInstance(); + a.setAtomicNumber(1); + a.setName("H2"); + a.setXYZ(-0.533333f, 0.603398f, 0.000000f); + m.addAtom(a); + + Molecule.guessCovalentBonds(m); + + return m; + } + + public float getXmax() { + if (!boundary_done) { + findBoundaries(); + } + return Xmax; + } + + public float getXmin() { + if (!boundary_done) { + findBoundaries(); + } + return Xmin; + } + + public float getYmax() { + if (!boundary_done) { + findBoundaries(); + } + return Ymax; + } + + public float getYmin() { + if (!boundary_done) { + findBoundaries(); + } + return Ymin; + } + + public float getZmax() { + if (!boundary_done) { + findBoundaries(); + } + return Zmax; + } + + public float getZmin() { + if (!boundary_done) { + findBoundaries(); + } + return Zmin; + } + + public static void guessAtomTypes(MoleculeInterface molec) { + guessAtomTypes(molec, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } + + public static void guessAtomTypes(MoleculeInterface molec, String propName, Map elementMapping) { + if (molec == null || molec.getNumberOfAtoms() < 1) { + System.err.println( + "guessAtomTypes: molec == null || molec.getNumberOfAtoms() < 1: Ignored..."); + return; + } + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface a = molec.getAtomInterface(i); + String type = guessAtomType(a, propName, elementMapping); + if (type != null) { + a.setProperty(propName, type); + } + } + } + + public static String guessAtomType(AtomInterface atom, String propName, Map elementMapping) { + + String element = ChemicalElements.getElementSymbol(atom.getAtomicNumber()); + //logger.info("Atom "+i+" element: "+element); + if (!elementMapping.containsKey(element)) { + //logger.info("No mapping for element: " + element); + return null; + } + + Map map = (Map) elementMapping.get(element); + //logger.info("Possible atom types for this element: "+map.size()); + + Set set = map.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String Key = me.getKey().toString(); + CCTAtomTypes Type = (CCTAtomTypes) me.getValue(); + //logger.info("Type: "+Key+" coord number: "+Type.getCoordinationNumber()+" ligands: "+a.getNumberOfBondedAtoms()); + if (Type.getCoordinationNumber() == atom.getNumberOfBondedAtoms()) { + //atom.setProperty(propName, Key); + return Key; + } + } + return null; + } + + public static void redoConnectivity(MoleculeInterface molec) { + for (int i = molec.getNumberOfBonds() - 1; i > -1; i--) { + BondInterface bond = molec.getBondInterface(i); + molec.deleteBond(bond); + guessCovalentBonds(molec); + } + } + + public void guessCovalentBonds() { + guessCovalentBonds(this); + } + + /** + * Tries to find all covalent bonds in the molecule based on the tabulated values of the covalent radii of atoms + * + * @param molec + */ + public static void guessCovalentBonds(MoleculeInterface molec) { + if (molec == null) { + System.err.println("guessCovalentBonds: molecule is null"); + return; + } + for (int i = 0; i < molec.getNumberOfAtoms() - 1; i++) { + //gAtom a_i = Atoms.getAtom(i); + AtomInterface a_i = molec.getAtomInterface(i); + if (a_i.getAtomicNumber() == 0) { + continue; // Dummy atom + } + float radius_i = ChemicalElements.getCovalentRadius(a_i.getAtomicNumber()); + for (int j = i + 1; j < molec.getNumberOfAtoms(); j++) { + AtomInterface a_j = molec.getAtomInterface(j); + if (a_j.getAtomicNumber() == 0) { + continue; // Dummy atom + } + float radius_j = ChemicalElements.getCovalentRadius(a_j.getAtomicNumber()); + double dist = a_i.distanceTo(a_j); + if (dist < 0.001) { + System.err.println("guessCovalentBonds: distance: " + dist + + " - bond is not created"); + } else if (dist <= radius_i + radius_j) { + //createNewBond(a_i, a_j); + BondInterface bond = molec.getNewBondInstance(a_i, a_j); + molec.addBond(bond); + } + } + } + //logger.info("Found " + molec.getNumberOfBonds() + + // " covalent bonds"); + } + + /** + * + * @param n int + * @param m int + */ + public void guessCovalentBondsBetweenMonomers(int n, int m) { + if (n < 0 || n >= getNumberOfMonomers()) { + logger.info( + "INTERNAL ERROR: guessCovalentBondsInMonomer: n < 0 || n >= getNumberOfMonomers()"); + return; + } + if (m < 0 || m >= getNumberOfMonomers()) { + logger.info( + "INTERNAL ERROR: guessCovalentBondsInMonomer: m < 0 || m >= getNumberOfMonomers()"); + return; + } + + Monomer mono_1 = getMonomer(n); + Monomer mono_2 = getMonomer(m); + + for (int i = 0; i < mono_1.getNumberOfAtoms(); i++) { + AtomInterface a_i = mono_1.getAtom(i); + if (a_i.getAtomicNumber() == 0) { + continue; // Dummy atom + } + float radius_i = ChemicalElements.getCovalentRadius(a_i.getAtomicNumber()); + for (int j = 0; j < mono_2.getNumberOfAtoms(); j++) { + AtomInterface a_j = mono_2.getAtom(j); + if (a_j.getAtomicNumber() == 0) { + continue; // Dummy atom + } + float radius_j = ChemicalElements.getCovalentRadius(a_j.getAtomicNumber()); + if (a_i.distanceTo(a_j) <= radius_i + radius_j) { + createNewBond(a_i, a_j); + } + } + } + //logger.info("Found " + Bonds.size() + " covalent bonds"); + } + + public void guessCovalentBondsInMonomer(int n) { + if (n < 0 || n >= getNumberOfMonomers()) { + logger.info( + "INTERNAL ERROR: guessCovalentBondsInMonomer: n < 0 || n >= getNumberOfMonomers()"); + return; + } + Monomer mono = getMonomer(n); + + for (int i = 0; i < mono.getNumberOfAtoms() - 1; i++) { + AtomInterface a_i = mono.getAtom(i); + if (a_i.getAtomicNumber() == 0) { + continue; // Dummy atom + } + float radius_i = ChemicalElements.getCovalentRadius(a_i.getAtomicNumber()); + for (int j = i + 1; j < mono.getNumberOfAtoms(); j++) { + AtomInterface a_j = mono.getAtom(j); + if (a_j.getAtomicNumber() == 0) { + continue; // Dummy atom + } + float radius_j = ChemicalElements.getCovalentRadius(a_j.getAtomicNumber()); + if (a_i.distanceTo(a_j) <= radius_i + radius_j) { + createNewBond(a_i, a_j); + } + } + } + //logger.info("Found " + Bonds.size() + " covalent bonds"); + } + + public static int guessTotalCharge(MoleculeInterface molec, + int multiplicity) throws Exception { + if (multiplicity < 1) { + throw new Exception("Multiplicity cannot be negative!"); + } + + int n_electrons = 0; + // --- Count number of electrons + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface atom = molec.getAtomInterface(i); + int element = atom.getAtomicNumber(); + n_electrons += element; + } + int unpaired = n_electrons % 2; + + if (unpaired == 0 && (multiplicity % 2 == 1)) { // Even number of electrons & odd multiplicity + return 0; + } else if (unpaired == 0 && (multiplicity % 2 == 0)) { // Even number of electrons & even multiplicity + return -1; + } else if (unpaired == 1 && (multiplicity % 2 == 0)) { // Odd number of electrons & even multiplicity + return 0; + } + + // Odd number of electrons & odd multiplicity + return -1; + } + + public static int guessTotalCharge(int elements[], int multiplicity) throws Exception { + if (multiplicity < 1) { + throw new Exception("Multiplicity cannot be negative!"); + } + + int n_electrons = 0; + // --- Count number of electrons + for (int i = 0; i < elements.length; i++) { + n_electrons += elements[i]; + } + int unpaired = n_electrons % 2; + + if (unpaired == 0 && (multiplicity % 2 == 1)) { // Even number of electrons & odd multiplicity + return 0; + } else if (unpaired == 0 && (multiplicity % 2 == 0)) { // Even number of electrons & even multiplicity + return -1; + } else if (unpaired == 1 && (multiplicity % 2 == 0)) { // Odd number of electrons & even multiplicity + return 0; + } + + // Odd number of electrons & odd multiplicity + return -1; + } + + public boolean hasAtom(Atom atom) { + return Atoms.hasAtom(atom); + } + + public static boolean isHeavyAtomsWithinRange(Point3fInterface point, + MonomerInterface monomer, + float radius) { + for (int i = 0; i < monomer.getNumberOfAtoms(); i++) { + AtomInterface atom = monomer.getAtom(i); + if (atom.getAtomicNumber() == 1 || atom.getAtomicNumber() == 0) { + continue; + } + if (Point3f.distance(point, atom) <= (double) radius) { + return true; + } + } + return false; + } + + public static boolean isMatchChargeAndMultiplicity(MoleculeInterface molec, + int charge, int mult) { + if (mult < 1) { + return false; + } + int n_electrons = 0; + // --- Count number of electrons + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface atom = molec.getAtomInterface(i); + int element = atom.getAtomicNumber(); + n_electrons += element; + } + int unpaired = (n_electrons - charge) % 2; + if (unpaired == 0 && mult % 2 == 1) { // Even number of electrons + return true; + } else if (unpaired == 1 && mult % 2 == 0) { // Odd number of electrons + return true; + } + return false; + } + + public static boolean isWithinWanDerWaalsRange(MoleculeInterface molec, + MonomerInterface monomer, + float closeness) { + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface atom = molec.getAtomInterface(i); + int el = atom.getAtomicNumber(); + if (el < 1) { + continue; // Dummy atom + } + float vdw = ChemicalElements.getVanDerWaalsRadius(el); + for (int j = 0; j < monomer.getNumberOfAtoms(); j++) { + AtomInterface m_atom = monomer.getAtom(j); + int m_el = m_atom.getAtomicNumber(); + if (m_el < 1) { + continue; // Dummy atom + } + float m_vdw = ChemicalElements.getVanDerWaalsRadius(m_el); + + if (Point3f.distance(m_atom, atom) + < (double) (closeness * (vdw + m_vdw))) { + return true; + } + } + } + return false; + } + + static public void makeInternalCoordinates(Molecule mol) throws Exception { + if (mol.getNumberOfAtoms() < 2) { + return; + } + VecmathTools.makeInternalCoord(mol.getAtom(1), mol.getAtom(0), null, null, mol.getAtom(1).getZmatrix()); + if (mol.getNumberOfAtoms() < 3) { + return; + } + int[] ijk = mol.getAtom(2).getIJK(); + VecmathTools.makeInternalCoord(mol.getAtom(2), mol.getAtom(ijk[0]), mol.getAtom(ijk[1]), null, + mol.getAtom(2).getZmatrix()); + if (mol.getNumberOfAtoms() < 4) { + return; + } + for (int i = 3; i < mol.getNumberOfAtoms(); i++) { + ijk = mol.getAtom(i).getIJK(); + VecmathTools.makeInternalCoord(mol.getAtom(i), mol.getAtom(ijk[0]), mol.getAtom(ijk[1]), mol.getAtom(ijk[2]), + mol.getAtom(i).getZmatrix()); + } + } + + public void markAtomAsSelected(int n, boolean mark) { + if (n < 0 || n >= Atoms.size()) { + return; + } + AtomInterface a = Atoms.getAtom(n); + a.setSelected(mark); + } + + public void mergeMolecule(MoleculeInterface mol) { + if (mol == null || mol.getNumberOfAtoms() == 0) { + System.err.println("Warning: mergeMolecule: empty molecule to append"); + return; + } + + int oldNumMonomers = this.getNumberOfMonomers(); + for (int i = 0; i < mol.getNumberOfMonomers(); i++) { + MonomerInterface mono = mol.getMonomerInterface(i); + addMonomer(mono.getName()); + for (int j = 0; j < mono.getNumberOfAtoms(); j++) { + addAtom(mono.getAtom(j), oldNumMonomers + i); + } + } + + for (int i = 0; i < mol.getNumberOfBonds(); i++) { + this.addBond(mol.getBondInterface(i)); + } + } + + public static List noncyclicAtomGroup(AtomInterface origin, AtomInterface target) { + List group = new ArrayList(); + + // --- Some special cases... + if (origin.getNumberOfBondedAtoms() == 0) { + group.add(origin); + return group; + } else if (origin.getNumberOfBondedAtoms() == 1 + && origin.isBondedTo(target)) { + group.add(origin); + return group; + } + + // --- General case + if (noncyclicAtomGroup(origin, origin, target, group)) { + return group; + } + + group.clear(); + group.add(origin); + + List bonded = origin.getBondedToAtoms(); + for (int i = 0; i < bonded.size(); i++) { + Atom a = (Atom) bonded.get(i); + if (a != target && a.getNumberOfBondedAtoms() == 1) { + group.add(a); + } + } + + return group; + } + + private static boolean noncyclicAtomGroup(AtomInterface start, AtomInterface origin, AtomInterface target, List group) { + if (start == target) { + return false; + } + + if (group.contains(start)) { + return true; + } + group.add(start); + + List bonded = start.getBondedToAtoms(); + for (int i = 0; i < bonded.size(); i++) { + AtomInterface a = (AtomInterface) bonded.get(i); + if (a == target) { + if (start != origin) { + return false; + } + continue; + } + if (group.contains(a)) { + continue; + } + if (noncyclicAtomGroup(a, origin, target, group)) { + continue; + } else { + return false; + } + } + return true; + } + + public static List noncyclicAtomGroup(AtomInterface origin, AtomInterface target, AtomInterface target_2) { + List group = new ArrayList(); + + // --- Some special cases... + if (origin.getNumberOfBondedAtoms() == 0) { + group.add(origin); + return group; + } else if (origin.getNumberOfBondedAtoms() == 1 + && (origin.isBondedTo(target) || origin.isBondedTo(target_2))) { + group.add(origin); + return group; + } + + // --- General case + if (noncyclicAtomGroup(origin, origin, target, target_2, group)) { + return group; + } + + group.clear(); + group.add(origin); + + List bonded = origin.getBondedToAtoms(); + for (int i = 0; i < bonded.size(); i++) { + Atom a = (Atom) bonded.get(i); + if (a != target && a.getNumberOfBondedAtoms() == 1) { + group.add(a); + } + } + + return group; + } + + private static boolean noncyclicAtomGroup(AtomInterface start, AtomInterface origin, AtomInterface target, AtomInterface target_2, + List group) { + if (start == target || start == target_2) { + return false; + } + + if (group.contains(start)) { + return true; + } + group.add(start); + + List bonded = start.getBondedToAtoms(); + for (int i = 0; i < bonded.size(); i++) { + Atom a = (Atom) bonded.get(i); + if (a == target) { + if (start != origin) { + return false; + } + continue; + } + if (group.contains(a)) { + continue; + } + if (noncyclicAtomGroup(a, origin, target, target_2, group)) { + continue; + } else { + return false; + } + } + return true; + } + + public int numberOfSelectedAtoms() { + int nsel = 0; + if (Atoms.size() < 1) { + return nsel; + } + for (int i = 0; i < Atoms.size(); i++) { + AtomInterface a = Atoms.getAtom(i); + if (a.isSelected()) { + ++nsel; + } + } + return nsel; + } + + public static void rotateAtomAroundAxis(MoleculeInterface molec, + int atom_index, float theta, + Point3fInterface p1, + Point3fInterface p2) { + AtomInterface atom = molec.getAtomInterface(atom_index); + Geometry3d.rotatePointAroundArbitraryAxis(atom, theta, p1, p2); + //logger.info("New XYZ coord: "+atom.getX()+atom.getY()+atom.getZ()); + } + + /** + * Rotates atom around axis defined by points p1 & p2 by angle theta + * + * @param atom AtomInterface + * @param theta float + * @param p1 Point3fInterface + * @param p2 Point3fInterface + */ + public static void rotateAtomAroundAxis(AtomInterface atom, float theta, + Point3fInterface p1, + Point3fInterface p2) { + + Geometry3d.rotatePointAroundArbitraryAxis(atom, theta, p1, p2); + //logger.info("New XYZ coord: "+atom.getX()+atom.getY()+atom.getZ()); + } + + public static void rotateAtomsAroundAxis(List group, float theta, Point3fInterface p1, Point3fInterface p2) { + if (group == null || group.size() < 1 || theta == 0) { + return; + } + + AtomInterface atom = (AtomInterface) group.get(0); + //vPoint3f origin = new Point3f(atom); // remember old atom position + + Geometry3d.rotatePointAroundArbitraryAxis(atom, theta, p1, p2); + + // --- get direction of translation + //origin.x = atom.getX() - origin.x; + //origin.y = atom.getY() - origin.y; + //origin.z = atom.getZ() - origin.z; + //float translation = origin.vectorNorm(); + //float d = atom.distanceToLine(p1,p2); + //origin.normalize(); + //float factor = translation/d; + for (int i = 1; i < group.size(); i++) { // Starting from the second atom + atom = (Atom) group.get(i); + //if (hasAtom(atom)) { + Geometry3d.rotatePointAroundArbitraryAxis(atom, theta, p1, p2); + //atom.translateAtom(origin, atom.distanceToLine(p1,p2)*factor); + //logger.info("New atom "+i+" coord: "+atom.getX()+" "+atom.getY()+" "+atom.getZ()); + //} + //else { + // logger.info( + // "INTERNAL ERROR: rotateAtomsAroundAxis: hasAtom(atom)"); + //} + } + } + + public void rotateMoleculeAroundAxis(float theta, Point3fInterface p1, Point3fInterface p2) { + rotateMoleculeAroundAxis(this, theta, p1, p2); + } + + /** + * Rotates all atoms of molecule around axis p1-p2 by angle theta + * + * @param mol MoleculeInterface + * @param theta float + * @param p1 Point3fInterface + * @param p2 Point3fInterface + */ + public static void rotateMoleculeAroundAxis(MoleculeInterface mol, float theta, + Point3fInterface p1, + Point3fInterface p2) { + if (mol == null || mol.getNumberOfAtoms() < 1 || theta == 0) { + System.err.println("rotateMoleculeAroundAxis: mol == null || mol.getNumberOfAtoms() < 1 || theta == 0"); + return; + } + + for (int i = 0; i < mol.getNumberOfAtoms(); i++) { // Starting from the second atom + AtomInterface atom = mol.getAtomInterface(i); + Geometry3d.rotatePointAroundArbitraryAxis(atom, theta, p1, p2); + } + } + + /** + * Randomly rotates a molecule + */ + public void rotateMoleculeRandomly() { + rotateMoleculeRandomly(this); + } + + /** + * Randomly rotates a molecule + * + * @param mol + */ + public static void rotateMoleculeRandomly(MoleculeInterface mol) { + float theta = (float) (-Math.PI + Math.random() * 2.0 * Math.PI); + Point3f p1 = new Point3f((float) (-1.0 + Math.random() * 2.0), + (float) (-1.0 + Math.random() * 2.0), + (float) (-1.0 + Math.random() * 2.0)); + Point3f p2 = new Point3f((float) (-1.0 + Math.random() * 2.0), + (float) (-1.0 + Math.random() * 2.0), + (float) (-1.0 + Math.random() * 2.0)); + rotateMoleculeAroundAxis(mol, theta, p1, p2); + } + + /** + * Selects (deselects) all atoms in molecule + * + * @param enable boolean "true" - select all, "false" - deselect all + */ + public void selectAllAtoms(boolean enable) { + for (int i = 0; i < getNumberOfAtoms(); i++) { + AtomInterface a = getAtom(i); + a.setSelected(enable); + } + } + + public static void selectAllAtoms(MoleculeInterface molec, boolean enable) { + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface a = molec.getAtomInterface(i); + a.setSelected(enable); + } + } + + public void setAtomInterface(AtomInterface a_interface) { + atomInterface = a_interface; + } + + public void setBondInterface(BondInterface b_interface) { + bondInterface = b_interface; + } + + public static boolean setCoordinates(MoleculeInterface molec, Point3f coord[]) { + if (molec == null || coord == null) { + return false; + } + if (coord.length < molec.getNumberOfAtoms()) { + logger.info( + "INTERNAL ERROR: setCoordinates: coord.length < this.getNumberOfAtoms()"); + return false; + } + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface a = molec.getAtomInterface(i); + a.setXYZ(coord[i]); + } + return true; + } + + public void setName(String name) { + molName = name; + } + + public static boolean toArchiveFormat(MoleculeInterface molec, + OutputStream out) { + if (molec.getNumberOfAtoms() < 1) { + return false; + } + int offset = 0; + String bufer = String.valueOf(molec.getNumberOfAtoms()) + "\n"; + int len = bufer.length(); + + // -- Write number of atoms + try { + out.write(bufer.getBytes(), offset, len); + //offset += len; + } catch (IOException e) { + logger.info( + "toArchiveFormat: cannot write number of atoms\n"); + return false; + } + + // --- Write atoms + try { + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface a = molec.getAtomInterface(i); + bufer = a.getAtomicNumber() + "," + a.getName() + "," + a.getX() + + "," + a.getY() + "," + a.getZ() + "\n"; + len = bufer.length(); + out.write(bufer.getBytes(), offset, len); + //offset += len; + } + } catch (IOException e) { + logger.info("toArchiveFormat: cannot write atom's info"); + return false; + } + + // -- Write number of bonds + bufer = String.valueOf(molec.getNumberOfBonds()) + "\n"; + try { + out.write(bufer.getBytes(), offset, bufer.length()); + //offset += len; + } catch (IOException e) { + logger.info( + "toArchiveFormat: cannot write number of bonds\n"); + return false; + } + + // --- Write bonds + try { + for (int i = 0; i < molec.getNumberOfBonds(); i++) { + BondInterface b = molec.getBondInterface(i); + AtomInterface a = b.getIAtomInterface(); + int at_i = molec.getAtomIndex(a); + if (at_i == -1) { + logger.info("toArchiveFormat: wrong a1 in bond" + + (i + 1)); + continue; + } + a = b.getJAtomInterface(); + int at_j = molec.getAtomIndex(a); + if (at_j == -1) { + logger.info("toArchiveFormat: wrong a2 in bond" + + (i + 1)); + continue; + } + + bufer = at_i + "," + at_j + "\n"; + len = bufer.length(); + out.write(bufer.getBytes(), offset, len); + //offset += len; + } + } catch (IOException e) { + logger.info("toArchiveFormat: cannot write bonds info"); + return false; + } + + // --- Close + try { + out.close(); + } catch (IOException e) { + //logger.info( "toArchiveFormat: cannot write atom's info"); + //return false; + } + + return true; + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < this.getNumberOfAtoms(); i++) { + AtomInterface atom = this.getAtom(i); + sb.append(String.format("%-3d %-5s %-2d %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f %-3d %-3d %-3d", + (i + 1), atom.getName(), atom.getAtomicNumber(), atom.getX(), atom.getY(), atom.getZ(), atom.getBond(), + atom.getAngle(), atom.getDihedralAngle(), atom.getNA() + 1, atom.getNB() + 1, atom.getNC() + 1)); + } + return sb.toString(); + } + + public static void translateAtom(MoleculeInterface molec, int atom_index, + float dir[], float increment) { + AtomInterface atom = molec.getAtomInterface(atom_index); + //atom.translateAtom(dir, increment); + atom.setX(atom.getX() + dir[0] * increment); + atom.setY(atom.getY() + dir[1] * increment); + atom.setZ(atom.getZ() + dir[2] * increment); + + } + + public static void translateAtom(AtomInterface atom, float dir[], + float increment) { + atom.setX(atom.getX() + dir[0] * increment); + atom.setY(atom.getY() + dir[1] * increment); + atom.setZ(atom.getZ() + dir[2] * increment); + } + + public static void translateAtoms(List group, float dir[], float increment) { + for (int i = 0; i < group.size(); i++) { + AtomInterface atom = (AtomInterface) group.get(i); + //if (hasAtom(atom)) { + Point3f.translatePoint(atom, dir, increment); + //logger.info("New atom "+i+" coord: "+atom.getX()+" "+atom.getY()+" "+atom.getZ()); + //} + // else { + // logger.info( + // "INTERNAL ERROR: translateAtoms: hasAtom(atom)"); + // } + } + } + + public void translateMolecule(float dir[], float increment) { + translateMolecule(this, dir, increment); + } + + public static void translateMolecule(MoleculeInterface mol, float dir[], float increment) { + for (int i = 0; i < mol.getNumberOfAtoms(); i++) { + AtomInterface atom = mol.getAtomInterface(i); + Point3f.translatePoint(atom, dir, increment); + } + } + + public static void updateCoordinates(MoleculeInterface molecule, String file_type_description, String file_name) throws + Exception { + if (molecule == null || molecule.getNumberOfAtoms() < 1) { + throw new Exception("Error updating coordinates: Reference molecule has no atoms"); + } + + if (!MolecularFileFormats.getUpdateCoordFormats().containsKey(file_type_description)) { + throw new Exception("Error: cannot update coordinates from file type: " + file_type_description); + } + + // --- Update from Amber coordinate file + if (file_type_description.equalsIgnoreCase(MolecularFileFormats.amberCoordFormat)) { + AmberUtilities.updateCoordFromInpcrd(molecule, file_name); + } // --- Update from PDB file + else if (file_type_description.equalsIgnoreCase(MolecularFileFormats.pdbFile)) { + PDB.updateCoordFromPDB(molecule, file_name); + } + + } + + public static void validateSets(MoleculeInterface mol) { + Object obj = mol.getProperty(MoleculeInterface.AtomicSets); + if (obj == null || !(obj instanceof AtomicSets)) { + return; + } + AtomicSets sets = (AtomicSets) obj; + if (sets.size() < 1) { + return; + } + + AtomicSets updated_sets = new AtomicSets(); + Iterator iter = sets.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + obj = me.getValue(); + if (!(obj instanceof AtomicSet)) { + System.err.println("validateSets: Expecting AtomicSet, got " + obj.getClass().getCanonicalName() + " Ignored..."); + continue; + } + AtomicSet aset = (AtomicSet) obj; + if (aset.size() < 1) { + continue; + } + + AtomicSet new_aset = new AtomicSet(aset.getName()); + for (int i = 0; i < aset.size(); i++) { + AtomInterface atom = aset.get(i); + if (mol.getAtomIndex(atom) == -1) { + continue; + } + new_aset.add(atom); + } + if (new_aset.size() < 1) { + continue; + } + + updated_sets.put(new_aset.getName(), new_aset); + } + + Map props = mol.getProperties(); + if (updated_sets.size() < 1) { + props.remove(sets); + return; + } + props.put(MoleculeInterface.AtomicSets, updated_sets); + } + + public static void validateTotalCharge(int elements[], int charge, int multiplicity) throws Exception { + if (multiplicity < 1) { + throw new Exception("Multiplicity should be > 0"); + } + + int n_electrons = -charge; + // --- Count number of electrons + for (int i = 0; i < elements.length; i++) { + n_electrons += elements[i]; + } + int unpaired = n_electrons % 2; + + if (unpaired == 0 && (multiplicity % 2 == 1)) { // Even number of electrons & odd multiplicity + return; + } else if (unpaired == 0 && (multiplicity % 2 == 0)) { // Even number of electrons & even multiplicity + throw new Exception("Charge " + charge + " and multiplicity " + multiplicity + " do not make sense"); + } else if (unpaired == 1 && (multiplicity % 2 == 0)) { // Odd number of electrons & even multiplicity + return; + } + + // Odd number of electrons & odd multiplicity + throw new Exception("Charge " + charge + " and multiplicity " + multiplicity + " do not make sense"); + } + + public static void validateTotalCharge(MoleculeInterface molec, int charge, int multiplicity) throws Exception { + if (multiplicity < 1) { + throw new Exception("Multiplicity should be > 0"); + } + + int n_electrons = -charge; + + // --- Count number of electrons + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface atom = molec.getAtomInterface(i); + int element = atom.getAtomicNumber(); + n_electrons += element; + } + + int unpaired = n_electrons % 2; + + if (unpaired == 0 && (multiplicity % 2 == 1)) { // Even number of electrons & odd multiplicity + return; + } else if (unpaired == 0 && (multiplicity % 2 == 0)) { // Even number of electrons & even multiplicity + throw new Exception("Charge " + charge + " and multiplicity " + multiplicity + " do not make sense"); + } else if (unpaired == 1 && (multiplicity % 2 == 0)) { // Odd number of electrons & even multiplicity + return; + } + + // Odd number of electrons & odd multiplicity + throw new Exception("Charge " + charge + " and multiplicity " + multiplicity + " do not make sense"); + } + + public Molecule(Map mol) { + + Integer temp = (Integer) mol.get("natoms"); + number_of_Atoms = temp.intValue(); +// number_of_Atoms = Integer.parseInt( (String) ); + logger.info("Number of atoms" + number_of_Atoms); + String key, value; + StringTokenizer tk; + Atom a; + + for (int i = 0; i < number_of_Atoms; i++) { + key = "a" + Integer.toString(i); + value = (String) mol.get(key); + a = new Atom(); + + if (value != null) { + tk = new StringTokenizer(value, ","); + a.setName(tk.nextToken()); + a.setX(Float.parseFloat(tk.nextToken())); + a.setY(Float.parseFloat(tk.nextToken())); + a.setZ(Float.parseFloat(tk.nextToken())); + Atoms.addAtom(a); + logger.info(i + value); + } else { + break; + } + } + } + +} diff --git a/src/main/java/cct/modelling/Monomer.java b/src/main/java/cct/modelling/Monomer.java new file mode 100644 index 0000000..ce79ee5 --- /dev/null +++ b/src/main/java/cct/modelling/Monomer.java @@ -0,0 +1,107 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +import java.util.ArrayList; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MonomerInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class Monomer + extends ArrayList implements MonomerInterface { + protected String name = ""; + + public Monomer() { + name = null; + } + + public Monomer(String r_name) { + name = r_name; + } + + public boolean addAtom(AtomInterface a) { + return add(a); + } + + @Override + public AtomInterface getAtom(int n) { + if (n < 0 || n >= size()) { + return null; + } + return (AtomInterface) get(n); + } + + @Override + public int getAtomIndex(AtomInterface atom) { + return this.indexOf(atom); + } + + @Override + public String getName() { + return name; + } + + @Override + public int getNumberOfAtoms() { + return size(); + } + + public void selectAllAtoms(boolean select) { + for (int i = 0; i < this.size(); i++) { + AtomInterface atom = (AtomInterface) get(i); + atom.setSelected(select); + } + } + + @Override + public void setName(String r_name) { + this.name = r_name; + } +} diff --git a/src/main/java/cct/modelling/Nonbonded15Table.java b/src/main/java/cct/modelling/Nonbonded15Table.java new file mode 100644 index 0000000..66fcf48 --- /dev/null +++ b/src/main/java/cct/modelling/Nonbonded15Table.java @@ -0,0 +1,97 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Nonbonded15Table { + int size = 0; + boolean[] table = null; + + public Nonbonded15Table(int natoms) { + if (natoms < 2) { + return; + } + table = new boolean[natoms * (natoms - 1) / 2]; + for (int i = 0; i < table.length; i++) { + table[i] = true; + } + } + + public void set15(int i, int j, boolean exist15) { + if (i == j) { + return; + } + if (i > j) { + if (i == 0) { + return; + } + table[i * (i - 1) / 2 + j] = exist15; + } + else if (j > 0) { + table[j * (j - 1) / 2 + i] = exist15; + } + } + + public boolean get15(int i, int j) { + if (i == j) { + return false; + } + if (i > j) { + if (i == 0) { + return false; + } + return table[i * (i - 1) / 2 + j]; + } + else if (j > 0) { + return table[j * (j - 1) / 2 + i]; + } + return false; + } + +} diff --git a/src/main/java/cct/modelling/NonbondedEnergy.java b/src/main/java/cct/modelling/NonbondedEnergy.java new file mode 100644 index 0000000..34775a7 --- /dev/null +++ b/src/main/java/cct/modelling/NonbondedEnergy.java @@ -0,0 +1,153 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.modelling; + +import java.util.List; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.vecmath.Point3f; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class NonbondedEnergy { + + private NonbondedEnergy() { + } + + public static double LennardJonesEnergy(MoleculeInterface molec, List nonbodedPairs, double SCNB) { + double energy = 0; + for (int i = 0; i < nonbodedPairs.size(); i++) { + NonbondedPair nb = (NonbondedPair) nonbodedPairs.get(i); + AtomInterface a1 = molec.getAtomInterface(nb.getI()); + AtomInterface a2 = molec.getAtomInterface(nb.getJ()); + double Rsq = 1.0 / Point3f.distanceSquared(a1, a2); + Rsq = Rsq * Rsq * Rsq; + + energy += (nb.A * Rsq - nb.C) * Rsq; + } + return SCNB * energy; + } + + /** + * Energy between atoms in molecule and surface(s) + * + * @param molec - Molecule + * @param surfaces - Surfaces list + * @param SCNB + * @return - non-bonded energy + */ + public static double LennardJonesSurfaceEnergy(MoleculeInterface molec, List surfaces) { + double energy = 0; + for (MolecularPlane mp : surfaces) { + List atomList = mp.getAtomList(); + for (AtomSurfaceEntity ase : atomList) { + AtomInterface atom = ase.getAtom(); + double dist = mp.distanceToPoint(atom.getX(), atom.getY(), atom.getZ()); + dist = Math.pow(1.0 / (dist * dist), 3); + energy += (ase.getA() * dist - ase.getC()) * dist; + } + } + return energy; + } + + public static double LennardJonesEnergy(MoleculeInterface molec, List nonbodedPairs, double SCNB, Point3f[] Gradients) { + double energy = 0; + for (int k = 0; k < nonbodedPairs.size(); k++) { + NonbondedPair nb = (NonbondedPair) nonbodedPairs.get(k); + int i = nb.getI(); + int j = nb.getJ(); + AtomInterface a1 = molec.getAtomInterface(i); + AtomInterface a2 = molec.getAtomInterface(j); + + float dx = a1.getX() - a2.getX(); + float dy = a1.getY() - a2.getY(); + float dz = a1.getZ() - a2.getZ(); + + double R6 = dx * dx + dy * dy + dz * dz; + //float r = (float)Math.sqrt(R6); + double R2 = R6; + R6 *= R6 * R6; + float coeff = (float) (6.0 * SCNB * (-2.0 * (nb.A - nb.C * R6) - nb.C * R6) / (R6 * R6 * R2)); + + Gradients[i].add(dx * coeff, dy * coeff, dz * coeff); + Gradients[j].add(-dx * coeff, -dy * coeff, -dz * coeff); + + energy += (nb.A - nb.C * R6) / (R6 * R6); + } + return SCNB * energy; + } + + public static double LennardJonesSurfaceEnergy(MoleculeInterface molec, List surfaces, Point3f[] Gradients) { + double energy = 0; + + for (MolecularPlane mp : surfaces) { + List atomList = mp.getAtomList(); + int count = 0; + for (AtomSurfaceEntity ase : atomList) { + AtomInterface atom = ase.getAtom(); + + double distSigned = mp.distanceToPointSigned(atom.getX(), atom.getY(), atom.getZ()); + double dist = 1.0 / Math.abs(distSigned); + double R6 = Math.pow(dist, 6); + energy += (ase.getA() * R6 - ase.getC()) * R6; + + double deriv = 6.0 * (-2.0 * ase.getA() + R6 * ase.getC()) * R6 * R6 * dist; + Gradients[count].add((float) (sign(mp.getA(), distSigned) * deriv), + (float) (sign(mp.getB(), distSigned) * deriv), + (float) (sign(mp.getC(), distSigned) * deriv)); + ++count; + } + } + + return energy; + } + + private static double sign(double value, double sign) { + return sign >= 0 ? value : -value; + } +} diff --git a/src/main/java/cct/modelling/NonbondedPair.java b/src/main/java/cct/modelling/NonbondedPair.java new file mode 100644 index 0000000..21985ea --- /dev/null +++ b/src/main/java/cct/modelling/NonbondedPair.java @@ -0,0 +1,84 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class NonbondedPair { + int ij[] = new int[2]; + double C = 0, A = 0; + public NonbondedPair(int a1, int a2) { + ij[0] = a1; + ij[1] = a2; + } + + public int getI() { + return ij[0]; + } + + public int getJ() { + return ij[1]; + } + + public void setA(float e) { + A = e; + } + + public void setA(double e) { + A = e; + } + + public void setC(float s) { + C = s; + } + + public void setC(double s) { + C = s; + } + +} diff --git a/src/main/java/cct/modelling/OperationsOnAtoms.java b/src/main/java/cct/modelling/OperationsOnAtoms.java new file mode 100644 index 0000000..37b978b --- /dev/null +++ b/src/main/java/cct/modelling/OperationsOnAtoms.java @@ -0,0 +1,86 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +public interface OperationsOnAtoms { + + int SELECTION_UNLIMITED = 0; + int SELECTION_ONE_ATOM_ONLY = 1; + int SELECTION_SPOT_ONLY = 2; + int SELECTION_TWO_ATOMS_ONLY = 3; + int SELECTION_THREE_ATOMS_ONLY = 4; + int SELECTION_FOUR_ATOMS_ONLY = 5; + + //public static final int SELECT_ATOMS = 0; + //public static final int SELECT_MONOMERS = 1; + //public static final int SELECT_MOLECULES = 2; + + //public static final int RULE_UNION = 0; + //public static final int RULE_DIFFERENCE = 1; + //public static final int RULE_INTERSECTION = 2; + + int SELECTED_NOTHING = -1; + int SELECTED_DISPLAY_ATOMS = 0; + int SELECTED_UNDISPLAY_ATOMS = 1; + int SELECTED_DELETE_ATOMS = 2; + int SELECTED_LABEL_ATOMS = 3; + int SELECTED_ADD_ATOMS = 4; + int SELECTED_UNLABEL_ATOMS = 5; + int SELECTED_MODIFY_ATOMS = 6; + int SELECTED_MODIFY_BONDS = 7; + int SELECTED_MODIFY_ANGLES = 8; + int SELECTED_MODIFY_DIHEDRALS = 9; + int SELECTED_FILL_VALENCES_WITH_HYDROGENS = 10; + int SELECTED_ADD_MOLECULE = 11; + int SELECTED_ADD_FRAGMENT = 12; + int SELECTED_CREATE_CENTROID = 13; + int SELECTED_SOLVATE_CAP = 14; + int SELECTED_SOLVATE_SHELL = 15; + int SELECTED_CHANGE_ATOM_LABELS_SIZE = 16; + int SELECTED_CHANGE_ATOM_LABELS_COLOR = 17; + int SELECTED_CHANGE_ATOM_COLORS = 18; + int SELECTED_CREATE_ATOMIC_SET = 19; + int SELECTED_ROTATION_CENTER = 20; + + int FIXED_ATOM = 0; + int ROTATE_GROUP = 1; + int TRANSLATE_GROUP = 2; + int TRANSLATE_ATOM = 3; + int ROTATE_ATOM = 4; + +} diff --git a/src/main/java/cct/modelling/ParseTriposMol2.java b/src/main/java/cct/modelling/ParseTriposMol2.java new file mode 100644 index 0000000..5804dbc --- /dev/null +++ b/src/main/java/cct/modelling/ParseTriposMol2.java @@ -0,0 +1,338 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +import java.io.BufferedReader; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; +import cct.interfaces.MoleculeInterface; +import cct.interfaces.MonomerInterface; + +/** + * + *

Title: ParseTriposMol2

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class ParseTriposMol2 + implements AtomProperties { + private ParseTriposMol2() { + } + + static final Logger logger = Logger.getLogger(ParseTriposMol2.class.getCanonicalName()); + + + public static void parseMol2File(String filename, MoleculeInterface mol) { + //Molecule mol = null; + AtomInterface atom; + BondInterface bond; + String line; + StringTokenizer st; + Integer natoms = new Integer(0), nbonds = new Integer(0), + nresidues = new Integer(0); + Float cartes = new Float(0.0f); + + try { + BufferedReader in = new BufferedReader(new FileReader(filename)); + //mol = new Molecule(); + while ( (line = in.readLine()) != null) { + //line.trim(); + + if (line.compareToIgnoreCase("@MOLECULE") == 0) { + // Read Molecule name + line = in.readLine(); + //line.trim(); + mol.setName(line); + + // read number of atoms & bonds + line = in.readLine(); + st = new StringTokenizer(line, " "); + + try { + natoms = new Integer(st.nextToken()); + nbonds = new Integer(st.nextToken()); + nresidues = new Integer(st.nextToken()); + } + catch (NumberFormatException e) { + break; + } + + } + + else if (line.compareToIgnoreCase("@ATOM") == 0) { + //@ATOM + // 1 P 5.9733 -6.8476 27.4300 P.3 1 A1 0.0000 BACKBONE|DICT|DIRECT + // 2 O1P 6.2573 -8.2786 27.2100 O.co2 1 A1 0.0000 BACKBONE|DICT + int current_subst_id = 0; + + for (int i = 0; i < natoms.intValue(); i++) { + if ( (line = in.readLine()) == null) { + break; + } + st = new StringTokenizer(line, " "); + + boolean new_residue = false; + String substr = null; + + st.nextToken(); // skip first token + + atom = mol.getNewAtomInstance(); // gAtom(); + atom.setProperty(AtomInterface.NAME, st.nextToken()); + + // --- Read in coordinates + if (st.countTokens() < 3) { + break; // Actually it's an error + } + + try { + atom.setX(Float.parseFloat(st.nextToken())); + atom.setY(Float.parseFloat(st.nextToken())); + atom.setZ(Float.parseFloat(st.nextToken())); + + } + catch (NumberFormatException e) { + logger.info( + "Error converting cartesin coordinates\n"); + break; + } + + if (st.countTokens() > 0) { // Parse Tripos Atom Type + String triposName = st.nextToken(); + atom.setProperty(AtomInterface.SYBYL_TYPE, + triposName); + atom.setAtomicNumber(triposAtomTypeToElement( + triposName)); + } + // --- + int subst_id = current_subst_id; + if (st.countTokens() > 0) { // Parse the ID number of the substructure containing the atom + try { + subst_id = Integer.parseInt(st.nextToken()); + --subst_id; + } + catch (NumberFormatException e) { + logger.info( + "Error converting ID number of the substructure containing the atom"); + break; + } + + if (subst_id < 0) { + logger.info( + "Error in MOL2 file: substructure ID is negative: " + subst_id); + break; + } + + if (subst_id > current_subst_id) { + new_residue = true; + current_subst_id = subst_id; + } + //a.setSubstructureNumber(Integer.parseInt(st. + // nextToken())); + } + + if (st.countTokens() > 0) { // Parse the name of the substructure containing the atom + //if ( new_residue ) { + StringTokenizer res = new StringTokenizer(st.nextToken(), "0123456789"); + substr = res.nextToken(); + //} + //else + // st.nextToken(); // Skip token + } + + if (st.countTokens() > 0) { + atom.setProperty(AtomInterface.ATOMIC_CHARGE, + st.nextToken()); + } + + logger.info(atom.getAtomicNumber() + " XYZ: " + + atom.getX() + " " + atom.getY() + " " + + atom.getZ()); + if (substr == null) { + substr = "UNK"; + } + mol.addAtom(atom, subst_id, substr); + } + + logger.info("Number of atoms in " + filename + " : " + + mol.getNumberOfAtoms()); + for (int i = 0; i < mol.getNumberOfAtoms(); i++) { + atom = mol.getAtomInterface(i); + logger.info(i + " " + atom.getName() + " " + atom.getSubstructureNumber()); + } + for (int i = 0; i < mol.getNumberOfMonomers(); i++) { + MonomerInterface m = mol.getMonomerInterface(i); + logger.info("Res: " + i + " " + m.getName() + " atoms:" + m.getNumberOfAtoms()); + } + + } + + else if (line.compareToIgnoreCase("@BOND") == 0) { + + for (int i = 0; i < nbonds.intValue(); i++) { + if ( (line = in.readLine()) == null) { + break; + } + st = new StringTokenizer(line, " "); + + // Inform about error and continue.... + if (st.countTokens() < 3) { + logger.info( + "Uncomplete BOND record... Continuing...\n"); + continue; + } + + st.nextToken(); // skip first token + + int a1, a2; + try { + a1 = Integer.parseInt(st.nextToken()) - 1; + a2 = Integer.parseInt(st.nextToken()) - 1; + } + catch (NumberFormatException e) { + logger.info( + "Error converting bonded atoms\n"); + break; + } + + AtomInterface a_i = mol.getAtomInterface(a1); + AtomInterface a_j = mol.getAtomInterface(a2); + bond = mol.getNewBondInstance(a_i, a_j); + mol.addBond(bond); + //mol.createNewBond(a_i, a_j); + + } + + logger.info("Number of bonds: " + + mol.getNumberOfBonds()); + + } + + } // --- End of while + + } + catch (IOException e) { + logger.info("parseMol2File: " + e.getMessage() + "\n"); + return; + } + /* + try { + StreamTokenizer tok = new StreamTokenizer( new FileReader( filename )); + tok.resetSyntax(); + tok.wordChars(1,255); + tok.whitespaceChars( ' ', ' '); + //tok.eolIsSignificant( true ); + + mol = new Molecule(); + + while( tok.nextToken() != tok.TT_EOF ) { + + } + } catch ( IOException e ) { + + } + */ + + return ; + } + + //************************************************************************** + public static void saveTriposMol2File(MoleculeInterface m, String filename) { + + FileOutputStream out; + try { + out = new FileOutputStream(filename); + } + catch (java.io.FileNotFoundException e) { + System.err.println(filename + " not found\n"); + return; + } + catch (SecurityException e) { + System.err.println(filename + ": " + e.getMessage()); + return; + } + catch (IOException e) { + logger.info(filename + ": " + e.getMessage()); + return; + } + + try { + out.write( ("@MOLECULE\n").getBytes()); + out.write( (m.getName() + "\n").getBytes()); + out.write( (m.getNumberOfAtoms() + "\n").getBytes()); + out.write( ("@ATOM\n").getBytes()); + for (int i = 0; i < m.getNumberOfAtoms(); i++) { + AtomInterface a = m.getAtomInterface(i); + out.write( ( (i + 1) + " " + a.getName()).getBytes()); + out.write( (" " + a.getX() + " " + a.getY() + " " + a.getZ()). + getBytes()); + out.write( (" " + a.getProperty(AtomInterface.SYBYL_TYPE)). + getBytes()); + out.write( (" " + a.getSubstructureNumber()).getBytes()); + out.write( (" " + "XXX").getBytes()); + out.write( (" " + a.getProperty(AtomInterface.ATOMIC_CHARGE)). + getBytes()); + out.write( ("\n").getBytes()); + } + out.close(); + } + catch (IOException e) { + logger.info("Error writing into " + filename); + return; + } + + } + + //************************************************************************** + public static int triposAtomTypeToElement(String atomType) { + StringTokenizer tok = new StringTokenizer(atomType, " ."); + return ChemicalElements.getAtomicNumber(tok.nextToken()); + } +} diff --git a/src/main/java/cct/modelling/SELECTION_RULE.java b/src/main/java/cct/modelling/SELECTION_RULE.java new file mode 100644 index 0000000..f83cdc0 --- /dev/null +++ b/src/main/java/cct/modelling/SELECTION_RULE.java @@ -0,0 +1,46 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.modelling; + +/** + * + * @author Vlad + */ +public enum SELECTION_RULE { + + UNION, DIFFERENCE, INTERSECTION +} diff --git a/src/main/java/cct/modelling/SELECTION_TYPE.java b/src/main/java/cct/modelling/SELECTION_TYPE.java new file mode 100644 index 0000000..c2eda47 --- /dev/null +++ b/src/main/java/cct/modelling/SELECTION_TYPE.java @@ -0,0 +1,47 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +/** + * + * @author Vlad + */ +public enum SELECTION_TYPE { + + ATOMS, MONOMERS, MOLECULES +} diff --git a/src/main/java/cct/modelling/SaveGJF.java b/src/main/java/cct/modelling/SaveGJF.java new file mode 100644 index 0000000..1a08468 --- /dev/null +++ b/src/main/java/cct/modelling/SaveGJF.java @@ -0,0 +1,142 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.logging.Logger; + +import cct.gaussian.Gaussian; +import cct.gaussian.GaussianMolecule; + +public class SaveGJF { + static final Logger logger = Logger.getLogger(SaveGJF.class.getCanonicalName()); + + public SaveGJF() { + } + + public static void saveGJF(Gaussian g, int job, String filename) { + + FileOutputStream out; + try { + out = new FileOutputStream(filename); + } + catch (java.io.FileNotFoundException e) { + logger.info(filename + " not found\n"); + return; + } + catch (SecurityException e) { + logger.info(filename + ": Security Eception\n"); + return; + } + catch (IOException e) { + logger.info(filename + ": Read-only file\n"); + return; + } + + int start = 0, end = g.getNumberOfMolecules() - 1; + if (end < 0) { + logger.info("saveGJF: no molecules"); + return; + } + if (job >= 0) { + start = end = job; + } + + int count = -1; + for (int i = start; i <= end; i++) { + ++count; + GaussianMolecule gmol = g.getGaussianMolecule(i); + + // --- Write Link section (if any) + + if (count > 0) { + try { + out.write( ("--Link1--\n").getBytes()); + } + catch (IOException e) { + logger.info("saveGJF: Error writing Link Section"); + return; + } + + } + + // --- Write Link 0 Commands (% lines) + + if (!gmol.writeLinkZeroCommands(out)) { + return; + } + + // --- Write Route Section + + if (!gmol.writeRouteSection(out)) { + return; + } + + // --- Write Title Section + + if (!gmol.writeTitleSection(out)) { + return; + } + + // --- Write Charge Section + + if (!gmol.writeChargeSection(out)) { + return; + } + + // --- Write Atom Coordinates + + if (!gmol.writeAtoms(out)) { + return; + } + + } + + // --- Finally, close a stream + try { + out.close(); + } + catch (IOException e) { + logger.info("Error closing " + filename); + return; + } + + } + +} diff --git a/src/main/java/cct/modelling/SingleTrajectory.java b/src/main/java/cct/modelling/SingleTrajectory.java new file mode 100644 index 0000000..d8fd276 --- /dev/null +++ b/src/main/java/cct/modelling/SingleTrajectory.java @@ -0,0 +1,500 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.modelling; + +import java.io.File; +import java.io.RandomAccessFile; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import cct.gaussian.G03MDTrajectory; +import cct.gaussian.GaussianAtom; +import cct.interfaces.MoleculeInterface; + +/** + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + * @deprecated + */ +public class SingleTrajectory { + + protected String Title = null; + protected String fileName = null; + protected RandomAccessFile raf = null; + protected MoleculeInterface referenceStructure = null; + protected boolean periodicConditions = false; + protected List trajectorySnapshots = new ArrayList(); + static final Logger logger = Logger.getLogger(SingleTrajectory.class.getCanonicalName()); + + public SingleTrajectory(MoleculeInterface mol) { + referenceStructure = mol; + } + + public static void main(String[] args) { + //SingleTrajectory trajectoryfile = new SingleTrajectory(); + } + + public void parseTrajectoryFile(String fileName, TRAJECTORY_FILE_FORMAT format, int additional_condition) throws Exception { + if (fileName == null || fileName.length() < 1) { + throw new Exception("Trajectory file name is not set"); + } + if (format == null) { + throw new Exception("Trajectory file format is not set"); + } + + try { + switch (format) { + case AMBER: + raf = parseAmberTrajectory(fileName, format, additional_condition); + break; + case G03_TRAJECTORY: + raf = parseG03Trajectory(fileName, format, additional_condition); + break; + case GULP_TRAJECTORY: + raf = parseGULPTrajectory(fileName, format, additional_condition); + break; + } + } catch (Exception ex) { + throw ex; + } + } + + public RandomAccessFile parseAmberTrajectory(String fileName, TRAJECTORY_FILE_FORMAT format, int flag_1) throws Exception { + if (fileName == null || fileName.length() < 1) { + throw new Exception("Trajectory file name is not set"); + } + if (referenceStructure == null || referenceStructure.getNumberOfAtoms() < 1) { + throw new Exception("Reference molecule is not set or has no atoms"); + } + + int n_atoms = referenceStructure.getNumberOfAtoms(); + + //FORMAT(20A4) ITITL + // ITITL : the title of the current run, from the AMBER + // parameter/topology file + //The following snapshot is written every NTWX steps in the trajectory (specified in the control input file): + //FORMAT(10F8.3) (X(i), Y(i), Z(i), i=1,NATOM) + // X,Y,Z : coordinates or velocities (velocity units: Angstroms per 1/20.455 ps) + //IF constant pressure (in 4.1, also constant volume) + //For each snapshot: + //FORMAT(10F8.3) BOX(1), BOX(2), BOX(3) + // BOX : size of periodic box + try { + File f = new File(fileName); + raf = new RandomAccessFile(f, "r"); + + int i, nlines; + + if ((3 * n_atoms) % 10 != 0) { + nlines = 3 * n_atoms / 10 + 1; + } else { + nlines = 3 * n_atoms / 10; + } + + if (nlines == 0) { + nlines = 1; + } + + if (flag_1 != 0) { + periodicConditions = true; + ++nlines; + } else { + periodicConditions = false; + } + + // --- Skip first line (run's title) + //fget_line( bufer, 256, t_file ); + Title = raf.readLine(); + long fileLength = raf.length(); + + while (fileLength > raf.getFilePointer()) { + // start to read atomic coordinates + long offset = raf.getFilePointer(); + TrajectorySnapshot snapshot = new TrajectorySnapshot(raf, offset); + trajectorySnapshots.add(snapshot); + + for (i = 0; i < nlines; i++) { + raf.readLine(); + if (fileLength == raf.getFilePointer()) { + trajectorySnapshots.remove(snapshot); + break; + } + } + + } + + } catch (Exception e) { + } + + try { + raf.seek(0); + //raf.close(); + } catch (Exception e) { + } + + logger.info("Found " + trajectorySnapshots.size() + "snapshots"); + /* + for (i = n_snapshots - found; i < n_snapshots; i++) { + fseek(t_file, snapshots[i].offset, SEEK_SET); + //fgets( bufer, 254, t_file ); + //bufer[255]=0x00; + //fget_line( bufer, 256, t_file ); + read_line(bufer, 256, t_file); + printf("%5d: %9ld %s\n", i + 1, snapshots[i].offset, bufer); + } + */ + + return raf; + } + + public RandomAccessFile parseG03Trajectory(String fileName, TRAJECTORY_FILE_FORMAT format, int flag_1) throws Exception { + if (fileName == null || fileName.length() < 1) { + throw new Exception("Trajectory file name is not set"); + } + if (referenceStructure == null || referenceStructure.getNumberOfAtoms() < 1) { + throw new Exception("Reference molecule is not set or has no atoms"); + } + + int n_atoms = referenceStructure.getNumberOfAtoms(); + + /* + Time in trajectory (femtosec) 2.000000D-01 + Total energy (au) -1.175171068D+02 + Total angular momentum (h-bar) 2.904529344D-14 + Coordinates (Bohr) + I= 1 X= -4.555420059248D-01 Y= -5.134698398949D-01 Z= -7.216904569806D-01 + I= 2 X= -2.221805396142D+00 Y= -1.254178689967D+00 Z= -2.596959873079D-02 + I= 3 X= -5.952104662883D-01 Y= 1.532677098577D+00 Z= -8.366401222195D-01 + */ + periodicConditions = false; + String line; + long offset; + + try { + File f = new File(fileName); + raf = new RandomAccessFile(f, "r"); + + List gAtoms = G03MDTrajectory.parseMolecularGeometryOnly(raf); + if (n_atoms != gAtoms.size()) { + throw new Exception("Number of atoms in molecule (" + n_atoms + ") do not match that in Trajectory file (" + + gAtoms.size() + ")"); + } + + /* + Time in trajectory (femtosec) 2.000000D-01 + Total energy (au) -1.175171068D+02 + Total angular momentum (h-bar) 2.904529344D-14 + Coordinates (Bohr) + I= 1 X= -4.555420059248D-01 Y= -5.134698398949D-01 Z= -7.216904569806D-01 + I= 2 X= -2.221805396142D+00 Y= -1.254178689967D+00 Z= -2.596959873079D-02 + */ + while ((line = raf.readLine()) != null) { + if (line.contains("Time in trajectory ")) { + + TrajectorySnapshot snapshot = new TrajectorySnapshot(raf, 0); // Temp value for offset + + // Add absolute time + double value; + try { + value = Double.parseDouble(line.substring(30, line.length() - 1).trim()); + snapshot.addProperty("Time in trajectory (femtosec)", new Double(value)); + } catch (Exception ex) { + + } + + // parsing Total energy (au) -1.175171068D+02 + if ((line = raf.readLine()) == null) { + break; + } + + try { + value = Double.parseDouble(line.substring(18, line.length() - 1).trim()); + snapshot.addProperty("Total energy (au)", new Double(value)); + } catch (Exception ex) { + + } + + // Skip 2 lines.... + if ((line = raf.readLine()) == null) { + break; + } + if ((line = raf.readLine()) == null) { + break; + } + + offset = raf.getFilePointer(); + snapshot.setOffset(offset); + + // ---Read atomic coordinates + for (int i = 0; i < n_atoms; i++) { + if ((line = raf.readLine()) == null) { + break; + } + } + if (line != null) { + trajectorySnapshots.add(snapshot); + } + } + + if (line == null) { + break; + } + + } + + } catch (Exception e) { + } + + try { + raf.seek(0); + //raf.close(); + } catch (Exception e) { + } + + logger.info("Found " + trajectorySnapshots.size() + "snapshots"); + /* + for (i = n_snapshots - found; i < n_snapshots; i++) { + fseek(t_file, snapshots[i].offset, SEEK_SET); + //fgets( bufer, 254, t_file ); + //bufer[255]=0x00; + //fget_line( bufer, 256, t_file ); + read_line(bufer, 256, t_file); + printf("%5d: %9ld %s\n", i + 1, snapshots[i].offset, bufer); + } + */ + + return raf; + } + + public RandomAccessFile parseGULPTrajectory(String fileName, TRAJECTORY_FILE_FORMAT format, int flag_1) throws Exception { + if (fileName == null || fileName.length() < 1) { + throw new Exception("Trajectory file name is not set"); + } + if (referenceStructure == null || referenceStructure.getNumberOfAtoms() < 1) { + throw new Exception("Reference molecule is not set or has no atoms"); + } + + int n_atoms = referenceStructure.getNumberOfAtoms(); + + /* + 3.30 + 64 3 + # Time/KE/E/T + 1.05000000000000 2.59560693399160 -1312.08156254049 318.737956024591 + # Coordinates + -0.184578838443719E-01 -0.650093939728458E-01 0.605513913742120E-01 + -0.505227067033068E-01 0.238634219912673E-01 4.13998804910851 + 0.257564345076467E-01 4.20040152534106 0.365911280462028E-02 + */ + periodicConditions = false; + String line = "", token; + long offset; + + try { + File f = new File(fileName); + raf = new RandomAccessFile(f, "r"); + + // Skip the first line + while ((line = raf.readLine()) != null) { + if (line.startsWith("#")) { + continue; + } else { + break; + } + } + if (line == null) { + throw new Exception("Unexpected end of file while reading the first line"); + } + + // Read the second line + while ((line = raf.readLine()) != null) { + if (line.startsWith("#")) { + continue; + } else { + break; + } + } + + if (line == null) { + throw new Exception("Unexpected end of file while reading the second line"); + } + + StringTokenizer st = new StringTokenizer(line, " "); + token = st.nextToken(); + try { + int nat = Integer.parseInt(token); + if (nat != n_atoms) { + throw new Exception("Number of atoms in reference structure (" + n_atoms + ") does not match that in trajectory (" + + nat + ")"); + } + } catch (Exception ex) { + throw new Exception("Error parsing number of atoms in the second line: " + line); + } + + // --- Start to read a snapshot info + while (true) { + + TrajectorySnapshot snapshot = new TrajectorySnapshot(raf, 0); // Temp value for offset + while ((line = raf.readLine()) != null) { + if (line.startsWith("#")) { + continue; + } else { + break; + } + } + if (line == null) { + return raf; + } + + /* + # Time/KE/E/T + 1.05000000000000 2.59560693399160 -1312.08156254049 318.737956024591 + */ + st = new StringTokenizer(line, " "); + double value; + if (st.hasMoreTokens()) { + token = st.nextToken(); + try { + value = Double.parseDouble(token); + snapshot.addProperty("Time", new Double(value)); + } catch (Exception ex) { + + } + } + if (st.hasMoreTokens()) { + token = st.nextToken(); + try { + value = Double.parseDouble(token); + snapshot.addProperty("KE", new Double(value)); + } catch (Exception ex) { + + } + } + if (st.hasMoreTokens()) { + token = st.nextToken(); + try { + value = Double.parseDouble(token); + snapshot.addProperty("E", new Double(value)); + } catch (Exception ex) { + + } + } + if (st.hasMoreTokens()) { + token = st.nextToken(); + try { + value = Double.parseDouble(token); + snapshot.addProperty("T", new Double(value)); + } catch (Exception ex) { + + } + } + + // --- Start to read coordinates + // -0.184578838443719E-01 -0.650093939728458E-01 0.605513913742120E-01 + offset = raf.getFilePointer(); + snapshot.setOffset(offset); + + int nat = 0; + while ((line = raf.readLine()) != null) { + if (line.startsWith("#")) { + continue; + } + ++nat; + if (nat >= n_atoms) { + break; + } + } + + // --- Start to read velocities + nat = 0; + while ((line = raf.readLine()) != null) { + if (line.startsWith("#")) { + continue; + } + ++nat; + if (nat >= n_atoms) { + break; + } + } + + if (line != null) { + trajectorySnapshots.add(snapshot); + } + } // --- End of global while + + } catch (Exception e) { + } + + try { + raf.seek(0); + //raf.close(); + } catch (Exception e) { + } + + logger.info("Found " + trajectorySnapshots.size() + "snapshots"); + /* + for (i = n_snapshots - found; i < n_snapshots; i++) { + fseek(t_file, snapshots[i].offset, SEEK_SET); + //fgets( bufer, 254, t_file ); + //bufer[255]=0x00; + //fget_line( bufer, 256, t_file ); + read_line(bufer, 256, t_file); + printf("%5d: %9ld %s\n", i + 1, snapshots[i].offset, bufer); + } + */ + + return raf; + } + + public List getTrajectorySnapshots() { + return trajectorySnapshots; + } +} diff --git a/src/main/java/cct/modelling/SingleTrajectoryNew.java b/src/main/java/cct/modelling/SingleTrajectoryNew.java new file mode 100644 index 0000000..76bfb7a --- /dev/null +++ b/src/main/java/cct/modelling/SingleTrajectoryNew.java @@ -0,0 +1,302 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.modelling; + +import java.io.File; +import java.io.RandomAccessFile; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import cct.interfaces.MoleculeInterface; +import cct.tools.DataSets; +import cct.tools.ui.JobProgressInterface; +import java.io.BufferedReader; +import java.io.IOException; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.logging.Level; + +/** + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +abstract public class SingleTrajectoryNew extends DataSets { + + public final static String TEMP_FILE_EXTENSION = ".trj"; + public final static String TEMP_FILE_TEMPLATE = "trj-"; + + protected String Title = null; + protected String fileName = null; + protected RandomAccessFile raf = null; + protected RandomAccessFile tmpRAF = null; + private MoleculeInterface referenceStructure = null; + private int numberOfAtoms = 0; // Set in case if referenceStructure is not set + private File tmpDirectory; + //private Set descriptors = new LinkedHashSet(); + + protected boolean periodicConditions = false; + private boolean keepCoordinatesInMemory = false; + private boolean useIntermediateFile = true; + private List trajectorySnapshots = new ArrayList(); + static final Logger logger = Logger.getLogger(SingleTrajectoryNew.class.getCanonicalName()); + + public SingleTrajectoryNew() { + } + + public SingleTrajectoryNew(MoleculeInterface mol) { + referenceStructure = mol; + if (mol != null) { + numberOfAtoms = mol.getNumberOfAtoms(); + } + } + + /** + * Class specific method to parse custom trajectory file + * + * @param fileName - file name + * @throws Exception + */ + public void parseTrajectoryFile(String fileName) throws Exception { + parseTrajectoryFile(fileName, null); + } + + /** + * + * @param fileName + * @param progress + * @throws Exception + */ + abstract public void parseTrajectoryFile(String fileName, JobProgressInterface progress) throws Exception; + + /** + * This method is not implemented in this class and will cause an Exception + * + * @param in + * @throws Exception + */ + public void parseData(BufferedReader in) throws Exception { + throw new Exception("void parseData(BufferedReader in) method is not implemented in " + this.getClass().getCanonicalName()); + } + + /** + * Class specific method to extract a given structure (coordinates) from a custom trajectory file + * + * @param coords[n][3] - coordinates + * @param raf - RandomAccessFile file handle + * @param offset - offset in RandomAccessFile file + * @throws Exception + */ + abstract public void readCoordsFromTrajFile(float coords[][], RandomAccessFile raf, long offset) throws Exception; + + public void addSnapshot(TrajectorySnapshot snapshot) { + trajectorySnapshots.add(snapshot); + if (useIntermediateFile) { + try { + long offset = saveCoordsIntoTmpFile(snapshot.getCoordinates()); + snapshot.setTmpFile(tmpRAF); + snapshot.setTmpOffset(offset); + } catch (Exception ex) { + Logger.getLogger(SingleTrajectoryNew.class.getName()).log(Level.SEVERE, null, ex); + } + + } + // --- + if (!keepCoordinatesInMemory) { + snapshot.clearCoordinates(); + } + } + + protected long saveCoordsIntoTmpFile(float coords[][]) throws Exception { + if (tmpRAF == null) { + tmpRAF = createRandomAccessFile(); + } + long offset = saveCoordsIntoTmpFile(coords, tmpRAF); + return offset; + } + + public static long saveCoordsIntoTmpFile(float coords[][], RandomAccessFile raf) throws Exception { + long offset = raf.getFilePointer(); + for (int i = 0; i < coords.length; i++) { + raf.writeFloat(coords[i][0]); + raf.writeFloat(coords[i][1]); + raf.writeFloat(coords[i][2]); + } + return offset; + } + + public static void readCoordsFromTmpFile(float coords[][], RandomAccessFile raf, long offset) throws Exception { + raf.seek(offset); + for (int i = 0; i < coords.length; i++) { + coords[i][0] = raf.readFloat(); + coords[i][1] = raf.readFloat(); + coords[i][2] = raf.readFloat(); + } + } + + protected RandomAccessFile createRandomAccessFile() throws Exception { + File file = createIntermediateFile(); + RandomAccessFile raf = new RandomAccessFile(file, "rw"); + return raf; + } + + protected File createIntermediateFile() throws Exception { + File tmpFile = null; + try { + + if (tmpDirectory == null) { // Use fefault location + tmpFile = File.createTempFile(TEMP_FILE_TEMPLATE, TEMP_FILE_EXTENSION); + } else { + tmpFile = File.createTempFile(TEMP_FILE_TEMPLATE, TEMP_FILE_EXTENSION, tmpDirectory); + } + } catch (IOException ex) { + Logger.getLogger(SingleTrajectoryNew.class.getName()).log(Level.SEVERE, null, ex); + throw new Exception(ex.getLocalizedMessage()); + } + tmpFile.deleteOnExit(); + return tmpFile; + } + + public int getNumberOfAtoms() { + if (referenceStructure != null) { + return referenceStructure.getNumberOfAtoms(); + } + return numberOfAtoms; + } + + public void setNumberOfAtoms(int numberOfAtoms) { + if (numberOfAtoms < 0) { + numberOfAtoms = 0; + } + this.numberOfAtoms = numberOfAtoms; + } + + //public Set getDescriptors() { + // return this.getDescriptors(); + //} + //public void addDescriptor(String descriptor) { + // descriptors.add(descriptor); + //} + //public boolean hasDescriptor(String descriptor) { + // return descriptors.contains(descriptor); + //} + public File getTmpDirectory() { + return tmpDirectory; + } + + public void setTmpDirectory(File tmpDirectory) { + this.tmpDirectory = tmpDirectory; + } + + public void setTmpDirectory(String tmpDir) throws Exception { + tmpDirectory = new File(tmpDir); + if (!tmpDirectory.isDirectory()) { + useIntermediateFile = false; + throw new Exception(tmpDirectory.getAbsolutePath() + " is not a directory!"); + } + if (!tmpDirectory.exists()) { + try { + tmpDirectory.mkdirs(); + } catch (Exception ex) { + useIntermediateFile = false; + throw new Exception("Error creating directory: " + tmpDirectory.getAbsolutePath() + " : " + ex.getLocalizedMessage()); + } + } + } + + public List getTrajectorySnapshots() { + return trajectorySnapshots; + } + + public TrajectorySnapshot getSnapshot(int n) { + if (trajectorySnapshots == null) { + return null; + } else if (n < 0 || n >= trajectorySnapshots.size()) { + return null; + } + return trajectorySnapshots.get(n); + } + + public int getSnapshotsCount() { + if (trajectorySnapshots == null) { + return 0; + } + return trajectorySnapshots.size(); + } + + public MoleculeInterface getReferenceStructure() { + return referenceStructure; + } + + public void setReferenceStructure(MoleculeInterface referenceStructure) { + this.referenceStructure = referenceStructure; + numberOfAtoms = referenceStructure.getNumberOfAtoms(); + } + + public boolean isKeepCoordinatesInMemory() { + return keepCoordinatesInMemory; + } + + public void setKeepCoordinatesInMemory(boolean keepCoordinatesInMemory) { + this.keepCoordinatesInMemory = keepCoordinatesInMemory; + } + + public boolean isUseIntermediateFile() { + return useIntermediateFile; + } + + public void setUseIntermediateFile(boolean useIntermediateFile) { + this.useIntermediateFile = useIntermediateFile; + } + + public static void main(String[] args) { + //SingleTrajectory trajectoryfile = new SingleTrajectory(); + } +} diff --git a/src/main/java/cct/modelling/StructureManager.java b/src/main/java/cct/modelling/StructureManager.java new file mode 100644 index 0000000..a59835d --- /dev/null +++ b/src/main/java/cct/modelling/StructureManager.java @@ -0,0 +1,382 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.modelling; + +import cct.gaussian.G03MDTrajectory; +import java.io.RandomAccessFile; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; + +import javax.swing.JOptionPane; + +import cct.interfaces.MoleculeInterface; +import cct.tools.DataSets; +import static cct.tools.DataSets.DATA_ROW_NUMBER; +import cct.tools.ui.JobProgressInterface; +import java.io.File; +import java.util.HashSet; + +/** + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class StructureManager { + + static final double ONE_BOHR = 0.529177249; // In Angstrom + protected Map structurePool = new LinkedHashMap(); + protected List snapshotReference = new ArrayList(); + protected MoleculeInterface referenceStructure = null; + private TRAJECTORY_FILE_FORMAT Format; + static final Logger logger = Logger.getLogger(StructureManager.class.getCanonicalName()); + + public StructureManager() { + + } + + public StructureManager(MoleculeInterface mol) { + referenceStructure = mol; + } + + public void setReferenceMolecule(MoleculeInterface mol) { + referenceStructure = mol; + } + + public MoleculeInterface getReferenceMolecule() { + return referenceStructure; + } + + public void deleteAllTrajectories() { + structurePool.clear(); + snapshotReference.clear(); + //referenceStructure = null; + } + + /** + * Returns all descriptors (data property's names) across all loaded trajectories + * + * @return + */ + public String[] getAllProperties() { + if (structurePool.size() < 1) { + return null; + } + Set set = new HashSet(); + for (String key : structurePool.keySet()) { + Object obj = structurePool.get(key); + if (obj instanceof DataSets) { + for (String descr : ((DataSets) obj).getDescriptors()) { + set.add(descr); + } + } else { + logger.severe("Don't know how to handle class " + obj.getClass().getCanonicalName()); + return null; + } + } + String[] props = new String[set.size()]; + return set.toArray(props); + } + + public int getNumberOfSnapshots() { + if (structurePool.size() < 1) { + return 0; + } + int numSnaps = 0; + for (String key : structurePool.keySet()) { + Object obj = structurePool.get(key); + if (obj instanceof DataSets) { + numSnaps += ((DataSets) obj).getDataSize(); + + } else { + logger.severe("Don't know how to handle class " + obj.getClass().getCanonicalName()); + return numSnaps; + } + } + return numSnaps; + } + + public double[] getRowNumbersAsDouble() { + if (structurePool.size() < 1 || getNumberOfSnapshots() < 1) { + return null; + } + double[] rn = new double[getNumberOfSnapshots()]; + for (int i = 0; i < getNumberOfSnapshots(); i++) { + rn[i] = (double) (i + 1); + } + return rn; + } + + public float[] getRowNumbersAsFloat() { + if (structurePool.size() < 1 || getNumberOfSnapshots() < 1) { + return null; + } + float[] rn = new float[getNumberOfSnapshots()]; + for (int i = 0; i < getNumberOfSnapshots(); i++) { + rn[i] = (float) (i + 1); + } + return rn; + } + + public double[] getDataAsDouble(String descriptor) { + if (structurePool.size() < 1 || getNumberOfSnapshots() < 1) { + return null; + } + + if (descriptor.equals(DATA_ROW_NUMBER)) { + return getRowNumbersAsDouble(); + } + + double[] values = new double[getNumberOfSnapshots()]; + + int counter = 0; + for (String key : structurePool.keySet()) { + Object obj = structurePool.get(key); + if (obj instanceof DataSets) { + double[] temp = ((DataSets) obj).getDataAsDouble(descriptor); + for (int i = 0; i < temp.length; i++, counter++) { + values[counter] = temp[i]; + } + } else { + logger.severe("Don't know how to handle class " + obj.getClass().getCanonicalName()); + return null; + } + } + + return values; + + } + + public static void main(String[] args) { + //StructureManager structuremanager = new StructureManager(); + } + + public void parseTrajectoryFile(String fileName, TRAJECTORY_FILE_FORMAT format) throws Exception { + parseTrajectoryFile(fileName, format, null); + } + + public void parseTrajectoryFile(String fileName, TRAJECTORY_FILE_FORMAT format, JobProgressInterface progress) throws Exception { + if (fileName == null || fileName.length() < 1) { + throw new Exception("Trajectory file name is not set"); + } + if (format == null) { + throw new Exception("Trajectory file format is not set"); + } + + if (structurePool.containsKey(fileName)) { + throw new Exception("Trajectory from file " + fileName + " is already loaded in"); + } + + Format = format; + + int additional_condition = 0; + if (format == TRAJECTORY_FILE_FORMAT.AMBER) { + int answer = JOptionPane.showConfirmDialog(null, "Does this trajectory contain Periodic Boundary Info?", + "Select type of trajectory", JOptionPane.YES_NO_OPTION); + if (answer == JOptionPane.YES_OPTION) { + additional_condition = 1; + } else { + additional_condition = 0; + } + } + + List snapshots = null; + + if (format == TRAJECTORY_FILE_FORMAT.G03_TRAJECTORY) { + SingleTrajectoryNew singleTraj = new G03MDTrajectory(referenceStructure); + + singleTraj.setTmpDirectory(new File(".")); + singleTraj.parseTrajectoryFile(fileName, progress); + singleTraj.setKeepCoordinatesInMemory(true); + singleTraj.setUseIntermediateFile(true); + snapshots = singleTraj.getTrajectorySnapshots(); + if (snapshots.size() < 1) { + throw new Exception("Didn't find coordinates in file " + fileName); + } + structurePool.put(fileName, singleTraj); + } else { + SingleTrajectory singleTraj = new SingleTrajectory(referenceStructure); + singleTraj.parseTrajectoryFile(fileName, format, additional_condition); + snapshots = singleTraj.getTrajectorySnapshots(); + if (snapshots.size() < 1) { + throw new Exception("Didn't find coordinates in file " + fileName); + } + structurePool.put(fileName, singleTraj); + } + + if (snapshotReference instanceof ArrayList) { + ((ArrayList) snapshotReference).ensureCapacity(snapshotReference.size() + snapshots.size()); + } + snapshotReference.addAll(snapshots); + } + + public int getTrajectoryCount() { + return structurePool.size(); + } + + public int getSnapshotsCount() { + return snapshotReference.size(); + } + + public String[] getAvailableTrajectories() { + if (structurePool.size() < 1) { + return null; + } + Set keys = structurePool.keySet(); + String[] files = new String[keys.size()]; + keys.toArray(files); + return files; + } + + public float[][] getStructure(int n) throws Exception { + float coords[][] = new float[referenceStructure.getNumberOfAtoms()][3]; + getStructure(n, coords); + return coords; + } + + public void getStructure(int n, float coords[][]) throws Exception { + if (n < 0 || n >= snapshotReference.size()) { + throw new Exception(this.getClass().getCanonicalName() + " getStructure: n < 0 || n >= snapshotReference.size()"); + } + + if (referenceStructure == null || referenceStructure.getNumberOfAtoms() < 1) { + throw new Exception(this.getClass().getCanonicalName() + + " getStructure: Reference structure is not set or number of atoms < 1"); + } + + if (coords.length < referenceStructure.getNumberOfAtoms()) { + throw new Exception(this.getClass().getCanonicalName() + + " getStructure: array for coordinates is less than number of atoms"); + } + + TrajectorySnapshot snapshot = snapshotReference.get(n); + + RandomAccessFile raFile = snapshot.getFile(); + long Offset = snapshot.getOffset(); + //TRAJECTORY_FILE_FORMAT Format = snapshot.getFormat(); + String buffer = null; + + long start = System.currentTimeMillis(); + switch (Format) { + case AMBER: + raFile.seek(Offset); + int counter = 10; + for (int i = 0; i < referenceStructure.getNumberOfAtoms(); i++) { + for (int j = 0; j < 3; j++) { + if (counter >= 10) { + buffer = raFile.readLine(); + counter = 0; + } + coords[i][j] = Float.parseFloat(buffer.substring(counter * 8, 8 * (counter + 1)).trim()); + ++counter; + } + } + break; + + case G03_TRAJECTORY: + // --- Maybe cooridnates are already in memory... + if (snapshot.getCoordinates() != null) { + float[][] trajCrd = snapshot.getCoordinates(); + for (int i = 0; i < referenceStructure.getNumberOfAtoms(); i++) { + coords[i][0] = trajCrd[i][0]; + coords[i][1] = trajCrd[i][1]; + coords[i][2] = trajCrd[i][2]; + } + break; + } + // --- If we use an intermediate file.. + if (snapshot.getTmpFile() != null) { + SingleTrajectoryNew.readCoordsFromTmpFile(coords, snapshot.getTmpFile(), snapshot.getTmpOffset()); + break; + } + // --- And finally + SingleTrajectoryNew traj = snapshot.getReferenceTrajectory(); + traj.readCoordsFromTrajFile(coords, snapshot.getFile(), snapshot.getOffset()); + // --- Old (disabled) stuff below + if (false) { // Old stuff + raFile.seek(Offset); + for (int i = 0; i < referenceStructure.getNumberOfAtoms(); i++) { + buffer = raFile.readLine(); + buffer = buffer.replaceAll("[D]", "E"); + buffer = buffer.replaceAll("[d]", "E"); + coords[i][0] = (float) (ONE_BOHR * Double.parseDouble(buffer.substring(11, 32).trim())); + coords[i][1] = (float) (ONE_BOHR * Double.parseDouble(buffer.substring(35, 56).trim())); + coords[i][2] = (float) (ONE_BOHR * Double.parseDouble(buffer.substring(59, 80).trim())); + } + } + break; + + case GULP_TRAJECTORY: + raFile.seek(Offset); + int nat = 0; + while (true) { + buffer = raFile.readLine(); + if (buffer.startsWith("#")) { + continue; + } + buffer = buffer.replaceAll("[D]", "E"); + buffer = buffer.replaceAll("[d]", "E"); + coords[nat][0] = (float) Double.parseDouble(buffer.substring(0, 25).trim()); + coords[nat][1] = (float) Double.parseDouble(buffer.substring(25, 51).trim()); + coords[nat][2] = (float) Double.parseDouble(buffer.substring(51, 77).trim()); + ++nat; + if (nat >= referenceStructure.getNumberOfAtoms()) { + break; + } + } + break; + + } + float secs = (System.currentTimeMillis() - start) / 1000.0f; + logger.info("Elapsed time to retrive coords for " + n + " snapshot: " + secs); + + } +} diff --git a/src/main/java/cct/modelling/StructureManagerInterface.java b/src/main/java/cct/modelling/StructureManagerInterface.java new file mode 100644 index 0000000..074fb04 --- /dev/null +++ b/src/main/java/cct/modelling/StructureManagerInterface.java @@ -0,0 +1,60 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public interface StructureManagerInterface { + float[][] getStructure(int n); + + float[][] getStructure(int n, String term); + + void selectStructure(int number) throws Exception; + + void selectStructure(int number, String term) throws Exception; +} diff --git a/src/main/java/cct/modelling/SurfaceParameter.java b/src/main/java/cct/modelling/SurfaceParameter.java new file mode 100644 index 0000000..96c9afb --- /dev/null +++ b/src/main/java/cct/modelling/SurfaceParameter.java @@ -0,0 +1,40 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.modelling; + +/** + * + * @author Vlad + */ +public class SurfaceParameter { + + private double R = 1.0, W = 0.0; + + public SurfaceParameter(double R, double W) { + this.R = R; + this.W = W; + } + + public double getR() { + return R; + } + + public void setR(double R) { + this.R = R; + } + + public double getW() { + return W; + } + + public void setW(double W) { + this.W = W; + } + + public void set(double R, double W) { + this.R = R; + this.W = W; + } +} diff --git a/src/main/java/cct/modelling/TRAJECTORY_FILE_FORMAT.java b/src/main/java/cct/modelling/TRAJECTORY_FILE_FORMAT.java new file mode 100644 index 0000000..014e024 --- /dev/null +++ b/src/main/java/cct/modelling/TRAJECTORY_FILE_FORMAT.java @@ -0,0 +1,56 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public enum TRAJECTORY_FILE_FORMAT { + AMBER, G03_TRAJECTORY, GULP_TRAJECTORY; + TRAJECTORY_FILE_FORMAT() { + } +} diff --git a/src/main/java/cct/modelling/Torsion.java b/src/main/java/cct/modelling/Torsion.java new file mode 100644 index 0000000..afce3fc --- /dev/null +++ b/src/main/java/cct/modelling/Torsion.java @@ -0,0 +1,88 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Torsion { + public int ijkl[] = new int[4]; + public Torsion() { + ijkl[0] = ijkl[1] = ijkl[2] = ijkl[3] = -1; + } + + public Torsion(int i, int j, int k, int l) { + ijkl[0] = i; + ijkl[1] = j; + ijkl[2] = k; + ijkl[3] = l; + } + + public Torsion(Torsion t) { + ijkl[0] = t.ijkl[0]; + ijkl[1] = t.ijkl[1]; + ijkl[2] = t.ijkl[2]; + ijkl[3] = t.ijkl[3]; + } + + public int getI() { + return ijkl[0]; + } + + public int getJ() { + return ijkl[1]; + } + + public int getK() { + return ijkl[2]; + } + + public int getL() { + return ijkl[3]; + } + +} diff --git a/src/main/java/cct/modelling/TorsionEnergy.java b/src/main/java/cct/modelling/TorsionEnergy.java new file mode 100644 index 0000000..e62fa13 --- /dev/null +++ b/src/main/java/cct/modelling/TorsionEnergy.java @@ -0,0 +1,317 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +import java.util.List; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.vecmath.Point3f; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class TorsionEnergy { + private TorsionEnergy() { + } + + public static double TorsionEnergy(MoleculeInterface molec, List torsionPars) { + if (torsionPars == null) { + return 0; + } + + double energy = 0; + + for (int i = 0; i < torsionPars.size(); i++) { + TorsionParameter tp = (TorsionParameter) torsionPars.get(i); + AtomInterface a1 = molec.getAtomInterface(tp.getI()); + AtomInterface a2 = molec.getAtomInterface(tp.getJ()); + AtomInterface a3 = molec.getAtomInterface(tp.getK()); + AtomInterface a4 = molec.getAtomInterface(tp.getL()); + + double angle = Point3f.dihedralAngle(a1, a2, a3, a4); + + List serie = tp.getSerie(); + for (int j = 0; j < serie.size(); j++) { + TorsionTerm tt = (TorsionTerm) serie.get(j); + energy += tt.V * + (1.0 + Math.cos(tt.Periodicity * (float) angle - tt.Phase)); + /* + if (p->n > 0) { // A negative n flags a 180 degree phase shift + etor += p->u * (1.0 + cos(p->n * angle)); + } + else { + etor += p->u * (1.0 - cos(p->n * angle)); + } + */ + } + } + + return energy; + } + + public static double TorsionEnergy(MoleculeInterface molec, List torsionPars, Point3f[] Gradients) { + double energy = 0; + + /* + //integer ii,jj,kk,ll, k; + //real f[3],g[3],h[3], a[3],b[3], sign[3]; + + real dih, A, A2, B, B2, ab, G, fg, hg, coeff; + + dihedral_energy = 0.0; + if ( ndihed <= 0 ) return dihedral_energy; + + for(integer i=0; i 0.0 ) dih = - dih; + + dihedral_energy += dihedrals[i].Pk * (1.0 + cos(dihedrals[i].Pn* + dih - dihedrals[i].Phase) ); + + coeff = - dihedrals[i].Pk * dihedrals[i].Pn * + sin(dihedrals[i].Pn*dih - dihedrals[i].Phase); + + for(k=0; k<3; k++) { + dxyz[ii].x[k] += coeff * ( - G / A2 * a[k] ); + dxyz[jj].x[k] += coeff * ( G/A2*a[k] + fg/(A2*G)*a[k] - hg/(B2*G)*b[k] ); + dxyz[kk].x[k] += coeff * ( hg/(B2*G)*b[k] - fg/(A2*G)*a[k] - G/B2*b[k] ); + dxyz[ll].x[k] += coeff * G / B2 * b[k]; + } + + } + */ + + if (torsionPars.size() < 1) { + return 0; + } + + Point3f a = new Point3f(); + Point3f b = new Point3f(); + Point3f sign = new Point3f(); + + Point3f f = new Point3f(); + Point3f g = new Point3f(); + Point3f h = new Point3f(); + + float A, A2, B, B2, ab, G, fg, hg, coeff; + double dih; + + for (int i = 0; i < torsionPars.size(); i++) { + TorsionParameter tp = (TorsionParameter) torsionPars.get(i); + AtomInterface a1 = molec.getAtomInterface(tp.getI()); + AtomInterface a2 = molec.getAtomInterface(tp.getJ()); + AtomInterface a3 = molec.getAtomInterface(tp.getK()); + AtomInterface a4 = molec.getAtomInterface(tp.getL()); + + /* + for( k=0; k<3; k++ ) { + f[k] = cartes[ii].x[k] - cartes[jj].x[k]; + g[k] = cartes[jj].x[k] - cartes[kk].x[k]; + h[k] = cartes[ll].x[k] - cartes[kk].x[k]; + } + + */ + f.subtract(a1, a2); + g.subtract(a2, a3); + h.subtract(a4, a3); + + //VectorProduct(f, g, a); + a.crossProduct(f, g); + + //VectorProduct(h, g, b); + b.crossProduct(h, g); + + //A2 = VectorSquare(a); + A2 = a.squaredNorm(); + + //B2 = VectorSquare(b); + B2 = b.squaredNorm(); + + //A = sqrt(A2); + A = (float) Math.sqrt(A2); + + //B = sqrt(B2); + B = (float) Math.sqrt(B2); + + //ab = ScalarProduct(a, b); + ab = a.product(b); + + //G = VectorLength(g); + G = g.vectorNorm(); + + //fg = ScalarProduct(f, g); + fg = f.product(g); + + //hg = ScalarProduct(h, g); + hg = h.product(g); + + dih = ArcCos(ab / (A * B)); + + //VectorProduct(a, b, sign); + sign.crossProduct(a, b); + + //if (ScalarProduct(sign, g) > 0.0) dih = -dih; + if (sign.product(g) > 0.0) { + dih = -dih; + } + + //double angle = Point3f.dihedralAngle(a1, a2, a3, a4); + //logger.info("Torsion: "+dih*Point3f.RADIANS_TO_DEGREES+" Angle: "+angle*Point3f.RADIANS_TO_DEGREES); + + List serie = tp.getSerie(); + for (int j = 0; j < serie.size(); j++) { + TorsionTerm tt = (TorsionTerm) serie.get(j); + + //dihedral_energy += dihedrals[i].Pk * (1.0 + cos(dihedrals[i].Pn * + // dih - dihedrals[i].Phase)); + energy += tt.V * (1.0 + Math.cos(tt.Periodicity * dih - tt.Phase)); + + //coeff = -dihedrals[i].Pk * dihedrals[i].Pn * + // sin(dihedrals[i].Pn * dih - dihedrals[i].Phase); + + coeff = -tt.V * tt.Periodicity * + (float) Math.sin(tt.Periodicity * dih - tt.Phase); + + //for (k = 0; k < 3; k++) { + // dxyz[ii].x[k] += coeff * ( -G / A2 * a[k]); + Gradients[tp.getI()].add(coeff * ( -G / A2 * a.getX()), + coeff * ( -G / A2 * a.getY()), + coeff * ( -G / A2 * a.getZ())); + + // dxyz[jj].x[k] += coeff * + // (G / A2 * a[k] + fg / (A2 * G) * a[k] - hg / (B2 * G) * b[k]); + + Gradients[tp.getJ()].add(coeff * + (G / A2 * a.getX() + + fg / (A2 * G) * a.getX() - + hg / (B2 * G) * b.getX()), + coeff * + (G / A2 * a.getY() + + fg / (A2 * G) * a.getY() - + hg / (B2 * G) * b.getY()), + coeff * + (G / A2 * a.getZ() + + fg / (A2 * G) * a.getZ() - + hg / (B2 * G) * b.getZ())); + + // dxyz[kk].x[k] += coeff * + // (hg / (B2 * G) * b[k] - fg / (A2 * G) * a[k] - G / B2 * b[k]); + + Gradients[tp.getK()].add(coeff * + (hg / (B2 * G) * b.getX() - + fg / (A2 * G) * a.getX() - + G / B2 * b.getX()), + coeff * + (hg / (B2 * G) * b.getY() - + fg / (A2 * G) * a.getY() - + G / B2 * b.getY()), + coeff * + (hg / (B2 * G) * b.getZ() - + fg / (A2 * G) * a.getZ() - + G / B2 * b.getZ())); + + // dxyz[ll].x[k] += coeff * G / B2 * b[k]; + + Gradients[tp.getL()].add(coeff * G / B2 * b.getX(), + coeff * G / B2 * b.getY(), + coeff * G / B2 * b.getZ()); + // } + + + } + } + + return energy; + } + + static double ArcCos(double A) { + return Math.acos(Math.abs(A) > 1.0 ? SIGN(1.0, A) : A); + } + + static float SIGN(float A, float B) { + if (B >= 0.0f) { + return A > 0.0f ? A : -A; + } + else { + return A < 0.0f ? A : -A; + } + } + + static double SIGN(double A, double B) { + if (B >= 0.0) { + return A > 0.0 ? A : -A; + } + else { + return A < 0.0 ? A : -A; + } + } + +} diff --git a/src/main/java/cct/modelling/TorsionParameter.java b/src/main/java/cct/modelling/TorsionParameter.java new file mode 100644 index 0000000..5768710 --- /dev/null +++ b/src/main/java/cct/modelling/TorsionParameter.java @@ -0,0 +1,96 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +import java.util.ArrayList; +import java.util.List; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class TorsionParameter { + protected Torsion Torsion = null; + protected List Serie = new ArrayList(); + + public TorsionParameter(Torsion torsion, List serie) { + Torsion = new Torsion(torsion); + setSerie(serie); + } + + public TorsionParameter(Torsion torsion) { + Torsion = new Torsion(torsion); + } + + public int getI() { + return Torsion.ijkl[0]; + } + + public int getJ() { + return Torsion.ijkl[1]; + } + + public int getK() { + return Torsion.ijkl[2]; + } + + public int getL() { + return Torsion.ijkl[3]; + } + + public List getSerie() { + return Serie; + } + + public void setSerie(List serie) { + if (serie == null) { + return; + } + for (int i = 0; i < serie.size(); i++) { + Serie.add(serie.get(i)); + } + } +} diff --git a/src/main/java/cct/modelling/TorsionTerm.java b/src/main/java/cct/modelling/TorsionTerm.java new file mode 100644 index 0000000..0ad5a1f --- /dev/null +++ b/src/main/java/cct/modelling/TorsionTerm.java @@ -0,0 +1,69 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class TorsionTerm { + public float V = 0, Periodicity = 0, Phase = 0; + public TorsionTerm() { + } + + public TorsionTerm(float v, int n, float phase) { + V = v; + Periodicity = n; + Phase = phase; + } + + public TorsionTerm(TorsionTerm tt) { + V = tt.V; + Periodicity = tt.Periodicity; + Phase = tt.Phase; + } + +} diff --git a/src/main/java/cct/modelling/TrajectoryClientInterface.java b/src/main/java/cct/modelling/TrajectoryClientInterface.java new file mode 100644 index 0000000..1bbde98 --- /dev/null +++ b/src/main/java/cct/modelling/TrajectoryClientInterface.java @@ -0,0 +1,54 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public interface TrajectoryClientInterface { + void setSnapshotsCount(int new_max); +} diff --git a/src/main/java/cct/modelling/TrajectorySnapshot.java b/src/main/java/cct/modelling/TrajectorySnapshot.java new file mode 100644 index 0000000..042501f --- /dev/null +++ b/src/main/java/cct/modelling/TrajectorySnapshot.java @@ -0,0 +1,175 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.modelling; + +import cct.vecmath.Point3f; +import java.io.RandomAccessFile; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; + +/** + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class TrajectorySnapshot { + + private RandomAccessFile raFile = null; + private long Offset = 0; + private RandomAccessFile tmpFile = null; + + private SingleTrajectoryNew referenceTrajectory; + private long tmpOffset = 0; + private float coordinates[][]; + private Map properties = null; + + static final Logger logger = Logger.getLogger(TrajectorySnapshot.class.getCanonicalName()); + + public TrajectorySnapshot() { + + } + + public TrajectorySnapshot(RandomAccessFile ra_file, long offset) { + raFile = ra_file; + Offset = offset; + + } + + public float[][] getCoordinates() { + return coordinates; + } + + public void setCoordinates(float[][] coordinates) { + this.coordinates = coordinates; + } + + public void setCoordinates(List coordList) { + coordinates = new float[coordList.size()][3]; + for (int i = 0; i < coordinates.length; i++) { + Point3f p3f = coordList.get(i); + coordinates[i][0] = p3f.getX(); + coordinates[i][1] = p3f.getY(); + coordinates[i][2] = p3f.getZ(); + } + } + + public void clearCoordinates() { + coordinates = null; + } + + public RandomAccessFile getFile() { + return raFile; + } + + public long getOffset() { + return Offset; + } + + public void setOffset(long offset) { + Offset = offset; + } + + public SingleTrajectoryNew getReferenceTrajectory() { + return referenceTrajectory; + } + + public void setReferenceTrajectory(SingleTrajectoryNew referenceTrajectory) { + this.referenceTrajectory = referenceTrajectory; + } + + public RandomAccessFile getTmpFile() { + return tmpFile; + } + + public void setTmpFile(RandomAccessFile tmpFile) { + this.tmpFile = tmpFile; + } + + public long getTmpOffset() { + return tmpOffset; + } + + public void setTmpOffset(long tmpOffset) { + this.tmpOffset = tmpOffset; + } + + public void addProperty(String key, Object value) { + if (properties == null) { + properties = new HashMap(); + } + properties.put(key, value); + } + + public Object getProperty(String key) { + if (properties == null) { + return null; + } + return properties.get(key); + } + + public Double getPropertyAsDouble(String key) { + if (properties == null) { + return null; + } + Object obj = properties.get(key); + + if (obj instanceof Number) { + return ((Number) obj).doubleValue(); + } else if (obj instanceof String) { + try { + return Double.parseDouble(((String) obj).trim()); + } catch (Exception ex) { + logger.severe("Error parsing String as a double number: "+obj.toString().trim()); + } + } + return null; + } + +} diff --git a/src/main/java/cct/modelling/VIBRATIONAL_SPECTRUM.java b/src/main/java/cct/modelling/VIBRATIONAL_SPECTRUM.java new file mode 100644 index 0000000..a3708db --- /dev/null +++ b/src/main/java/cct/modelling/VIBRATIONAL_SPECTRUM.java @@ -0,0 +1,72 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +import java.util.HashMap; +import java.util.Map; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ + +public enum VIBRATIONAL_SPECTRUM { + INFRARED_SPECTRUM, RAMAN_SPECTRUM, VCD_ROTATIONAL_STRENGTH_SPECTRUM, P_DEPOLARIZATION_SPECTRUM, U_DEPOLARIZATION_SPECTRUM; + + static final Map nameReference = new HashMap (); + static { + nameReference.put(INFRARED_SPECTRUM, "Infrared Spectrum"); + nameReference.put(RAMAN_SPECTRUM, "Raman Spectrum"); + nameReference.put(VCD_ROTATIONAL_STRENGTH_SPECTRUM, "VCD Rotational Strength Spectrum"); + nameReference.put(P_DEPOLARIZATION_SPECTRUM, "P-Depolarization Spectrum"); + nameReference.put(U_DEPOLARIZATION_SPECTRUM, "U-Depolarization Spectrum"); + } + + public static String getSpectrumName(VIBRATIONAL_SPECTRUM spectrum) { + return nameReference.get(spectrum); + } + +} diff --git a/src/main/java/cct/modelling/VIBRATIONAL_SPECTRUM_CURVE.java b/src/main/java/cct/modelling/VIBRATIONAL_SPECTRUM_CURVE.java new file mode 100644 index 0000000..30b2915 --- /dev/null +++ b/src/main/java/cct/modelling/VIBRATIONAL_SPECTRUM_CURVE.java @@ -0,0 +1,54 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public enum VIBRATIONAL_SPECTRUM_CURVE { + GAUSSIAN, LORENTZ, GAUSSIAN_LORENTZ, VOIGHT +} diff --git a/src/main/java/cct/modelling/ui/EditAndPasteCoordFrame.java b/src/main/java/cct/modelling/ui/EditAndPasteCoordFrame.java new file mode 100644 index 0000000..432eed7 --- /dev/null +++ b/src/main/java/cct/modelling/ui/EditAndPasteCoordFrame.java @@ -0,0 +1,306 @@ +package cct.modelling.ui; + +import java.awt.BorderLayout; +import java.awt.FileDialog; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.io.BufferedReader; +import java.io.StringReader; +import java.util.HashMap; +import java.util.Map; + +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; + +import cct.interfaces.AtomInterface; +import cct.interfaces.CoordinateParserInterface; +import cct.interfaces.MoleculeInterface; +import cct.j3d.Java3dUniverse; +import cct.modelling.CCTAtomTypes; +import cct.modelling.FormatManager; +import cct.modelling.Molecule; +import cct.tools.IOUtils; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class EditAndPasteCoordFrame + extends JFrame implements ItemListener { + private BorderLayout borderLayout1 = new BorderLayout(); + private JPanel jPanel1 = new JPanel(); + private JPanel jPanel2 = new JPanel(); + private JScrollPane jScrollPane1 = new JScrollPane(); + private JPanel formatsPanel = new JPanel(); + private BorderLayout borderLayout2 = new BorderLayout(); + private JTextArea coordTextArea = new JTextArea(); + private JButton cancelButton = new JButton(); + private JRadioButton jRadioButton1 = new JRadioButton(); + private FlowLayout flowLayout1 = new FlowLayout(); + private ButtonGroup buttonGroup = new ButtonGroup(); + private JButton okButton = new JButton(); + + private Java3dUniverse java3dUniverse = null; + private String selectedBuilder = ""; + private String defaultFileName = "text.txt"; + private JMenuBar jMenuBar1 = new JMenuBar(); + private JMenu jMenu1 = new JMenu(); + private JMenuItem jMenuItem1 = new JMenuItem(); + private JMenuItem jMenuItem2 = new JMenuItem(); + private JButton validateButton = new JButton(); + + private Map refTable = new HashMap (); + + public EditAndPasteCoordFrame() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + getContentPane().setLayout(borderLayout1); + jPanel1.setLayout(borderLayout2); + coordTextArea.setText("jTextArea1"); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + cancelButton_actionPerformed(e); + } + }); + jRadioButton1.setText("jRadioButton1"); + formatsPanel.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + okButton.setText(" OK "); + okButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + okButton_actionPerformed(e); + } + }); + this.setJMenuBar(jMenuBar1); + jMenu1.setText("File"); + jMenuItem1.setText("Save As"); + jMenuItem1.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + jMenuItem1_actionPerformed(e); + } + }); + jMenuItem2.setText("Exit"); + jMenuItem2.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + jMenuItem2_actionPerformed(e); + } + }); + validateButton.setText("Validate Geometry"); + validateButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + validateButton_actionPerformed(e); + } + }); + this.getContentPane().add(jPanel1, BorderLayout.CENTER); + this.getContentPane().add(jPanel2, BorderLayout.SOUTH); + jPanel2.add(okButton); + jPanel2.add(validateButton); + jPanel2.add(cancelButton); + jPanel1.add(jScrollPane1, BorderLayout.CENTER); + jScrollPane1.getViewport().add(coordTextArea); + jPanel1.add(formatsPanel, BorderLayout.SOUTH); + formatsPanel.add(jRadioButton1); + buttonGroup.add(jRadioButton1); + jMenuBar1.add(jMenu1); + jMenu1.add(jMenuItem1); + jMenu1.addSeparator(); + jMenu1.add(jMenuItem2); + Font currentFont = coordTextArea.getFont(); + int size = currentFont.getSize(); + int style = currentFont.getStyle(); + String fontName = currentFont.getFontName(); + + if (size < 12) { + Font newFont = new Font(fontName, style, 12); + coordTextArea.setFont(newFont); + } + + setFormatManager(); + + } + + private void setFormatManager() throws Exception { + String[] parsers = FormatManager.getCoordinateParsers(); + + formatsPanel.removeAll(); + refTable.clear(); + + if (parsers == null) { + throw new Exception("Cannot get list of coordinate parsers: "); + } + + coordTextArea.setText(""); + for (int i = 0; i < parsers.length; i++) { + JRadioButton jRadioButton = new JRadioButton(); + jRadioButton.setText(parsers[i]); + jRadioButton.setActionCommand(parsers[i]); + formatsPanel.add(jRadioButton); + buttonGroup.add(jRadioButton); + refTable.put(parsers[i], jRadioButton); + jRadioButton.addItemListener(this); + if (i == 0) { + jRadioButton.setSelected(true); + } + else { + jRadioButton.setSelected(false); + } + } + okButton.grabFocus(); + + this.pack(); + } + + public void setDefaultFileName(String file_name) { + defaultFileName = file_name; + } + + private void saveTextIntoFile() { + String text = coordTextArea.getText(); + if (text == null || text.length() < 1) { + JOptionPane.showMessageDialog(this, "Nothing to save", "Warning", JOptionPane.WARNING_MESSAGE); + return; + } + + FileDialog fd = new FileDialog(this, "Save File", FileDialog.SAVE); + fd.setFile(defaultFileName); + fd.setVisible(true); + if (fd.getFile() != null) { + String fileName = fd.getFile(); + String workingDirectory = fd.getDirectory(); + try { + IOUtils.saveStringIntoFile(text, workingDirectory + fileName); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error Saving file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + } + } + + public void setJava3dUniverse(Java3dUniverse j3d) { + java3dUniverse = j3d; + } + + public static void main(String[] args) { + EditAndPasteCoordFrame editandpastecoordframe = new EditAndPasteCoordFrame(); + } + + public void jMenuItem2_actionPerformed(ActionEvent e) { + setVisible(false); + } + + public void jMenuItem1_actionPerformed(ActionEvent e) { + saveTextIntoFile(); + } + + public void cancelButton_actionPerformed(ActionEvent e) { + setVisible(false); + } + + @Override + public void itemStateChanged(ItemEvent e) { + + if (e.getStateChange() == ItemEvent.SELECTED) { + selectedBuilder = ( (JRadioButton) e.getSource()).getActionCommand(); + + } + okButton.grabFocus(); + } + + private void parseCoordinates() throws Exception { + + if (coordTextArea.getText().trim().length() < 7) { + JOptionPane.showMessageDialog(this, "Text area does not have enough data", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + try { + BufferedReader in = new BufferedReader(new StringReader(coordTextArea.getText())); + MoleculeInterface molecule = new Molecule(); + + CoordinateParserInterface cpi = FormatManager.getCoordinateParser(selectedBuilder); + cpi.parseCoordinates(in, molecule); + + if (molecule == null || molecule.getNumberOfAtoms() < 1) { + JOptionPane.showMessageDialog(this, "Didn't find coordinates", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + Molecule.guessCovalentBonds(molecule); + Molecule.guessAtomTypes(molecule, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + java3dUniverse.setMolecule(molecule); + + } + catch (Exception ex) { + throw ex; + } + + } + + public void setCoordinates(String text) { + coordTextArea.setText(text); + String parser = FormatManager.guessSimpleCoordinateParser(text); + if (parser != null) { + JRadioButton jRadioButton = refTable.get(parser); + jRadioButton.setSelected(true); + } + } + + public void validateButton_actionPerformed(ActionEvent e) { + try { + parseCoordinates(); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error while parsing coordinates: " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + } + + public void okButton_actionPerformed(ActionEvent e) { + try { + parseCoordinates(); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error while parsing coordinates: " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + setVisible(false); + } + +} diff --git a/src/main/java/cct/modelling/ui/EditAndSaveCoordDialog.form b/src/main/java/cct/modelling/ui/EditAndSaveCoordDialog.form new file mode 100644 index 0000000..3a08fa0 --- /dev/null +++ b/src/main/java/cct/modelling/ui/EditAndSaveCoordDialog.form @@ -0,0 +1,146 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/cct/modelling/ui/EditAndSaveCoordDialog.java b/src/main/java/cct/modelling/ui/EditAndSaveCoordDialog.java new file mode 100644 index 0000000..50acfbe --- /dev/null +++ b/src/main/java/cct/modelling/ui/EditAndSaveCoordDialog.java @@ -0,0 +1,288 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +/* + * EditAndSaveCoordDialog.java + * + * Created on 09/12/2013, 12:45:24 PM + */ +package cct.modelling.ui; + +import cct.interfaces.CoordinateBuilderInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.FormatManager; +import cct.tools.IOUtils; +import cct.tools.TextClipboard; +import java.awt.FileDialog; +import java.awt.Font; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import javax.swing.JOptionPane; +import javax.swing.JRadioButton; + +/** + * + * @author Vlad + */ +public class EditAndSaveCoordDialog extends javax.swing.JFrame implements ItemListener { + + private String defaultFileName = "text.txt"; + private FormatManager formatManager; + private String selectedBuilder = ""; + private MoleculeInterface molecule = null; + + public EditAndSaveCoordDialog(String title) { + super(title); + initComponents(); + + Font currentFont = coordTextArea.getFont(); + int size = currentFont.getSize(); + int style = currentFont.getStyle(); + String fontName = currentFont.getFontName(); + + if (size < 12) { + Font newFont = new Font(fontName, style, 12); + coordTextArea.setFont(newFont); + } + } + + /** + * Creates new form EditAndSaveCoordDialogNew + */ + public EditAndSaveCoordDialog() { + this("Edit & Save Coordinates Dialog"); + } + + public void setDefaultFileName(String file_name) { + defaultFileName = file_name; + } + + public void setMoleculeInterface(MoleculeInterface mol) { + molecule = mol; + buildCoordinates(); + okButton.grabFocus(); + } + + private void buildCoordinates() { + if (molecule == null || molecule.getNumberOfAtoms() < 1) { + return; + } + + try { + CoordinateBuilderInterface cbi = FormatManager.getCoordinateBuilder(selectedBuilder); + coordTextArea.setText(cbi.getCoordinatesAsString(molecule, true)); + this.validate(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Cannot get coordinate builder " + selectedBuilder + " : " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + } + + public void setFormatManager(FormatManager format_manager) throws Exception { + formatManager = format_manager; + String[] builders = FormatManager.getCoordinateBuilders(); + + formatsPanel.removeAll(); + + if (builders == null) { + throw new Exception("Cannot get list of coordinate builders: "); + } + + coordTextArea.setText(""); + for (int i = 0; i < builders.length; i++) { + JRadioButton jRadioButton = new JRadioButton(); + jRadioButton.setText(builders[i]); + jRadioButton.setActionCommand(builders[i]); + formatsPanel.add(jRadioButton); + buttonGroup.add(jRadioButton); + jRadioButton.addItemListener(this); + if (i == 0) { + jRadioButton.setSelected(true); + } else { + jRadioButton.setSelected(false); + } + } + okButton.grabFocus(); + + this.pack(); + } + + @Override + public void itemStateChanged(ItemEvent e) { + + if (e.getStateChange() == ItemEvent.SELECTED) { + selectedBuilder = ((JRadioButton) e.getSource()).getActionCommand(); + buildCoordinates(); + } + okButton.grabFocus(); + } + + /** + * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this + * method is always regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + buttonGroup = new javax.swing.ButtonGroup(); + jScrollPane1 = new javax.swing.JScrollPane(); + coordTextArea = new javax.swing.JTextArea(); + jPanel1 = new javax.swing.JPanel(); + formatsPanel = new javax.swing.JPanel(); + jRadioButton1 = new JRadioButton(); + jRadioButton2 = new JRadioButton(); + jPanel3 = new javax.swing.JPanel(); + okButton = new javax.swing.JButton(); + cancelButton = new javax.swing.JButton(); + jMenuBar1 = new javax.swing.JMenuBar(); + jMenu1 = new javax.swing.JMenu(); + jMenuItem1 = new javax.swing.JMenuItem(); + jSeparator1 = new javax.swing.JPopupMenu.Separator(); + jMenuItem2 = new javax.swing.JMenuItem(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + + coordTextArea.setColumns(40); + coordTextArea.setRows(40); + jScrollPane1.setViewportView(coordTextArea); + + getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER); + + jPanel1.setLayout(new java.awt.BorderLayout()); + + formatsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Formats")); + formatsPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + jRadioButton1.setText("Sample Format"); + formatsPanel.add(jRadioButton1); + + jRadioButton2.setText("Other Format"); + formatsPanel.add(jRadioButton2); + + jPanel1.add(formatsPanel, java.awt.BorderLayout.NORTH); + + okButton.setText("OK"); + okButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + okButtonActionPerformed(evt); + } + }); + jPanel3.add(okButton); + + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + cancelButtonActionPerformed(evt); + } + }); + jPanel3.add(cancelButton); + + jPanel1.add(jPanel3, java.awt.BorderLayout.SOUTH); + + getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH); + + jMenu1.setText("File"); + + jMenuItem1.setText("Save as"); + jMenuItem1.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jMenuItem1ActionPerformed(evt); + } + }); + jMenu1.add(jMenuItem1); + jMenu1.add(jSeparator1); + + jMenuItem2.setText("Exit"); + jMenuItem2.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jMenuItem2ActionPerformed(evt); + } + }); + jMenu1.add(jMenuItem2); + + jMenuBar1.add(jMenu1); + + setJMenuBar(jMenuBar1); + + pack(); + }// //GEN-END:initComponents + + private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed + setVisible(false); + }//GEN-LAST:event_cancelButtonActionPerformed + + private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed + TextClipboard textTransfer = new TextClipboard(); + textTransfer.setClipboardContents(coordTextArea.getText()); + setVisible(false); + }//GEN-LAST:event_okButtonActionPerformed + + private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed + setVisible(false); + }//GEN-LAST:event_jMenuItem2ActionPerformed + + private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed + saveTextIntoFile(); + }//GEN-LAST:event_jMenuItem1ActionPerformed + + private void saveTextIntoFile() { + String text = coordTextArea.getText(); + if (text == null || text.length() < 1) { + JOptionPane.showMessageDialog(this, "Nothing to save", "Warning", JOptionPane.WARNING_MESSAGE); + return; + } + + FileDialog fd = new FileDialog(this, "Save File", FileDialog.SAVE); + fd.setFile(defaultFileName); + fd.setVisible(true); + if (fd.getFile() != null) { + String fileName = fd.getFile(); + String workingDirectory = fd.getDirectory(); + try { + IOUtils.saveStringIntoFile(text, workingDirectory + fileName); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error Saving file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + } + } + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + EditAndSaveCoordDialog frame = new EditAndSaveCoordDialog(); + frame.setTextArea("\"Amber\" refers to two things: a set of molecular mechanical force fields for the simulation of biomolecules (which are in the public domain, and are used in a variety of simulation programs); and a package of molecular simulation programs which includes source code and demos. "); + frame.setVisible(true); + } + }); + } + + public void setTextArea(String text) { + coordTextArea.setText(text); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.ButtonGroup buttonGroup; + private javax.swing.JButton cancelButton; + private javax.swing.JTextArea coordTextArea; + private javax.swing.JPanel formatsPanel; + private javax.swing.JMenu jMenu1; + private javax.swing.JMenuBar jMenuBar1; + private javax.swing.JMenuItem jMenuItem1; + private javax.swing.JMenuItem jMenuItem2; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel3; + private JRadioButton jRadioButton1; + private JRadioButton jRadioButton2; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JPopupMenu.Separator jSeparator1; + private javax.swing.JButton okButton; + // End of variables declaration//GEN-END:variables + +} diff --git a/src/main/java/cct/modelling/ui/EditAndSaveCoordDialog_toDelete.java b/src/main/java/cct/modelling/ui/EditAndSaveCoordDialog_toDelete.java new file mode 100644 index 0000000..f680806 --- /dev/null +++ b/src/main/java/cct/modelling/ui/EditAndSaveCoordDialog_toDelete.java @@ -0,0 +1,321 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.modelling.ui; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FileDialog; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.SystemColor; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; + +import javax.swing.BorderFactory; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.WindowConstants; +import javax.swing.border.TitledBorder; + +import cct.interfaces.CoordinateBuilderInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.FormatManager; +import cct.tools.IOUtils; +import cct.tools.TextClipboard; +import javax.swing.ScrollPaneConstants; + +/** + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class EditAndSaveCoordDialog_toDelete + extends JFrame implements ItemListener { + + private JPanel jPanel1 = new JPanel(); + private JPanel jPanel2 = new JPanel(); + private JTextArea coordTextArea = new JTextArea(); + private JScrollPane jScrollPane1 = new JScrollPane(coordTextArea); + private JButton cancelButton = new JButton(); + private JRadioButton jRadioButton1 = new JRadioButton(); + private JPanel formatsPanel = new JPanel(); + private BorderLayout borderLayout3 = new BorderLayout(); + private JButton okButton = new JButton(); + private ButtonGroup buttonGroup = new ButtonGroup(); + private JRadioButton jRadioButton2 = new JRadioButton(); + private FlowLayout flowLayout1 = new FlowLayout(); + private MoleculeInterface molecule = null; + private String selectedBuilder = ""; + private JMenuBar jMenuBar1 = new JMenuBar(); + private JMenu jMenu1 = new JMenu(); + private JMenuItem jMenuItem1 = new JMenuItem(); + private JMenuItem jMenuItem2 = new JMenuItem(); + private String defaultFileName = "text.txt"; + private JPanel jPanel3 = new JPanel(); + private BorderLayout borderLayout2 = new BorderLayout(); + private FlowLayout flowLayout2 = new FlowLayout(); + + public EditAndSaveCoordDialog_toDelete(String title) { + super(title); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public EditAndSaveCoordDialog_toDelete() { + this("Edit And Save Coordinates Dialog"); + } + + private void jbInit() throws Exception { + coordTextArea.setText("jTextArea1"); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + cancelButton_actionPerformed(e); + } + }); + jRadioButton1.setSelected(true); + jRadioButton1.setText("jRadioButton1"); + formatsPanel.setLayout(flowLayout1); + jPanel2.setLayout(borderLayout3); + okButton.setToolTipText(""); + okButton.setText(" OK "); + okButton.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + okButton_actionPerformed(e); + } + }); + jRadioButton2.setText("jRadioButton1"); + flowLayout1.setAlignment(FlowLayout.LEFT); + formatsPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder(SystemColor.controlDkShadow, 1), "Formats")); + coordTextArea.setMinimumSize(new Dimension(10, 10)); + coordTextArea.setPreferredSize(new Dimension(10, 10)); + this.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); + this.setJMenuBar(jMenuBar1); + jMenu1.setText("File"); + jMenuItem1.setText("Save As"); + jMenuItem1.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + jMenuItem1_actionPerformed(e); + } + }); + jMenuItem2.setText("Exit"); + jMenuItem2.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + jMenuItem2_actionPerformed(e); + } + }); + //jPanel3.setLayout(borderLayout2); + jPanel1.setLayout(flowLayout2); + jPanel1.add(okButton); + jPanel1.add(cancelButton); + jPanel2.add(formatsPanel, BorderLayout.NORTH); + jPanel2.add(jPanel1, BorderLayout.SOUTH); + formatsPanel.add(jRadioButton2, null); + formatsPanel.add(jRadioButton1, null); + //jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER); + //jScrollPane1.getViewport().add(coordTextArea); + jScrollPane1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); + jScrollPane1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); + jScrollPane1.setWheelScrollingEnabled(true); + buttonGroup.add(jRadioButton2); + buttonGroup.add(jRadioButton1); + jMenuBar1.add(jMenu1); + jMenu1.add(jMenuItem1); + jMenu1.addSeparator(); + jMenu1.add(jMenuItem2); + this.getContentPane().add(jPanel2, BorderLayout.SOUTH); + + //this.getContentPane().add(jPanel3, java.awt.BorderLayout.CENTER); + getContentPane().add(jScrollPane1, BorderLayout.CENTER); + + Font currentFont = coordTextArea.getFont(); + int size = currentFont.getSize(); + int style = currentFont.getStyle(); + String fontName = currentFont.getFontName(); + + if (size < 12) { + Font newFont = new Font(fontName, style, 12); + coordTextArea.setFont(newFont); + } + + setFormatManager(); + } + + public void setFormatManager() throws Exception { + String[] builders = FormatManager.getCoordinateBuilders(); + + formatsPanel.removeAll(); + + if (builders == null) { + throw new Exception("Cannot get list of coordinate builders: "); + } + + coordTextArea.setText(""); + for (int i = 0; i < builders.length; i++) { + JRadioButton jRadioButton = new JRadioButton(); + jRadioButton.setText(builders[i]); + jRadioButton.setActionCommand(builders[i]); + formatsPanel.add(jRadioButton); + buttonGroup.add(jRadioButton); + jRadioButton.addItemListener(this); + if (i == 0) { + jRadioButton.setSelected(true); + } else { + jRadioButton.setSelected(false); + } + } + okButton.grabFocus(); + + this.pack(); + } + + public void setDefaultFileName(String file_name) { + defaultFileName = file_name; + } + + public void setMoleculeInterface(MoleculeInterface mol) { + molecule = mol; + buildCoordinates(); + okButton.grabFocus(); + } + + private void buildCoordinates() { + if (molecule == null || molecule.getNumberOfAtoms() < 1) { + return; + } + + try { + CoordinateBuilderInterface cbi = FormatManager.getCoordinateBuilder(selectedBuilder); + coordTextArea.setText(cbi.getCoordinatesAsString(molecule, true)); + this.validate(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Cannot get coordinate builder " + selectedBuilder + " : " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + } + + @Override + public void itemStateChanged(ItemEvent e) { + + if (e.getStateChange() == ItemEvent.SELECTED) { + selectedBuilder = ((JRadioButton) e.getSource()).getActionCommand(); + buildCoordinates(); + } + okButton.grabFocus(); + } + + public void cancelButton_actionPerformed(ActionEvent e) { + setVisible(false); + } + + public void jMenuItem2_actionPerformed(ActionEvent e) { + setVisible(false); + } + + private void saveTextIntoFile() { + String text = coordTextArea.getText(); + if (text == null || text.length() < 1) { + JOptionPane.showMessageDialog(this, "Nothing to save", "Warning", JOptionPane.WARNING_MESSAGE); + return; + } + + FileDialog fd = new FileDialog(this, "Save File", FileDialog.SAVE); + fd.setFile(defaultFileName); + fd.setVisible(true); + if (fd.getFile() != null) { + String fileName = fd.getFile(); + String workingDirectory = fd.getDirectory(); + try { + IOUtils.saveStringIntoFile(text, workingDirectory + fileName); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error Saving file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + } + } + + public void jMenuItem1_actionPerformed(ActionEvent e) { + saveTextIntoFile(); + } + + public void okButton_actionPerformed(ActionEvent e) { + TextClipboard textTransfer = new TextClipboard(); + textTransfer.setClipboardContents(coordTextArea.getText()); + setVisible(false); + } + + public static void main(String[] args) { + EditAndSaveCoordDialog_toDelete frame = new EditAndSaveCoordDialog_toDelete(); + frame.setVisible(true); + } +} diff --git a/src/main/java/cct/modelling/ui/JSetupEnergyDialog.java b/src/main/java/cct/modelling/ui/JSetupEnergyDialog.java new file mode 100644 index 0000000..77d6b6d --- /dev/null +++ b/src/main/java/cct/modelling/ui/JSetupEnergyDialog.java @@ -0,0 +1,968 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling.ui; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.SystemColor; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JFormattedTextField; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JSpinner; +import javax.swing.JTabbedPane; +import javax.swing.JTextField; +import javax.swing.SpinnerNumberModel; +import javax.swing.SwingConstants; +import javax.swing.border.Border; +import javax.swing.border.TitledBorder; + +import cct.interfaces.ForceFieldInterface; +import cct.math.MinimizerInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class JSetupEnergyDialog + extends JDialog { + + ForceFieldInterface forceFields[] = null; + MinimizerInterface minimizers[] = null; + boolean okPressed = true; + private int energySetupTab = 0; + private int minimizationSetupTab = 1; + float nbCutoff = 10; + + JTabbedPane jTabbedPane1 = new JTabbedPane(); + JPanel energyPanel = new JPanel(); + JLabel jLabel1 = new JLabel(); + JComboBox forceFieldComboBox = new JComboBox(); + JLabel jLabel2 = new JLabel(); + JFormattedTextField nbCutoffTextField = new JFormattedTextField(); + JCheckBox nbCutoffCheckBox = new JCheckBox(); + JLabel jLabel3 = new JLabel(); + JTextField vdw14TextField = new JTextField(); + JLabel jLabel4 = new JLabel(); + JTextField els14TextField = new JTextField(); + JCheckBox calculateElsCheckBox = new JCheckBox(); + JLabel jLabel5 = new JLabel(); + JComboBox dielFuncComboBox = new JComboBox(); + JLabel jLabel6 = new JLabel(); + JTextField dielConstTextField = new JTextField(); + JCheckBox ignoreAtomsCheckBox = new JCheckBox(); + JButton setupIgnoreAtomsButton = new JButton(); + JCheckBox constraintsCheckBox = new JCheckBox(); + JButton setupConstraintsButton = new JButton(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + JPanel jPanel3 = new JPanel(); + JButton CalcButton = new JButton(); + JButton cancelButton = new JButton(); + JButton helpButton = new JButton(); + JPanel minPanel = new JPanel(); + JLabel jLabel7 = new JLabel(); + JComboBox minimizersComboBox = new JComboBox(); + JPanel minimizationPanel = new JPanel(); + JCheckBox jCheckBox1 = new JCheckBox(); + JTextField jTextField1 = new JTextField(); + JLabel jLabel9 = new JLabel(); + Border border1 = BorderFactory.createLineBorder(SystemColor.controlShadow, 1); + Border border2 = new TitledBorder(border1, "Termination Conditions"); + JCheckBox maxGradCheckBox = new JCheckBox(); + JTextField maxGradTextField = new JTextField(); + JLabel jLabel10 = new JLabel(); + JLabel jLabel8 = new JLabel(); + JPanel jPanel4 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + FlowLayout flowLayout1 = new FlowLayout(); + JTextField maxIterTextField = new JTextField(); + JPanel jPanel5 = new JPanel(); + JLabel jLabel12 = new JLabel(); + FlowLayout flowLayout2 = new FlowLayout(); + JSpinner refreshRateTextField = new JSpinner(new SpinnerNumberModel(1, 0, 1000, + 1)); + GridBagLayout gridBagLayout2 = new GridBagLayout(); + JCheckBox maxGRMSCheckBox = new JCheckBox(); + JTextField maxGRSMTextField = new JTextField(); + JLabel jLabel13 = new JLabel(); + + public JSetupEnergyDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JSetupEnergyDialog() { + this(new Frame(), "JSetupEnergyDialog", false); + } + + private void jbInit() throws Exception { + jLabel2.setToolTipText("Cutoff for Nonbonded Interactions"); + nbCutoffTextField.setFormatterFactory(null); + nbCutoffTextField.setToolTipText("Non-Bonded Cutoff Value"); + nbCutoffTextField.setText(String.valueOf(nbCutoff)); + nbCutoffTextField.setColumns(5); + nbCutoffTextField.addActionListener(new + JSetupEnergyDialog_nbCutoffTextField_actionAdapter(this)); + nbCutoffCheckBox.setEnabled(false); + nbCutoffCheckBox.setToolTipText(""); + nbCutoffCheckBox.setText("Use NB Cutoff"); + nbCutoffCheckBox.addItemListener(new + JSetupEnergyDialog_nbCutoffCheckBox_itemAdapter(this)); + jLabel3.setToolTipText(""); + jLabel3.setText("1-4 van der Waals Scaling: "); + vdw14TextField.setToolTipText(""); + vdw14TextField.setText("2"); + vdw14TextField.setColumns(5); + jLabel4.setToolTipText(""); + jLabel4.setText("1-4 Electrostatics Scaling: "); + els14TextField.setToolTipText(""); + els14TextField.setText("1"); + els14TextField.setColumns(5); + calculateElsCheckBox.setEnabled(false); + calculateElsCheckBox.setToolTipText(""); + calculateElsCheckBox.setText("Calculate Electrostatics"); + calculateElsCheckBox.addItemListener(new + JSetupEnergyDialog_calculateElsCheckBox_itemAdapter(this)); + jLabel5.setToolTipText(""); + jLabel5.setText("Dielectric Function: "); + jLabel6.setToolTipText(""); + jLabel6.setText("Dielectric Constant: "); + dielConstTextField.setToolTipText(""); + dielConstTextField.setText("1"); + dielConstTextField.setColumns(5); + ignoreAtomsCheckBox.setEnabled(false); + ignoreAtomsCheckBox.setToolTipText(""); + ignoreAtomsCheckBox.setText("Ignore Atoms"); + ignoreAtomsCheckBox.addItemListener(new + JSetupEnergyDialog_ignoreAtomsCheckBox_itemAdapter(this)); + setupIgnoreAtomsButton.setText("Setup"); + constraintsCheckBox.setEnabled(false); + constraintsCheckBox.setToolTipText(""); + constraintsCheckBox.setText("Constraints"); + constraintsCheckBox.addItemListener(new + JSetupEnergyDialog_constraintsCheckBox_itemAdapter(this)); + setupConstraintsButton.setToolTipText(""); + setupConstraintsButton.setText("Setup"); + energyPanel.setLayout(gridBagLayout1); + this.setDefaultCloseOperation(javax.swing.WindowConstants. + DO_NOTHING_ON_CLOSE); + CalcButton.setToolTipText("Start Calculation with selected parameters"); + CalcButton.setText("Calculate"); + CalcButton.addActionListener(new + CalcButton_actionAdapter(this)); + cancelButton.setToolTipText("Cancel Setup"); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new + JSetupEnergyDialog_cancelButton_actionAdapter(this)); + helpButton.setEnabled(false); + helpButton.setToolTipText("Help on Energy Setup"); + helpButton.setText("Help"); + helpButton.addActionListener(new + JSetupEnergyDialog_helpButton_actionAdapter(this)); + forceFieldComboBox.addActionListener(new + JSetupEnergyDialog_forceFieldComboBox_actionAdapter(this)); + jLabel7.setToolTipText(""); + jLabel7.setHorizontalAlignment(SwingConstants.LEFT); + jLabel7.setText("Method: "); + jCheckBox1.setEnabled(false); + jCheckBox1.setToolTipText(""); + jCheckBox1.setText("Min Function Change:"); + jTextField1.setEnabled(false); + jTextField1.setToolTipText(""); + jTextField1.setText("0.01"); + jTextField1.setColumns(5); + jLabel9.setToolTipText(""); + jLabel9.setText(" kcal/mol"); + minimizationPanel.setBorder(border2); + minimizationPanel.setLayout(gridBagLayout2); + maxGradCheckBox.setToolTipText(""); + maxGradCheckBox.setText("Max Gradient:"); + maxGradTextField.setToolTipText(""); + maxGradTextField.setText("0.5"); + maxGradTextField.setColumns(5); + jLabel10.setToolTipText(""); + jLabel10.setText(" kcal/(mol*A)"); + jLabel8.setToolTipText(""); + jLabel8.setText("Max Iterations:"); + minPanel.setLayout(borderLayout1); + jPanel4.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + maxIterTextField.setToolTipText(""); + maxIterTextField.setText("1000"); + maxIterTextField.setColumns(5); + jLabel12.setToolTipText(""); + jLabel12.setText("Screen Refresh Period:"); + jPanel5.setLayout(flowLayout2); + flowLayout2.setAlignment(FlowLayout.LEFT); + refreshRateTextField.setToolTipText(""); + + maxGRMSCheckBox.setToolTipText(""); + maxGRMSCheckBox.setText("Max RMS Gradient:"); + maxGRSMTextField.setToolTipText(""); + maxGRSMTextField.setText("0.25"); + maxGRSMTextField.setColumns(5); + jLabel13.setToolTipText(""); + jLabel13.setText(" kcal/(mol*A)"); + this.getContentPane().add(jTabbedPane1, BorderLayout.CENTER); + jLabel1.setToolTipText(""); + jLabel1.setText("Force Field: "); + jLabel2.setText("NB Cutoff: "); + energyPanel.add(jLabel1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + energyPanel.add(forceFieldComboBox, + new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + jPanel3.add(CalcButton); + jPanel3.add(cancelButton); + jPanel3.add(helpButton); + this.getContentPane().add(jPanel3, BorderLayout.SOUTH); + energyPanel.add(nbCutoffCheckBox, + new GridBagConstraints(0, 1, 2, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + energyPanel.add(vdw14TextField, + new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + energyPanel.add(jLabel3, new GridBagConstraints(0, 2, 2, 1, 0.0, 0.0 + , GridBagConstraints.EAST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + jPanel4.add(jLabel7); + jPanel4.add(minimizersComboBox); + jPanel5.add(jLabel12); + jPanel5.add(refreshRateTextField); + minPanel.add(minimizationPanel, BorderLayout.CENTER); + minPanel.add(jPanel5, BorderLayout.SOUTH); + minPanel.add(jPanel4, BorderLayout.NORTH); + jTabbedPane1.add(energyPanel, "Energy Setup"); + jTabbedPane1.add(minPanel, "Minimization Setup"); + energyPanel.add(ignoreAtomsCheckBox, + new GridBagConstraints(0, 6, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTHEAST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + energyPanel.add(setupIgnoreAtomsButton, + new GridBagConstraints(1, 6, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + energyPanel.add(constraintsCheckBox, + new GridBagConstraints(2, 6, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTHEAST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + energyPanel.add(setupConstraintsButton, + new GridBagConstraints(3, 6, 1, 1, 0.0, 1.0 + , GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + energyPanel.add(calculateElsCheckBox, + new GridBagConstraints(0, 4, 2, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + energyPanel.add(jLabel4, new GridBagConstraints(0, 3, 2, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + energyPanel.add(jLabel2, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + energyPanel.add(nbCutoffTextField, + new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + energyPanel.add(jLabel5, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + energyPanel.add(dielFuncComboBox, + new GridBagConstraints(1, 5, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + energyPanel.add(jLabel6, new GridBagConstraints(2, 5, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + energyPanel.add(dielConstTextField, + new GridBagConstraints(3, 5, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + energyPanel.add(els14TextField, + new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + minimizationPanel.add(jCheckBox1, + new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + minimizationPanel.add(jTextField1, + new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + minimizationPanel.add(jLabel8, + new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + minimizationPanel.add(maxIterTextField, + new GridBagConstraints(1, 3, 1, 1, 0.0, 1.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + minimizationPanel.add(maxGradTextField, + new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + minimizationPanel.add(jLabel10, + new GridBagConstraints(2, 2, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + minimizationPanel.add(maxGRSMTextField, + new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(0, 0, 0, 0), 0, 0)); + minimizationPanel.add(jLabel13, + new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + minimizationPanel.add(jLabel9, + new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + minimizationPanel.add(maxGRMSCheckBox, + new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + minimizationPanel.add(maxGradCheckBox, + new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + nbCutoffTextField.setEnabled(nbCutoffCheckBox.isSelected()); + + els14TextField.setEnabled(calculateElsCheckBox.isSelected()); + dielFuncComboBox.setEnabled(calculateElsCheckBox.isSelected()); + dielConstTextField.setEnabled(calculateElsCheckBox.isSelected()); + + setupIgnoreAtomsButton.setEnabled(ignoreAtomsCheckBox.isSelected()); + + setupConstraintsButton.setEnabled(constraintsCheckBox.isSelected()); + + dielFuncComboBox.addItem("Constant"); + dielFuncComboBox.addItem("Distance"); + dielFuncComboBox.setSelectedIndex(0); + } + + public boolean areMinimizersSet() { + return minimizers != null; + } + + public void setMinimizers(MinimizerInterface mins[]) { + if (mins == null || mins.length < 1) { + return; + } + minimizers = mins; + minimizersComboBox.removeAllItems(); + for (int i = 0; i < mins.length; i++) { + minimizersComboBox.addItem(mins[i].getName()); + } + this.selectMinimizer(mins[0].getName()); + } + + public MinimizerInterface getSelectedMinimizer() { + if (minimizers == null || minimizers.length < 1) { + return null; + } + return minimizers[minimizersComboBox.getSelectedIndex()]; + } + + public void setForceFields(ForceFieldInterface ff[]) { + if (ff == null || ff.length < 1) { + return; + } + forceFields = ff; + forceFieldComboBox.removeAllItems(); + for (int i = 0; i < ff.length; i++) { + forceFieldComboBox.addItem(ff[i].getName()); + } + selectForceField(ff[0].getName()); + } + + public void selectMinimizer(String minName) { + if (minimizers == null) { + return; + } + minimizersComboBox.setEnabled(false); + minimizersComboBox.setSelectedItem(minName); + int n = minimizersComboBox.getSelectedIndex(); + MinimizerInterface min = minimizers[n]; + + // Set Max iterations + maxIterTextField.setEnabled(false); + maxIterTextField.setText(String.valueOf(min.getMaxIterations())); + maxIterTextField.setEnabled(true); + + // Max gradient + + if (min.useGradients()) { + maxGradCheckBox.setSelected(min.isMaxGradConvergence()); + + maxGradTextField.setEnabled(false); + maxGradTextField.setText(String.valueOf(min.getMaxGradientConv())); + maxGradTextField.setEnabled(maxGradCheckBox.isSelected()); + + maxGRMSCheckBox.setSelected(min.isMaxRMSGradConvergence()); + maxGRSMTextField.setEnabled(false); + maxGRSMTextField.setText(String.valueOf(min.getMaxRMSGradientConv())); + maxGRSMTextField.setEnabled(true); + } + else { + maxGradCheckBox.setEnabled(false); + maxGradTextField.setEnabled(false); + + maxGRMSCheckBox.setEnabled(false); + maxGRSMTextField.setEnabled(false); + } + + minimizersComboBox.setEnabled(true); + } + + public void selectForceField(String ffName) { + if (forceFields == null) { + return; + } + forceFieldComboBox.setEnabled(false); + forceFieldComboBox.setSelectedItem(ffName); + int n = forceFieldComboBox.getSelectedIndex(); + ForceFieldInterface ff = forceFields[n]; + + // --- Electrostatic setup + calculateElsCheckBox.setSelected(ff.isCalculateElectrostatics()); + dielFuncComboBox.setEnabled(calculateElsCheckBox.isSelected()); + + dielFuncComboBox.setSelectedIndex(ff.getDielectricFunction()); + + dielConstTextField.setEnabled(calculateElsCheckBox.isSelected()); + dielConstTextField.setText(String.valueOf(ff.getDielectricConstant())); + + nbCutoffCheckBox.setSelected(ff.isUseNBCutoff()); + nbCutoffTextField.setEnabled(nbCutoffCheckBox.isSelected()); + nbCutoffTextField.setText(String.valueOf(ff.getNBCutoff())); + + // --- 1-4 setup + + vdw14TextField.setEnabled(false); + vdw14TextField.setText(String.valueOf(ff.get14NBScale())); + vdw14TextField.setEnabled(true); + + els14TextField.setEnabled(false); + els14TextField.setText(String.valueOf(ff.get14ElsScale())); + els14TextField.setEnabled(true); + els14TextField.setEnabled(calculateElsCheckBox.isSelected()); + + forceFieldComboBox.setEnabled(true); + + } + + public void energySetupMode() { + jTabbedPane1.setSelectedIndex(energySetupTab); + jTabbedPane1.setEnabledAt(minimizationSetupTab, false); + } + + public void minimizationSetupMode() { + jTabbedPane1.setEnabledAt(minimizationSetupTab, true); + jTabbedPane1.setSelectedIndex(minimizationSetupTab); + } + + public void nbCutoffCheckBox_itemStateChanged(ItemEvent e) { + nbCutoffTextField.setEnabled(nbCutoffCheckBox.isSelected()); + int n = forceFieldComboBox.getSelectedIndex(); + ForceFieldInterface ff = forceFields[n]; + ff.enableUseNBCutoff(nbCutoffCheckBox.isSelected()); + } + + public boolean isOkPressed() { + return okPressed; + } + + public void cancelButton_actionPerformed(ActionEvent e) { + okPressed = false; + setVisible(false); + } + + public void CalcButton_actionPerformed(ActionEvent e) { + + // First, process energy setup (always) + + int n = forceFieldComboBox.getSelectedIndex(); + ForceFieldInterface ff = forceFields[n]; + + // --- Use NB Cutoff + + ff.enableUseNBCutoff(nbCutoffCheckBox.isSelected()); + + // --- Do calculate electrostatics? + + ff.enableCalculateElectrostatics(calculateElsCheckBox.isSelected()); + + // --- Dielectric function + + ff.setDielectricFunction(dielFuncComboBox.getSelectedIndex()); + + // --- Parse cutoff + + float cutoff = 0; + try { + cutoff = parseCutoff(nbCutoffTextField.getText()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + ff.setNBCutoff(cutoff); + + // --- Parse 1-4 vdw + + float vdw14 = 0; + try { + vdw14 = parsePositiveFloat(vdw14TextField.getText()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "1-4 VDW Scale factor: " + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + ff.set14NBScale(vdw14); + + // --- Parse 1-4 els + + if (calculateElsCheckBox.isSelected()) { + float els14 = 0; + try { + els14 = parsePositiveFloat(els14TextField.getText()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "1-4 Electrostatics Scale factor: " + + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + ff.set14ElsScale(els14); + } + + // --- Dielectric constant + + if (calculateElsCheckBox.isSelected()) { + float dielC = 0; + try { + dielC = parsePositiveFloat(dielConstTextField.getText()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Dielectric Constant: " + + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + ff.setDielectricConstant(dielC); + } + + // -- Now process minimization setup (if needed) + + if (jTabbedPane1.isEnabledAt(minimizationSetupTab)) { + int m = minimizersComboBox.getSelectedIndex(); + MinimizerInterface min = minimizers[m]; + + // --- Parse Max iterations + int maxIter = 0; + try { + maxIter = parsePositiveInteger(maxIterTextField.getText()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Max Iterations: " + + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + min.setMaxIterations(maxIter); + + // --- Enable max rms grad convergence + + min.enableMaxGRMSConvergence(maxGRMSCheckBox.isSelected()); + + // --- Max GRMS + + float maxGRMS = 0; + try { + maxGRMS = parsePositiveFloat(this.maxGRSMTextField.getText()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Max RMS Gradient: " + + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + min.setMaxRMSGradientConv(maxGRMS); + + // --- Enable max grad convergence + + min.enableMaxGradConvergence(maxGradCheckBox.isSelected()); + + // --- max gradient + + float maxG = 0; + try { + maxG = parsePositiveFloat(maxGradTextField.getText()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Max Gradient: " + + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + min.setMaxGradientConv(maxG); + + } + + okPressed = true; + setVisible(false); + } + + public void nbCutoffTextField_actionPerformed(ActionEvent e) { + if (!nbCutoffTextField.isEnabled()) { + return; + } + nbCutoffTextField.setEnabled(false); + float cutoff = 0; + try { + cutoff = parseCutoff(nbCutoffTextField.getText()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + nbCutoffTextField.setEnabled(true); + return; + } + + int n = forceFieldComboBox.getSelectedIndex(); + ForceFieldInterface ff = forceFields[n]; + ff.setNBCutoff(cutoff); + nbCutoffTextField.setEnabled(true); + } + + public boolean isUseCutoff() { + return nbCutoffCheckBox.isSelected(); + } + + public int getScreenRefreshRate() { + int rate = 1; + try { + String size = refreshRateTextField.getModel().getValue().toString(); + rate = Integer.parseInt(size); + } + catch (NumberFormatException nfe) { + } + return rate; + } + + public int getSelectedFFIndex() { + return forceFieldComboBox.getSelectedIndex(); + } + + public ForceFieldInterface getSelectedFF() { + return forceFields[getSelectedFFIndex()]; + } + + public static float parseCutoff(String text) throws Exception { + float cutoff = 0.0f; + try { + cutoff = Float.parseFloat(text.trim()); + } + catch (Exception ex) { + throw new Exception("Wrong number for cutoff: " + + text + " : " + + ex.getMessage()); + } + + if (cutoff < 0) { + throw new Exception( + "Cutoff should be positive number. Current value: " + + text); + } + + return cutoff; + } + + public static int parsePositiveInteger(String text) throws Exception { + int number = 0; + try { + number = Integer.parseInt(text.trim()); + } + catch (Exception ex) { + throw new Exception("Wrong number: " + text + " : " + + ex.getMessage()); + } + + if (number < 0) { + throw new Exception( + "Number should be positive. Current value: " + + text); + } + + return number; + } + + public static float parsePositiveFloat(String text) throws Exception { + float cutoff = 0.0f; + try { + cutoff = Float.parseFloat(text.trim()); + } + catch (Exception ex) { + throw new Exception("Wrong number: " + text + " : " + + ex.getMessage()); + } + + if (cutoff < 0) { + throw new Exception( + "Number should be positive. Current value: " + + text); + } + + return cutoff; + } + + public void calculateElsCheckBox_itemStateChanged(ItemEvent e) { + els14TextField.setEnabled(calculateElsCheckBox.isSelected()); + dielFuncComboBox.setEnabled(calculateElsCheckBox.isSelected()); + dielConstTextField.setEnabled(calculateElsCheckBox.isSelected()); + } + + public void forceFieldComboBox_actionPerformed(ActionEvent e) { + if (!forceFieldComboBox.isEnabled()) { + return; + } + forceFieldComboBox.setEnabled(false); + selectForceField(forceFieldComboBox.getSelectedItem().toString()); + forceFieldComboBox.setEnabled(true); + } + + public void helpButton_actionPerformed(ActionEvent e) { + JOptionPane.showMessageDialog(this, + "It's very easy to setup energy", + "Help", + JOptionPane.INFORMATION_MESSAGE); + + } + + public void ignoreAtomsCheckBox_itemStateChanged(ItemEvent e) { + setupIgnoreAtomsButton.setEnabled(ignoreAtomsCheckBox.isSelected()); + } + + public void constraintsCheckBox_itemStateChanged(ItemEvent e) { + setupConstraintsButton.setEnabled(constraintsCheckBox.isSelected()); + } + + private class JSetupEnergyDialog_constraintsCheckBox_itemAdapter + implements ItemListener { + private JSetupEnergyDialog adaptee; + JSetupEnergyDialog_constraintsCheckBox_itemAdapter(JSetupEnergyDialog + adaptee) { + this.adaptee = adaptee; + } + + @Override + public void itemStateChanged(ItemEvent e) { + adaptee.constraintsCheckBox_itemStateChanged(e); + } + } + +} + +class JSetupEnergyDialog_ignoreAtomsCheckBox_itemAdapter + implements ItemListener { + private JSetupEnergyDialog adaptee; + JSetupEnergyDialog_ignoreAtomsCheckBox_itemAdapter(JSetupEnergyDialog + adaptee) { + this.adaptee = adaptee; + } + + @Override + public void itemStateChanged(ItemEvent e) { + adaptee.ignoreAtomsCheckBox_itemStateChanged(e); + } +} + +class JSetupEnergyDialog_helpButton_actionAdapter + implements ActionListener { + private JSetupEnergyDialog adaptee; + JSetupEnergyDialog_helpButton_actionAdapter(JSetupEnergyDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.helpButton_actionPerformed(e); + } +} + +class JSetupEnergyDialog_forceFieldComboBox_actionAdapter + implements ActionListener { + private JSetupEnergyDialog adaptee; + JSetupEnergyDialog_forceFieldComboBox_actionAdapter(JSetupEnergyDialog + adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.forceFieldComboBox_actionPerformed(e); + } +} + +class JSetupEnergyDialog_calculateElsCheckBox_itemAdapter + implements ItemListener { + private JSetupEnergyDialog adaptee; + JSetupEnergyDialog_calculateElsCheckBox_itemAdapter(JSetupEnergyDialog + adaptee) { + this.adaptee = adaptee; + } + + @Override + public void itemStateChanged(ItemEvent e) { + adaptee.calculateElsCheckBox_itemStateChanged(e); + } +} + +class JSetupEnergyDialog_nbCutoffTextField_actionAdapter + implements ActionListener { + private JSetupEnergyDialog adaptee; + JSetupEnergyDialog_nbCutoffTextField_actionAdapter(JSetupEnergyDialog + adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.nbCutoffTextField_actionPerformed(e); + } +} + +class CalcButton_actionAdapter + implements ActionListener { + private JSetupEnergyDialog adaptee; + CalcButton_actionAdapter(JSetupEnergyDialog adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.CalcButton_actionPerformed(e); + } +} + +class JSetupEnergyDialog_nbCutoffCheckBox_itemAdapter + implements ItemListener { + private JSetupEnergyDialog adaptee; + JSetupEnergyDialog_nbCutoffCheckBox_itemAdapter(JSetupEnergyDialog adaptee) { + this.adaptee = adaptee; + } + + public void itemStateChanged(ItemEvent e) { + adaptee.nbCutoffCheckBox_itemStateChanged(e); + } +} + +class JSetupEnergyDialog_cancelButton_actionAdapter + implements ActionListener { + private JSetupEnergyDialog adaptee; + JSetupEnergyDialog_cancelButton_actionAdapter(JSetupEnergyDialog adaptee) { + this.adaptee = adaptee; + } + + public void actionPerformed(ActionEvent e) { + adaptee.cancelButton_actionPerformed(e); + } +} diff --git a/src/main/java/cct/modelling/ui/MinimizationProgressDialog.java b/src/main/java/cct/modelling/ui/MinimizationProgressDialog.java new file mode 100644 index 0000000..55f1985 --- /dev/null +++ b/src/main/java/cct/modelling/ui/MinimizationProgressDialog.java @@ -0,0 +1,108 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling.ui; + +import java.awt.BorderLayout; +import java.awt.Frame; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.SwingConstants; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class MinimizationProgressDialog + extends JDialog { + JPanel panel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JLabel progressLabel = new JLabel(); + JButton cancelButton = new JButton(); + JPanel jPanel1 = new JPanel(); + public MinimizationProgressDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public MinimizationProgressDialog() { + this(new Frame(), "MinimizationProgressDialog", false); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + this.setDefaultCloseOperation(javax.swing.WindowConstants. + DO_NOTHING_ON_CLOSE); + progressLabel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + progressLabel.setHorizontalAlignment(SwingConstants.CENTER); + progressLabel.setText("Minimization progress is here"); + cancelButton.setToolTipText(""); + cancelButton.setText("Cancel Minimization"); + getContentPane().add(panel1); + jPanel1.add(cancelButton); + panel1.add(jPanel1, BorderLayout.SOUTH); + panel1.add(progressLabel, BorderLayout.NORTH); + } + + public void setProgress(String progress) { + progressLabel.setText(progress); + + } + + public JButton getCancelButton() { + return this.cancelButton; + } +} diff --git a/src/main/java/cct/modelling/ui/OpenFile.java b/src/main/java/cct/modelling/ui/OpenFile.java new file mode 100644 index 0000000..d35fa89 --- /dev/null +++ b/src/main/java/cct/modelling/ui/OpenFile.java @@ -0,0 +1,579 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.modelling.ui; + +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; +import java.util.prefs.Preferences; + +import javax.swing.JFileChooser; +import javax.swing.filechooser.FileFilter; + +import cct.adf.ADF; +import cct.amber.ReadPrmtopDialog; +import cct.gamess.Gamess; +import cct.gamess.GamessOutput; +import cct.gaussian.Gaussian; +import cct.gaussian.GaussianCube; +import cct.gaussian.GaussianFragment; +import cct.gaussian.ui.GaussianInputEditorFrame; +import cct.gromacs.GromacsParserFactory; +import cct.interfaces.AtomInterface; +import cct.interfaces.GraphicsRendererInterface; +import cct.interfaces.MoleculeInterface; +import cct.j3d.UnitCellGraphics; +import cct.mdl.MDLMol; +import cct.modelling.CCTAtomTypes; +import cct.modelling.CHEMISTRY_FILE_FORMAT; +import cct.modelling.MolecularFileFormats; +import cct.modelling.Molecule; +import cct.mopac.Mopac; +import cct.mopac.MopacOutput; +import cct.pdb.PDB; +import cct.qchem.QChem; +import cct.qchem.QChemOutput; +import cct.tools.CCTParser; +import cct.tools.FileFilterImpl; +import cct.tools.SimpleParserFactory; +import cct.tools.XMolXYZ; +import cct.tools.ui.JShowText; +import cct.tripos.TriposParser; +import cct.vasp.ui.ReadPoscarDialog; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +enum OPEN_FILE_MODE { + + SIMPLE, ADVANCED +} + +@Deprecated +public class OpenFile + implements ActionListener { + + static private Preferences prefs = Preferences.userNodeForPackage(OpenFile.class.getClass()); + private static String lastPWDKey = "lastPWD"; + Frame Parent = null; + ReadPoscarDialog vaspDialog = null; + ReadPrmtopDialog prmtopDialog = null; + GaussianInputEditorFrame gaussianInputEditorFrame = null; + GraphicsRendererInterface Renderer = null; + Gaussian gaussianData; + private String fileName = null; + static final Logger logger = Logger.getLogger(OpenFile.class.getCanonicalName()); + + public OpenFile() { + } + + public OpenFile(Frame parent) { + Parent = parent; + } + + public static void main(String[] args) { + OpenFile openfile = new OpenFile(); + } + + public void setGraphicsRenderer(GraphicsRendererInterface renderer) { + Renderer = renderer; + } + + public Object[] loadMolecule(Frame parent, File currentWorkingDirectory) throws Exception { + Map readFormats = MolecularFileFormats.commonReadFormats; + //Map readFormatsDescr = MolecularFileFormats.commonReadFormatDescription; + int count = 0; + FileFilterImpl[] filter = new FileFilterImpl[readFormats.size()]; + + Map reference = new HashMap(); + + JFileChooser chooser = new JFileChooser(); + + Set set = readFormats.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + CHEMISTRY_FILE_FORMAT format = (CHEMISTRY_FILE_FORMAT) me.getKey(); + String extensions = readFormats.get(format); + String temp[] = extensions.split(";"); + filter[count] = new FileFilterImpl(); + String descr = MolecularFileFormats.getFileFormatDescription(format); + + for (int i = 0; i < temp.length; i++) { + if (i == 0) { + descr += " ("; + } else { + descr += ";"; + } + filter[count].addExtension(temp[i]); + descr += "*." + temp[i]; + if (i == temp.length - 1) { + descr += ")"; + } + } + filter[count].setDescription(descr); + chooser.addChoosableFileFilter(filter[count]); + reference.put(descr, format); + ++count; + } + chooser.setMultiSelectionEnabled(false); + chooser.setAcceptAllFileFilterUsed(false); + + if (currentWorkingDirectory != null) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } else { + String lastPWD = prefs.get(lastPWDKey, ""); + if (lastPWD.length() > 0) { + currentWorkingDirectory = new File(lastPWD); + if (currentWorkingDirectory.isDirectory() + && currentWorkingDirectory.exists()) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } + } + } + + int returnVal = JFileChooser.CANCEL_OPTION; + + returnVal = chooser.showOpenDialog(parent); + if (returnVal == JFileChooser.CANCEL_OPTION) { + return null; + } + FileFilter ff = chooser.getFileFilter(); + CHEMISTRY_FILE_FORMAT format = reference.get(ff.getDescription()); + fileName = chooser.getSelectedFile().getPath(); + + return openFile(fileName, format, OPEN_FILE_MODE.SIMPLE); + } + + public String getFileName() { + return fileName; + } + + public Object[] openFile(String fileName, CHEMISTRY_FILE_FORMAT fileType, OPEN_FILE_MODE mode) throws Exception { + + if (fileName == null) { + throw new Exception(OpenFile.class.getCanonicalName() + ": empty file name"); + } + + MoleculeInterface m = null; + JShowText showResume; + Object[] obj = null; + + switch (fileType) { + case ALL_FORMATS: + break; + /* + case G03_GJF: + if (gaussianInputEditorFrame != null && + gaussianInputEditorFrame.isVisible()) { + gaussianInputEditorFrame.setVisible(false); + } + + gaussianData = new Gaussian(); + int n = gaussianData.parseGJF(fileName, 0); + logger.info("Number of molecules: " + n); + if (n < 1) { + throw new Exception("Didn't find atoms in file"); + } + + // --- In a SIMPLE mode just take the first structure + if (mode == OPEN_FILE_MODE.SIMPLE) { + m = Molecule.getNewInstance(); + m = gaussianData.getMolecule(m, 0); + if (m == null || m.getNumberOfAtoms() < 1) { + throw new Exception("Didn't find atoms in file"); + } + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, + CCTAtomTypes.getElementMapping()); + break; + } + + if (n > 1) { + if (gaussianInputEditorFrame == null) { + gaussianData.setGraphicsRenderer(Renderer); + gaussianInputEditorFrame = new GaussianInputEditorFrame(gaussianData); + gaussianInputEditorFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); + try { + gaussianInputEditorFrame.removeMenuItem("File", "Exit"); + } + catch (Exception ex) { + + } + JMenuItem item = new JMenuItem("Select current step & exit"); + //GaussianInputEditorFrame_selectStep_actionAdapter al = new + // GaussianInputEditorFrame_selectStep_actionAdapter(); + + item.addActionListener(this); + gaussianInputEditorFrame.addMenuItem("File", item); + gaussianInputEditorFrame.returnBackButton.setVisible(true); + gaussianInputEditorFrame.returnBackButton.addActionListener(this); + + } + gaussianInputEditorFrame.setupEditor(gaussianData); + JOptionPane.showMessageDialog(null, + "Gaussian Input file has more than 1 step\n" + + "Select step in the next dialog", + "Info", + JOptionPane.INFORMATION_MESSAGE); + + gaussianInputEditorFrame.setVisible(true); + //logger.info("Loading 1st Molecule..."); + } + else { + m = Molecule.getNewInstance(); + m = gaussianData.getMolecule(m, 0); + if (m == null || m.getNumberOfAtoms() < 1) { + throw new Exception("Didn't find atoms in file"); + } + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, + CCTAtomTypes.getElementMapping()); + //MoleculeInterface m2 = Molecule.divideIntoMolecules(m); + } + + break; + */ + /* + case G03_OUTPUT: + if (fileName == null) { + fileName = chooseFileDialog(MolecularFileFormats.gaussian03Output, + "Gaussian G03 Output Files (*.log;*.out)", + JFileChooser.OPEN_DIALOG); + } + if (fileName != null) { + j3d.openMolecularModelingFile(MolecularFileFormats.gaussian03Output, fileName); + } + + break; + */ + case G03_CUBE: + try { + m = new Molecule(); + GaussianCube.extractGeometry(fileName, m); + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, + CCTAtomTypes.getElementMapping()); + //MoleculeInterface m2 = Molecule.divideIntoMolecules(mol); + } catch (Exception ex) { + throw new Exception("Error Loading Gaussian Cube file : " + ex.getMessage()); + } + break; + + case G03_FRAGMENT: + m = new Molecule(); + m = GaussianFragment.parseGaussianFragmentFile(m, fileName); + break; + + case GAMESS_INPUT: + Gamess gamess = new Gamess(); + gamess.parseGamessInput(fileName, 0); + m = new Molecule(); + gamess.getMolecularInterface(m); + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, + CCTAtomTypes.getElementMapping()); + break; + + case GAMESS_OUTPUT: + GamessOutput gamess_out = new GamessOutput(); + gamess_out.parseGamessOutputFile(fileName); + m = new Molecule(); + gamess_out.getMolecularInterface(m); + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + break; + + case MOPAC2002_LOG: + MopacOutput mopac = new MopacOutput(); + mopac.parseMopacLogFile(fileName); + m = new Molecule(); + mopac.getMolecularInterface(m); + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, + CCTAtomTypes.getElementMapping()); + + showResume = new JShowText("MOPAC Log File Resume"); + showResume.setSize(600, 640); + showResume.setTitle("MOPAC Log File Resume: " + fileName); + showResume.setLocationByPlatform(true); + showResume.setText(mopac.getOutputResume()); + showResume.setVisible(true); + break; + + case MOPAC_INPUT: + Mopac mopac_in = new Mopac(); + mopac_in.parseMopacInput(fileName, 0); + m = new Molecule(); + mopac_in.getMolecularInterface(m); + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + break; + + case MOPAC_OUTPUT: + MopacOutput mopac_out = new MopacOutput(); + mopac_out.parseMopacOutputFile(fileName); + m = new Molecule(); + mopac_out.getMolecularInterface(m); + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, + CCTAtomTypes.getElementMapping()); + + showResume = new JShowText("MOPAC Output File Resume"); + showResume.setSize(600, 640); + showResume.setTitle("MOPAC Output File Resume: " + fileName); + showResume.setLocationByPlatform(true); + showResume.setText(mopac_out.getOutputResume()); + showResume.setVisible(true); + + break; + case PDB: + m = new Molecule(); + PDB.parsePDBFile(fileName, m); + break; + + case ADF_INPUT: + ADF adf_input = new ADF(); + adf_input.parseInput(fileName, 0); + m = new Molecule(); + adf_input.getMolecularInterface(m); + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, + CCTAtomTypes.getElementMapping()); + break; + + case MOL2: + m = new Molecule(); + TriposParser triposParser = new TriposParser(); + triposParser.parseMol2File(fileName, m); + break; + + case MDL_MOLFILE: + m = new Molecule(); + MDLMol mol = new MDLMol(); + m = mol.parseFile(fileName, m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + break; + + case GROMACS_GRO: + m = new Molecule(); + m = GromacsParserFactory.parseGromacsCoordFile(fileName, m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + break; + + case AMBER_PRMTOP: + if (prmtopDialog == null) { + prmtopDialog = new ReadPrmtopDialog(Parent, "Open Amber Topology File (prmtop)", true, null); + prmtopDialog.setLocationRelativeTo(Parent); + } + m = new Molecule(); + prmtopDialog.setMolecule(m); + + prmtopDialog.setVisible(true); + + if (prmtopDialog.isOKPressed() + && prmtopDialog.getMolecule().getNumberOfAtoms() > 0) { + //this.java3dUniverse.addMolecule(prmtopDialog.getMolecule()); + } else { + return null; + } + + break; + + case CCT: + m = new Molecule(); + CCTParser cctParser = new CCTParser(m); + List mols = cctParser.parseCCTFile(fileName, m); + m = (Molecule) mols.get(0); + break; + + case XMOL_XYZ: + m = new Molecule(); + XMolXYZ xMolXYZ = new XMolXYZ(); + m = xMolXYZ.parseXMolXYZ(fileName, m); + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, + CCTAtomTypes.getElementMapping()); + + break; + case VASP_POSCAR: + if (vaspDialog == null) { + vaspDialog = new ReadPoscarDialog(Parent, "Open VASP Poscar File (poscar)", true, null); + vaspDialog.setLocationRelativeTo(Parent); + } + m = new Molecule(); + vaspDialog.setMolecule(m); + + vaspDialog.setVisible(true); + + if (vaspDialog.isOKPressed() + && vaspDialog.getMolecule().getNumberOfAtoms() > 0) { + m = vaspDialog.getMolecule(); + Molecule.guessCovalentBonds(m); + UnitCellGraphics poscarUC = new UnitCellGraphics("VASP Unit Cell"); + obj = new Object[2]; + obj[0] = m; + obj[1] = poscarUC.getCellGraphicsObject(vaspDialog.getLatticeVectors()); + } + return obj; + //break; + + case QCHEM_INPUT: + QChem qchem = new QChem(); + qchem.parseQChemInput(fileName, 0); + m = new Molecule(); + qchem.getMolecularInterface(m); + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + break; + + case QCHEM_OUTPUT: + QChemOutput qchem_out = new QChemOutput(); + qchem_out.parseQChemOutputFile(fileName, false); + m = new Molecule(); + qchem_out.getMolecularInterface(m); + Molecule.guessCovalentBonds(m); + Molecule.guessAtomTypes(m, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + + showResume = new JShowText("Q-Chem Output File Resume"); + showResume.setSize(600, 640); + showResume.setTitle("Q-Chem Calculation Summary: " + fileName); + showResume.setLocationByPlatform(true); + showResume.setText(qchem_out.getOutputResume()); + showResume.setVisible(true); + + break; + + } + logger.info("Number of atoms: " + m.getNumberOfAtoms()); + obj = new Object[1]; + obj[0] = m; + return obj; + } + + /* + String chooseFileDialog(String fileType, String formatDescr, int dialogType) { + JFileChooser chooser = new JFileChooser(); + FileFilterImpl filter = new FileFilterImpl(); + String extensions = MolecularFileFormats.readFormats.get(fileType).toString(); + String temp[] = extensions.split(";"); + for (int i = 0; i < temp.length; i++) { + filter.addExtension(temp[i]); + } + filter.setDescription(formatDescr); + chooser.setFileFilter(filter); + chooser.setDialogType(dialogType); + if (dialogType == JFileChooser.OPEN_DIALOG) { + chooser.setDialogTitle("Open File"); + chooser.setDialogType(JFileChooser.OPEN_DIALOG); + } + else if (dialogType == JFileChooser.SAVE_DIALOG) { + chooser.setDialogTitle("Save File"); + chooser.setDialogType(JFileChooser.SAVE_DIALOG); + } + + if (currentWorkingDirectory != null) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } + else { + String lastPWD = prefs.get(lastPWDKey, ""); + if (lastPWD.length() > 0) { + currentWorkingDirectory = new File(lastPWD); + if (currentWorkingDirectory.isDirectory() && + currentWorkingDirectory.exists()) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } + } + } + + int returnVal = JFileChooser.CANCEL_OPTION; + + if (dialogType == JFileChooser.OPEN_DIALOG) { + returnVal = chooser.showOpenDialog(this); + } + else if (dialogType == JFileChooser.SAVE_DIALOG) { + returnVal = chooser.showSaveDialog(this); + } + + if (returnVal == JFileChooser.APPROVE_OPTION) { + String fileName = chooser.getSelectedFile().getPath(); + //String separator = chooser.getSelectedFile().pathSeparator; + //String fileName = chooser.getSelectedFile().getName(); + currentWorkingDirectory = chooser.getCurrentDirectory(); + try { + prefs.put(lastPWDKey, currentWorkingDirectory.getAbsolutePath()); + } + catch (Exception ex) { + System.err.println("Cannot save cwd: " + ex.getMessage() + + " Ignored..."); + } + logger.info("You chose to open this file: " + + fileName); + return fileName; + } + return null; + } + */ + @Override + public void actionPerformed(ActionEvent e) { /// !!! WRONG + gaussianInputEditorFrame.setVisible(false); + int n = gaussianInputEditorFrame.getSelectedStep(); + MoleculeInterface m = Molecule.getNewInstance(); + m = gaussianData.getMolecule(m, n); + Molecule.guessCovalentBonds(m); + + //if (this.processingSelected == SELECTED_ADD_MOLECULE) { + // enableMousePicking(true); + //} + } +} diff --git a/src/main/java/cct/modelling/ui/SetNamePanel.java b/src/main/java/cct/modelling/ui/SetNamePanel.java new file mode 100644 index 0000000..ae084a4 --- /dev/null +++ b/src/main/java/cct/modelling/ui/SetNamePanel.java @@ -0,0 +1,143 @@ +package cct.modelling.ui; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Map; + +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTextField; + +import cct.interfaces.MoleculeInterface; +import cct.j3d.Java3dUniverse; +import cct.modelling.AtomicSet; +import cct.modelling.AtomicSets; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class SetNamePanel + extends JPanel { + private BorderLayout borderLayout1 = new BorderLayout(); + private JPanel jPanel1 = new JPanel(); + private JLabel jLabel1 = new JLabel(); + private JTextField nameTextField = new JTextField(); + private FlowLayout flowLayout1 = new FlowLayout(); + private JButton nameButton = new JButton(); + + private Java3dUniverse j3d = null; + + public SetNamePanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public void setJava3dUniverse(Java3dUniverse j3d) { + this.j3d = j3d; + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + jLabel1.setToolTipText(""); + jLabel1.setText("Set Name: "); + jPanel1.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + nameButton.setToolTipText(""); + nameButton.setText("Set Name"); + nameButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + nameButton_actionPerformed(e); + } + }); + nameTextField.setToolTipText("Type Set Name and Press Enter"); + nameTextField.setColumns(20); + nameTextField.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + jTextField1_actionPerformed(e); + } + }); + this.add(jPanel1, BorderLayout.CENTER); + jPanel1.add(jLabel1); + jPanel1.add(nameTextField); + jPanel1.add(nameButton); + } + + public void nameButton_actionPerformed(ActionEvent e) { + String name = nameTextField.getText().trim().toUpperCase().replaceAll("[ ]", "_"); + setSetName(name); + } + + public void jTextField1_actionPerformed(ActionEvent e) { + String name = nameTextField.getText().trim().toUpperCase().replaceAll("[ ]", "_"); + setSetName(name); + } + + private void setSetName(String name) { + if (name.length() < 1) { + return; + } + if (j3d == null) { + JOptionPane.showMessageDialog(null, "Java3dUniverse is not set!", "Internal Error", JOptionPane.ERROR_MESSAGE); + return; + } + Map properties = j3d.getMoleculeInterface().getProperties(); + Object obj = properties.get(MoleculeInterface.AtomicSets); + AtomicSets sets; + if (obj == null) { + sets = new AtomicSets(); + } + else if (! (obj instanceof AtomicSets)) { + System.err.println(this.getClass().getCanonicalName() + ": setSetName: expected AtomicSets, got " + + obj.getClass().getCanonicalName() + " Ignored..."); + sets = new AtomicSets(); + } + else { + sets = (AtomicSets) obj; + } + + AtomicSet aset = sets.get(name); + + if (aset != null) { + int n = JOptionPane.showConfirmDialog(this, "Atomic Set " + name + " already exists\n" + + "Do you want to overwrite it? - Press Yes\n" + + "To give it another name - Press No", + "Name is already in use", JOptionPane.YES_NO_OPTION); + if (n == JOptionPane.NO_OPTION || n == JOptionPane.CLOSED_OPTION) { + return; + } + } + else { + aset = new AtomicSet(name); + } + + aset.clear(); + aset.addAll(j3d.getSelectedAtoms()); + + sets.put(name, aset); + + properties.put(MoleculeInterface.AtomicSets, sets); + + JOptionPane.showMessageDialog(null, "Set " + name + " of " + j3d.getSelectedAtoms().size() + " atom(s) was created", "Info", + JOptionPane.INFORMATION_MESSAGE); + nameTextField.setText(""); + } +} diff --git a/src/main/java/cct/modelling/ui/VibrationsControlFrame.java b/src/main/java/cct/modelling/ui/VibrationsControlFrame.java new file mode 100644 index 0000000..9c7d06c --- /dev/null +++ b/src/main/java/cct/modelling/ui/VibrationsControlFrame.java @@ -0,0 +1,127 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.modelling.ui; + +import java.awt.BorderLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.WindowConstants; + +import cct.interfaces.OutputResultsInterface; +import cct.interfaces.VibrationsRendererProvider; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class VibrationsControlFrame + extends JFrame { + private BorderLayout borderLayout1 = new BorderLayout(); + private JPanel jPanel1 = new JPanel(); + private VibrationsControlPanel vibrationsControlPanel1 = new VibrationsControlPanel(); + private JButton helpButton = new JButton(); + private JButton hideButton = new JButton(); + + public VibrationsControlFrame() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + getContentPane().setLayout(borderLayout1); + hideButton.setToolTipText(""); + hideButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + hideButton_actionPerformed(e); + } + }); + helpButton.setToolTipText(""); + this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + this.getContentPane().add(vibrationsControlPanel1, BorderLayout.CENTER); + helpButton.setText(" Help "); + this.getContentPane().add(jPanel1, BorderLayout.SOUTH); + hideButton.setText(" Hide "); + jPanel1.add(hideButton); + jPanel1.add(helpButton); + + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent we) { + vibrationsControlPanel1.cleanupMess(); + we.getWindow().setVisible(false); + } + }); + + } + + public void setSpectraProvider(OutputResultsInterface provider) { + vibrationsControlPanel1.setSpectraProvider(provider); + } + + public void setVibrationsRendererProvider(VibrationsRendererProvider provider) { + vibrationsControlPanel1.setVibrationsRendererProvider(provider); + } + + public static void main(String[] args) { + VibrationsControlFrame vibrationscontrolframe = new VibrationsControlFrame(); + } + + public void hideButton_actionPerformed(ActionEvent e) { + vibrationsControlPanel1.cleanupMess(); + setVisible(false); + } +} diff --git a/src/main/java/cct/modelling/ui/VibrationsControlPanel.java b/src/main/java/cct/modelling/ui/VibrationsControlPanel.java new file mode 100644 index 0000000..4c831da --- /dev/null +++ b/src/main/java/cct/modelling/ui/VibrationsControlPanel.java @@ -0,0 +1,506 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.modelling.ui; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.SystemColor; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.Hashtable; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSlider; +import javax.swing.JTable; +import javax.swing.ListSelectionModel; +import javax.swing.border.TitledBorder; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.TableModel; + +import cct.chart.ChartFrame; +import cct.chart.VibrationSpectrumChart; +import cct.interfaces.OutputResultsInterface; +import cct.interfaces.VibrationsRendererProvider; +import cct.modelling.VIBRATIONAL_SPECTRUM; + +/** + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class VibrationsControlPanel + extends JPanel implements ListSelectionListener { + + private BorderLayout borderLayout1 = new BorderLayout(); + private JPanel tablePanel = new JPanel(); + private JScrollPane jScrollPane1 = new JScrollPane(); + private JTable jTable1 = new JTable(); + private JPanel buttonPanel = new JPanel(); + private JPanel controlsPanel = new JPanel(); + private JButton spectrumButton = new JButton(); + private JPanel displacementPanel = new JPanel(); + private JSlider displacementSlider = new JSlider(); + private JPanel speedPanel = new JPanel(); + private JSlider speedSlider = new JSlider(); + private JPanel jPanel1 = new JPanel(); + private BorderLayout borderLayout2 = new BorderLayout(); + private BorderLayout borderLayout4 = new BorderLayout(); + private BorderLayout borderLayout5 = new BorderLayout(); + private JPanel jPanel2 = new JPanel(); + private JCheckBox animateCheckBox = new JCheckBox(); + private BorderLayout borderLayout6 = new BorderLayout(); + private JCheckBox showVectorsCheckBox = new JCheckBox(); + private FlowLayout flowLayout1 = new FlowLayout(); + private JComboBox spectrumComboBox = new JComboBox(); + private BorderLayout borderLayout7 = new BorderLayout(); + + private OutputResultsInterface outputResultsInterface = null; + private VibrationsRendererProvider vibrationsRendererProvider = null; + private int previouslySelectedRow = -1; + private GridBagLayout gridBagLayout1 = new GridBagLayout(); + private Hashtable speedLabelTable = new Hashtable(); + private Hashtable displLabelTable = new Hashtable(); + private VIBRATIONAL_SPECTRUM[] spectra = null; + private boolean savingActive = false; + private JButton saveSceneButton = new JButton(); + + public VibrationsControlPanel() { + try { + jbInit(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + speedLabelTable.put(new Integer(0), new JLabel("Fast")); + speedLabelTable.put(new Integer(speedSlider.getMaximum()), new JLabel("Slow")); + displLabelTable.put(new Integer(0), new JLabel("Small")); + speedSlider.setInverted(true); + speedSlider.setLabelTable(speedLabelTable); + speedSlider.setPaintLabels(true); + this.setLayout(borderLayout1); + spectrumButton.setText("Show Spectrum"); + spectrumButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + spectrumButton_actionPerformed(e); + } + }); + speedPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder(SystemColor.controlDkShadow, 1), "Animation Speed")); + speedPanel.setLayout(borderLayout5); + displacementPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder(SystemColor.controlDkShadow, 1), "Displacement")); + displacementPanel.setLayout(borderLayout4); + controlsPanel.setLayout(borderLayout2); + jPanel1.setLayout(gridBagLayout1); + animateCheckBox.setToolTipText(""); + animateCheckBox.setText("Animate Vibrations"); + animateCheckBox.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + animateCheckBox_itemStateChanged(e); + } + }); + jPanel2.setLayout(borderLayout6); + showVectorsCheckBox.setToolTipText(""); + showVectorsCheckBox.setText("Show Displacement Vectors"); + showVectorsCheckBox.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + showVectorsCheckBox_itemStateChanged(e); + } + }); + buttonPanel.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + tablePanel.setLayout(borderLayout7); + tablePanel.setMinimumSize(new Dimension(23, 50)); + tablePanel.setPreferredSize(new Dimension(452, 200)); + speedSlider.setEnabled(false); + speedSlider.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + speedSlider_stateChanged(e); + } + }); + displacementSlider.setLabelTable(displLabelTable); + displacementSlider.setPaintLabels(true); + displacementSlider.setEnabled(false); + saveSceneButton.setEnabled(true); + saveSceneButton.setText("Save Scene"); + saveSceneButton.addActionListener(new VibrationsControlPanel_saveSceneButton_actionAdapter(this)); + jScrollPane1.getViewport().add(jTable1); + buttonPanel.add(spectrumComboBox); + buttonPanel.add(spectrumButton); + buttonPanel.add(saveSceneButton); + this.add(controlsPanel, BorderLayout.CENTER); + displacementPanel.add(displacementSlider, BorderLayout.CENTER); + controlsPanel.add(jPanel2, BorderLayout.SOUTH); + controlsPanel.add(jPanel1, BorderLayout.NORTH); + jPanel2.add(showVectorsCheckBox, BorderLayout.CENTER); + jPanel2.add(buttonPanel, BorderLayout.SOUTH); + jPanel2.add(animateCheckBox, BorderLayout.NORTH); + this.add(tablePanel, BorderLayout.NORTH); + tablePanel.add(jScrollPane1, BorderLayout.CENTER); + jPanel1.add(displacementPanel, new GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(2, 2, 2, 2), 0, 0)); + jPanel1.add(speedPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(2, 2, 2, 2), 0, 0)); + speedPanel.add(speedSlider, BorderLayout.CENTER); + } + + public void setSpectraProvider(OutputResultsInterface provider) { + outputResultsInterface = provider; + ChartTableModel model = new ChartTableModel(outputResultsInterface); + jTable1 = new JTable(model); + jTable1.getSelectionModel().addListSelectionListener(this); + jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + jScrollPane1.getViewport().removeAll(); + jScrollPane1.getViewport().add(jTable1); + spectra = provider.availableVibrationalSpectra(); + spectrumComboBox.removeAllItems(); + if (spectra != null) { + for (int i = 0; i < spectra.length; i++) { + spectrumComboBox.addItem(VIBRATIONAL_SPECTRUM.getSpectrumName(spectra[i])); + } + } + if (spectrumComboBox.getItemCount() > 0) { + spectrumComboBox.setSelectedIndex(0); + } + + } + + public void setVibrationsRendererProvider(VibrationsRendererProvider provider) { + vibrationsRendererProvider = provider; + //speedSlider.setLabelTable(speedLabelTable); + speedSlider.setEnabled(false); + speedSlider.setMinimum(vibrationsRendererProvider.getMinimumDuration()); + speedSlider.setMaximum(vibrationsRendererProvider.getMaximumDuration()); + speedSlider.setValue(vibrationsRendererProvider.getDuration()); + + speedLabelTable.clear(); + speedLabelTable.put(new Integer(0), new JLabel("Fast")); + speedLabelTable.put(new Integer(speedSlider.getMaximum()), new JLabel("Slow")); + speedSlider.setLabelTable(speedLabelTable); + + speedSlider.setEnabled(true); + } + + public void cleanupMess() { + if (previouslySelectedRow != -1) { + if (animateCheckBox.isSelected()) { + vibrationsRendererProvider.animateVibrations(previouslySelectedRow, false); + } + if (showVectorsCheckBox.isSelected()) { + vibrationsRendererProvider.showDisplacementVectors(previouslySelectedRow, false); + } + } + } + + @Override + public void valueChanged(ListSelectionEvent e) { + + if (e.getValueIsAdjusting()) { + return; + } + if (jTable1.getSelectedRowCount() == 0 || jTable1.getSelectedRowCount() > 1) { + return; + } + int n = jTable1.getSelectedRow(); + + if (vibrationsRendererProvider != null) { + if (previouslySelectedRow != -1) { + if (animateCheckBox.isSelected()) { + vibrationsRendererProvider.animateVibrations(previouslySelectedRow, false); + } + if (showVectorsCheckBox.isSelected()) { + vibrationsRendererProvider.showDisplacementVectors(previouslySelectedRow, false); + } + } else if (n == -1 && previouslySelectedRow != -1) { + if (animateCheckBox.isSelected()) { + vibrationsRendererProvider.animateVibrations(previouslySelectedRow, false); + } + if (showVectorsCheckBox.isSelected()) { + vibrationsRendererProvider.showDisplacementVectors(previouslySelectedRow, false); + } + + } + + previouslySelectedRow = n; + + if (n != -1) { + if (animateCheckBox.isSelected()) { + vibrationsRendererProvider.setDuration(speedSlider.getValue()); + vibrationsRendererProvider.animateVibrations(previouslySelectedRow, true); + } + if (showVectorsCheckBox.isSelected()) { + vibrationsRendererProvider.showDisplacementVectors(previouslySelectedRow, true); + } + + } + } + } + + public void showVectorsCheckBox_stateChanged(ChangeEvent e) { + int n = jTable1.getSelectedRow(); + if (n == -1) { + return; + } + vibrationsRendererProvider.showDisplacementVectors(n, showVectorsCheckBox.isSelected()); + } + + public void animateCheckBox_stateChanged(ChangeEvent e) { + int n = jTable1.getSelectedRow(); + if (n == -1) { + return; + } + vibrationsRendererProvider.animateVibrations(n, animateCheckBox.isSelected()); + } + + public void speedSlider_stateChanged(ChangeEvent e) { + if (!speedSlider.isEnabled()) { + return; + } + if (speedSlider.getValueIsAdjusting()) { + return; + } + + //if (animateCheckBox.isSelected()) { + vibrationsRendererProvider.setDuration(speedSlider.getValue()); + //} + + } + + public void showVectorsCheckBox_itemStateChanged(ItemEvent e) { + int n = jTable1.getSelectedRow(); + if (n == -1) { + return; + } + vibrationsRendererProvider.showDisplacementVectors(n, showVectorsCheckBox.isSelected()); + } + + public void animateCheckBox_itemStateChanged(ItemEvent e) { + int n = jTable1.getSelectedRow(); + if (n == -1) { + return; + } + vibrationsRendererProvider.animateVibrations(n, animateCheckBox.isSelected()); + } + + public void spectrumButton_actionPerformed(ActionEvent e) { + if (outputResultsInterface == null || spectrumComboBox.getItemCount() < 1) { + return; + } + + int n = spectrumComboBox.getSelectedIndex(); + if (n == -1) { + return; + } + + VibrationSpectrumChart vsChart = new VibrationSpectrumChart(outputResultsInterface); + ChartFrame chart = null; + try { + chart = vsChart.createChart(spectra[n]); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Cannot plot " + + VIBRATIONAL_SPECTRUM.getSpectrumName(spectra[n]) + " : " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + chart.setLocationRelativeTo(this); + chart.showChart(true); + } + + public void saveSceneButton_actionPerformed(ActionEvent e) { + int n = jTable1.getSelectedRow(); + if (n == -1) { + return; + } + + if (savingActive) { + return; + } + + String[] choices = {"VRML", "PovRay"}; + String input = (String) JOptionPane.showInputDialog(null, "Choose file format...", + "The Choice of Animation Format", JOptionPane.QUESTION_MESSAGE, null, // Use + // default + // icon + choices, // Array of choices + choices[0]); // Initial choice + if (input == null) { + return; + } + + savingActive = true; + try { + vibrationsRendererProvider.saveScene(n, input); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error Saving " + input + " file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + savingActive = false; + } + + class ChartTableModel + extends AbstractTableModel implements TableModel { + + private OutputResultsInterface provider = null; + private String[] spectra = null; + private VIBRATIONAL_SPECTRUM[] vSpectra = null; + //private Object[][] data; + + /** + * Creates a new table model + * + * @param rows the row count. + */ + public ChartTableModel(OutputResultsInterface p) { + provider = p; + vSpectra = provider.availableVibrationalSpectra(); + + if (vSpectra == null || vSpectra.length < 1) { + return; + } + + spectra = new String[vSpectra.length]; + for (int i = 0; i < spectra.length; i++) { + spectra[i] = VIBRATIONAL_SPECTRUM.getSpectrumName(vSpectra[i]); + } + } + + /** + * Returns the column count. + * + * @return 7. + */ + @Override + public int getColumnCount() { + return provider.countSpectra() + 2; + } + + /** + * Returns the row count. + * + * @return The row count. + */ + @Override + public int getRowCount() { + return provider.countFrequencies(); + } + + /** + * Returns the value at the specified cell in the table. + * + * @param row the row index. + * @param column the column index. + * + * @return The value. + */ + @Override + public Object getValueAt(int row, int column) { + switch (column) { + case 0: + return new Integer(row + 1); + case 1: + return provider.getFrequency(row); + default: + return provider.getSpectrumValue(row, vSpectra[column - 2]); + } + } + + /** + * Returns the column name. + * + * @param column the column index. + * + * @return The column name. + */ + @Override + public String getColumnName(int column) { + switch (column) { + case 0: + return "N"; + case 1: + return "Frequency"; + default: + return spectra[column - 2]; + } + } + + } + +} + +class VibrationsControlPanel_saveSceneButton_actionAdapter + implements ActionListener { + + private VibrationsControlPanel adaptee; + + VibrationsControlPanel_saveSceneButton_actionAdapter(VibrationsControlPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.saveSceneButton_actionPerformed(e); + } +} diff --git a/src/main/java/cct/mopac/Mopac.java b/src/main/java/cct/mopac/Mopac.java new file mode 100644 index 0000000..7296291 --- /dev/null +++ b/src/main/java/cct/mopac/Mopac.java @@ -0,0 +1,1870 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.mopac; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.ChemicalElements; + +/** + *

Title:

+ * + *

Description:

+ * Data-sets consist of at least three parts. Later on in this Chapter we will elaborate on these parts, but for now it is sufficient to identify them. + * + * In order, the three essential parts of a MOPAC data-set are: + * + * Line 1: Keywords (one line). These control the calculation. The number of keywords used can range from none to about 20, space permitting. When more keywords are needed than will fit on one line, then more lines can be used (see Keyword & ). + * + * Line 2: Description of the calculation, e.g. the name of the molecule or ion. + * + * Line 3: Any other information describing the calculation. + * + * Line 4: Internal or Cartesian coordinates (many lines). See Geometry Specification. + * + * Line 5: Blank line to terminate the geometry definition. + * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ + + +// In addition to the elements, other symbols used in geometry definition are: +// XX A dummy atom for assisting with geometry specification +// Tv A translation vector for use with polymers, layer systems, and solids +// Cb The "capped bond" atom +// +3 A "sparkle" with a charge of +3 +// ++ A "sparkle" with a charge of +2 +// + A "sparkle" with a charge of +1 +// Fr A "sparkle" with a charge of +1/2 +// At A "sparkle" with a charge of -1/2 +// - A "sparkle" with a charge of -1 +// -- A "sparkle" with a charge of -2 +// -3 A "sparkle" with a charge of -3 + + +public class Mopac { + + static final float DEGREES_TO_RADIANS = (float) (Math.PI / 180.0); + static Set otherSymbols = new HashSet (); + static final Logger logger = Logger.getLogger(Mopac.class.getCanonicalName()); + + static { + otherSymbols.add("99"); + otherSymbols.add("X"); + otherSymbols.add("XX"); + otherSymbols.add("TV"); + otherSymbols.add("CB"); + otherSymbols.add("+3"); + otherSymbols.add("++"); + otherSymbols.add("+"); + otherSymbols.add("FR"); + otherSymbols.add("AT"); + otherSymbols.add("-"); + otherSymbols.add("--"); + otherSymbols.add("-3"); + } + + String Keywords = ""; + int keywordLines = 0; + boolean gaussianInput = false; + boolean yesSymmetryData = false; + boolean yesXYZ = false; + boolean yesTv = false; + String Comment_1 = "", Comment_2 = ""; + int netCharge = 0; + int spinMultiplicity = 1; + List Atoms = new ArrayList (100); + List originalGeometry = new ArrayList (100); + List originalSymmetry = new ArrayList (10); + List originalTv = new ArrayList (3); + Map symbolicStrings = new HashMap (300); + Symmetry symmetryRelations[] = null; + Tv Tvs[] = null; + + public Mopac() { + } + + public void getMolecularInterface(MoleculeInterface molec) throws + Exception { + if (molec == null) { + throw new Exception(this.getClass().getCanonicalName() + + " : molec == null"); + } + if (Atoms.size() < 1) { + throw new Exception(this.getClass().getCanonicalName() + + " : no Mopac atoms"); + } + + float factor = 1.0f; + + molec.addProperty(MoleculeInterface.ChargeProperty, new Integer(netCharge)); + molec.addProperty(MoleculeInterface.MultiplicityProperty, new Integer(spinMultiplicity)); + + molec.addMonomer("Mopac"); + + for (int i = 0; i < Atoms.size(); i++) { + MopacAtom ga = Atoms.get(i); + AtomInterface atom = molec.getNewAtomInstance(); + atom.setName(ga.getName()); + atom.setAtomicNumber(ga.getAtomicNumber()); + atom.setXYZ(ga.getX() * factor, ga.getY() * factor, ga.getZ() * factor); + molec.addAtom(atom); + } + } + + public void parseMopacInput(String inputfile, int fileType) throws + Exception { + + String line = null; + BufferedReader in = null; + + if (fileType == 0) { // Read from file + try { + in = new BufferedReader(new FileReader(inputfile)); + } + catch (Exception ex) { + throw ex; + } + } + else if (fileType == 1) { // Read from String + in = new BufferedReader(new StringReader(inputfile)); + } + else { + throw new Exception( + "parseMopacInput: INTERNAL ERROR: Unknown file type"); + } + + try { + + // --- Read keywords + + Keywords = readKeywords(in); + parseKeywords(); + + // --- Read comments (if any) + + int count = 3 - keywordLines; + + for (int i = 0; i < count; i++) { + line = in.readLine(); + if (line == null) { + throw new Exception("Unexpected end-of-file while reading comment..."); + } + if (i == 0) { + Comment_1 = line; + } + else if (i == 1) { + Comment_2 = line; + } + } + + // The molecular or unit cell geometry is supplied in the data-set as one atom per line. + // Sometimes it is useful to have points within a geometry defined. + // These points need not represent atoms. To allow for this, users can add entities called "dummy atoms". + + // The format in which the data is supplied is essentially the "Free-Format" style of FORTRAN. + // In fact, a character input is used in order to accommodate the chemical symbols, + // but the numeric data can be regarded as "free-format". + // This means that integers and real numbers can be interspersed, + // and numbers can be separated by one or more spaces, a tab and/or by one comma. + // If a number is not specified, its value is set to zero. + + // The geometry can be defined in terms of either internal or Cartesian coordinates, + // or a mixture of the two, or it can be in PDB or Gaussian format. + + // --- Reading geometry + + while ( (line = in.readLine()) != null) { + if (line.startsWith("*")) { + continue; + } + line = line.trim(); + + if (line.length() == 0 || line.startsWith("0")) { // Blank line after geometry input + break; + } + originalGeometry.add(line); + } + + gaussianInput = isGaussianInput(originalGeometry); + + if (gaussianInput) { + parseGaussianGeometry(originalGeometry, in); + } + else { + parseMopacGeometry(originalGeometry); + } + + // --- Read symmetry data (if any) + + if (yesSymmetryData) { + while ( (line = in.readLine()) != null) { + if (line.startsWith("*")) { + continue; + } + line = line.trim(); + + if (line.length() == 0) { // Blank line after geometry input + break; + } + originalSymmetry.add(line); + } + + parseSymmetryRelations(originalSymmetry); + if (!yesXYZ) { + imposeInternalCoordinateSymmetry(Atoms, symmetryRelations); + } + } + + fromZMatrixToCartesians(Atoms); + if (yesXYZ && yesSymmetryData) { + imposeCartesianCoordinateSymmetry(Atoms, symmetryRelations); + } + + if (yesTv) { + parseTranslationVectors(originalTv, Atoms); + for (int i = 0; i < Tvs.length; i++) { // Remove vectors from atom list + Atoms.remove(Atoms.size() - 1); + } + } + + in.close(); + } + catch (Exception e) { + in.close(); + throw e; + } + + } + + void parseTranslationVectors(List originalTvs, List atoms) throws Exception { + if (originalTvs.size() < 1 || atoms.size() < 1) { + return; + } + if (originalTvs.size() > 3) { + throw new Exception("parseTranslationVectors: Can be no more that 3 translation vectors. Got " + originalTvs.size()); + } + + Tvs = new Tv[originalTvs.size()]; + + String token; + for (int i = 0; i < originalTvs.size(); i++) { + String line = originalTvs.get(i); + String streppedLine = this.stripAtomLabel(line); + StringTokenizer st = new StringTokenizer(streppedLine, " \t,"); + if (st.countTokens() < 8) { + throw new Exception("parseTranslationVectors: Translation vector should have at least 9 tokens\nGot " + line); + } + + Tvs[i] = new Tv(); + + token = st.nextToken(); + try { + Tvs[i].length = Float.parseFloat(token); + } + catch (Exception ex) { + throw new Exception("parseTranslationVectors: Cannot parse Translation vector length\nGot " + line); + } + + // --- Skip 5 tokens + st.nextToken(); + st.nextToken(); + st.nextToken(); + st.nextToken(); + st.nextToken(); + + // --- Get direction + + try { + token = st.nextToken(); + int first = Integer.parseInt(token) - 1; + + if (first < 0 || first >= atoms.size()) { + throw new Exception("parseTranslationVectors: Wrong number for the first connectivity\nGot " + line); + } + + token = st.nextToken(); + int second = Integer.parseInt(token) - 1; + if (second < 0 || second >= atoms.size() || second == first) { + throw new Exception("parseTranslationVectors: Wrong number for the second connectivity\nGot " + line); + } + + MopacAtom a1 = atoms.get(first); + MopacAtom a2 = atoms.get(second); + + float dx = a2.xyz[0] - a1.xyz[0]; + float dy = a2.xyz[1] - a1.xyz[1]; + float dz = a2.xyz[2] - a1.xyz[2]; + float s = (float) Math.sqrt(dx * dx + dy * dy + dz * dz); + + Tvs[i].dir[0] = dx / s; + Tvs[i].dir[1] = dy / s; + Tvs[i].dir[2] = dz / s; + } + catch (Exception ex) { + throw new Exception("parseTranslationVectors: Cannot parse Translation vector connectivity\nGot " + line); + } + + } + } + + void imposeInternalCoordinateSymmetry(List geometry, Symmetry symmetry[]) throws Exception { + if (geometry == null || geometry.size() < 1 || symmetry == null || symmetry.length < 1) { + return; + } + for (int i = 0; i < symmetry.length; i++) { + int ref = symmetry[i].definingAtom; + MopacAtom refAtom = geometry.get(ref); + int func = symmetry[i].symmetryRelation; + float multiple = symmetry[i].multiplyingFactor; + int atoms[] = symmetry[i].definedAtoms; + for (int j = 0; j < atoms.length; j++) { + MopacAtom def_atom = geometry.get(atoms[j]); + switch (func) { + case 1: // Bond length is set equal to the reference bond length + def_atom.bondLength = refAtom.bondLength; + break; + case 2: // Bond angle is set equal to the reference bond angle + def_atom.alpha = refAtom.alpha; + break; + case 3: // Dihedral angle is set equal to the reference dihedral angle + def_atom.beta = refAtom.beta; + break; + case 4: // Dihedral angle varies as 90o - reference dihedral + def_atom.beta = 90.0f - refAtom.beta; + break; + case 5: // Dihedral angle varies as 90o + reference dihedral + def_atom.beta = 90.0f + refAtom.beta; + break; + case 6: // Dihedral angle varies as 120o - reference dihedral + def_atom.beta = 120.0f - refAtom.beta; + break; + case 7: // Dihedral angle varies as 120o + reference dihedral + def_atom.beta = 120.0f + refAtom.beta; + break; + case 8: // Dihedral angle varies as 180o - reference dihedral + def_atom.beta = 180.0f - refAtom.beta; + break; + case 9: // Dihedral angle varies as 180o + reference dihedral + def_atom.beta = 180.0f + refAtom.beta; + break; + case 10: // Dihedral angle varies as 240o - reference dihedral + def_atom.beta = 240.0f - refAtom.beta; + break; + case 11: // Dihedral angle varies as 240o + reference dihedral + def_atom.beta = 240.0f + refAtom.beta; + break; + case 12: // Dihedral angle varies as 270o - reference dihedral + def_atom.beta = 270.0f - refAtom.beta; + break; + case 13: // Dihedral angle varies as 270o + reference dihedral + def_atom.beta = 270.0f + refAtom.beta; + break; + case 14: // Dihedral angle varies as the negative of the reference dihedral + def_atom.beta = -refAtom.beta; + break; + case 15: // Bond length varies as half the reference bond length + def_atom.bondLength = refAtom.bondLength / 2.0f; + break; + case 16: // Bond angle varies as half the reference bond angle + def_atom.alpha = refAtom.alpha / 2.0f; + break; + case 17: // Bond angle varies as 180o -reference bond angle + def_atom.alpha = 180.0f - refAtom.alpha; + break; + case 18: // (not used) + break; + case 19: // Bond length is a multiple of the reference bond length + def_atom.bondLength = refAtom.bondLength * multiple; + //throw new Exception("Function 19 is not implemented yet"); + //break; + } + } + } + } + + void imposeCartesianCoordinateSymmetry(List geometry, Symmetry symmetry[]) throws Exception { + if (geometry == null || geometry.size() < 1 || symmetry == null || symmetry.length < 1) { + return; + } + for (int i = 0; i < symmetry.length; i++) { + int ref = symmetry[i].definingAtom; + MopacAtom refAtom = geometry.get(i); + int func = symmetry[i].symmetryRelation; + int atoms[] = symmetry[i].definedAtoms; + for (int j = 0; j < atoms.length; j++) { + MopacAtom def_atom = geometry.get(atoms[j]); + switch (func) { + case 1: // X coordinate is set equal to the reference X coordinate + def_atom.xyz[0] = refAtom.xyz[0]; + break; + case 2: // Y coordinate is set equal to the reference Y coordinate + def_atom.xyz[1] = refAtom.xyz[1]; + break; + case 3: // Z coordinate is set equal to the reference Z coordinate + def_atom.xyz[2] = refAtom.xyz[2]; + break; + case 4: // X coordinate is set equal to - the reference X coordinate + def_atom.xyz[0] = -refAtom.xyz[0]; + break; + case 5: // Y coordinate is set equal to - the reference Y coordinate + def_atom.xyz[1] = -refAtom.xyz[1]; + break; + case 6: // Z coordinate is set equal to - the reference Z coordinate + def_atom.xyz[2] = -refAtom.xyz[2]; + break; + case 7: // X coordinate is set equal to the reference Y coordinate + def_atom.xyz[0] = refAtom.xyz[1]; + break; + case 8: // Y coordinate is set equal to the reference Z coordinate + def_atom.xyz[1] = refAtom.xyz[2]; + break; + case 9: // Z coordinate is set equal to the reference X coordinate + def_atom.xyz[2] = refAtom.xyz[0]; + break; + case 10: // X coordinate is set equal to - the reference Y coordinate + def_atom.xyz[0] = refAtom.xyz[1]; + break; + case 11: // Y coordinate is set equal to - the reference Z coordinate + def_atom.xyz[1] = -refAtom.xyz[2]; + break; + case 12: // Z coordinate is set equal to - the reference X coordinate + def_atom.xyz[2] = -refAtom.xyz[0]; + break; + case 13: // X coordinate is set equal to the reference Z coordinate + def_atom.xyz[0] = refAtom.xyz[2]; + break; + case 14: // Y coordinate is set equal to the reference X coordinate + def_atom.xyz[1] = refAtom.xyz[0]; + break; + case 15: // Z coordinate is set equal to the reference Y coordinate + def_atom.xyz[2] = refAtom.xyz[1]; + break; + case 16: // X coordinate is set equal to - the reference Z coordinate + def_atom.xyz[0] = -refAtom.xyz[2]; + break; + case 17: // Y coordinate is set equal to - the reference X coordinatebreak; + def_atom.xyz[1] = -refAtom.xyz[0]; + break; + case 18: // Z coordinate is set equal to - the reference Y coordinate + def_atom.xyz[2] = -refAtom.xyz[1]; + break; + } + } + } + } + + String stripAtomLabel(String label) { + if (label.matches("(?i).{1,2}[(]{1}.*[)]{1}.*")) { + label = label.substring(label.indexOf(")") + 1); + if (label.length() == 0) { + return label; + } + if (!label.startsWith(" ") && !label.startsWith("\t") && !label.startsWith(",")) { + StringTokenizer st = new StringTokenizer(label, " \t,"); + String token = st.nextToken(); + label = label.substring(label.indexOf(token) + token.length()); + } + } + else { + StringTokenizer st = new StringTokenizer(label, " \t,"); + if (st.countTokens() == 0) { + return label; + } + String token = st.nextToken(); + label = label.substring(label.indexOf(token) + token.length()); + } + return label.trim(); + } + + String getAtomLabel(String label) { + if (label.matches("(?i).{1,2}[(]{1}.*[)]{1}.*")) { + int index = label.indexOf(")") + 1; + StringTokenizer st = new StringTokenizer(label.substring(index), " \t,"); + if (st.countTokens() == 0) { + return label.substring(0, index).trim(); + } + + return label.substring(0, index + st.nextToken().length()).trim(); + } + else { + StringTokenizer st = new StringTokenizer(label, " \t,"); + if (st.countTokens() == 0) { + return label; + } + return st.nextToken(); + } + } + + boolean isGaussianInput(List geometry) throws Exception { + + StringTokenizer st = null; + // Checking the first atom + + String strippedLine = null; + String line = geometry.get(0); + strippedLine = this.stripAtomLabel(line); + + st = new StringTokenizer(strippedLine, " \t,"); + if (st.countTokens() == 6) { + return false; // Cartesian + } + //if (st.countTokens() != 1) { + // throw new Exception("The first atom in internal coordinates input should have only one token. Got: " + line); + //} + + if (geometry.size() == 1) { + return false; + } + + // --- Checking the second atom + + line = geometry.get(1); + strippedLine = this.stripAtomLabel(line); + + st = new StringTokenizer(strippedLine, " \t,"); + if (st.countTokens() == 6) { + return false; // Cartesian + } + if (st.countTokens() < 1) { + throw new Exception("The second atom in internal coordinates input should have at least 2 tokens. Got: " + line); + } + + //st.nextToken(); // Skip + String token = st.nextToken(); // Second token + if (token.contains(".") || (!token.equals("1"))) { + return false; // it's MOPAC bond length... + } + + token = st.nextToken(); // Third token + + try { + float bond = Float.parseFloat(token); + } + catch (Exception ex) { + if (token.length() > 8) { + throw new Exception("Symbolic length in Gaussian input should be up to 8 characters. Got: " + line); + } + return true; // Symbolic bond length + //throw new Exception("Error parsing the second token for the second atom\nExpecting a number, got: " + line); + } + + if (geometry.size() == 2) { + return false; + } + + // --- Checking the third atom... + + line = geometry.get(2); + strippedLine = stripAtomLabel(line); + st = new StringTokenizer(strippedLine, " \t,"); + if (st.countTokens() == 6) { + return false; // Cartesian + } + else if (st.countTokens() == 4) { + return true; // Gaussian internal + } + else if (st.countTokens() >= 4) { + return false; // Mopac internal + } + else { + throw new Exception("The third atom should have at least 4 tokens. Got: " + line); + } + } + + public String readKeywords(BufferedReader in) throws Exception { + String keywords = ""; + String line; + try { + keywordLines = 0; + while ( (line = in.readLine()) != null) { + if (line.startsWith("*")) { + continue; + } + + line = line.trim(); + if (keywords.length() > 0) { + keywords += " "; + } + keywords += line; + + if (line.contains("+")) { + continue; + } + + ++keywordLines; + if (!line.contains("&") && !line.contains("+")) { + break; + } + + if (keywordLines == 3) { + break; + } + } + + if (line == null && keywordLines == 0) { + throw new Exception("Unexpected end-of-file while reading Mopac keywords..."); + } + } + catch (Exception ex) { + throw new Exception("Error reading Mopac keywords: " + ex.getMessage()); + } + return keywords; + } + + void parseKeywords() throws Exception { + String token = null, upToken = null; + StringTokenizer st = new StringTokenizer(Keywords, " \t,"); + while (st.hasMoreTokens()) { + token = st.nextToken(); + upToken = token.toUpperCase(); + + // parse system charge + if (upToken.startsWith("CHARGE=")) { + String charge = upToken.substring("CHARGE=".length()); + try { + netCharge = Integer.parseInt(charge); + } + catch (Exception ex) { + throw new Exception("Error parsing system charge " + token + " : " + ex.getMessage()); + } + //spinMultiplicity = 1; + } + + // parse multiplicity + + else if (upToken.equals("SINGLET")) { + spinMultiplicity = 1; + } + else if (upToken.equals("DOUBLET")) { + spinMultiplicity = 2; + } + else if (upToken.equals("TRIPLET")) { + spinMultiplicity = 3; + } + else if (upToken.equals("QUARTET")) { + spinMultiplicity = 4; + } + else if (upToken.equals("QUINTET")) { + spinMultiplicity = 5; + } + else if (upToken.equals("SEXTET")) { + spinMultiplicity = 6; + } + else if (upToken.equals("SEPTET")) { + spinMultiplicity = 7; + } + else if (upToken.equals("OCTET")) { + spinMultiplicity = 8; + } + + // --- To read symmetry information ? + + else if (upToken.equals("SYMMETRY") || upToken.equals("SYM")) { + yesSymmetryData = true; + } + + // --- To optimize in cartesians + + else if (upToken.equals("XYZ")) { + yesXYZ = true; + } + + } + } + + void parseSymmetryRelations(List symmetry) throws Exception { + if (symmetry.size() < 1) { + return; + } + symmetryRelations = new Symmetry[symmetry.size()]; + String line, token; + for (int i = 0; i < symmetry.size(); i++) { + line = symmetry.get(i); + StringTokenizer st = new StringTokenizer(line, " \t,"); + if (st.countTokens() < 3) { + throw new Exception("Symmetry relation should have at least three tokens. Got " + line); + } + + symmetryRelations[i] = new Symmetry(); + + // --- parse reference atom + + try { + token = st.nextToken(); + symmetryRelations[i].definingAtom = Integer.parseInt(token) - 1; + if (symmetryRelations[i].definingAtom < 0 || symmetryRelations[i].definingAtom >= Atoms.size()) { + throw new Exception("Reference atom in Symmetry relations should be > 0 and < " + (Atoms.size() + 1) + " Got: " + + line); + } + } + catch (Exception ex) { + throw new Exception("Error parsing reference atom in Symmetry relations: " + line + " : " + ex.getMessage()); + } + + // --- Parse symmetry relation + + try { + token = st.nextToken(); + symmetryRelations[i].symmetryRelation = Integer.parseInt(token); + if (symmetryRelations[i].symmetryRelation < 1 || symmetryRelations[i].symmetryRelation > 19) { + throw new Exception("Symmetry relation should be > 0 and < 20. Got: " + line); + } + + if (symmetryRelations[i].symmetryRelation == 19 && st.countTokens() < 2) { + throw new Exception("Symmetry relation 19 should have at least 4 tokens. Got: " + line); + } + } + catch (Exception ex) { + throw new Exception("Error parsing Symmetry relation: " + line + " : " + ex.getMessage()); + } + + // --- Parse Bond length multiple (if any) + + if (symmetryRelations[i].symmetryRelation == 19) { + try { + token = st.nextToken(); + symmetryRelations[i].multiplyingFactor = Float.parseFloat(token); + } + catch (Exception ex) { + throw new Exception("Error: Cannot parse Bond length multiple for Symmetry relation 19\n" + line + " : " + + ex.getMessage()); + } + } + + // --- Parse defined atoms + + symmetryRelations[i].definedAtoms = new int[st.countTokens()]; + + for (int j = 0; j < symmetryRelations[i].definedAtoms.length; j++) { + try { + token = st.nextToken(); + symmetryRelations[i].definedAtoms[j] = Integer.parseInt(token) - 1; + if (symmetryRelations[i].definedAtoms[j] < 0 || symmetryRelations[i].definedAtoms[j] >= Atoms.size()) { + throw new Exception("Defined atom in Symmetry relations should be > 0 and < " + (Atoms.size() + 1) + " Got: " + + line); + } + } + catch (Exception ex) { + throw new Exception("Error defined atom in Symmetry relations: " + line + " : " + ex.getMessage()); + } + } + + } + } + + public void parseMopacGeometry(List geometry) throws Exception { + // The order of the data is thus: (real and dummy atoms) (translation vector(s)) (blank line) + // (symmetry data or MECI data etc, if needed). + String line; + + // Comment lines are already removed... + + for (int i = 0; i < geometry.size(); i++) { + line = geometry.get(i); + + String label = this.getAtomLabel(line); + line = this.stripAtomLabel(line); + StringTokenizer st = new StringTokenizer(line, " \t,"); + //if (st.countTokens() < 1) { + // throw new Exception("Expecting Mopac geometry, got blank line..."); + //} + + // --- Process Tv + + if (label.equalsIgnoreCase("TV")) { + yesTv = true; + if (originalTv.size() >= 3) { + throw new Exception("Should be no more than 3 translation vectors"); + } + originalTv.add(line); + } + else if (yesTv) { + throw new Exception("No real or dummy atoms should come after a Tv"); + } + + MopacAtom atom = new MopacAtom(); + parseElement(label, atom); + + // --- The first atom + if (Atoms.size() == 0) { // Read the first atom + if (st.countTokens() == 0 || st.countTokens() != 6) { // Internal coordinates + atom.cartesian = false; + parseInternalCoord(st, atom); + } + else if (st.countTokens() == 6) { + parseCartesianCoord(st, atom); + } + //else { + // throw new Exception("the first atom may have one or 7 tokens. Got " + line); + //} + } + + // --- the second atom + else if (Atoms.size() == 1) { // Read the second atom + if (st.countTokens() == 6) { // Cartesian coordinates + parseCartesianCoord(st, atom); + } + else if (st.countTokens() >= 1) { + parseInternalCoord(st, atom); + } + else { + throw new Exception("The second atom should have at least two tokens. Got " + line); + } + } + + // --- the third atom + else if (Atoms.size() == 2) { // Read the third atom + MopacAtom a = Atoms.get(1); + if (st.countTokens() == 6 && a.cartesian) { // Cartesian coordinates + parseCartesianCoord(st, atom); + } + else if (st.countTokens() >= 3) { + parseInternalCoord(st, atom); + } + else { + throw new Exception("The third atom should have at least 4 tokens. Got " + line); + } + } + + // --- >3 atoms + else if (Atoms.size() > 2) { + if (st.countTokens() == 6) { // Cartesian coordinates + parseCartesianCoord(st, atom); + } + else if (st.countTokens() >= 9) { + parseInternalCoord(st, atom); + } + else { + throw new Exception("Atom " + (Atoms.size() + 1) + " should have at least 6 tokens. Got " + line); + } + } + + Atoms.add(atom); + } + + /* + try { + while ( (line = in.readLine()) != null) { + if (line.startsWith("*")) { + continue; + } + + } + } + catch (Exception ex) { + throw new Exception("Error reading Mopac geometry: " + ex.getMessage()); + } + */ + } + + public void parseInternalCoord(StringTokenizer st, MopacAtom atom) throws Exception { + /* + MINDO/3 + Formic acid + Example of normal geometry definition + O + C 1.20 1 + O 1.32 1 116.8 1 0.0 0 2 1 + H 0.98 1 123.9 1 0.0 0 3 2 1 + H 1.11 1 127.3 1 180.0 0 2 1 3 + 0 0.00 0 0.0 0 0.0 0 0 0 0 + + */ + atom.cartesian = false; + String token = null; + + // --- The first atom + if (Atoms.size() == 0) { + return; + } + //else if (Atoms.size() == 0 && st.countTokens() > 0) { + // throw new Exception("The first atom in internal coordinate input should have only one token..."); + //} + + // --- The second atom + else if (Atoms.size() == 1 && st.countTokens() >= 1) { + token = st.nextToken(); + try { + atom.bondLength = Float.parseFloat(token); + + if (st.countTokens() == 0) { + atom.opt[0] = 0; + return; + } + + token = st.nextToken(); + if (token.equalsIgnoreCase("T")) { + atom.opt[0] = -2; + } + else { + if (token.startsWith("+")) { + token = token.substring(1); + } + atom.opt[0] = Integer.parseInt(token); + } + } + catch (Exception ex) { + throw new Exception("Error parsing internal coordinate for the second atoms: " + token); + } + + } + else if (Atoms.size() == 1 && st.countTokens() < 1) { + throw new Exception("The second atom in internal coordinate input should have at least two tokens..."); + } + + // --- The third atom + + else if (Atoms.size() == 2 && st.countTokens() >= 3) { + token = st.nextToken(); + try { + atom.bondLength = Float.parseFloat(token); + token = st.nextToken(); + if (token.equalsIgnoreCase("T")) { + atom.opt[0] = -2; + } + else { + if (token.startsWith("+")) { + token = token.substring(1); + } + atom.opt[0] = Integer.parseInt(token); + } + + token = st.nextToken(); + atom.alpha = Float.parseFloat(token); + + if (st.countTokens() == 0) { + atom.opt[1] = 0; + atom.i1 = 1; + atom.i2 = 0; + return; + } + + token = st.nextToken(); + if (token.equalsIgnoreCase("T")) { + atom.opt[1] = -2; + } + else { + if (token.startsWith("+")) { + token = token.substring(1); + } + atom.opt[1] = Integer.parseInt(token); + } + + if (st.countTokens() == 0) { + atom.i1 = 1; + atom.i2 = 0; + return; + } + + // --- Skip two tokens... + if (st.countTokens() >= 4) { + st.nextToken(); + st.nextToken(); + } + + // --- Connectivity + + token = st.nextToken(); + atom.i1 = Integer.parseInt(token) - 1; + token = st.nextToken(); + atom.i2 = Integer.parseInt(token) - 1; + + } + catch (Exception ex) { + throw new Exception("Error parsing internal coordinate for the third atom: " + token); + } + + } + else if (Atoms.size() == 2 && st.countTokens() < 3) { + throw new Exception("The third atom in internal coordinate input should have at least 4 tokens..."); + } + + // --- >3 atoms + + else if (Atoms.size() > 2 && st.countTokens() >= 9) { + token = st.nextToken(); + try { + atom.bondLength = Float.parseFloat(token); + token = st.nextToken(); + if (token.equalsIgnoreCase("T")) { + atom.opt[0] = -2; + } + else { + if (token.startsWith("+")) { + token = token.substring(1); + } + atom.opt[0] = Integer.parseInt(token); + } + + token = st.nextToken(); + atom.alpha = Float.parseFloat(token); + token = st.nextToken(); + if (token.equalsIgnoreCase("T")) { + atom.opt[1] = -2; + } + else { + if (token.startsWith("+")) { + token = token.substring(1); + } + atom.opt[1] = Integer.parseInt(token); + } + + token = st.nextToken(); + atom.beta = Float.parseFloat(token); + token = st.nextToken(); + if (token.equalsIgnoreCase("T")) { + atom.opt[2] = -2; + } + else { + if (token.startsWith("+")) { + token = token.substring(1); + } + atom.opt[2] = Integer.parseInt(token); + } + + // --- Connectivity + + token = st.nextToken(); + atom.i1 = Integer.parseInt(token) - 1; + token = st.nextToken(); + atom.i2 = Integer.parseInt(token) - 1; + token = st.nextToken(); + atom.i3 = Integer.parseInt(token) - 1; + + } + catch (Exception ex) { + throw new Exception("Error parsing internal coordinate for the second atoms: " + token); + } + + } + else if (Atoms.size() > 2 && st.countTokens() < 9) { + throw new Exception("Atom " + (Atoms.size() + 1) + " in internal coordinate input should have 10 tokens..."); + } + + } + + public void parseCartesianCoord(StringTokenizer st, MopacAtom atom) throws Exception { + if (st.countTokens() < 6) { + throw new Exception("Cartesian coordinates should have at least 6 tokens. Got " + st.countTokens()); + } + + String token = null; + try { + token = st.nextToken(); + atom.xyz[0] = Float.parseFloat(token); + + token = st.nextToken(); + if (token.equalsIgnoreCase("T")) { + atom.opt[0] = -2; + } + else if (token.matches("[^0-9]+")) { + throw new Exception("Unknown flag (could be 0, 1, -1, and T): " + token); + } + if (token.startsWith("+")) { + token = token.substring(1); + } + atom.opt[0] = Integer.parseInt(token); + + token = st.nextToken(); + atom.xyz[1] = Float.parseFloat(token); + + token = st.nextToken(); + if (token.equalsIgnoreCase("T")) { + atom.opt[1] = -2; + } + else if (token.matches("[^0-9]+")) { + throw new Exception("Unknown flag (could be 0, 1, -1, and T): " + token); + } + + if (token.startsWith("+")) { + token = token.substring(1); + } + atom.opt[1] = Integer.parseInt(token); + + token = st.nextToken(); + atom.xyz[2] = Float.parseFloat(token); + + token = st.nextToken(); + if (token.equalsIgnoreCase("T")) { + atom.opt[2] = -2; + } + else if (token.matches("[^0-9]+")) { + throw new Exception("Unknown flag (could be 0, 1, -1, and T): " + token); + } + + if (token.startsWith("+")) { + token = token.substring(1); + } + atom.opt[2] = Integer.parseInt(token); + } + catch (Exception ex) { + throw new Exception("Error parsing Cartesian coordinate or flag " + token + " : " + ex.getMessage()); + } + + } + + public void parseElement(String label, MopacAtom atom) throws Exception { + if ( (label.contains("(") && !label.contains(")")) || (!label.contains("(") && label.contains(")"))) { + throw new Exception("Parentheses are not matched in atom label: " + label); + } + + String upperLabel = label.toUpperCase(); + //otherSymbols.add("TV"); + + // --- Process special cases + + if (upperLabel.startsWith("99") || upperLabel.startsWith("XX") || upperLabel.startsWith("X")) { + atom.charge = 0; + atom.element = 0; + atom.name = label; + return; + } + else if (upperLabel.startsWith("CB")) { + atom.charge = 0; + atom.element = 0; + atom.name = label; + return; + } + else if (upperLabel.startsWith("+3")) { + atom.charge = 3.0f; + atom.element = 0; + atom.name = label; + return; + } + else if (upperLabel.startsWith("++")) { + atom.charge = 2.0f; + atom.element = 0; + atom.name = label; + return; + } + else if (upperLabel.startsWith("+")) { + atom.charge = 1.0f; + atom.element = 0; + atom.name = label; + return; + } + else if (upperLabel.startsWith("-3")) { + atom.charge = -3.0f; + atom.element = 0; + atom.name = label; + return; + } + else if (upperLabel.startsWith("--")) { + atom.charge = -2.0f; + atom.element = 0; + atom.name = label; + return; + } + else if (upperLabel.startsWith("-")) { + atom.charge = -1.0f; + atom.element = 0; + atom.name = label; + return; + } + else if (upperLabel.startsWith("FR")) { + atom.charge = 0.5f; + atom.element = 0; + atom.name = label; + return; + } + else if (upperLabel.startsWith("AT")) { + atom.charge = -0.5f; + atom.element = 0; + atom.name = label; + return; + } + + // --- "Normal" atom + + if (label.contains("(") && label.matches("(?i).{1,2}[(]{1}.*[)]{1}.*")) { + StringTokenizer st = new StringTokenizer(label, "()"); + String token = st.nextToken(); + atom.charge = 0.0f; + atom.element = ChemicalElements.getAtomicNumber(token); + atom.name = token; + + } + else if (label.contains("(") && !label.matches("(?i).{1,2}[(]{1}.*[)]{1}.*")) { + throw new Exception("Wrong atom label format: " + label); + } + else { + try { + int element = Integer.parseInt(label); + atom.charge = 0.0f; + atom.element = element; + atom.name = ChemicalElements.getElementSymbol(element); + return; + } + catch (Exception ex) {} + + //line.matches("(?i).*job_state.*=.*") + + if (label.length() == 1) { + atom.charge = 0.0f; + atom.element = ChemicalElements.getAtomicNumber(label); + atom.name = label; + return; + } + else if (label.length() == 2 && upperLabel.matches("[A-Z]{2}")) { + atom.charge = 0.0f; + atom.element = ChemicalElements.getAtomicNumber(label); + atom.name = label; + return; + } + else if (label.length() == 2 && upperLabel.matches("[A-Z]{1}[0-9]{1}")) { + atom.charge = 0.0f; + atom.element = ChemicalElements.getAtomicNumber(label.substring(0, 1)); + atom.name = label.substring(0, 1); + try { + atom.isotopeMass = Float.parseFloat(label.substring(1)); + } + catch (Exception ex) { + throw new Exception("Error extracting isotope mass from atom label " + label + " : " + ex.getMessage()); + } + return ; + } + else if (upperLabel.substring(0, 2).matches("[A-Z]{2}")) { + atom.charge = 0.0f; + atom.element = ChemicalElements.getAtomicNumber(label.substring(0, 2)); + atom.name = label.substring(0, 2); + try { + atom.isotopeMass = Float.parseFloat(label.substring(2)); + } + catch (Exception ex) { + throw new Exception("Error extracting isotope mass from atom label " + label + " : " + ex.getMessage()); + } + return ; + } + else if (upperLabel.substring(0, 1).matches("[A-Z]{1}")) { + atom.charge = 0.0f; + atom.element = ChemicalElements.getAtomicNumber(label.substring(0, 1)); + atom.name = label.substring(0, 1); + try { + atom.isotopeMass = Float.parseFloat(label.substring(1)); + } + catch (Exception ex) { + throw new Exception("Error extracting isotope mass from atom label " + label + " : " + ex.getMessage()); + } + return ; + } + else { + throw new Exception("Cannot parse atom label " + label); + } + } + } + + public static void fromZMatrixToCartesians(List atoms) throws + Exception { + int i, ii, jj, kk, ll; + int natoms = atoms.size(); + MopacAtom a, a1, a2, a3, a_first; + float xyz[] = new float[3], x1[], x2[], x3[]; + + double SIN2, COS2, SIN3, COS3, + VT[] = new double[3], V1[] = new double[3], + V2[] = new double[3]; + double R2, + V3[] = new double[3], VA1, VB1, VC1, R3, V[] = new double[3]; + + if (natoms < 1) { + return; + } + + float factor = 1.0f; + + // --- The first atom. Put it into the origin + + MopacAtom atom = atoms.get(0); + a_first = atom; + if (!atom.cartesian) { + atom.setXYZ(0, 0, 0); + } + + if (natoms < 2) { + return; + } + + // --- ther second atom: put it along the X-axis + + atom = atoms.get(1); + if (!atom.cartesian) { + atom.setXYZ(a_first.xyz[0] + atom.getBondLength() * factor, a_first.xyz[1] + 0, a_first.xyz[2] + 0); + } + + if (natoms < 3) { + return; + } + + // --- Third atom (put it into the XOY plane + + a = atoms.get(2); + if (!atom.cartesian) { + + x1 = new float[3]; + int index = a.get_i1(); + a1 = atoms.get(index); + x1[0] = a1.getX(); + x1[1] = a1.getY(); + x1[2] = a1.getZ(); + + xyz[2] = a_first.xyz[2] + 0.0f; // Z-coordinate + + if (index == 0) { // Connected to the first atom + //logger.info("To the 1st"); + xyz[0] = a_first.xyz[0] + a.getBondLength() * factor * + (float) Math.cos( (double) (a.getAlpha() * DEGREES_TO_RADIANS)); // So, we put it along X-axis + xyz[1] = a_first.xyz[1] + a.getBondLength() * factor * + (float) Math.sin( (double) (a.getAlpha() * DEGREES_TO_RADIANS)); + } + else { + //logger.info("To the 2nd"); + xyz[0] = x1[0] - + a.getBondLength() * factor * + (float) Math.cos( (double) (a.getAlpha() * DEGREES_TO_RADIANS)); // So, we put it along X-axis + xyz[1] = -a.getBondLength() * factor * + (float) Math.sin( (double) (a.getAlpha() * DEGREES_TO_RADIANS)); + } + + a.setXYZ(xyz[0], xyz[1], xyz[2]); + } + + // Other atoms + + for (i = 3; i < natoms; i++) { + + a = atoms.get(i); + + if (atom.cartesian) { + continue; + } + + a1 = atoms.get(a.get_i1()); + a2 = atoms.get(a.get_i2()); + a3 = atoms.get(a.get_i3()); + + x1 = a1.xyz; + x2 = a2.xyz; + x3 = a3.xyz; + + SIN2 = Math.sin( (double) (a.getAlpha() * DEGREES_TO_RADIANS)); + COS2 = Math.cos( (double) (a.getAlpha() * DEGREES_TO_RADIANS)); + SIN3 = Math.sin( (double) (a.getBeta() * DEGREES_TO_RADIANS)); + COS3 = Math.cos( (double) (a.getBeta() * DEGREES_TO_RADIANS)); + + VT[0] = a.getBondLength() * factor * COS2; + VT[1] = a.getBondLength() * factor * SIN2 * SIN3; + VT[2] = a.getBondLength() * factor * SIN2 * COS3; + + V1[0] = x3[0] - x2[0]; + V1[1] = x3[1] - x2[1]; + V1[2] = x3[2] - x2[2]; + + V2[0] = x2[0] - x1[0]; + V2[1] = x2[1] - x1[1]; + V2[2] = x2[2] - x1[2]; + + R2 = Math.sqrt(V2[0] * V2[0] + V2[1] * V2[1] + V2[2] * V2[2]); + if (R2 == 0.0) { + R2 = 0.0001; + } + + V3[0] = V1[1] * V2[2] - V1[2] * V2[1]; + V3[1] = V1[2] * V2[0] - V1[0] * V2[2]; + V3[2] = V1[0] * V2[1] - V1[1] * V2[0]; + + R3 = Math.sqrt(V3[0] * V3[0] + V3[1] * V3[1] + V3[2] * V3[2]); + if (R3 == 0.0) { + R3 = 0.0001; + } + + V2[0] = V2[0] / R2; + V2[1] = V2[1] / R2; + V2[2] = V2[2] / R2; + + V3[0] = V3[0] / R3; + V3[1] = V3[1] / R3; + V3[2] = V3[2] / R3; + + V[0] = V2[1] * V3[2] - V2[2] * V3[1]; + V[1] = V2[2] * V3[0] - V2[0] * V3[2]; + V[2] = V2[0] * V3[1] - V2[1] * V3[0]; + + VA1 = V2[0] * VT[0] + V3[0] * VT[1] + V[0] * VT[2]; + VB1 = V2[1] * VT[0] + V3[1] * VT[1] + V[1] * VT[2]; + VC1 = V2[2] * VT[0] + V3[2] * VT[1] + V[2] * VT[2]; + + xyz[0] = x1[0] + (float) VA1; + xyz[1] = x1[1] + (float) VB1; + xyz[2] = x1[2] + (float) VC1; + + a.setXYZ(xyz); + } + } + + public void parseGaussianGeometry(List geometry, BufferedReader in) throws Exception { + // The information contained in the Gaussian Z-matrix is identical to that in a MOPAC Z-matrix, + // but the order of presentation is different. Atom N, (real or dummy) is specified in the format: + // Element N1 Length N2 Alpha N3 Beta + // where Element is the same as for the MOPAC Z-matrix. N1, N2, and N3 are the connectivity, + // the same as the MOPAC Z-matrix NA, NB, and NC: bond lengths are between N and N1, + // angles are between N, N1 and N2, and dihedrals are between N, N1, N2, and N3. + // The same rules apply to N1, N2, and N3 as to NA, NB, and NC. + + // Length, Alpha, and Beta are the bond lengths, the angle, and dihedral. + // They can be 'real', e.g. 1.45, 109.4, 180.0, or 'symbolic'. + // A symbolic is an alphanumeric string of up to 8 characters, + // e.g. R51, A512, D5213, CH, CHO, CHOC, etc. + // Two or more symbolics can be the same. Dihedral symbolics can optionally be preceded by a minus sign, + // in which case the value of the dihedral is the negative of the value of the symbolic. + // This is the equivalent of the normal MOPAC SYMMETRY operations 1, 2, 3, and 14. + + // If an internal coordinate is real, it will not be optimized. + // This is the equivalent of the MOPAC optimization flag "0". + // If an internal coordinate is symbolic, it can be optimized. + + // The Z-matrix is terminated by a blank line, after which comes the starting values of the symbolics, + // one per line. If there is a blank line in this set, + // then all symbolics after the blank line are considered fixed; that is, they will not be optimized. + // The set before the blank line will be optimized. + + String line = null, token; + + // Comment lines are already removed... + + for (int i = 0; i < geometry.size(); i++) { + line = geometry.get(i); + + String label = this.getAtomLabel(line); + line = this.stripAtomLabel(line).toUpperCase(); + StringTokenizer st = new StringTokenizer(line, " \t,"); + + // --- Process Tv + + if (label.equalsIgnoreCase("TV")) { + yesTv = true; + if (originalTv.size() >= 3) { + throw new Exception("Should be no more than 3 translation vectors"); + } + originalTv.add(line); + } + else if (yesTv) { + throw new Exception("No real or dummy atoms should come after a Tv"); + } + + MopacAtom atom = new MopacAtom(); + atom.cartesian = false; + parseElement(label, atom); + + if (Atoms.size() == 0) { // The first atom + Atoms.add(atom); + continue; + } + + if (Atoms.size() == 1 && st.countTokens() < 2) { + throw new Exception("The second atom in Gaussian Z-matrix should have at least 3 tokens. Got: " + line); + } + + // --- reading reference atom A + + token = st.nextToken(); + try { + atom.i1 = Integer.parseInt(token) - 1; + if (atom.i1 < 0 || atom.i1 >= Atoms.size()) { + throw new Exception("Wrong value for N1: " + (atom.i1 + 1) + " Should be between 1 and " + Atoms.size()); + } + } + catch (Exception ex) { + throw new Exception("Cannot parse N1 for " + (Atoms.size() + 1) + " atom\nInput line: " + line + "\nError message: " + + ex.getMessage()); + } + + // --- Reading Bond Length + + token = st.nextToken(); + + boolean isNumber = true; + float value = 0; + + try { + value = Float.parseFloat(token); + } + catch (Exception ex) { + isNumber = false; + } + + // --- if it's a parameter + + if (!isNumber) { + String symbolic = token; + if (token.startsWith("-")) { + symbolic = token.substring(1); + } + if (!symbolicStrings.containsKey(symbolic)) { + symbolicStrings.put(symbolic, null); + } + + atom.setBondLength(token); + } + else { + atom.setBondLength(value); + } + + // --- Special case, Z-matrix, 2nd atom + + if (Atoms.size() == 1) { // The second atom + Atoms.add(atom); + continue; + } + + if (st.countTokens() < 2) { + throw new Exception("Expecting NB and alpha. Got: " + line); + } + + // --- Reading reference Atom B + + token = st.nextToken(); + try { + atom.i2 = Integer.parseInt(token) - 1; + if (atom.i2 < 0 || atom.i2 >= Atoms.size() || atom.i2 == atom.i1) { + throw new Exception("Wrong value for N2: " + (atom.i2 + 1) + " Should be between 1 and " + Atoms.size() + + " and not equal to " + (atom.i1 + 1)); + } + } + catch (Exception ex) { + throw new Exception("Cannot parse N2 for " + (Atoms.size() + 1) + " atom\nInput line: " + line + "\nError message: " + + ex.getMessage()); + } + + // --- Reading Angle + + if (!st.hasMoreTokens()) { + throw new Exception("Expecting angle value"); + } + token = st.nextToken(); + + isNumber = true; + + try { + value = Float.parseFloat(token); + } + catch (Exception ex) { + isNumber = false; + } + + // --- if it's a parameter + if (!isNumber) { + String symbolic = token; + if (token.startsWith("-")) { + symbolic = token.substring(1); + } + if (!symbolicStrings.containsKey(symbolic)) { + symbolicStrings.put(symbolic, null); + } + + atom.setAlpha(token); + } + else { + atom.setAlpha(value); + } + + // --- Special case - the third atom + + if (Atoms.size() == 2) { + Atoms.add(atom); + continue; + } + + // --- Reading reference atom N3 + + if (!st.hasMoreTokens()) { + throw new Exception("Expecting reference atom parameter N3"); + } + token = st.nextToken(); + try { + atom.i3 = Integer.parseInt(token) - 1; + if (atom.i3 < 0 || atom.i3 >= Atoms.size() || atom.i3 == atom.i1 || atom.i3 == atom.i2) { + throw new Exception("Wrong value for N3: " + (atom.i3 + 1) + " Should be between 1 and " + Atoms.size() + + " and not equal to " + (atom.i1 + 1) + " and " + (atom.i2 + 1)); + } + } + catch (Exception ex) { + throw new Exception("Cannot parse N3 for " + (Atoms.size() + 1) + " atom\nInput line: " + line + "\nError message: " + + ex.getMessage()); + } + + // --- Reading torsion angle + + if (!st.hasMoreTokens()) { + throw new Exception("Expecting torsion angle"); + } + token = st.nextToken(); + + isNumber = true; + + try { + value = Float.parseFloat(token); + } + catch (Exception ex) { + isNumber = false; + } + + // --- if it's a parameter + if (!isNumber) { + String symbolic = token; + if (token.startsWith("-")) { + symbolic = token.substring(1); + } + if (!symbolicStrings.containsKey(symbolic)) { + symbolicStrings.put(symbolic, null); + } + + atom.setBeta(token); + } + else { + atom.setBeta(value); + } + + Atoms.add(atom); + } // --- End of parsing geometry + + // --- Resolve Parameters + + if (symbolicStrings.size() > 0) { + logger.info("Expecting " + symbolicStrings.size() + + " unique symbolic strings"); + + // --- Start to read symbolic strings + + int symbolicsFound = 0; + boolean optimizedSymbolics = true; + + while ( (line = in.readLine()) != null) { + line = line.trim().toUpperCase(); + + if (line.startsWith("*")) { + continue; + } + + if (line.length() == 0) { // blank line + if (optimizedSymbolics) { + logger.info("Finished to read symbolics to optimize"); + optimizedSymbolics = false; + if (isReadAllSymbolics(symbolicStrings)) { + break; + } + continue; + } + + if (!isReadAllSymbolics(symbolicStrings)) { + throw new Exception("Found blank line before all symbolic's values are read in..."); + } + break; + } + + StringTokenizer st = new StringTokenizer(line, "=, \t"); + + String currentString = st.nextToken(); + + if (st.countTokens() < 1) { + throw new Exception( + "Expecting at least two values for symbolic strings"); + } + + // --- Read symbol + + if (!symbolicStrings.containsKey(currentString)) { + System.err.println( + "Warning: atom parameters do not have symbolic " + + currentString); + continue; + } + + // --- Read value + + ++symbolicsFound; + token = st.nextToken(); + try { + Float f = new Float(token); + symbolicStrings.put(currentString, f); + } + catch (Exception ex) { + throw new Exception("Wrong value for symbolic string " + token); + } + } + } + + if (!isReadAllSymbolics(symbolicStrings) && line == null) { + throw new Exception("Found end-of-file before all symbolic's values are read in..."); + } + + if (symbolicStrings.size() > 0) { + try { + resolveSymbolicStrings(symbolicStrings, Atoms); + } + catch (Exception ex) { + throw ex; + } + } + + } + + boolean isReadAllSymbolics(Map symbolicStrings) { + + if (symbolicStrings.containsValue(null)) { + return false; + } + Set set = symbolicStrings.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String string = me.getKey().toString(); + Object value = me.getValue(); + + if (value == null) { + return false; + } + } + return true; + } + + private void resolveSymbolicStrings(Map symbolicStrings, List atoms) throws Exception { + + // --- Error check + + boolean error = false; + String Errors = ""; + Set set = symbolicStrings.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String string = me.getKey().toString(); + Object value = me.getValue(); + + if (value == null) { + error = true; + Errors += "No value for string " + string + "\n"; + } + else { + logger.info(me.getKey().toString() + "=" + + me.getValue().toString()); + } + } + + if (error) { + throw new Exception(Errors); + } + + // --- resolve strings + + int nsymbols = 0; + for (int i = 0; i < atoms.size(); i++) { + MopacAtom atom = atoms.get(i); + + String string = atom.getBondLengthPar(); + if (string != null) { + boolean negative = string.startsWith("-"); + if (negative) { + string = string.substring(1); + } + Float f = symbolicStrings.get(string); + if (negative) { + f = -f; + } + atom.setBondLength(f); + } + + string = atom.getAlphaPar(); + if (string != null) { + boolean negative = string.startsWith("-"); + if (negative) { + string = string.substring(1); + } + Float f = symbolicStrings.get(string); + if (negative) { + f = -f; + } + atom.setAlpha(f); + } + + string = atom.getBetaPar(); + if (string != null) { + boolean negative = string.startsWith("-"); + if (negative) { + string = string.substring(1); + } + Float f = symbolicStrings.get(string); + if (negative) { + f = -f; + } + atom.setBeta(f); + } + } + + } + + private class Symmetry { + int definingAtom; + int symmetryRelation; + int[] definedAtoms = null; + float multiplyingFactor = 1.0f; + } + + private class Tv { + float length; + float dir[] = new float[3]; + } +} diff --git a/src/main/java/cct/mopac/MopacAtom.java b/src/main/java/cct/mopac/MopacAtom.java new file mode 100644 index 0000000..5491558 --- /dev/null +++ b/src/main/java/cct/mopac/MopacAtom.java @@ -0,0 +1,168 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.mopac; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class MopacAtom { + + String name = ""; + String comment = ""; + int element = 0; + boolean cartesian = true; + float xyz[] = new float[3], charge; + float isotopeMass = 0; + float bondLength, alpha, beta; + String bondLengthPar = null, alphaPar = null, betaPar = null; + int opt[] = new int[3]; + int i1 = -1, i2 = -1, i3 = -1; + + public MopacAtom() { + } + + public int getAtomicNumber() { + return element; + } + + public void setName(String Name) { + name = Name; + } + + public void setXYZ(float x, float y, float z) { + this.xyz[0] = x; + this.xyz[1] = y; + this.xyz[2] = z; + } + + public float getBondLength() { + return bondLength; + } + + public void setBondLength(String bond) { + bondLengthPar = bond; + } + + public void setBondLength(float bond) { + bondLength = bond; + } + + public void setAlpha(float a) { + alpha = a; + } + + public float getAlpha() { + return alpha; + } + + public void setAlpha(String a) { + alphaPar = a; + } + + public String getAlphaPar() { + return alphaPar; + } + + public void setBeta(float b) { + beta = b; + } + + public float getBeta() { + return beta; + } + + public void setBeta(String b) { + betaPar = b; + } + + public String getBetaPar() { + return betaPar; + } + + public int get_i1() { + return i1; + } + + public int get_i2() { + return i2; + } + + public int get_i3() { + return i3; + } + + public float getX() { + return xyz[0]; + } + + public float getY() { + return xyz[1]; + } + + public float getZ() { + return xyz[2]; + } + + public void setXYZ(float[] xyz) { + this.xyz[0] = xyz[0]; + this.xyz[1] = xyz[1]; + this.xyz[2] = xyz[2]; + } + + public String getName() { + return name; + } + + public void setElement(int el) { + element = el; + } + + public String getBondLengthPar() { + return bondLengthPar; + } + +} diff --git a/src/main/java/cct/mopac/MopacOutput.java b/src/main/java/cct/mopac/MopacOutput.java new file mode 100644 index 0000000..a9f3df9 --- /dev/null +++ b/src/main/java/cct/mopac/MopacOutput.java @@ -0,0 +1,577 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.mopac; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.ChemicalElements; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class MopacOutput { + + public MopacOutput() { + } + + static final float ONE_BOHR_FLOAT = (float) 0.529177249; // In Angstrom + + Map outputResume = new LinkedHashMap (100); + Map moleculeProps = new HashMap (); + boolean normalTermination = false; + List Geometries = new ArrayList (); + int natoms = -1; + String runTitle = null; + private float[] charges = null, noOfELECS, sPop, pPop; + + public void parseMopacOutputFile(String filename) throws Exception { + outputResume.clear(); + normalTermination = false; + Geometries.clear(); + moleculeProps.clear(); + String line; + try { + BufferedReader in = new BufferedReader(new FileReader(filename)); + + while ( (line = in.readLine()) != null) { + + if (line.contains("FINAL HEAT OF FORMATION")) { + this.outputResume.put("FINAL HEAT OF FORMATION", line + "\n"); + /* + FINAL HEAT OF FORMATION = -10272.31507 KCAL = -42979.36624 KJ + NO. OF FILLED LEVELS = 4743 + */ + moleculeProps.put("HEAT OF FORMATION", + line.substring(35, 52).trim()); + int count = 0; + while ( (line = in.readLine()) != null) { + if (line.contains("MOLECULAR DIMENSIONS")) { + break; + } + else if (line.trim().length() == 0) { + continue; + } + + if (line.contains("ELECTRONIC ENERGY")) { + moleculeProps.put("ELECTRONIC ENERGY", + line.substring(35, 52).trim()); + } + else if (line.contains("CORE-CORE REPULSION")) { + moleculeProps.put("CORE-CORE REPULSION", + line.substring(35, 52).trim()); + } + else if (line.contains("NO. OF FILLED LEVELS")) { + moleculeProps.put("NO. OF FILLED LEVELS", + line.substring(35).trim()); + } + + ++count; + outputResume.put("res" + count, line); + } + } + + else if (line.contains("COMPUTATION TIME")) { + this.outputResume.put("COMPUTATION TIME", "\n" + line); + } + + else if (line.contains("WALL CLOCK TIME")) { + this.outputResume.put("WALL CLOCK TIME", line); + } + + else if (line.contains("HAMILTONIAN")) { + this.outputResume.put("HAMILTONIAN", line + "\n"); + /* + * AM1 - THE AM1 HAMILTONIAN TO BE USED + */ + moleculeProps.put("METHOD", line.substring(2, 13).trim()); + } + + else if (line.contains(" CHARGE ON SYSTEM")) { + this.outputResume.put("CHARGE ON SYSTEM", line + "\n"); + /* + * CHARGE ON SYSTEM = -9 + */ + try { + moleculeProps.put(MoleculeInterface.ChargeProperty, + line.substring(37, 42).trim()); + } + catch (Exception ex) { + System.err.println("Cannot parse system charge: " + + line); + } + } + + else if (line.contains("CARTESIAN COORDINATES")) { + List atoms = new ArrayList (100); + + // Skip three lines + for (int i = 0; i < 3; i++) { + if ( (line = in.readLine()) == null) { + throw new Exception( + "Unexpected end-of-file while reading molecular geometry"); + } + } + + // --- Start to read geometry + + while ( (line = in.readLine()) != null) { + if (line.trim().length() == 0) { + break; + } + MopacAtom atom = MopacOutput.parseCartesianCoordinates(line); + atoms.add(atom); + } + + Geometries.add(atoms); + } + + else if (line.contains( + "NET ATOMIC CHARGES AND DIPOLE CONTRIBUTIONS")) { + if (Geometries.size() == 0) { + System.err.println( + "Found NET ATOMIC CHARGES AND DIPOLE CONTRIBUTIONS string but no atoms"); + continue; + } + List atoms = Geometries.get(0); + + charges = new float[atoms.size()]; + noOfELECS = new float[atoms.size()]; + sPop = new float[atoms.size()]; + pPop = new float[atoms.size()]; + + // Skip two lines + boolean unexpectedEnd = false; + for (int i = 0; i < 2; i++) { + if ( (line = in.readLine()) == null) { + unexpectedEnd = true; + break; + //throw new Exception( + // "Unexpected end-of-file while reading molecular geometry"); + } + } + if (unexpectedEnd) { + continue; + } + + // --- Start to read charges + + for (int i = 0; i < atoms.size(); i++) { + if ( (line = in.readLine()) == null || + line.trim().length() == 0) { + break; + } + + StringTokenizer st = new StringTokenizer(line, " \t"); + + // --- Skip two tokens + + st.nextToken(); + st.nextToken(); + + try { + if (st.hasMoreTokens()) { + charges[i] = Float.parseFloat(st.nextToken()); + } + else { + continue; + } + + if (st.hasMoreTokens()) { + noOfELECS[i] = Float.parseFloat(st.nextToken()); + } + else { + continue; + } + + if (st.hasMoreTokens()) { + sPop[i] = Float.parseFloat(st.nextToken()); + } + else { + continue; + } + + if (st.hasMoreTokens()) { + pPop[i] = Float.parseFloat(st.nextToken()); + } + else { + continue; + } + } + catch (Exception ex) { + + } + } + + } + } + } + catch (IOException e) { + System.err.println("parseGamessOutputFile: error parsing " + filename + + " : " + e.getMessage()); + throw new Exception("Error parsing " + filename + " : " + e.getMessage()); + } + + } + + /** + * Parses MOPAC 2002 Log Files + * @param filename String - File name + * @throws Exception - in case of any error + */ + public void parseMopacLogFile(String filename) throws Exception { + outputResume.clear(); + moleculeProps.clear(); + normalTermination = false; + Geometries.clear(); + String line; + try { + BufferedReader in = new BufferedReader(new FileReader(filename)); + + while ( (line = in.readLine()) != null) { + + if (line.contains("HEAT OF FORMATION")) { + this.outputResume.put("Heat of form", line + "\n"); + /* + HEAT OF FORMATION = -10272.315067 KCAL = -42979.36624 KJ + */ + moleculeProps.put("HEAT OF FORMATION", + line.substring(35, 52).trim()); + int count = 0; + while ( (line = in.readLine()) != null) { + if (line.trim().length() == 0) { + break; + } + + if (line.contains("ELECTRONIC ENERGY")) { + moleculeProps.put("ELECTRONIC ENERGY", + line.substring(35, 52).trim()); + } + else if (line.contains("CORE-CORE REPULSION")) { + moleculeProps.put("CORE-CORE REPULSION", + line.substring(35, 52).trim()); + } + else if (line.contains("DIPOLE")) { + moleculeProps.put("DIPOLE", line.substring(35, 52).trim()); + } + else if (line.contains("NO. OF FILLED LEVELS")) { + moleculeProps.put("NO. OF FILLED LEVELS", + line.substring(35).trim()); + } + else if (line.contains("CHARGE ON SYSTEM")) { + try { + moleculeProps.put(MoleculeInterface.ChargeProperty, + new Integer(Integer.parseInt(line. + substring(40).trim()))); + } + catch (Exception ex) { + System.err.println("Cannot parse system charge: " + + line); + } + + } + + ++count; + outputResume.put("res" + count, line); + } + } + + else if (line.contains("EMPIRICAL FORMULA")) { + this.outputResume.put("Formula", line + "\n"); + } + + else if (line.contains("FINAL GEOMETRY OBTAINED")) { + List atoms = new ArrayList (100); + + // Options + if ( (line = in.readLine()) == null) { + throw new Exception( + "Unexpected end-of-file while reading molecular geometry"); + } + this.outputResume.put("Options", line + "\n"); + + moleculeProps.put(MoleculeInterface.MultiplicityProperty, + new Integer(1)); + if (line.contains("DOUBLET")) { + moleculeProps.put(MoleculeInterface.MultiplicityProperty, + new Integer(2)); + } + else if (line.contains("TRIPLET")) { + moleculeProps.put(MoleculeInterface.MultiplicityProperty, + new Integer(3)); + } + else if (line.contains("QUARTET")) { + moleculeProps.put(MoleculeInterface.MultiplicityProperty, + new Integer(4)); + } + else if (line.contains("QUINTET")) { + moleculeProps.put(MoleculeInterface.MultiplicityProperty, + new Integer(5)); + } + else if (line.contains("SEXTET")) { + moleculeProps.put(MoleculeInterface.MultiplicityProperty, + new Integer(6)); + } + else if (line.contains("SEPTET")) { + moleculeProps.put(MoleculeInterface.MultiplicityProperty, + new Integer(7)); + } + else if (line.contains("OCTET")) { + moleculeProps.put(MoleculeInterface.MultiplicityProperty, + new Integer(8)); + } + + StringTokenizer st = new StringTokenizer(line, " \t"); + while ( + st.hasMoreTokens()) { + String token = st.nextToken(); + if (token.contains("MNDO") || token.contains("AM1") || + token.contains("PM3") || token.contains("PM5") || + token.contains("MINDO")) { + moleculeProps.put("METHOD", token); + break; + } + + } + + // Skip 2 lines + if ( (line = in.readLine()) == null) { + throw new Exception( + "Unexpected end-of-file while reading molecular geometry"); + } + if ( (line = in.readLine()) == null) { + throw new Exception( + "Unexpected end-of-file while reading molecular geometry"); + } + + while ( (line = in.readLine()) != null) { + if (line.trim().length() == 0) { + break; + } + MopacAtom atom = parseAtomData(line); + atoms.add(atom); + } + + Geometries.add(atoms); + } + + } + } + catch (IOException e) { + System.err.println("parseGamessOutputFile: error parsing " + filename + + " : " + e.getMessage()); + throw new Exception("Error parsing " + filename + " : " + e.getMessage()); + } + + } + + public static MopacAtom parseCartesianCoordinates(String data) throws + Exception { + MopacAtom atom = new MopacAtom(); + StringTokenizer st = new StringTokenizer(data, " \t"); + + if (st.countTokens() < 5) { + throw new Exception( + "Expecting at least 5 tokens for reading cartesian coordinates, got " + + data); + } + + st.nextToken(); // Skip atom number + + atom.setName(st.nextToken()); + atom.setElement(ChemicalElements.getAtomicNumber(atom.name)); + + try { + atom.xyz[0] = Float.parseFloat(st.nextToken()); + atom.xyz[1] = Float.parseFloat(st.nextToken()); + atom.xyz[2] = Float.parseFloat(st.nextToken()); + } + catch (Exception ex) { + throw new Exception( + "Error while parsing float point atom data: " + data); + } + + return atom; + } + + public static MopacAtom parseAtomData(String data) throws Exception { + MopacAtom atom = new MopacAtom(); + StringTokenizer st = new StringTokenizer(data, " \t"); + + if (st.countTokens() < 6) { + throw new Exception( + "Expecting at least 6 tokens while reading molecular geometry, got " + + data); + } + + atom.setName(st.nextToken()); + atom.setElement(ChemicalElements.getAtomicNumber(atom.name)); + + try { + atom.xyz[0] = Float.parseFloat(st.nextToken()); + st.nextToken(); + atom.xyz[1] = Float.parseFloat(st.nextToken()); + st.nextToken(); + atom.xyz[2] = Float.parseFloat(st.nextToken()); + if (st.hasMoreTokens()) { + st.nextToken(); + } + if (st.hasMoreTokens()) { + atom.charge = Float.parseFloat(st.nextToken()); + } + + } + catch (Exception ex) { + throw new Exception( + "Error while parsing float point atom data: " + data); + } + + return atom; + } + + public void getMolecularInterface(MoleculeInterface molec) throws + Exception { + if (molec == null) { + throw new Exception(this.getClass().getCanonicalName() + + " : molec == null"); + } + if (Geometries.size() < 1) { + throw new Exception(this.getClass().getCanonicalName() + + " : didn't find atoms in file"); + } + + molec.addMonomer("MOPAC"); + + List atoms = Geometries.get(Geometries.size() - 1); + + boolean yesCharges = false; + boolean yesNoOfELECS = false; + boolean yesSPop = false; + boolean yesPPop = false; + + for (int i = 0; i < atoms.size(); i++) { + MopacAtom ga = atoms.get(i); + AtomInterface atom = molec.getNewAtomInstance(); + atom.setName(ga.name); + atom.setAtomicNumber(ga.element); + atom.setXYZ(ga.xyz[0], ga.xyz[1], ga.xyz[2]); + molec.addAtom(atom); + if (charges != null) { + if (!yesCharges) { + yesCharges = Math.abs(charges[i]) > 0.00001; + } + if (!yesNoOfELECS) { + yesNoOfELECS = Math.abs(noOfELECS[i]) > 0.00001; + } + if (!yesSPop) { + yesSPop = Math.abs(sPop[i]) > 0.00001; + } + if (!yesPPop) { + yesPPop = Math.abs(pPop[i]) > 0.00001; + } + } + } + + if (charges != null) { + for (int i = 0; i < atoms.size(); i++) { + AtomInterface atom = molec.getAtomInterface(i); + if (yesCharges) { + atom.setProperty("MOPAC Mulliken Charge", new Float(charges[i])); + } + if (yesNoOfELECS) { + atom.setProperty("MOPAC No. of ELECS.", new Float(noOfELECS[i])); + } + if (yesSPop) { + atom.setProperty("MOPAC s-Pop", new Float(sPop[i])); + } + if (yesPPop) { + atom.setProperty("MOPAC p-Pop", new Float(pPop[i])); + } + } + } + + Set set = this.moleculeProps.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String key = me.getKey().toString(); + Object obj = me.getValue(); + molec.addProperty(key, obj); + } + + } + + public String getOutputResume() { + StringWriter sWriter = new StringWriter(); + Set set = outputResume.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String line = me.getValue().toString(); + sWriter.write(line + "\n"); + } + + //if (!normalTermination) { + // sWriter.write( + // "\n***** !!!!! IT IS NOT A NORMAL TERMINATION of GAUSSIAN !!!!! *****"); + //} + return sWriter.toString(); + } + +} diff --git a/src/main/java/cct/oogl/.DS_Store b/src/main/java/cct/oogl/.DS_Store new file mode 100644 index 0000000..99d5c1d Binary files /dev/null and b/src/main/java/cct/oogl/.DS_Store differ diff --git a/src/main/java/cct/oogl/._.DS_Store b/src/main/java/cct/oogl/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/cct/oogl/._.DS_Store differ diff --git a/src/main/java/cct/oogl/Color.java b/src/main/java/cct/oogl/Color.java new file mode 100644 index 0000000..89da658 --- /dev/null +++ b/src/main/java/cct/oogl/Color.java @@ -0,0 +1,26 @@ +package cct.oogl; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Color { + public float r = .666f, g = .666f, b = .666f, a = .666f; + public Color() { + } + + public Color(float _r, float _g, float _b, float _a) { + r = _r; + g = _g; + b = _b; + a = _a; + } +} diff --git a/src/main/java/cct/oogl/Face.java b/src/main/java/cct/oogl/Face.java new file mode 100644 index 0000000..d233713 --- /dev/null +++ b/src/main/java/cct/oogl/Face.java @@ -0,0 +1,109 @@ +package cct.oogl; + +import java.util.ArrayList; +import java.util.List; + +/** + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2007

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Face { + + int Nv = 0; // # vertices on this face + public int v[] = null; // vertex indices + public int r, g, b, a = 255; //3 or 4 integers: RGB[A] values 0..255 + public float rf, gf, bf, af = 1; // # 3 or 4 floats: RGB[A] values 0..1 + public List vertices = new ArrayList(); + public boolean visible = true; + + public Face() { + } + + public Face(Face f) { + if (f.v.length > 0) { + v = new int[f.v.length]; + for (int i = 0; i < v.length; i++) { + v[i] = f.v[i]; + } + Nv = v.length; + } else { + Nv = f.vertices.size(); + } + r = f.r; + g = f.g; + b = f.b; + a = f.a; + rf = f.rf; + gf = f.gf; + bf = f.bf; + af = f.af; + + vertices.addAll(f.vertices); + } + + public void incrementIndices(int inc) { + for (int i = 0; i < v.length; i++) { + v[i] += inc; + } + } + + public Face(Vertex v1, Vertex v2, Vertex v3) { + addVertex(v1); + addVertex(v2); + addVertex(v3); + Nv = 3; + } + + public Face(int _v[]) { + v = _v; + Nv = v.length; + } + + public Face(int i, int j, int k) { + v = new int[]{i, j, k}; + Nv = v.length; + } + + public void addVertex(Vertex vertex) { + vertices.add(vertex); + } + + public int getNVertices() { + return Nv; + } + + + public void setColor(Color color) { + rf = color.r; + gf = color.g; + bf = color.b; + af = color.a; + + r = (int) (rf * 255.0f); + g = (int) (gf * 255.0f); + b = (int) (bf * 255.0f); + a = (int) (af * 255.0f); + } + + public boolean isVisible() { + boolean visible = false; + for (Vertex vertex : vertices) { + if (vertex.isVisible()) { + return true; + } + } + return visible; + } +} diff --git a/src/main/java/cct/oogl/OOGL.java b/src/main/java/cct/oogl/OOGL.java new file mode 100644 index 0000000..6ae349d --- /dev/null +++ b/src/main/java/cct/oogl/OOGL.java @@ -0,0 +1,931 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.oogl; + +import cct.vecmath.Point3d; +import java.awt.FileDialog; +import java.awt.Frame; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.StreamTokenizer; +import java.io.StringReader; +import java.util.StringTokenizer; +import cct.vecmath.Point3f; +import java.io.BufferedWriter; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.util.List; + +/** + *

+ * Title: Molecular Structure Viewer/Editor

+ * + *

+ * Description: Computational Chemistry Toolkit

+ * Syntax Common to All OOGL File Formats Most OOGL object file formats are free-format ASCII -- any amount of white + * space (blanks, tabs, newlines) may appear between tokens (numbers, key words, etc.). + * + * Line breaks are almost always insignificant, with a couple of exceptions as noted. + * + * Comments begin with # and continue to the end of the line; they're allowed anywhere a newline is. + * + * Binary formats are also defined for several objects; See section Binary format, and the individual object + * descriptions. + * + * Typical OOGL objects begin with a key word designating object type, possibly with modifiers indicating presence of + * color information etc. In some formats the key word is optional, for compatibility with file formats defined + * elsewhere. Object type is then determined by guessing from the file suffix (if any) or from the data itself. + * + * Key words are case sensitive. Some have optional prefix letters indicating presence of color or other data; in this + * case the order of prefixes is significant, e.g. CNMESH is meaningful but NCMESH is invalid. + * + *

+ * Copyright: Copyright (c) 2006

+ * + *

+ * Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +enum PARSE_STATUS { + READING_COMMENT, LOOKING_FOR_HEADER, LOOKING_FOR_SPACE_DIM, + LOOKING_FOR_NFACES, LOOKING_FOR_NVERTICES, LOOKING_FOR_NEDGES, + LOOKING_FOR_VERTICES, LOOKING_FOR_NORMALS, LOOKING_FOR_COLORS, + LOOKING_FOR_FACES, LOOKING_FOR_FACE_COLORS +} + +public class OOGL { + + int NVertices = 0, NFaces = 0, NEdges = 0; + int Ndim; + boolean yesSpaceDimension = false; + boolean yesNormals = false; + boolean yesColors = false; + boolean yesTextures = false; + Point3f Vertices[] = null; + Point3d Vertices3d[] = null; + Color colors[] = null; + Point3f normals[] = null; + Point3d normals3d[] = null; + Face faces[] = null; + + int vertexComponents = 3; + int vertexNumbers = 0; + + public OOGL() { + } + + public OOGL(Point3d Vertices3d[], Point3d normals3d[], List faces) { + this.Vertices3d = Vertices3d; + this.normals3d = normals3d; + this.faces = new Face[faces.size()]; + for (int i = 0; i < faces.size(); i++) { + this.faces[i] = faces.get(i); + } + } + + public boolean hasNormals() { + return yesNormals; + } + + public int getNFaces() { + return this.NFaces; + } + + public int getNVertices() { + return this.NVertices; + } + + public Point3f[] getVertices() { + return Vertices; + } + + public Color[] getColors() { + return colors; + } + + public Point3f[] getNormals() { + return normals; + } + + public Face[] getFaces() { + return faces; + } + + public void parseOFF(String filename, int fileType) throws Exception { + String line; + BufferedReader in = null; + + if (fileType == 0) { // Read from file + try { + in = new BufferedReader(new FileReader(filename)); + } catch (java.io.FileNotFoundException e) { + throw new Exception("Error parsing file " + filename + ": " + + e.getMessage()); + } + } else if (fileType == 1) { // Read from String + in = new BufferedReader(new StringReader(filename)); + } else { + throw new Exception("Unknown file type"); + } + + vertexComponents = 3; + vertexNumbers = 0; + + try { + //BufferedReader in = new BufferedReader(new FileReader(filename)); + + while ((line = in.readLine()) != null) { + // [ST][C][N][4][n]OFF # Header keyword + + line = line.trim(); + if (line.length() < 1) { + continue; + } + + StringTokenizer st = new StringTokenizer(line, " \t"); + String header = st.nextToken(); + + if (header.startsWith("#")) { + continue; + } + + if (!header.contains("OFF")) { + throw new Exception("Error parsing file " + filename + + ": header does not have OFF string"); + } + if (header.contains("n")) { + yesSpaceDimension = true; + } + + if (header.contains("N")) { + yesNormals = true; + vertexNumbers += 3; + } + + if (header.contains("C")) { + yesColors = true; + vertexNumbers += 4; + } + + if (header.contains("ST")) { + yesTextures = true; + vertexNumbers += 1; + } + + // --- [Ndim] # Space dimension of vertices, present only if nOFF (if any) + if (yesSpaceDimension) { + line = in.readLine(); + st = new StringTokenizer(line, " \t"); + try { + Ndim = Integer.parseInt(st.nextToken()); + } catch (Exception ex) { + throw new Exception("Error parsing file " + filename + + ": wrong number for Space dimension: " + line); + } + + if (header.contains("4OFF")) { + vertexComponents = 4; + } else if (header.contains("nOFF")) { + vertexComponents = Ndim; + } else if (header.contains("4nOFF")) { + vertexComponents = Ndim + 1; + } + vertexNumbers += vertexComponents; + } + + // --- NVertices NFaces NEdges # NEdges not used or checked + line = in.readLine(); + + st = new StringTokenizer(line, " \t"); + if (st.countTokens() < 3) { + throw new Exception("Error parsing file " + filename + + ": expecting three numbers for NVertices, NFaces, and NEdges. Got: " + + line); + } + + try { + NVertices = Integer.parseInt(st.nextToken()); + } catch (Exception ex) { + throw new Exception("Error parsing file " + filename + + ": wrong number for NVertices: " + line); + } + + try { + NFaces = Integer.parseInt(st.nextToken()); + } catch (Exception ex) { + throw new Exception("Error parsing file " + filename + + ": wrong number for NFaces: " + line); + } + + try { + NEdges = Integer.parseInt(st.nextToken()); + } catch (Exception ex) { + //throw new Exception("Error parsing file " + filename + + // ": wrong number for NFaces: " + line); + System.err.println("Error parsing file " + filename + + ": wrong number for NFaces: " + line + + " Error ignored..."); + } + + // x[0] y[0] z[0] # Vertices, possibly with normals, + // # colors, and/or texture coordinates, in that order, + // # if the prefixes N, C, ST + // # are present. + // # If 4OFF, each vertex has 4 components, + // # including a final homogeneous component. + // # If nOFF, each vertex has Ndim components. + // # If 4nOFF, each vertex has Ndim+1 components. + Vertices = new Point3f[NVertices]; + + if (yesColors) { + colors = new Color[NVertices]; + } + if (yesNormals) { + normals = new Point3f[NVertices]; + } + + for (int i = 0; i < NVertices; i++) { + line = in.readLine(); + + st = new StringTokenizer(line, " \t"); + // --- Error check here + try { + Vertices[i] = new Point3f(Float.parseFloat(st.nextToken()), + Float.parseFloat(st.nextToken()), + Float.parseFloat(st.nextToken())); + } catch (Exception ex) { + throw new Exception("Error parsing file " + filename + + ": wrong number(s) for vertex coordinate(s): " + + line); + + } + + // --- Parsing normals (if any ) + // --- Error check here + if (yesNormals) { + try { + normals[i] = new Point3f(Float.parseFloat(st.nextToken()), + Float.parseFloat(st.nextToken()), + Float.parseFloat(st.nextToken())); + } catch (Exception ex) { + throw new Exception("Error parsing file " + filename + + ": wrong number(s) for vertex coordinate(s): " + + line); + + } + + } + + // --- Parsing colors (if any ) + // --- Error check here + if (yesColors) { + try { + colors[i] = new Color(Float.parseFloat(st.nextToken()), + Float.parseFloat(st.nextToken()), + Float.parseFloat(st.nextToken()), + Float.parseFloat(st.nextToken())); + } catch (Exception ex) { + throw new Exception("Error parsing file " + filename + + ": wrong number(s) for vertex color: " + + line); + + } + } + + // --- Ignore texture for now !!! + } + + // # Faces + // # Nv = # vertices on this face + // # v[0] ... v[Nv-1]: vertex indices + // # in range 0..NVertices-1 + // Nv v[0] v[1] ... v[Nv-1] colorspec + // ... + // # colorspec continues past v[Nv-1] + // # to end-of-line; may be 0 to 4 numbers + // # nothing: default + // # integer: colormap index + // # 3 or 4 integers: RGB[A] values 0..255 + // # 3 or 4 floats: RGB[A] values 0..1 + faces = new Face[NFaces]; + + for (int i = 0; i < NFaces; i++) { + line = in.readLine(); + + st = new StringTokenizer(line, " \t"); + int nV = 0; + + try { + nV = Integer.parseInt(st.nextToken()); + } catch (Exception ex) { + throw new Exception("Error parsing file " + filename + + ": wrong number for # vertices: " + line); + } + int v[] = new int[nV]; + for (int j = 0; j < nV; j++) { + try { + v[j] = Integer.parseInt(st.nextToken()); + } catch (Exception ex) { + throw new Exception("Error parsing file " + filename + + ": wrong number for vertex indices: " + line); + } + faces[i] = new Face(v); + } + + } + + } + + if (fileType == 0) { + in.close(); + } + } catch (Exception e) { + throw new Exception("Error parsing file " + filename + + " : " + e.getMessage()); + } + + } + + public void parseOFF(String inputfile) throws Exception { + + PARSE_STATUS status = PARSE_STATUS.LOOKING_FOR_HEADER; + + try { + // Create the tokenizer to read from a file + FileReader rd = new FileReader(inputfile); + StreamTokenizer st = new StreamTokenizer(rd); + + // Prepare the tokenizer for Java-style tokenizing rules + //st.parseNumbers(); + st.wordChars('1', '9'); + st.wordChars('0', '0'); + st.wordChars('_', '_'); + st.wordChars('$', '$'); + st.wordChars('.', '.'); + + st.eolIsSignificant(true); + + // If whitespace is not to be discarded, make this call + //st.ordinaryChars(0, ' '); + st.whitespaceChars('=', '='); + //st.ordinaryChar('$'); + + // These calls caused comments to be discarded + st.slashSlashComments(false); + st.slashStarComments(false); + + boolean reading_comment = false; + boolean finished_reading_vertices = false; + boolean finished_reading_faces = false; + boolean finished_reading_file = false; + int vertex_index = 0; + int normal_index = 0; + int color_index = 0; + int vertices_count = 0; + int faces_count = -1; + int face_index = 0; + int n_faces = 0; + int v[] = null; + Color face_color = null; + + // Parse the file + int token = st.nextToken(); + while (token != StreamTokenizer.TT_EOF) { + + if (token != StreamTokenizer.TT_EOL && reading_comment) { + token = st.nextToken(); + continue; + } + + switch (token) { + + case StreamTokenizer.TT_EOL: + + // End of line character found + if (reading_comment) { + reading_comment = false; + break; + } else if (status == PARSE_STATUS.LOOKING_FOR_COLORS) { + if (color_index == 2) { + throw new Exception( + "Number of color values for vertex should be 1, 3, or 4, got " + + color_index); + } else if (color_index > 0) { + color_index = 0; // Reset + adjustColor(colors[vertices_count - 1]); + colors[vertices_count - 1].a = 1.0f; + } + + if (finished_reading_vertices) { + status = PARSE_STATUS.LOOKING_FOR_FACES; + } else { + status = PARSE_STATUS.LOOKING_FOR_VERTICES; + } + } else if (status == PARSE_STATUS.LOOKING_FOR_FACE_COLORS) { + if (color_index == 2) { + throw new Exception( + "Number of color values for the face should be 1, 3, or 4, got " + + color_index); + } else if (color_index > 0) { + color_index = 0; // Reset + adjustColor(face_color); + face_color.a = 1.0f; + faces[faces_count - 1].setColor(face_color); + } + + if (finished_reading_faces) { + finished_reading_file = true; + } else { + status = PARSE_STATUS.LOOKING_FOR_FACES; + } + } + + break; + + case StreamTokenizer.TT_NUMBER: + + // A number was found; the value is in nval + double num = st.nval; + + if (status == PARSE_STATUS.LOOKING_FOR_HEADER + || // No header... + status == PARSE_STATUS.LOOKING_FOR_NVERTICES) { + NVertices = (int) num; + if (NVertices < 3) { + throw new Exception("Number of vertices should >2, got " + + NVertices); + } + + Vertices = new Point3f[NVertices]; + + if (yesColors) { + colors = new Color[NVertices]; + } + if (yesNormals) { + normals = new Point3f[NVertices]; + } + + status = PARSE_STATUS.LOOKING_FOR_NFACES; + } else if (status == PARSE_STATUS.LOOKING_FOR_NFACES) { + NFaces = (int) num; + status = PARSE_STATUS.LOOKING_FOR_NEDGES; + } else if (status == PARSE_STATUS.LOOKING_FOR_NEDGES) { + NEdges = (int) num; + status = PARSE_STATUS.LOOKING_FOR_VERTICES; + } else if (status == PARSE_STATUS.LOOKING_FOR_SPACE_DIM) { + Ndim = (int) num; + status = PARSE_STATUS.LOOKING_FOR_NVERTICES; + } else if (status == PARSE_STATUS.LOOKING_FOR_VERTICES + && !(finished_reading_vertices)) { + // --- !!! REDo here !!!! + if (vertex_index == 0) { + Vertices[vertices_count] = new Point3f(); + Vertices[vertices_count].setX((float) num); + } else if (vertex_index == 1) { + Vertices[vertices_count].setY((float) num); + } else if (vertex_index == 2) { + Vertices[vertices_count].setZ((float) num); + } + + boolean reading_vertex = true; + ++vertex_index; + if (vertex_index == 3) { // !!!!! + reading_vertex = false; + vertex_index = 0; // Reset + ++vertices_count; + } + + if (vertices_count == NVertices) { + finished_reading_vertices = true; + } else if (reading_vertex) { + break; + } + + if (yesNormals) { + status = PARSE_STATUS.LOOKING_FOR_NORMALS; + } else if (yesColors) { + status = PARSE_STATUS.LOOKING_FOR_COLORS; + } else if (finished_reading_vertices) { + status = PARSE_STATUS.LOOKING_FOR_FACES; + } + + } else if (status == PARSE_STATUS.LOOKING_FOR_NORMALS) { + + if (normal_index == 0) { + normals[vertices_count - 1] = new Point3f(); + normals[vertices_count - 1].setX((float) num); + } else if (normal_index == 1) { + normals[vertices_count - 1].setY((float) num); + } else if (normal_index == 2) { + normals[vertices_count - 1].setZ((float) num); + } + + ++normal_index; + if (normal_index == 3) { + normal_index = 0; // Reset + } + + if (yesColors) { + status = PARSE_STATUS.LOOKING_FOR_COLORS; + } else if (finished_reading_vertices) { + status = PARSE_STATUS.LOOKING_FOR_FACES; + } else { + status = PARSE_STATUS.LOOKING_FOR_VERTICES; + } + } else if (status == PARSE_STATUS.LOOKING_FOR_COLORS) { + + if (color_index == 0) { + colors[vertices_count - 1] = new Color(); + colors[vertices_count - 1].r = (float) num; + } else if (color_index == 1) { + colors[vertices_count - 1].g = (float) num; + } else if (color_index == 2) { + colors[vertices_count - 1].b = (float) num; + } else if (color_index == 3) { + colors[vertices_count - 1].a = (float) num; + } + + ++color_index; + if (color_index == 4) { + reading_comment = true; + color_index = 0; // Reset + adjustColor(colors[vertices_count - 1]); + if (finished_reading_vertices) { + status = PARSE_STATUS.LOOKING_FOR_FACES; + } else { + status = PARSE_STATUS.LOOKING_FOR_VERTICES; + } + } + } else if ((status == PARSE_STATUS.LOOKING_FOR_VERTICES + && finished_reading_vertices) + || status == PARSE_STATUS.LOOKING_FOR_FACES) { // Start to read faces + if (faces_count == -1) { + faces_count = 0; + faces = new Face[NFaces]; + face_index = 0; + n_faces = -1; + } + + if (n_faces == -1) { + n_faces = (int) st.nval; + if (n_faces < 3) { + throw new Exception("Number of faces should be > 2, got" + + n_faces); + } + v = new int[n_faces]; + face_index = 0; + } else { + v[face_index] = (int) st.nval; + if (v[face_index] < 0 || v[face_index] >= NVertices) { + throw new Exception("Vertex number should be >= 0 and <=" + + (NVertices - 1) + " got" + v[face_index]); + } + ++face_index; + } + + if (face_index == n_faces) { + faces[faces_count] = new Face(v); + n_faces = -1; + ++faces_count; + } else { + break; + } + + if (faces_count == this.NFaces) { + finished_reading_faces = false; + } + + color_index = 0; + status = PARSE_STATUS.LOOKING_FOR_FACE_COLORS; + } else if (status == PARSE_STATUS.LOOKING_FOR_FACE_COLORS) { + if (color_index == 0) { + face_color = new Color(); + face_color.r = (float) num; + } else if (color_index == 1) { + face_color.g = (float) num; + } else if (color_index == 2) { + face_color.b = (float) num; + } else if (color_index == 3) { + face_color.a = (float) num; + } + + ++color_index; + if (color_index == 4) { + reading_comment = true; + color_index = 0; // Reset + adjustColor(face_color); + faces[faces_count - 1].setColor(face_color); + if (finished_reading_faces) { + finished_reading_file = true; + } else { + status = PARSE_STATUS.LOOKING_FOR_FACES; + } + } + + } + + break; + + case StreamTokenizer.TT_WORD: + + if (st.sval.startsWith("#")) { // Start to read a comment + if (status == PARSE_STATUS.LOOKING_FOR_COLORS) { + if (color_index == 2) { + throw new Exception( + "Number of color values for vertex should be 1, 3, or 4, got " + + color_index); + } else if (color_index > 0) { + color_index = 0; // Reset + adjustColor(colors[vertices_count - 1]); + colors[vertices_count - 1].a = 1.0f; + } + + if (finished_reading_vertices) { + status = PARSE_STATUS.LOOKING_FOR_FACES; + } else { + status = PARSE_STATUS.LOOKING_FOR_VERTICES; + } + } else if (status == PARSE_STATUS.LOOKING_FOR_FACE_COLORS) { + if (color_index == 2) { + throw new Exception( + "Number of color values for the face should be 1, 3, or 4, got " + + color_index); + } else if (color_index > 0) { + color_index = 0; // Reset + adjustColor(face_color); + face_color.a = 1.0f; + faces[faces_count - 1].setColor(face_color); + } + + if (finished_reading_faces) { + finished_reading_file = true; + } else { + status = PARSE_STATUS.LOOKING_FOR_FACES; + } + } + reading_comment = true; + break; + } else if (status == PARSE_STATUS.LOOKING_FOR_HEADER) { + parseOFFHeader(st.sval); + if (yesSpaceDimension) { + status = PARSE_STATUS.LOOKING_FOR_SPACE_DIM; + } else { + status = PARSE_STATUS.LOOKING_FOR_NVERTICES; + } + break; + } // --- Error check + else if (status == PARSE_STATUS.LOOKING_FOR_SPACE_DIM) { + throw new Exception("Expecting Space Dimension, got " + + st.sval); + } else if (status == PARSE_STATUS.LOOKING_FOR_NVERTICES) { + throw new Exception("Expecting Number of Vertices, got " + + st.sval); + } else if (status == PARSE_STATUS.LOOKING_FOR_VERTICES) { + throw new Exception("Expecting vertex coordinate, got " + + st.sval); + } else if (status == PARSE_STATUS.LOOKING_FOR_NORMALS) { + throw new Exception("Expecting normal coordinate, got " + st.sval); + } else if (status == PARSE_STATUS.LOOKING_FOR_COLORS) { + throw new Exception("Expecting color value, got " + st.sval); + } else if (status == PARSE_STATUS.LOOKING_FOR_FACES) { + throw new Exception("Expecting integer for faces, got " + st.sval); + } else if (status == PARSE_STATUS.LOOKING_FOR_FACE_COLORS) { + throw new Exception("Expecting value for face color, got " + + st.sval); + } else if (status == PARSE_STATUS.LOOKING_FOR_NEDGES) { + //throw new Exception("Expecting Number of Vertices, got " + st.sval); + System.err.println("Expecting Number of Edges, got " + st.sval + + " Ignored..."); + status = PARSE_STATUS.LOOKING_FOR_VERTICES; + } + + // A word was found; the value is in sval + String word = st.sval; + break; + case '"': + + // A double-quoted string was found; sval contains the contents + String dquoteVal = st.sval; + break; + case '\'': + + // A single-quoted string was found; sval contains the contents + String squoteVal = st.sval; + break; + + case StreamTokenizer.TT_EOF: + + // End of file has been reached + break; + default: + + // A regular character was found; the value is the token itself + char ch = (char) st.ttype; + if ("#".equals(String.valueOf(ch))) { + status = PARSE_STATUS.READING_COMMENT; + } + + break; + } + + if (finished_reading_file) { + break; + } + + token = st.nextToken(); + + } + + rd.close(); + + } catch (Exception e) { + throw new Exception("Error parsing OFF input file: " + e.getMessage()); + } + + // --- If no colors in file, we set "default" color R,G,B,A=.666. + if (!yesColors) { + colors = new Color[NVertices]; + for (int i = 0; i < NVertices; i++) { + colors[i] = new Color(0.666f, 0.666f, 0.666f, 0.666f); + } + } + + } + + void adjustColor(Color color) { + if (color.r < 0) { + color.r = 0; + } + if (color.g < 0) { + color.g = 0; + } + if (color.b < 0) { + color.b = 0; + } + if (color.a < 0) { + color.a = 0; + } + if (color.r > 1.0f || color.g > 1.0f || color.b > 1.0f || color.a > 1.0f) { + if (color.r > 255.0f) { + color.r = 255.0f; + } + if (color.g > 255.0f) { + color.g = 255.0f; + } + if (color.b > 255.0f) { + color.b = 255.0f; + } + if (color.a > 255.0f) { + color.a = 255.0f; + } + + color.r /= 255.0f; + color.g /= 255.0f; + color.b /= 255.0f; + color.a /= 255.0f; + } else { + if (color.r > 1.0f) { + color.r = 1.0f; + } + if (color.g > 1.0f) { + color.g = 1.0f; + } + if (color.b > 1.0f) { + color.b = 1.0f; + } + if (color.a > 1.0f) { + color.a = 1.0f; + } + + } + + } + + public static void saveAsOff(List vertices3d, List faces, String filename) throws Exception { + + Vertex[] v = new Vertex[vertices3d.size()]; + for (int i = 0; i < vertices3d.size(); i++) { + v[i] = vertices3d.get(i); + } + + Face[] facesArray = new Face[faces.size()]; + for (int i = 0; i < faces.size(); i++) { + facesArray[i] = faces.get(i); + } + saveAsOff(v, facesArray, filename); + } + + public static void saveAsOff(Vertex vertices3d[], Face faces[], String filename) throws Exception { + + BufferedWriter writer = null; + try { + writer = new BufferedWriter(new FileWriter(filename)); + writer.write("NOFF\n"); + writer.write(vertices3d.length + " " + faces.length + " 0\n"); + } catch (Exception ex) { + ex.printStackTrace(); + } + + for (int i = 0; i < vertices3d.length; i++) { + writer.write( + String.format("%8.4f", vertices3d[i].getX()) + " " + + String.format("%8.4f", vertices3d[i].getY()) + " " + + String.format("%8.4f", vertices3d[i].getZ()) + " " + + String.format("%8.4f", vertices3d[i].getNormals()[0]) + " " + + String.format("%8.4f", vertices3d[i].getNormals()[1]) + " " + + String.format("%8.4f", vertices3d[i].getNormals()[2]) + "\n"); + } + + for (int i = 0; i < faces.length; i++) { + writer.write(String.valueOf(faces[i].Nv)); + for (int j = 0; j < faces[i].Nv; j++) { + writer.write(" " + faces[i].v[j]); + } + writer.newLine(); + } + + writer.close(); + } + + public static void main(String[] args) { + + String fileName = "", workingDirectory = ""; + FileDialog fd = new FileDialog(new Frame(), + "Open OOGL File", + FileDialog.LOAD); + fd.setFile("*.off;*.ogl"); + fd.setVisible(true); + if (fd.getFile() != null) { + fileName = new String(fd.getFile()); + workingDirectory = new String(fd.getDirectory()); + } + + OOGL oogl = new OOGL(); + try { + oogl.parseOFF(workingDirectory + fileName); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + void parseOFFHeader(String header) throws Exception { + if (!header.contains("OFF")) { + throw new Exception("Header does not have OFF string"); + } + if (header.contains("n")) { + yesSpaceDimension = true; + } + + if (header.contains("N")) { + yesNormals = true; + vertexNumbers += 3; + } + + if (header.contains("C")) { + yesColors = true; + vertexNumbers += 4; + } + + if (header.contains("ST")) { + yesTextures = true; + vertexNumbers += 1; + } + + } +} diff --git a/src/main/java/cct/oogl/Vertex.java b/src/main/java/cct/oogl/Vertex.java new file mode 100644 index 0000000..dc1d392 --- /dev/null +++ b/src/main/java/cct/oogl/Vertex.java @@ -0,0 +1,62 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.oogl; + +/** + * + * @author vvv900 + */ +import cct.vecmath.Point3d; +import java.util.ArrayList; +import java.util.List; + +/** + * + * @author vvv900 + */ +public class Vertex extends Point3d { + + boolean visible = true; + + List faces = new ArrayList(); + double[] normals = new double[3]; + + public Vertex(double x, double y, double z) { + super(x, y, z); + double dist = Math.sqrt(x * x + y * y + z * z); + normals[0] = x / dist; + normals[1] = y / dist; + normals[2] = z / dist; + } + + public Vertex(Point3d origin, double x, double y, double z) { + super(x, y, z); + double dist = origin.distanceTo(x, y, z); + normals[0] = (x - origin.getX()) / dist; + normals[1] = (y - origin.getY()) / dist; + normals[2] = (z - origin.getZ()) / dist; + } + + public boolean isVisible() { + return visible; + } + + public void setVisible(boolean visible) { + this.visible = visible; + } + + public List getFaces() { + return faces; + } + + public double[] getNormals() { + return normals; + } + + public void setNormals(double[] normals) { + this.normals = normals; + } +} diff --git a/src/main/java/cct/oogl/java3d/OoglJava3d.java b/src/main/java/cct/oogl/java3d/OoglJava3d.java new file mode 100644 index 0000000..d6e790a --- /dev/null +++ b/src/main/java/cct/oogl/java3d/OoglJava3d.java @@ -0,0 +1,311 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.oogl.java3d; + +import java.util.logging.Logger; + +import org.scijava.java3d.Appearance; +import org.scijava.java3d.GeometryArray; +import org.scijava.java3d.Material; +import org.scijava.java3d.Node; +import org.scijava.java3d.PolygonAttributes; +import org.scijava.java3d.Shape3D; +import org.scijava.java3d.TriangleArray; +import org.scijava.vecmath.Color4f; +import org.scijava.vecmath.Point3f; +import org.scijava.vecmath.Vector3f; + +import cct.interfaces.GraphicsObjectInterface; +import cct.j3d.VerticesObject; +import cct.oogl.Color; +import cct.oogl.Face; +import cct.oogl.OOGL; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class OoglJava3d { + static final Logger logger = Logger.getLogger(OoglJava3d.class.getCanonicalName()); + + private OoglJava3d() { + } + + public static GraphicsObjectInterface getGraphicsObject(OOGL oogl_object) { + GraphicsObjectInterface graph = null; + + GraphicsObjectInterface graphics = new VerticesObject(); + graphics.setName("OOGL Object"); + + Shape3D shape3d = new Shape3D(); + shape3d.setCapability(Node.ALLOW_PARENT_READ); + shape3d.setCapability(Shape3D.ALLOW_GEOMETRY_READ); + shape3d.setCapability(Shape3D.ALLOW_GEOMETRY_WRITE); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_READ); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_READ); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); + shape3d.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_WRITE); + + TriangleArray surface = getSurface(oogl_object); + + Appearance app = new Appearance(); + + //ColoringAttributes ca = new ColoringAttributes(); + //ca.setShadeModel(ColoringAttributes.SHADE_GOURAUD); + //app.setColoringAttributes(ca); + + // --- Polygon attributes + + PolygonAttributes pa = new PolygonAttributes(); + pa.setCullFace(PolygonAttributes.CULL_NONE); + pa.setBackFaceNormalFlip(true); + + pa.setCapability(PolygonAttributes.ALLOW_MODE_READ); + pa.setCapability(PolygonAttributes.ALLOW_MODE_WRITE); + pa.setCapability(PolygonAttributes.ALLOW_CULL_FACE_READ); + pa.setCapability(PolygonAttributes.ALLOW_CULL_FACE_WRITE); + + app.setPolygonAttributes(pa); + + // --- Set up the material properties + + Material material = new Material(); + material.setLightingEnable(true); + material.setColorTarget(Material.DIFFUSE); + + // --- Set Shininess + material.setShininess(15.0f); + + // --- Diffuse Color + material.setDiffuseColor(0.666f, 0.666f, 0.666f); + + // --- Ambient Color + material.setAmbientColor(0.2f, 0.2f, 0.2f); + + // --- Emissive Color + material.setEmissiveColor(0.0f, 0.0f, 0.0f); + + // --- Specular Color + material.setSpecularColor(1.0f, 1.0f, 1.0f); + + + material.setCapability(Material.ALLOW_COMPONENT_READ); + material.setCapability(Material.ALLOW_COMPONENT_WRITE); + + app.setMaterial(material); + + shape3d.setGeometry(surface); + shape3d.setAppearance(app); + + graph = new VerticesObject(); + graph.addGraphics("OOGL Object", shape3d); + graphics.addGraphics(graph); + + return graphics; + } + + public static TriangleArray getSurface(OOGL oogl) { + int nTriangles = 0; + Face[] faces = oogl.getFaces(); + for (int i = 0; i < oogl.getNFaces(); i++) { + if (faces[i].getNVertices() == 3) { + ++nTriangles; + } + else { + nTriangles += faces[i].getNVertices() - 2; + } + } + logger.info("# Triangles: " + nTriangles); + TriangleArray geometry = new TriangleArray(nTriangles * 3, + GeometryArray.COORDINATES | + GeometryArray.COLOR_4 | GeometryArray.NORMALS); + Point3f[] coordinates = new Point3f[nTriangles * 3]; + Color4f[] Colors = new Color4f[nTriangles * 3]; + + cct.vecmath.Point3f[] vertices = oogl.getVertices(); + Color[] colors = oogl.getColors(); + cct.vecmath.Point3f oogl_normals[] = null; + if (oogl.hasNormals()) { + oogl_normals = oogl.getNormals(); + } + + Vector3f[] normals = new Vector3f[nTriangles * 3]; + + int count = 0; + for (int i = 0; i < oogl.getNFaces(); i++) { + if (faces[i].getNVertices() == 3) { + coordinates[3 * count] = new Point3f(vertices[faces[i].v[0]].getX(), + vertices[faces[i].v[0]].getY(), + vertices[faces[i].v[0]].getZ()); + Colors[3 * + count] = new Color4f(colors[faces[i].v[0]].r, + colors[faces[i].v[0]].g, + colors[faces[i].v[0]].b, + colors[faces[i].v[0]].a); + + coordinates[3 * count + + 1] = new Point3f(vertices[faces[i].v[1]].getX(), + vertices[faces[i].v[1]].getY(), + vertices[faces[i].v[1]].getZ()); + Colors[3 * count + + 1] = new Color4f(colors[faces[i].v[1]].r, colors[faces[i].v[1]].g, + colors[faces[i].v[1]].b, colors[faces[i].v[1]].a); + + coordinates[3 * count + + 2] = new Point3f(vertices[faces[i].v[2]].getX(), + vertices[faces[i].v[2]].getY(), + vertices[faces[i].v[2]].getZ()); + Colors[3 * count + + 2] = new Color4f(colors[faces[i].v[2]].r, colors[faces[i].v[2]].g, + colors[faces[i].v[2]].b, colors[faces[i].v[2]].a); + if (oogl.hasNormals()) { + normals[3 * count] = new Vector3f(oogl_normals[faces[i].v[0]].getX(), + oogl_normals[faces[i].v[0]].getY(), + oogl_normals[faces[i].v[0]].getZ()); + normals[3 * count + 1] = new Vector3f(oogl_normals[faces[i].v[1]].getX(), + oogl_normals[faces[i].v[1]].getY(), + oogl_normals[faces[i].v[1]].getZ()); + normals[3 * count + 2] = new Vector3f(oogl_normals[faces[i].v[2]].getX(), + oogl_normals[faces[i].v[2]].getY(), + oogl_normals[faces[i].v[2]].getZ()); + } + else { + normals[3 * count] = getNormal(coordinates[3 * count], + coordinates[3 * count + 1], + coordinates[3 * count + 2]); + normals[3 * count + 1] = new Vector3f(normals[3 * count]); + normals[3 * count + 2] = new Vector3f(normals[3 * count]); + } + ++count; + } + else { + for (int j = 0; j <= faces[i].getNVertices() - 3; j++, count++) { + coordinates[3 * count] = new Point3f(vertices[faces[i].v[0]].getX(), + vertices[faces[i].v[0]].getY(), + vertices[faces[i].v[0]].getZ()); + Colors[3 * + count] = new Color4f(colors[faces[i].v[0]].r, + colors[faces[i].v[0]].g, + colors[faces[i].v[0]].b, + colors[faces[i].v[0]].a); + + coordinates[3 * count + + 1] = new Point3f(vertices[faces[i].v[j + 1]].getX(), + vertices[faces[i].v[j + 1]].getY(), + vertices[faces[i].v[j + 1]].getZ()); + Colors[3 * count + + 1] = new Color4f(colors[faces[i].v[j + 1]].r, + colors[faces[i].v[j + 1]].g, + colors[faces[i].v[j + 1]].b, + colors[faces[i].v[j + 1]].a); + + coordinates[3 * count + + 2] = new Point3f(vertices[faces[i].v[j + 2]].getX(), + vertices[faces[i].v[j + 2]].getY(), + vertices[faces[i].v[j + 2]].getZ()); + Colors[3 * count + + 2] = new Color4f(colors[faces[i].v[j + 2]].r, + colors[faces[i].v[j + 2]].g, + colors[faces[i].v[j + 2]].b, + colors[faces[i].v[j + 2]].a); + + if (oogl.hasNormals()) { + normals[3 * count] = new Vector3f(oogl_normals[faces[i].v[0]].getX(), + oogl_normals[faces[i].v[0]].getY(), + oogl_normals[faces[i].v[0]].getZ()); + normals[3 * count + + 1] = new Vector3f(oogl_normals[faces[i].v[j + 1]].getX(), + oogl_normals[faces[i].v[j + 1]].getY(), + oogl_normals[faces[i].v[j + 1]].getZ()); + normals[3 * count + + 2] = new Vector3f(oogl_normals[faces[i].v[j + 2]].getX(), + oogl_normals[faces[i].v[j + 2]].getY(), + oogl_normals[faces[i].v[j + 2]].getZ()); + } + else { + normals[3 * count] = getNormal(coordinates[3 * count], + coordinates[3 * count + 1], + coordinates[3 * count + 2]); + normals[3 * count + 1] = new Vector3f(normals[3 * count]); + normals[3 * count + 2] = new Vector3f(normals[3 * count]); + } + + } + } + } + + geometry.setCoordinates(0, coordinates); + geometry.setColors(0, Colors); + geometry.setNormals(0, normals); + + return geometry; + } + + /** + * Normal points toward the side from which the vertices p1, p2, and p3 + * appear in counterclockwise order. + * @param p1 Point3f + * @param p2 Point3f + * @param p3 Point3f + * @return Point3f - normal + */ + public static Vector3f getNormal(Point3f p1, Point3f p2, Point3f p3) { + Vector3f crossVector = new Vector3f(); + Point3f v1 = new Point3f(p1.x - p2.x, p1.y - p2.y, p1.z - p2.z); + Point3f v2 = new Point3f(p3.x - p2.x, p3.y - p2.y, p3.z - p2.z); + crossVector.x = v1.y * v2.z - v1.z * v2.y; + crossVector.y = v1.z * v2.x - v1.x * v2.z; + crossVector.z = v1.x * v2.y - v1.y * v2.x; + + crossVector.normalize(); + crossVector.x = -crossVector.x; + crossVector.y = -crossVector.y; + crossVector.z = -crossVector.z; + + return crossVector; + } + +} diff --git a/src/main/java/cct/oogl/ui/OOGLViewerFrame.java b/src/main/java/cct/oogl/ui/OOGLViewerFrame.java new file mode 100644 index 0000000..0ef4beb --- /dev/null +++ b/src/main/java/cct/oogl/ui/OOGLViewerFrame.java @@ -0,0 +1,222 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.oogl.ui; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Point; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class OOGLViewerFrame + extends JFrame { + JPanel contentPane; + BorderLayout borderLayout1 = new BorderLayout(); + JMenuBar jMenuBar1 = new JMenuBar(); + JMenu jMenuFile = new JMenu(); + JMenuItem jMenuFileExit = new JMenuItem(); + JMenu jMenuHelp = new JMenu(); + JMenuItem jMenuHelpAbout = new JMenuItem(); + JToolBar jToolBar = new JToolBar(); + JButton jButton1 = new JButton(); + JButton jButton2 = new JButton(); + JButton jButton3 = new JButton(); + ImageIcon image1 = new ImageIcon(OOGLViewerFrame.class.getResource("openFile.png")); + ImageIcon image2 = new ImageIcon(OOGLViewerFrame.class.getResource("closeFile.png")); + ImageIcon image3 = new ImageIcon(OOGLViewerFrame.class.getResource("help.png")); + JLabel statusBar = new JLabel(); + + public OOGLViewerFrame() { + try { + setDefaultCloseOperation(EXIT_ON_CLOSE); + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + /** + * Component initialization. + * + * @throws Exception + */ + private void jbInit() throws Exception { + contentPane = (JPanel) getContentPane(); + contentPane.setLayout(borderLayout1); + setSize(new Dimension(400, 300)); + setTitle("Frame Title"); + statusBar.setText(" "); + jMenuFile.setText("File"); + jMenuFileExit.setText("Exit"); + jMenuFileExit.addActionListener(new OOGLViewerFrame_jMenuFileExit_ActionAdapter(this)); + jMenuHelp.setText("Help"); + jMenuHelpAbout.setText("About"); + jMenuHelpAbout.addActionListener(new OOGLViewerFrame_jMenuHelpAbout_ActionAdapter(this)); + jMenuBar1.add(jMenuFile); + jMenuFile.add(jMenuFileExit); + jMenuBar1.add(jMenuHelp); + jMenuHelp.add(jMenuHelpAbout); + setJMenuBar(jMenuBar1); + jButton1.setIcon(image1); + jButton1.setToolTipText("Open File"); + jButton2.setIcon(image2); + jButton2.setToolTipText("Close File"); + jButton3.setIcon(image3); + jButton3.setToolTipText("Help"); + jToolBar.add(jButton1); + jToolBar.add(jButton2); + jToolBar.add(jButton3); + contentPane.add(jToolBar, BorderLayout.NORTH); + contentPane.add(statusBar, BorderLayout.SOUTH); + } + + /** + * File | Exit action performed. + * + * @param actionEvent ActionEvent + */ + void jMenuFileExit_actionPerformed(ActionEvent actionEvent) { + System.exit(0); + } + + /** + * Help | About action performed. + * + * @param actionEvent ActionEvent + */ + void jMenuHelpAbout_actionPerformed(ActionEvent actionEvent) { + OOGLViewerFrame_AboutBox dlg = new OOGLViewerFrame_AboutBox(this); + Dimension dlgSize = dlg.getPreferredSize(); + Dimension frmSize = getSize(); + Point loc = getLocation(); + dlg.setLocation( (frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y); + dlg.setModal(true); + dlg.pack(); + dlg.setVisible(true); + } + + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + /* + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } + catch (Exception exception) { + exception.printStackTrace(); + } + */ + + OOGLViewerFrame frame = new OOGLViewerFrame(); + + frame.pack(); + frame.setSize(640,480); + + // Center the window + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension frameSize = frame.getSize(); + if (frameSize.height > screenSize.height) { + frameSize.height = screenSize.height; + } + if (frameSize.width > screenSize.width) { + frameSize.width = screenSize.width; + } + frame.setLocation( (screenSize.width - frameSize.width) / 2, + (screenSize.height - frameSize.height) / 2); + + frame.setVisible(true); + } + }); + } + +} + +class OOGLViewerFrame_jMenuFileExit_ActionAdapter + implements ActionListener { + OOGLViewerFrame adaptee; + + OOGLViewerFrame_jMenuFileExit_ActionAdapter(OOGLViewerFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent actionEvent) { + adaptee.jMenuFileExit_actionPerformed(actionEvent); + } +} + +class OOGLViewerFrame_jMenuHelpAbout_ActionAdapter + implements ActionListener { + OOGLViewerFrame adaptee; + + OOGLViewerFrame_jMenuHelpAbout_ActionAdapter(OOGLViewerFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent actionEvent) { + adaptee.jMenuHelpAbout_actionPerformed(actionEvent); + } + +} diff --git a/src/main/java/cct/oogl/ui/OOGLViewerFrame_AboutBox.java b/src/main/java/cct/oogl/ui/OOGLViewerFrame_AboutBox.java new file mode 100644 index 0000000..14436d2 --- /dev/null +++ b/src/main/java/cct/oogl/ui/OOGLViewerFrame_AboutBox.java @@ -0,0 +1,155 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.oogl.ui; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class OOGLViewerFrame_AboutBox + extends JDialog implements ActionListener { + JPanel panel1 = new JPanel(); + JPanel panel2 = new JPanel(); + JPanel insetsPanel1 = new JPanel(); + JPanel insetsPanel2 = new JPanel(); + JPanel insetsPanel3 = new JPanel(); + JButton button1 = new JButton(); + JLabel imageLabel = new JLabel(); + JLabel label1 = new JLabel(); + JLabel label2 = new JLabel(); + JLabel label3 = new JLabel(); + JLabel label4 = new JLabel(); + ImageIcon image1 = new ImageIcon(); + BorderLayout borderLayout1 = new BorderLayout(); + BorderLayout borderLayout2 = new BorderLayout(); + FlowLayout flowLayout1 = new FlowLayout(); + GridLayout gridLayout1 = new GridLayout(); + String product = ""; + String version = "1.0"; + String copyright = "Copyright (c) 2007"; + String comments = ""; + + public OOGLViewerFrame_AboutBox(Frame parent) { + super(parent); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public OOGLViewerFrame_AboutBox() { + this(null); + } + + /** + * Component initialization. + * + * @throws Exception + */ + private void jbInit() throws Exception { + image1 = new ImageIcon(OOGLViewerFrame.class.getResource("about.png")); + imageLabel.setIcon(image1); + setTitle("About"); + panel1.setLayout(borderLayout1); + panel2.setLayout(borderLayout2); + insetsPanel1.setLayout(flowLayout1); + insetsPanel2.setLayout(flowLayout1); + insetsPanel2.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + gridLayout1.setRows(4); + gridLayout1.setColumns(1); + label1.setText(product); + label2.setText(version); + label3.setText(copyright); + label4.setText(comments); + insetsPanel3.setLayout(gridLayout1); + insetsPanel3.setBorder(BorderFactory.createEmptyBorder(10, 60, 10, 10)); + button1.setText("OK"); + button1.addActionListener(this); + insetsPanel2.add(imageLabel, null); + panel2.add(insetsPanel2, BorderLayout.WEST); + getContentPane().add(panel1, null); + insetsPanel3.add(label1, null); + insetsPanel3.add(label2, null); + insetsPanel3.add(label3, null); + insetsPanel3.add(label4, null); + panel2.add(insetsPanel3, BorderLayout.CENTER); + insetsPanel1.add(button1, null); + panel1.add(insetsPanel1, BorderLayout.SOUTH); + panel1.add(panel2, BorderLayout.NORTH); + setResizable(true); + } + + /** + * Close the dialog on a button event. + * + * @param actionEvent ActionEvent + */ + @Override + public void actionPerformed(ActionEvent actionEvent) { + if (actionEvent.getSource() == button1) { + dispose(); + } + } + + +} diff --git a/src/main/java/cct/oogl/ui/about.png b/src/main/java/cct/oogl/ui/about.png new file mode 100644 index 0000000..754005c Binary files /dev/null and b/src/main/java/cct/oogl/ui/about.png differ diff --git a/src/main/java/cct/oogl/ui/closeFile.png b/src/main/java/cct/oogl/ui/closeFile.png new file mode 100644 index 0000000..81cc1a6 Binary files /dev/null and b/src/main/java/cct/oogl/ui/closeFile.png differ diff --git a/src/main/java/cct/oogl/ui/help.png b/src/main/java/cct/oogl/ui/help.png new file mode 100644 index 0000000..d7a33f8 Binary files /dev/null and b/src/main/java/cct/oogl/ui/help.png differ diff --git a/src/main/java/cct/oogl/ui/openFile.png b/src/main/java/cct/oogl/ui/openFile.png new file mode 100644 index 0000000..d4f742a Binary files /dev/null and b/src/main/java/cct/oogl/ui/openFile.png differ diff --git a/src/main/java/cct/pdb/.DS_Store b/src/main/java/cct/pdb/.DS_Store new file mode 100644 index 0000000..939c27d Binary files /dev/null and b/src/main/java/cct/pdb/.DS_Store differ diff --git a/src/main/java/cct/pdb/._.DS_Store b/src/main/java/cct/pdb/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/cct/pdb/._.DS_Store differ diff --git a/src/main/java/cct/pdb/MONOMER_TYPE.java b/src/main/java/cct/pdb/MONOMER_TYPE.java new file mode 100644 index 0000000..6171153 --- /dev/null +++ b/src/main/java/cct/pdb/MONOMER_TYPE.java @@ -0,0 +1,17 @@ +package cct.pdb; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public enum MONOMER_TYPE { + AMINOACID +} diff --git a/src/main/java/cct/pdb/PDB.java b/src/main/java/cct/pdb/PDB.java new file mode 100644 index 0000000..17d6d2e --- /dev/null +++ b/src/main/java/cct/pdb/PDB.java @@ -0,0 +1,728 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.pdb; + +import cct.interfaces.*; +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; +import java.util.logging.Logger; +import java.util.regex.PatternSyntaxException; +import java.util.zip.GZIPInputStream; + +import cct.modelling.ChemicalElements; +import cct.tools.UncompressInputStream; +import java.io.*; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class PDB + implements CoordinateBuilderInterface, CoordinateParserInterface { + + static boolean Debug = false; + static final Logger logger = Logger.getLogger(PDB.class.getCanonicalName()); + + public PDB() { + } + + public static MoleculeInterface parsePDBFile(URL url, MoleculeInterface mol) throws + Exception { + + boolean Zcompressed = false; + boolean gzipCompressed = false; + if (url.getFile().endsWith(".Z")) { + Zcompressed = true; + } else if (url.getFile().endsWith(".gz")) { + gzipCompressed = true; + } + + try { + if (Zcompressed) { + UncompressInputStream uis = new UncompressInputStream(url.openStream()); + BufferedReader in = new BufferedReader(new InputStreamReader(uis)); + return parsePDBFile(in, mol); + } else if (gzipCompressed) { + GZIPInputStream gzip = new GZIPInputStream(url.openStream()); + BufferedReader in = new BufferedReader(new InputStreamReader(gzip)); + return parsePDBFile(in, mol); + } else { + BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); + return parsePDBFile(in, mol); + } + } catch (Exception ex) { + throw new Exception("Error opening url " + url.toString() + " : " + + ex.getMessage()); + } + } + + public static MoleculeInterface parsePDBFile(String filename, MoleculeInterface mol) throws Exception { + boolean Zcompressed = false; + if (filename.endsWith(".Z")) { + Zcompressed = true; + } + try { + if (Zcompressed) { + UncompressInputStream uis = new UncompressInputStream(new FileInputStream(filename)); + BufferedReader in = new BufferedReader(new InputStreamReader(uis)); + MoleculeInterface m = parsePDBFile(in, mol); + try { + in.close(); + } catch (Exception ex) { + } + try { + uis.close(); + } catch (Exception ex) { + } + return m; + } else { + BufferedReader in = new BufferedReader(new FileReader(filename)); + MoleculeInterface m = parsePDBFile(in, mol); + try { + in.close(); + } catch (Exception ex) { + } + return m; + } + } catch (Exception ex) { + throw new Exception("Error opening PDB File: " + filename + " : " + ex.getMessage()); + } + } + + public static MoleculeInterface parsePDBFile(BufferedReader in, MoleculeInterface mol) throws Exception { + //Molecule mol = null; + //mol = null; + AtomInterface atom; + BondInterface bond; + String line, bufer; + StringTokenizer st; + List serialNumbers = new ArrayList(); // Temporary array + Integer serialN; + Float cartes = new Float(0.0f); + int current_residue = 0; + + try { + //BufferedReader in = new BufferedReader(new FileReader(filename)); + //mol = new Molecule(); + //mol = mol.getInstance(); + while ((line = in.readLine()) != null) { + line = line.trim(); + /* + * COLUMNS DATA TYPE FIELD DEFINITION --------------------------------------------------------------------------------- 1 - + * 6 Record name "ATOM " 7 - 11 Integer serial Atom serial number. 13 - 16 Atom name Atom name. 17 Character altLoc + * Alternate location indicator. 18 - 20 Residue name resName Residue name. 22 Character chainID Chain identifier. 23 - 26 + * Integer resSeq Residue sequence number. 27 AChar iCode Code for insertion of residues. 31 - 38 Real(8.3) x Orthogonal + * coordinates for X in Angstroms. 39 - 46 Real(8.3) y Orthogonal coordinates for Y in Angstroms. 47 - 54 Real(8.3) z + * Orthogonal coordinates for Z in Angstroms. 55 - 60 Real(6.2) occupancy Occupancy. 61 - 66 Real(6.2) tempFactor + * Temperature factor. 73 - 76 LString(4) segID Segment identifier, left-justified. 77 - 78 LString(2) element Element + * symbol, right-justified. 79 - 80 LString(2) charge Charge on the atom. + * + * + * COLUMNS DATA TYPE FIELD DEFINITION -------------------------------------------------------------------------------- 1 - 6 + * Record name "HETATM" 7 - 11 Integer serial Atom serial number. 13 - 16 Atom name Atom name. 17 Character altLoc Alternate + * location indicator. 18 - 20 Residue name resName Residue name. 22 Character chainID Chain identifier. 23 - 26 Integer + * resSeq Residue sequence number. 27 AChar iCode Code for insertion of residues. 31 - 38 Real(8.3) x Orthogonal coordinates + * for X. 39 - 46 Real(8.3) y Orthogonal coordinates for Y. 47 - 54 Real(8.3) z Orthogonal coordinates for Z. 55 - 60 + * Real(6.2) occupancy Occupancy. 61 - 66 Real(6.2) tempFactor Temperature factor. 73 - 76 LString(4) segID Segment + * identifier; left-justified. 77 - 78 LString(2) element Element symbol; right-justified. 79 - 80 LString(2) charge Charge + * on the atom. + */ + + /* + * Example: 1 2 3 4 5 6 7 8 12345678901234567890123456789012345678901234567890123456789012345678901234567890 ATOM 145 N VAL + * A 25 32.433 16.336 57.540 1.00 11.92 N ATOM 146 CA VAL A 25 31.132 16.439 58.160 1.00 11.85 C ATOM 147 C VAL A 25 30.447 + * 15.105 58.363 1.00 12.34 C ATOM 148 O VAL A 25 29.520 15.059 59.174 1.00 15.65 O ATOM 149 CB AVAL A 25 30.385 17.437 + * 57.230 0.28 13.88 C ATOM 150 CB BVAL A 25 30.166 17.399 57.373 0.72 15.41 C ATOM 151 CG1AVAL A 25 28.870 17.401 57.336 + * 0.28 12.64 C ATOM 152 CG1BVAL A 25 30.805 18.788 57.449 0.72 15.11 C ATOM 153 CG2AVAL A 25 30.835 18.826 57.661 0.28 + * 13.58 C ATOM 154 CG2BVAL A 25 29.909 16.996 55.922 0.72 13.25 C + */ + + if (line.startsWith("ATOM ") || line.startsWith("HETATM")) { + + //a = new gAtom(); + atom = mol.getNewAtomInstance(); + if (Debug) { + System.out.print("Atom: " + (mol.getNumberOfAtoms() + 1)); + } + + // --- Parsing atom serial number + + bufer = line.substring(6, 11); + try { + serialN = new Integer(bufer); + serialNumbers.add(serialN); + } catch (NumberFormatException e) { + serialNumbers.add(new Integer(0)); + // Just skip it + } + + // --- Parse Atom name + boolean first_blank = false; + String atom_name = line.substring(12, 16); + if (atom_name.startsWith(" ")) { + first_blank = true; + } + String element = line.substring(12, 13).trim(); + atom_name = atom_name.trim(); + if (!first_blank && atom_name.matches("[0-9].*")) { + atom_name = atom_name.substring(1) + atom_name.substring(0, 1); + first_blank = true; + } + atom.setName(atom_name); + atom.setProperty(AtomInterface.NAME, atom_name); + if (Debug) { + System.out.print(" Name: " + atom_name); + } + + // Parse Alternate location indicator. (to be done) + + // Parse Residue name + + String res_name = line.substring(17, 20); + res_name = res_name.trim(); + if (Debug) { + System.out.print(" Res: " + res_name); + } + + if (line.length() < 78) { // We need to deduct element from atom name or using dictionary + int elem = guessElement(atom_name, first_blank); + atom.setAtomicNumber(elem); + } + + // Parse Chain identifier. + + String chainID = line.substring(21, 22); + + // Parse Residue sequence number + // 23 - 26 Integer resSeq Residue sequence number. + + bufer = line.substring(22, 26); + bufer = bufer.trim(); + + int resSeq; + try { + resSeq = Integer.parseInt(bufer); // Base of 1 + --resSeq; // Switch to base of 0 + } catch (NumberFormatException e) { + System.err.println( + "Error converting parsing Residue sequence number"); + break; + } + if (Debug) { + System.out.print(" resSeq: " + resSeq); + } + + if (mol.getNumberOfAtoms() == 0) { + current_residue = resSeq; + } + + // Parse Code for insertion of residues (to be done) + // 27 AChar iCode Code for insertion of residues. + + // Parse rthogonal coordinates for X + // 31 - 38 Real(8.3) x Orthogonal coordinates for X + + bufer = line.substring(30, 38); + try { + atom.setX(Float.parseFloat(bufer)); + } catch (NumberFormatException e) { + throw new Exception("Error converting X-coordinate : " + bufer); + //System.err.println("Error converting X-coordinate"); + //break; + } + + // Parse Orthogonal coordinates for Y + // 39 - 46 Real(8.3) y Orthogonal coordinates for Y + + bufer = line.substring(38, 46); + try { + atom.setY(Float.parseFloat(bufer)); + } catch (NumberFormatException e) { + throw new Exception("Error converting Y-coordinate : " + bufer); + //System.err.println("Error converting Y-coordinate"); + //break; + } + + // Parse Orthogonal coordinates for Z + // 47 - 54 Real(8.3) z Orthogonal coordinates for Z + + bufer = line.substring(46, 54); + try { + atom.setZ(Float.parseFloat(bufer)); + } catch (NumberFormatException e) { + throw new Exception("Error converting Z-coordinate : " + bufer); + //System.err.println("Error converting Z-coordinate"); + //break; + } + + // Parse Occupancy (to be done) + // 55 - 60 Real(6.2) occupancy Occupancy. + + // Parse Temperature factor (to be done) + // 61 - 66 Real(6.2) tempFactor Temperature factor. + + // Parse Segment identifier (to be done) + // 73 - 76 LString(4) segID Segment identifier; + + // Parse Element symbol + // 77 - 78 LString(2) element Element symbol; right-justified + + try { + bufer = line.substring(76, 78); + bufer = bufer.trim(); + int elem = ChemicalElements.getAtomicNumber(bufer); + if (elem == 0) { + elem = guessElement(atom_name, first_blank); + } + atom.setAtomicNumber(elem); + if (Debug) { + System.out.print(" elem: " + bufer + " " + element); + } + } catch (IndexOutOfBoundsException e) { + // try to guess from the atom name + try { + if (element.matches("\\d.")) { + atom_name = atom_name.substring(1) + + atom_name.substring(0, 1); + atom.setName(atom_name); + } + + } catch (PatternSyntaxException ex) { + System.err.println(ex.getMessage()); + atom.setAtomicNumber(guessElement(atom_name, first_blank)); + } + + // --- just do nothing + } + + // Parse Charge on the atom + // 79 - 80 LString(2) charge Charge on the atom. + + try { + bufer = line.substring(78, 80); + try { + float charge = Float.parseFloat(bufer); + atom.setProperty(AtomInterface.ATOMIC_CHARGE, + new Float(charge)); + } catch (NumberFormatException e) { + // Do nothing + } + + } catch (IndexOutOfBoundsException e) { + // --- just do nothing + } + + if (Debug) { + logger.info(" "); + } + + // Resolving residue information + + if (mol.getNumberOfMonomers() == 0) { + //mol.addAtom(a, res_name); + mol.addMonomer(res_name); + mol.addAtom(atom); + } else if (current_residue != resSeq) { // New residue + int n = mol.getNumberOfMonomers() - 1; + mol.guessCovalentBondsInMonomer(n); + if (n > 0) { + mol.guessCovalentBondsBetweenMonomers(n - 1, n); + } + //mol.addAtom(a, res_name); + mol.addMonomer(res_name); + mol.addAtom(atom); + current_residue = resSeq; + } else { + mol.addAtom(atom); + } + + } /* + * COLUMNS DATA TYPE FIELD DEFINITION --------------------------------------------------------------------------------- 1 - + * 6 Record name "CONECT" 7 - 11 Integer serial Atom serial number 12 - 16 Integer serial Serial number of bonded atom 17 - + * 21 Integer serial Serial number of bonded atom 22 - 26 Integer serial Serial number of bonded atom 27 - 31 Integer serial + * Serial number of bonded atom 32 - 36 Integer serial Serial number of hydrogen bonded atom 37 - 41 Integer serial Serial + * number of hydrogen bonded atom 42 - 46 Integer serial Serial number of salt bridged atom 47 - 51 Integer serial Serial + * number of hydrogen bonded atom 52 - 56 Integer serial Serial number of hydrogen bonded atom 57 - 61 Integer serial Serial + * number of salt bridged atom + */ else if (line.startsWith("CONECT")) { + } + + } // --- End of while + + mol.guessCovalentBondsInMonomer(mol.getNumberOfMonomers() - 1); + + if (Debug) { + logger.info("Number of atoms : " + + mol.getNumberOfAtoms()); + for (int i = 0; i < mol.getNumberOfAtoms(); i++) { + atom = mol.getAtomInterface(i); + logger.info(i + " " + atom.getName() + " " + + atom.getSubstructureNumber()); + } + for (int i = 0; i < mol.getNumberOfMonomers(); i++) { + MonomerInterface m = mol.getMonomerInterface(i); + logger.info("Res: " + i + " " + m.getName() + + " atoms:" + m.getNumberOfAtoms()); + } + } + } catch (IOException e) { + throw new Exception("I/O Error : " + e.getMessage()); + //System.err.println("parsePDBFile: " + e.getMessage() + "\n"); + //return mol; + } + + return mol; + } + + /** + * @param mol + * @param filename + * + */ + @Deprecated + public static void saveAsPDBFile(MoleculeInterface mol, String filename) { + + FileWriter out = null; + try { + out = new FileWriter(filename); + } catch (FileNotFoundException e) { + System.err.println(filename + " not found\n"); + return; + } catch (SecurityException e) { + System.err.println(filename + ": Security Eception\n"); + return; + } catch (IOException e) { + System.err.println(filename + ": Read-only file\n"); + return; + } + + try { + savePDB(mol, out); + } catch (Exception ex) { + System.err.println("Error saving PDB file " + filename + " : " + ex.getMessage() + "\n"); + return; + } + } + + static int guessElement(String name, boolean first_blank) { + if (first_blank || name.length() == 1) { + return ChemicalElements.getAtomicNumber(name.substring(0, 1)); + } else { + if (name.matches(".{1}[0-9]{1}.*")) { + return ChemicalElements.getAtomicNumber(name.substring(0, 1)); + } else { + return ChemicalElements.getAtomicNumber(name.substring(0, 2)); + } + } + } + + /** + * Update coordinates of atom from PDB file + * + * @param molecule MoleculeInterface + * @param file_name String + * @throws Exception + */ + public static void updateCoordFromPDB(MoleculeInterface molecule, + String file_name) throws Exception { + if (molecule == null || molecule.getNumberOfAtoms() < 1) { + throw new Exception( + "Error updating coordinates: Reference molecule has no atoms"); + } + + String line; + int natoms = 0; + BufferedReader in; + float xyz[][] = new float[molecule.getNumberOfAtoms()][3]; + + try { + in = new BufferedReader(new FileReader(file_name)); + + while ((line = in.readLine()) != null) { + line = line.toUpperCase(); + if (line.startsWith("ATOM ") || line.startsWith("HETATM")) { + + if (natoms >= molecule.getNumberOfAtoms()) { + xyz = null; + in.close(); + throw new Exception( + "Error: PDB file contains more atoms than a molecule"); + } + + if (line.length() < 54) { + throw new Exception( + "Error: uncomplete line in PDB file: " + line); + } + + // Parse rthogonal coordinates for X, Y, Z + // 31 - 38 Real(8.3) x Orthogonal coordinates for X + + try { + xyz[natoms][0] = Float.parseFloat(line.substring(30, 38).trim()); + } catch (NumberFormatException e) { + throw new Exception("Error converting X-coordinate: " + + e.getMessage()); + } + + // Parse Orthogonal coordinates for Y + // 39 - 46 Real(8.3) y Orthogonal coordinates for Y + + try { + xyz[natoms][1] = Float.parseFloat(line.substring(38, 46).trim()); + } catch (NumberFormatException e) { + throw new Exception("Error converting Y-coordinate: " + + e.getMessage()); + } + + // Parse Orthogonal coordinates for Z + // 47 - 54 Real(8.3) z Orthogonal coordinates for Z + + try { + xyz[natoms][2] = Float.parseFloat(line.substring(46, 54).trim()); + } catch (NumberFormatException e) { + throw new Exception("Error converting Z-coordinate: " + + e.getMessage()); + } + + ++natoms; + } + } + + if (natoms != molecule.getNumberOfAtoms()) { + xyz = null; + in.close(); + throw new Exception( + "Error: PDB file does not contain the same number of atoms (" + + natoms + ") as a molecule: " + molecule.getNumberOfAtoms()); + } + + for (int i = 0; i < natoms; i++) { + AtomInterface atom = molecule.getAtomInterface(i); + atom.setXYZ(xyz[i][0], xyz[i][1], xyz[i][2]); + } + + xyz = null; + in.close(); + } catch (Exception ex) { + xyz = null; + throw new Exception("Error updating coordinates from PDB file: " + + ex.getMessage()); + } + + } + + @Override + public void parseCoordinates(BufferedReader in, MoleculeInterface molecule) throws Exception { + + try { + parsePDBFile(in, molecule); + } catch (Exception ex) { + throw ex; + } + + } + + @Override + public double evaluateCompliance(BufferedReader in) throws Exception { + double score = 0; + try { + String line; + while ((line = in.readLine()) != null) { + + if (!line.startsWith("ATOM ") && !line.startsWith("HETATM")) { + continue; + } + + score = 1; + + if (line.length() < 54) { // Minimum line length + return 0; + } + + // --- Getting x,y,z + + try { + Float.parseFloat(line.substring(30, 38)); + Float.parseFloat(line.substring(38, 46)); + Float.parseFloat(line.substring(46, 54)); + } catch (Exception ex) { + return 0; + } + return score; + } + + } catch (Exception ex) { + throw ex; + } + return score; + } + + public void getCoordinates(MoleculeInterface mol, boolean inAngstroms, Writer writer) throws Exception { + savePDB(mol, writer); + } + + public String getCoordinatesAsString(MoleculeInterface molec, boolean inAngstroms) throws Exception { + StringWriter sw = new StringWriter(); + savePDB(molec, sw); + return sw.toString(); + } + + public static void savePDB(String filename, MoleculeInterface mol) throws Exception { + try { + savePDB(mol, new FileWriter(filename)); + } catch (Exception ex) { + throw new Exception("Error saving into file " + filename + " : " + ex.getMessage()); + } + } + + public static void savePDB(MoleculeInterface mol, Writer writer) throws Exception { + AtomInterface atom; + BondInterface bond; + String line, bufer; + StringTokenizer st; + List serialNumbers = new ArrayList(); // Temporary array + Integer serialN; + Float cartes = new Float(0.0f); + int current_residue = 0; + + BufferedWriter out; + try { + out = new BufferedWriter(writer); + } catch (Exception ex) { + throw new Exception("Cannot write :" + ex.getMessage()); + } + + + try { + //out.write((mol.getName() + "\n").getBytes()); + for (int i = 0; i < mol.getNumberOfAtoms(); i++) { + atom = mol.getAtomInterface(i); + int res = atom.getSubstructureNumber(); + MonomerInterface m = mol.getMonomerInterface(res); + int element = atom.getAtomicNumber(); + String symbol = ChemicalElements.getElementSymbol(element); + if (symbol == null) { + symbol = "DU"; + } + symbol = symbol.toUpperCase(); + + String atom_name = atom.getName(); + if (atom_name == null) { + atom_name = "XX"; + } + atom_name = atom_name.toUpperCase(); + + if (atom_name.startsWith(symbol)) { + if (symbol.length() == 1) { + atom_name = " " + atom_name; + } + if (atom_name.length() > 4) { + atom_name = atom_name.substring(0, 4); + } + } else { + if (symbol.length() == 1) { + symbol = " " + symbol; + } + if (atom_name.length() > 2) { + atom_name = atom_name.substring(0, 2); + } + atom_name = symbol.concat(atom_name); + } + + String resName = m.getName(); + if (resName == null) { + resName = "UNK"; + } + if (resName.length() > 3) { + resName = resName.substring(0, 3); + } + + // COLUMNS DATA TYPE FIELD DEFINITION + // --------------------------------------------------------------------------------- + // 1 - 6 Record name "ATOM " + // 7 - 11 Integer serial Atom serial number. + // 13 - 16 Atom name Atom name. + // 17 Character altLoc Alternate location indicator. + // 18 - 20 Residue name resName Residue name. + // 22 Character chainID Chain identifier. + // 23 - 26 Integer resSeq Residue sequence number. + // 27 AChar iCode Code for insertion of residues. + // 31 - 38 Real(8.3) x Orthogonal coordinates for X in Angstroms. + // 39 - 46 Real(8.3) y Orthogonal coordinates for Y in Angstroms. + // 47 - 54 Real(8.3) z Orthogonal coordinates for Z in Angstroms. + // 55 - 60 Real(6.2) occupancy Occupancy. + // 61 - 66 Real(6.2) tempFactor Temperature factor. + // 73 - 76 LString(4) segID Segment identifier, left-justified. + // 77 - 78 LString(2) element Element symbol, right-justified. + // 79 - 80 LString(2) charge Charge on the atom. + + line = String.format("ATOM %5d %-4s %3s %4d %8.3f%8.3f%8.3f\n", + (i + 1), atom_name, resName, (res + 1), + atom.getX(), + atom.getY(), atom.getZ()); + + out.write(line); + + } + } catch (IOException e) { + throw e; + } + + // --- Finally, close a stream + try { + out.close(); + } catch (Exception e) { + throw e; + } + } +} diff --git a/src/main/java/cct/pdb/PDBAtom.java b/src/main/java/cct/pdb/PDBAtom.java new file mode 100644 index 0000000..bafbf52 --- /dev/null +++ b/src/main/java/cct/pdb/PDBAtom.java @@ -0,0 +1,25 @@ +package cct.pdb; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class PDBAtom { + String name; + String cctAtomType; + int element; + + public PDBAtom(String name, int element, String cct_atom_type) { + this.name = name.toUpperCase(); + this.element = element; + cctAtomType = cct_atom_type; + } + } diff --git a/src/main/java/cct/pdb/PDBBankFetcherInterface.java b/src/main/java/cct/pdb/PDBBankFetcherInterface.java new file mode 100644 index 0000000..20665cf --- /dev/null +++ b/src/main/java/cct/pdb/PDBBankFetcherInterface.java @@ -0,0 +1,17 @@ +package cct.pdb; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface PDBBankFetcherInterface { + void fetchStructure(String host, String entry_directory, String code); +} diff --git a/src/main/java/cct/pdb/PDBBond.java b/src/main/java/cct/pdb/PDBBond.java new file mode 100644 index 0000000..66c25ca --- /dev/null +++ b/src/main/java/cct/pdb/PDBBond.java @@ -0,0 +1,22 @@ +package cct.pdb; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class PDBBond { + int i, l; + String i_name, j_name; + public PDBBond(String i, String j) { + i_name = i; + j_name = j; + } +} diff --git a/src/main/java/cct/pdb/PDBDictionary.java b/src/main/java/cct/pdb/PDBDictionary.java new file mode 100644 index 0000000..26c0fd0 --- /dev/null +++ b/src/main/java/cct/pdb/PDBDictionary.java @@ -0,0 +1,262 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.pdb; + +import java.io.File; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.Comment; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class PDBDictionary { + + static final String ROOT = "PDBDictionary"; + static final String RESIDUE_ELEMENT = "Residue"; + static final String ATOM_ELEMENT = "Atom"; + static final String BOND_ELEMENT = "Bond"; + + static final String DICTIONARY_NAME_ATTRIBUTE = "name"; + + static final String RESIDUE_NAME_ATTRIBUTE = "name"; + + static final String ATOM_NAME_ATTRIBUTE = "name"; + static final String ATOM_ELEMENT_ATTRIBUTE = "element"; + static final String ATOM_CCTTYPE_ATTRIBUTE = "cct-type"; + + static final String BOND_A1_ATTRIBUTE = "a1"; + static final String BOND_A2_ATTRIBUTE = "a2"; + + static PDBDictionary defaultDictionary = null; + + String dicName; + private Map Residues = new LinkedHashMap (); + + public PDBDictionary(String name) { + dicName = name; + if (defaultDictionary == null) { + + } + } + + public void addResidue(PDBResidue res) throws Exception { + if (Residues.containsKey(res.residueName)) { + throw new Exception("Dcitionary " + dicName + " already has residue named " + res.residueName); + } + Residues.put(res.residueName, res); + } + + private PDBDictionary() throws Exception { + dicName = "default"; + PDBResidue res; + PDBAtom atom; + // --- Setup Glycine + /* + ATOM 154 N GLY A 702 10.474 9.811 66.187 1.00 29.99 N + ATOM 155 CA GLY A 702 9.179 10.419 65.925 1.00 32.21 C + ATOM 156 C GLY A 702 8.818 10.120 64.473 1.00 39.13 C + ATOM 157 O GLY A 702 8.145 10.902 63.803 1.00 40.76 O + + */ + + res = new PDBResidue("GLY", MONOMER_TYPE.AMINOACID); + atom = new PDBAtom("N", 7, "N.3"); + res.addAtom(atom); + atom = new PDBAtom("CA", 6, "C.4"); + res.addAtom(atom); + atom = new PDBAtom("C", 6, "C.3"); + res.addAtom(atom); + atom = new PDBAtom("O", 8, "O.2"); + res.addAtom(atom); + + atom = new PDBAtom("H", 1, "H"); + res.addAtom(atom); + atom = new PDBAtom("HA1", 1, "H"); + res.addAtom(atom); + atom = new PDBAtom("HA2", 1, "H"); + res.addAtom(atom); + + res.addBond("N", "CA"); + res.addBond("CA", "C"); + res.addBond("C", "O"); + + res.addBond("N", "H"); + res.addBond("CA", "HA1"); + res.addBond("CA", "HA2"); + + this.addResidue(res); + + // --- Setup ALA + /* + ATOM 149 N ALA A 701 12.755 8.724 67.096 1.00 23.60 N + ATOM 150 CA ALA A 701 12.882 9.578 65.929 1.00 26.37 C + ATOM 151 C ALA A 701 11.576 10.323 65.649 1.00 29.47 C + ATOM 152 O ALA A 701 11.579 11.354 64.970 1.00 28.14 O + ATOM 153 CB ALA A 701 13.272 8.762 64.709 1.00 27.79 C + + */ + + } + + public static PDBDictionary setupDefaultDictionary(PDBDictionary dic) { + try { + dic = new PDBDictionary(); + } + catch (Exception ex) { + System.err.println("INTERNAL ERROR: Cannot setup default PDB dictionary"); + } + return dic; + } + + public void saveDictionary(String file_name) throws Exception { + + File file = new File(file_name); + + //Create instance of DocumentBuilderFactory + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + //Get the DocumentBuilder + DocumentBuilder parser = factory.newDocumentBuilder(); + //Create blank DOM Document + Document doc = parser.newDocument(); + + //create the root element + Element root = doc.createElement(ROOT); + //all it to the xml tree + doc.appendChild(root); + + root.setAttribute(DICTIONARY_NAME_ATTRIBUTE, dicName); + + // create a comment + Comment comment = doc.createComment("Dictionary of PDB residues"); + //add in the root element + root.appendChild(comment); + + // --- Start to add residues + + Set set = Residues.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String resName = me.getKey().toString(); + PDBResidue res = (PDBResidue) me.getValue(); + + // create residue element + Element residueElement = doc.createElement(RESIDUE_ELEMENT); + //Add the atribute to the child + residueElement.setAttribute(RESIDUE_NAME_ATTRIBUTE, resName); + + // --- create atom elements + + for (int i = 0; i < res.countAtoms(); i++) { + PDBAtom atom = res.getAtom(i); + + // create atom element + Element atomElement = doc.createElement(ATOM_ELEMENT); + //Add the atribute to the child + atomElement.setAttribute(ATOM_NAME_ATTRIBUTE, atom.name); + atomElement.setAttribute(ATOM_ELEMENT_ATTRIBUTE, String.valueOf(atom.element)); + atomElement.setAttribute(ATOM_CCTTYPE_ATTRIBUTE, atom.cctAtomType); + + residueElement.appendChild(atomElement); + } + + // --- create bond elements + + for (int i = 0; i < res.countBonds(); i++) { + PDBBond bond = res.getBond(i); + + // create bond element + Element bondElement = doc.createElement(ATOM_ELEMENT); + //Add the atribute to the child + bondElement.setAttribute(BOND_A1_ATTRIBUTE, bond.i_name); + bondElement.setAttribute(BOND_A2_ATTRIBUTE, bond.j_name); + + residueElement.appendChild(bondElement); + } + + root.appendChild(residueElement); + } + + // An finally we will print the DOM tree + + TransformerFactory tranFactory = TransformerFactory.newInstance(); + Transformer aTransformer = tranFactory.newTransformer(); + + Source src = new DOMSource(doc); + //Result dest = new StreamResult(System.out); + Result dest = new StreamResult(file); + aTransformer.transform(src, dest); + + } + + public static void main(String[] args) { + PDBDictionary dic = new PDBDictionary("Test"); + dic = PDBDictionary.setupDefaultDictionary(dic); + try { + dic.saveDictionary("dic-test.xml"); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + +} diff --git a/src/main/java/cct/pdb/PDBResidue.java b/src/main/java/cct/pdb/PDBResidue.java new file mode 100644 index 0000000..b9b00cf --- /dev/null +++ b/src/main/java/cct/pdb/PDBResidue.java @@ -0,0 +1,165 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.pdb; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class PDBResidue { + + MONOMER_TYPE Type; + String residueName; + private Map Atoms = new LinkedHashMap (); + private Map bondedTo = new LinkedHashMap (); + private List atomArray = new ArrayList (); + private List Bonds = new ArrayList (); + + public PDBResidue(String name, MONOMER_TYPE type) { + residueName = name.toUpperCase(); + Type = type; + } + + public boolean hasAtom(String atom_name) { + String name = atom_name.toUpperCase(); + return Atoms.containsKey(name); + } + + public int countAtoms() { + return Atoms.size(); + } + + public PDBAtom getAtom(int n) { + return atomArray.get(n); + } + + public PDBAtom getAtom(String atom_name) { + atom_name = atom_name.toUpperCase().trim(); + return Atoms.get(atom_name); + } + + public void addAtom(PDBAtom atom) throws Exception { + if (Atoms.containsKey(atom.name)) { + throw new Exception("Residue " + residueName + " already contains atom " + atom.name); + } + Atoms.put(atom.name, atom); + bondedTo.put(atom.name, new HashSet()); + atomArray.add(atom); + } + + public void addBond(int i, int j) throws Exception { + if (i < 0 || i >= Atoms.size()) { + throw new Exception("i < 0 || i >= Atoms.size()"); + } + if (j < 0 || j >= Atoms.size()) { + throw new Exception("j < 0 || j >= Atoms.size()"); + } + if (j == i) { + throw new Exception("j == i"); + } + + Set i_bonds = bondedTo.get(i); + Set j_bonds = bondedTo.get(j); + + PDBAtom atom_i = Atoms.get(i); + PDBAtom atom_j = Atoms.get(j); + + if (i_bonds.contains(atom_j.name)) { + throw new Exception("Atom " + i + " " + atom_i.name + " is already bonded to atom " + j + " " + atom_j.name); + } + + if (j_bonds.contains(atom_i.name)) { + throw new Exception("Atom " + j + " " + atom_j.name + " is already bonded to atom " + i + " " + atom_i.name); + } + + i_bonds.add(atom_j.name); + j_bonds.add(atom_i.name); + + PDBBond bond = new PDBBond(atom_i.name, atom_j.name); + Bonds.add(bond); + } + + public int countBonds() { + return Bonds.size(); + } + + public PDBBond getBond(int n) { + return Bonds.get(n); + } + + public void addBond(String i_name, String j_name) throws Exception { + i_name = i_name.toUpperCase().trim(); + j_name = j_name.toUpperCase().trim(); + + if (i_name.equals(j_name)) { + throw new Exception("i_name.equals(j_name)"); + } + + if (!this.hasAtom(i_name)) { + throw new Exception("Residue " + residueName + " does not have atom named " + i_name); + } + + if (!this.hasAtom(j_name)) { + throw new Exception("Residue " + residueName + " does not have atom named " + j_name); + } + + Set i_bonds = bondedTo.get(i_name); + Set j_bonds = bondedTo.get(j_name); + + i_bonds.add(j_name); + j_bonds.add(i_name); + + PDBBond bond = new PDBBond(i_name, j_name); + Bonds.add(bond); + } +} diff --git a/src/main/java/cct/pdb/ui/PDBBankFormPanel.java b/src/main/java/cct/pdb/ui/PDBBankFormPanel.java new file mode 100644 index 0000000..3ff6ab2 --- /dev/null +++ b/src/main/java/cct/pdb/ui/PDBBankFormPanel.java @@ -0,0 +1,145 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.pdb.ui; + +import java.awt.BorderLayout; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class PDBBankFormPanel + extends JPanel { + + static String defaultPDB_Host = "ftp.wwpdb.org"; + static String defaultPDB_EntryDir = "/pub/pdb/data/structures/divided"; + + JLabel jLabel1 = new JLabel(); + JTextField pdbCodeTextField = new JTextField(); + JLabel jLabel2 = new JLabel(); + private JComboBox hostsComboBox = new JComboBox(); + JLabel jLabel3 = new JLabel(); + private JTextField entryDirTextField = new JTextField(); + JPanel controlsPanel = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JButton removeHostButton = new JButton(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + public PDBBankFormPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + + this.setLayout(borderLayout1); + jLabel1.setToolTipText(""); + jLabel1.setText("FTP archive: "); + pdbCodeTextField.setToolTipText(""); + pdbCodeTextField.setCaretPosition(0); + pdbCodeTextField.setText(" "); + pdbCodeTextField.setColumns(6); + jLabel2.setToolTipText(""); + jLabel2.setText("4-character PDB ID: "); + jLabel3.setToolTipText(""); + jLabel3.setText("FTP entry directory: "); + entryDirTextField.setToolTipText(""); + entryDirTextField.setColumns(50); + removeHostButton.setToolTipText("Remove server from the list"); + removeHostButton.setText("Remove"); + controlsPanel.setLayout(gridBagLayout1); + this.add(controlsPanel, BorderLayout.NORTH); + controlsPanel.add(jLabel2, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + controlsPanel.add(jLabel1, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + controlsPanel.add(pdbCodeTextField, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + controlsPanel.add(hostsComboBox, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0)); + controlsPanel.add(removeHostButton, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + controlsPanel.add(entryDirTextField, new GridBagConstraints(1, 2, 2, 1, 1.0, 1.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0)); + controlsPanel.add(jLabel3, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + + hostsComboBox.addItem(defaultPDB_Host); + entryDirTextField.setText(defaultPDB_EntryDir); + + } + + public String getHost() { + if (hostsComboBox.getItemCount() < 1) { + return defaultPDB_Host; + } + + Object item = hostsComboBox.getSelectedItem(); + if (item != null) { + return item.toString().trim(); + } + return defaultPDB_Host; + } + + public String getEntryDirectory() { + if (entryDirTextField.getText().trim().length() < 1) { + return defaultPDB_EntryDir; + } + return entryDirTextField.getText().trim(); + } +} diff --git a/src/main/java/cct/pdb/ui/PDBFormFrame.java b/src/main/java/cct/pdb/ui/PDBFormFrame.java new file mode 100644 index 0000000..d6e7d36 --- /dev/null +++ b/src/main/java/cct/pdb/ui/PDBFormFrame.java @@ -0,0 +1,160 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.pdb.ui; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JFrame; +import javax.swing.JOptionPane; +import javax.swing.JPanel; + +import cct.pdb.PDBBankFetcherInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class PDBFormFrame + extends JFrame implements ActionListener { + BorderLayout borderLayout1 = new BorderLayout(); + PDBBankFormPanel pDBBankFormPanel1 = new PDBBankFormPanel(); + JPanel jPanel1 = new JPanel(); + JPanel jPanel2 = new JPanel(); + JPanel jPanel3 = new JPanel(); + BorderLayout borderLayout2 = new BorderLayout(); + JButton helpButton = new JButton(); + JButton cancelButton = new JButton(); + JButton fetchButton = new JButton(); + JCheckBox hideCheckBox = new JCheckBox(); + FlowLayout flowLayout1 = new FlowLayout(); + + PDBBankFetcherInterface Fetcher = null; + + public PDBFormFrame(PDBBankFetcherInterface fetcher) { + Fetcher = fetcher; + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + getContentPane().setLayout(borderLayout1); + jPanel1.setLayout(borderLayout2); + helpButton.setToolTipText(""); + helpButton.setText(" Help "); + helpButton.addActionListener(this); + cancelButton.setToolTipText(""); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(this); + fetchButton.setToolTipText("Fetch structure"); + fetchButton.setText("Fetch"); + fetchButton.addActionListener(this); + hideCheckBox.setToolTipText(""); + hideCheckBox.setText("Don\'t hide dialog after Fetch"); + jPanel3.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + this.getContentPane().add(jPanel1, BorderLayout.SOUTH); + jPanel1.add(jPanel3, BorderLayout.NORTH); + jPanel3.add(hideCheckBox); + jPanel1.add(jPanel2, BorderLayout.SOUTH); + jPanel2.add(fetchButton); + jPanel2.add(cancelButton); + jPanel2.add(helpButton); + this.getContentPane().add(pDBBankFormPanel1, BorderLayout.CENTER); + } + + public static void main(String[] args) { + PDBBankFetcherInterface fetcher = null; + PDBFormFrame pdbformframe = new PDBFormFrame(fetcher); + pdbformframe.pack(); + pdbformframe.setVisible(true); + //System.exit(0); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == this.cancelButton) { + setVisible(false); + } + else if (e.getSource() == this.helpButton) { + JOptionPane.showMessageDialog(this, + "1) Type 4-character PDB Code\n" + + "2) (Optional) Enter PDB archive mirror host name\n" + + "3) (Optional) Enter PDB archive entry directory\n", + "Help", + JOptionPane.INFORMATION_MESSAGE); + } + else if (e.getSource() == this.fetchButton) { + // --- Error check + String code = pDBBankFormPanel1.pdbCodeTextField.getText().trim(); + if (code.length() != 4) { + JOptionPane.showMessageDialog(this, "PDB code should consist of 4 characters", + "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + code = code.toLowerCase(); + + if (Fetcher == null) { + JOptionPane.showMessageDialog(this, "PDBBankFetcherInterface is not set...", + "Error", JOptionPane.ERROR_MESSAGE); + return; + } + Fetcher.fetchStructure(pDBBankFormPanel1.getHost(), pDBBankFormPanel1.getEntryDirectory(), code); + if (!hideCheckBox.isSelected()) { + setVisible(false); + } + } + } +} diff --git a/src/main/java/cct/poly/CENTERELEMENT.java b/src/main/java/cct/poly/CENTERELEMENT.java new file mode 100644 index 0000000..2d8f797 --- /dev/null +++ b/src/main/java/cct/poly/CENTERELEMENT.java @@ -0,0 +1,24 @@ +package cct.poly; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class CENTERELEMENT { + /* list of cube locations */ + int i, j, k; /* cube location */ + public CENTERELEMENT(int _i, int _j, int _k) { + i = _i; + j = _j; + k = _k; + } + +} diff --git a/src/main/java/cct/poly/CENTERLIST.java b/src/main/java/cct/poly/CENTERLIST.java new file mode 100644 index 0000000..1059b4c --- /dev/null +++ b/src/main/java/cct/poly/CENTERLIST.java @@ -0,0 +1,21 @@ +package cct.poly; + +import java.util.ArrayList; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class CENTERLIST + extends ArrayList { + public CENTERLIST() { + } +} diff --git a/src/main/java/cct/poly/CORNER.java b/src/main/java/cct/poly/CORNER.java new file mode 100644 index 0000000..0c3e508 --- /dev/null +++ b/src/main/java/cct/poly/CORNER.java @@ -0,0 +1,22 @@ +package cct.poly; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class CORNER { + /* corner of a cube */ + int i, j, k; /* (i, j, k) is index within lattice */ + float x, y, z, value; /* location and function value */ + + public CORNER() { + } +} diff --git a/src/main/java/cct/poly/CORNERELEMENT.java b/src/main/java/cct/poly/CORNERELEMENT.java new file mode 100644 index 0000000..031ce4c --- /dev/null +++ b/src/main/java/cct/poly/CORNERELEMENT.java @@ -0,0 +1,28 @@ +package cct.poly; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class CORNERELEMENT { + /* list of corners */ + int i, j, k; /* corner id */ + float value; /* corner value */ + public CORNERELEMENT(int _i, int _j, int _k, float _value) { + i = _i; + j = _j; + k = _k; + value = _value; + } + + public CORNERELEMENT() { + } +} diff --git a/src/main/java/cct/poly/CORNERLIST.java b/src/main/java/cct/poly/CORNERLIST.java new file mode 100644 index 0000000..bea2fd6 --- /dev/null +++ b/src/main/java/cct/poly/CORNERLIST.java @@ -0,0 +1,25 @@ +package cct.poly; + +import java.util.ArrayList; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class CORNERLIST + extends ArrayList { + public CORNERLIST() { + } + + public void push_front(Object elem) { + this.add(0, elem); + } +} diff --git a/src/main/java/cct/poly/CUBE.java b/src/main/java/cct/poly/CUBE.java new file mode 100644 index 0000000..5c1f013 --- /dev/null +++ b/src/main/java/cct/poly/CUBE.java @@ -0,0 +1,22 @@ +package cct.poly; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class CUBE { + /* partitioning cell (cube) */ + public int i, j, k; /* lattice location of cube */ + public CORNER corners[] = new CORNER[8]; /* eight corners */ + + public CUBE() { + } +} diff --git a/src/main/java/cct/poly/CUBETABLE.java b/src/main/java/cct/poly/CUBETABLE.java new file mode 100644 index 0000000..709fe39 --- /dev/null +++ b/src/main/java/cct/poly/CUBETABLE.java @@ -0,0 +1,157 @@ +package cct.poly; + +import java.util.ArrayList; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class CUBETABLE { + + /**** Cubical Polygonization (optional) ****/ + + + final static int LB = 0; /* left bottom edge */ + final static int LT = 1; /* left top edge */ + final static int LN = 2; /* left near edge */ + final static int LF = 3; /* left far edge */ + final static int RB = 4; /* right bottom edge */ + final static int RT = 5; /* right top edge */ + final static int RN = 6; /* right near edge */ + final static int RF = 7; /* right far edge */ + final static int BN = 8; /* bottom near edge */ + final static int BF = 9; /* bottom far edge */ + final static int TN = 10; /* top near edge */ + final static int TF = 11; /* top far edge */ + + static int L = 0; /* left direction: -x, -i */ + static int R = 1; /* right direction: +x, +i */ + static int B = 2; /* bottom direction: -y, -j */ + static int T = 3; /* top direction: +y, +j */ + static int N = 4; /* near direction: -z, -k */ + static int F = 5; /* far direction: +z, +k */ + static int LBN = 0; /* left bottom near corner */ + static int LBF = 1; /* left bottom far corner */ + static int LTN = 2; /* left top near corner */ + static int LTF = 3; /* left top far corner */ + static int RBN = 4; /* right bottom near corner */ + static int RBF = 5; /* right bottom far corner */ + static int RTN = 6; /* right top near corner */ + static int RTF = 7; /* right top far corner */ + + /* edge: LB, LT, LN, LF, RB, RT, RN, RF, BN, BF, TN, TF */ + public static final int corner1[] = { + LBN, LTN, LBN, LBF, RBN, RTN, RBN, RBF, LBN, LBF, LTN, LTF}; + public static final int corner2[] = { + LBF, LTF, LTN, LTF, RBF, RTF, RTN, RTF, RBN, RBF, RTN, RTF}; + static int leftface[] = { + B, L, L, F, R, T, N, R, N, B, T, F}; + /* face on left when going corner1 to corner2 */ + static int rightface[] = { + L, T, N, L, B, R, R, F, B, F, N, T}; + /* face on right when going corner1 to corner2 */ + + + //vector ctable; + static ArrayList ctable = new ArrayList(256); + + public CUBETABLE() { + int i, e, c, done[] = new int[12], pos[] = new int[8]; + for (i = 0; i < 256; i++) { + for (e = 0; e < 12; e++) { + done[e] = 0; + } + for (c = 0; c < 8; c++) { + pos[c] = BIT(i, c); + } + for (e = 0; e < 12; e++) { + //if (!done[e] && (pos[corner1[e]] != pos[corner2[e]])) { + if (done[e] == 0 && (pos[corner1[e]] != pos[corner2[e]])) { + INTLIST ints = new INTLIST(); + int start = e, edge = e; + + /* get face that is to right of edge from pos to neg corner: */ + //int face = pos[corner1[e]] ? rightface[e] : leftface[e]; + int face = pos[corner1[e]] != 0 ? rightface[e] : leftface[e]; + while (true) { + edge = nextcwedge(edge, face); + done[edge] = 1; + if (pos[corner1[edge]] != pos[corner2[edge]]) { + ints.push_front(edge); + if (edge == start) { + break; + } + face = otherface(edge, face); + } + } + //ctable[i].push_front(ints); + ctable.add(0, ints); + } + } + } + } + + static INTLISTS get_lists(int i) { + //return (INTLISTS) ctable[i]; + return (INTLISTS) ctable.get(i); + } + + public static INTLISTS get_cubetable_entry(int i) { + //static CUBETABLE c; + //return c.get_lists(i); + return get_lists(i); + } + + int BIT(int i, int bit) { + return (i >> bit) & 1; + } + + /* nextcwedge: return next clockwise edge from given edge around given face */ + + int nextcwedge(int edge, int face) { + switch (edge) { + case LB: + return (face == L) ? LF : BN; + case LT: + return (face == L) ? LN : TF; + case LN: + return (face == L) ? LB : TN; + case LF: + return (face == L) ? LT : BF; + case RB: + return (face == R) ? RN : BF; + case RT: + return (face == R) ? RF : TN; + case RN: + return (face == R) ? RT : BN; + case RF: + return (face == R) ? RB : TF; + case BN: + return (face == B) ? RB : LN; + case BF: + return (face == B) ? LB : RF; + case TN: + return (face == T) ? LT : RN; + case TF: + return (face == T) ? RT : LF; + } + System.err.println("nextcwedge: should not be here..."); + return 0; + } + + /* otherface: return face adjoining edge that is not the given face */ + + int otherface(int edge, int face) { + int other = leftface[edge]; + return face == other ? rightface[edge] : other; + } + +} diff --git a/src/main/java/cct/poly/EDGEELEMENT.java b/src/main/java/cct/poly/EDGEELEMENT.java new file mode 100644 index 0000000..5758094 --- /dev/null +++ b/src/main/java/cct/poly/EDGEELEMENT.java @@ -0,0 +1,22 @@ +package cct.poly; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class EDGEELEMENT { + /* list of edges */ + public int i1, j1, k1, i2, j2, k2; /* edge corner ids */ + public int vid; /* vertex id */ + + public EDGEELEMENT() { + } +} diff --git a/src/main/java/cct/poly/EDGELIST.java b/src/main/java/cct/poly/EDGELIST.java new file mode 100644 index 0000000..40a8538 --- /dev/null +++ b/src/main/java/cct/poly/EDGELIST.java @@ -0,0 +1,25 @@ +package cct.poly; + +import java.util.ArrayList; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class EDGELIST + extends ArrayList { + public EDGELIST() { + } + + public void push_front(Object new_obj) { + this.add(0, new_obj); + } +} diff --git a/src/main/java/cct/poly/EDGETABLE.java b/src/main/java/cct/poly/EDGETABLE.java new file mode 100644 index 0000000..896131b --- /dev/null +++ b/src/main/java/cct/poly/EDGETABLE.java @@ -0,0 +1,100 @@ +package cct.poly; + +import java.util.ArrayList; +import java.util.Iterator; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class EDGETABLE { + + static int HASHBIT = 5; + static int HASHSIZE = (1<< (3 * HASHBIT)); + + //vector table; /* edge and vertex id hash table */ + ArrayList table = new ArrayList(2 * HASHSIZE); + + // EDGETABLE(): table(2*HASHSIZE) {} + + + /* setedge: set vertex id for edge */ + void setedge(int i1, int j1, int k1, int i2, int j2, int k2, int vid) { + int index; //unsigned int index; + + if (i1 > i2 || (i1 == i2 && (j1 > j2 || (j1 == j2 && k1 > k2)))) { + int t = i1; + i1 = i2; + i2 = t; + t = j1; + j1 = j2; + j2 = t; + t = k1; + k1 = k2; + k2 = t; + } + index = Polygonizer.HASH(i1, j1, k1) + Polygonizer.HASH(i2, j2, k2); + + EDGEELEMENT new_obj = new EDGEELEMENT(); + new_obj.i1 = i1; + new_obj.j1 = j1; + new_obj.k1 = k1; + new_obj.i2 = i2; + new_obj.j2 = j2; + new_obj.k2 = k2; + new_obj.vid = vid; + + //table[index].push_front(new_obj); + EDGELIST el = (EDGELIST) table.get(index); + + } + + /* getedge: return vertex id for edge; return -1 if not set */ + + int getedge(int i1, int j1, int k1, int i2, int j2, int k2) { + + if (i1 > i2 || (i1 == i2 && (j1 > j2 || (j1 == j2 && k1 > k2)))) { + int t = i1; + i1 = i2; + i2 = t; + t = j1; + j1 = j2; + j2 = t; + t = k1; + k1 = k2; + k2 = t; + } + + int hashval = Polygonizer.HASH(i1, j1, k1) + Polygonizer.HASH(i2, j2, k2); + //EDGELIST::const_iterator q = table[hashval].begin(); + EDGELIST xxx = (EDGELIST) table.get(hashval); + Iterator q = xxx.iterator(); + //for (; q != table[hashval].end(); ++q) + while (q.hasNext()) { + EDGEELEMENT ee = (EDGEELEMENT) q.next(); + //if (q.i1 == i1 && q.j1 == j1 && q.k1 == k1 && + // q.i2 == i2 && q.j2 == j2 && q.k2 == k2) + // return q.vid; + if (ee.i1 == i1 && ee.j1 == j1 && ee.k1 == k1 && + ee.i2 == i2 && ee.j2 == j2 && ee.k2 == k2) { + return ee.vid; + } + + } + return -1; + } + + public EDGETABLE() { + for (int i = 0; i < 2 * HASHSIZE; i++) { + table.add(new EDGELIST()); + } + } +} diff --git a/src/main/java/cct/poly/INTLIST.java b/src/main/java/cct/poly/INTLIST.java new file mode 100644 index 0000000..6f6ac64 --- /dev/null +++ b/src/main/java/cct/poly/INTLIST.java @@ -0,0 +1,23 @@ +package cct.poly; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class INTLIST + extends java.util.ArrayList { + public INTLIST() { + } + + public void push_front(int n) { + this.add(0, new Integer(n)); + } +} diff --git a/src/main/java/cct/poly/INTLISTS.java b/src/main/java/cct/poly/INTLISTS.java new file mode 100644 index 0000000..94a5c46 --- /dev/null +++ b/src/main/java/cct/poly/INTLISTS.java @@ -0,0 +1,19 @@ +package cct.poly; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class INTLISTS + extends java.util.ArrayList { + public INTLISTS() { + } +} diff --git a/src/main/java/cct/poly/ImplicitFunction.java b/src/main/java/cct/poly/ImplicitFunction.java new file mode 100644 index 0000000..eaceaa0 --- /dev/null +++ b/src/main/java/cct/poly/ImplicitFunction.java @@ -0,0 +1,20 @@ +package cct.poly; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public abstract class ImplicitFunction { + public ImplicitFunction() { + } + + public abstract float eval(float x, float y, float z); +} diff --git a/src/main/java/cct/poly/ImplicitFunctionInterface.java b/src/main/java/cct/poly/ImplicitFunctionInterface.java new file mode 100644 index 0000000..f9b6d75 --- /dev/null +++ b/src/main/java/cct/poly/ImplicitFunctionInterface.java @@ -0,0 +1,17 @@ +package cct.poly; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public interface ImplicitFunctionInterface { + float eval(float x, float y, float z); +} diff --git a/src/main/java/cct/poly/NORMAL.java b/src/main/java/cct/poly/NORMAL.java new file mode 100644 index 0000000..b637f7e --- /dev/null +++ b/src/main/java/cct/poly/NORMAL.java @@ -0,0 +1,19 @@ +package cct.poly; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class NORMAL + extends POINT { + public NORMAL() { + } +} diff --git a/src/main/java/cct/poly/POINT.java b/src/main/java/cct/poly/POINT.java new file mode 100644 index 0000000..6e377fe --- /dev/null +++ b/src/main/java/cct/poly/POINT.java @@ -0,0 +1,19 @@ +package cct.poly; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class POINT { + public float x, y, z; + public POINT() { + } +} diff --git a/src/main/java/cct/poly/PROCESS.java b/src/main/java/cct/poly/PROCESS.java new file mode 100644 index 0000000..cf508c1 --- /dev/null +++ b/src/main/java/cct/poly/PROCESS.java @@ -0,0 +1,956 @@ +package cct.poly; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.logging.Logger; + +import cct.interfaces.ImplicitFunctionInterface; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class PROCESS { + + static final Logger logger = Logger.getLogger(PROCESS.class.getCanonicalName()); + static int facebit[] = { + 2, 2, 1, 1, 0, 0}; + + int TET = 0; // use tetrahedral decomposition + int NOTET = 1; // no tetrahedral decomposition */ + + /* parameters, function, storage */ + + //std::vector* gnormals; + List gnormals = new ArrayList(); + //std::vector* gvertices; + List gvertices = new ArrayList(); + //std::vector *gtriangles; + List gtriangles = new ArrayList(); + + ImplicitFunctionInterface function = null; /* implicit surface function */ + + static float greenColor[] = { + 0, 1, 0}; + float size[] = null, delta; /* cube size, normal delta */ + int bounds[] = null; /* cube range within lattice */ + POINT start = new POINT(); /* start point on surface */ + + // Global list of corners (keeps track of memory) + //list corner_lst; + List corner_lst = new ArrayList(); + + //list cubes; /* active cubes */ + List cubes = new ArrayList(); + //vector centers; /* cube center hash table */ + List centers = new ArrayList(); + //vector corners; /* corner value hash table */ + ArrayList corners = new ArrayList(); + EDGETABLE edges = new EDGETABLE(); + + boolean triangle(int i1, int i2, int i3) { + TRIANGLE t = new TRIANGLE(); + t.v0 = i1; + t.v1 = i2; + t.v2 = i3; + //gtriangles.push_back(t); + gtriangles.add(t); + return true; + } + + public PROCESS() { + } + + /* setcorner: return corner with the given lattice location + set (and cache) its function value */ + CORNER setcorner(int i, int j, int k) { + /* for speed, do corner value caching here */ + //corner_lst.push_back(CORNER()); + corner_lst.add(new CORNER()); + //CORNER c = corner_lst.back(); + CORNER c = (CORNER) corner_lst.get(corner_lst.size() - 1); + int index = Polygonizer.HASH(i, j, k); + + c.i = i; + c.x = start.x + ( i - .5f) * size[0]; + c.j = j; + c.y = start.y + ( j - .5f) * size[1]; + c.k = k; + c.z = start.z + ( k - .5f) * size[2]; + + //CORNERLIST::const_iterator l = corners[index].begin(); + CORNERLIST cl = (CORNERLIST) corners.get(index); + Iterator l = cl.iterator(); + //for (; l != corners[index].end(); ++l) { + while (l.hasNext()) { + CORNERELEMENT ce = (CORNERELEMENT) l.next(); + //if (l.i == i && l.j == j && l.k == k) { + if (ce.i == i && ce.j == j && ce.k == k) { + //c.value = l.value; + c.value = ce.value; + return c; + } + } + + c.value = (float) function.eval(c.x, c.y, c.z); + CORNERELEMENT elem = new CORNERELEMENT(i, j, k, c.value); + //corners[index].push_front(elem); + cl.push_front(elem); + return c; + } + + /* setcorner: return corner with the given lattice location + set (and cache) its function value */ + CORNER setcorner2(int i, int j, int k, int ix, int iy, int iz, float x, + float y, float z) { + + // for speed, do corner value caching here + //corner_lst.push_back(CORNER()); + corner_lst.add(new CORNER()); + //CORNER c = corner_lst.back(); + CORNER c = (CORNER) corner_lst.get(corner_lst.size() - 1); + /* + //int index = Polygonizer.HASH(i, j, k); + int index = Polygonizer.HASH(i + ix, j + iy, k + iz); + */ + /* + n, i,j,k: 0 0 0 0 + n, i,j,k: 1 0 0 1 + n, i,j,k: 2 0 1 0 + n, i,j,k: 3 0 1 1 + n, i,j,k: 4 1 0 0 + n, i,j,k: 5 1 0 1 + n, i,j,k: 6 1 1 0 + n, i,j,k: 7 1 1 1 + + */ + + c.i = ix + i; + //c.x = start.x + ( (float) i - .5f) * size[0]; + c.x = x + i * size[0]; + c.j = iy + j; + //c.y = start.y + ( (float) j - .5f) * size[1]; + c.y = y + j * size[1]; + c.k = iz + k; + //c.z = start.z + ( (float) k - .5f) * size[2]; + c.z = z + k * size[2]; + + /* + //CORNERLIST::const_iterator l = corners[index].begin(); + CORNERLIST cl = (CORNERLIST) corners.get(index); + Iterator l = cl.iterator(); + //for (; l != corners[index].end(); ++l) { + while (l.hasNext()) { + CORNERELEMENT ce = (CORNERELEMENT) l.next(); + //if (l.i == i && l.j == j && l.k == k) { + if (ce.i == i && ce.j == j && ce.k == k) { + //c.value = l.value; + c.value = ce.value; + return c; + } + } + */ + + c.value = (float) function.eval(c.x, c.y, c.z); + + /* + CORNERELEMENT elem = new CORNERELEMENT(i, j, k, c.value); + //corners[index].push_front(elem); + cl.push_front(elem); + */ + + return c; + } + + int FLIP(int i, int bit) { + return i ^ 1 << bit; + } + + int BIT(int i, int bit) { + return (i >> bit) & 1; + } + + /* testface: given cube at lattice (i, j, k), and four corners of face, + * if surface crosses face, compute other four corners of adjacent cube + * and add new cube to cube stack */ + + void testface(int i, int j, int k, CUBE old, int face, int c1, int c2, int c3, + int c4) { + //static int facebit[6] = { + // 2, 2, 1, 1, 0, 0}; + int n, bit = facebit[face]; + //int pos = old.corners[c1].value > 0.0 ? 1 : 0; + boolean pos = old.corners[c1].value > 0.0; + + /* test if no surface crossing, cube out of bounds, or already visited: */ + if ( (old.corners[c2].value > 0) == pos && + (old.corners[c3].value > 0) == pos && + (old.corners[c4].value > 0) == pos) { + return; + } + if (Math.abs(i) > bounds[0] || Math.abs(j) > bounds[1] || + Math.abs(k) > bounds[2]) { + return; + } + //if (setcenter(centers, i, j, k)) { + if (Polygonizer.setcenter(centers, i, j, k)) { + return; + } + + CUBE new_obj = new CUBE(); + + /* create new_obj cube: */ + new_obj.i = i; + new_obj.j = j; + new_obj.k = k; + for (n = 0; n < 8; n++) { + new_obj.corners[n] = null; + } + new_obj.corners[FLIP(c1, bit)] = old.corners[c1]; + new_obj.corners[FLIP(c2, bit)] = old.corners[c2]; + new_obj.corners[FLIP(c3, bit)] = old.corners[c3]; + new_obj.corners[FLIP(c4, bit)] = old.corners[c4]; + for (n = 0; n < 8; n++) { + if (new_obj.corners[n] == null) { + new_obj.corners[n] = setcorner(i + BIT(n, 2), j + BIT(n, 1), + k + BIT(n, 0)); + } + } + + // Add new cube to top of stack + //cubes.push_front(new_obj); + cubes.add(0, new_obj); + } + + /* find: search for point with value of given sign (0: neg, 1: pos) */ + + TEST find(int sign, float x, float y, float z) { + int i; + boolean sign2 = sign != 0; + TEST test = new TEST(); + float range[] = { + size[0], size[1], size[2]}; + test.ok = 1; + for (i = 0; i < 10000; i++) { + + //test.p.x = x + range * (RAND() - 0.5); + //test.p.y = y + range * (RAND() - 0.5); + //test.p.z = z + range * (RAND() - 0.5); + test.p.x = x + range[0] * (float) (Math.random() - 0.5); + test.p.y = y + range[1] * (float) (Math.random() - 0.5); + test.p.z = z + range[2] * (float) (Math.random() - 0.5); + + test.value = (float) function.eval(test.p.x, test.p.y, test.p.z); + //if (sign == (test.value > 0.0)) { + if (sign2 && (test.value > 0.0)) { + return test; + } + else if ( (!sign2) && (! (test.value > 0.0))) { + return test; + } + + range[0] = range[0] * 1.0005f; /* slowly expand search outwards */ + range[1] = range[1] * 1.0005f; /* slowly expand search outwards */ + range[2] = range[2] * 1.0005f; /* slowly expand search outwards */ + } + test.ok = 0; + return test; + } + + /* vertid: return index for vertex on edge: + * c1.value and c2.value are presumed of different sign + * return saved index if any; else compute vertex and save */ + + int vertid(CORNER c1, CORNER c2) { + VERTEX v = new VERTEX(); + NORMAL n = new NORMAL(); + POINT a = new POINT(), b = new POINT(); + int vid = edges.getedge(c1.i, c1.j, c1.k, c2.i, c2.j, c2.k); + if (vid != -1) { + return vid; /* previously computed */ + } + a.x = c1.x; + a.y = c1.y; + a.z = c1.z; + b.x = c2.x; + b.y = c2.y; + b.z = c2.z; + Polygonizer.converge(a, b, c1.value, function, v); /* position */ + //vnormal(function, & v, & n, delta); /* normal */ + n = Polygonizer.vnormal(function, v, n, delta); /* normal */ + //gvertices.push_back(v); /* save vertex */ + gvertices.add(v); + //gnormals.push_back(n); /* save vertex */ + gnormals.add(n); + vid = gvertices.size() - 1; + edges.setedge(c1.i, c1.j, c1.k, c2.i, c2.j, c2.k, vid); + return vid; + } + + /* vertid: return index for vertex on edge: + * c1.value and c2.value are presumed of different sign + * return saved index if any; else compute vertex and save */ + + int vertid2(CORNER c1, CORNER c2) { + VERTEX v = new VERTEX(); + NORMAL n = new NORMAL(); + POINT a = new POINT(), b = new POINT(); + int vid; + //int vid = edges.getedge(c1.i, c1.j, c1.k, c2.i, c2.j, c2.k); + //if (vid != -1) { + // return vid; /* previously computed */ + //} + a.x = c1.x; + a.y = c1.y; + a.z = c1.z; + b.x = c2.x; + b.y = c2.y; + b.z = c2.z; + if (false) { // Use extra function calls + Polygonizer.converge(a, b, c1.value, function, v); /* position */ + } + else { // Use liniar interpolation + v.x = c1.x - c1.value * (c2.x - c1.x) / (c2.value - c1.value); + v.y = c1.y - c1.value * (c2.y - c1.y) / (c2.value - c1.value); + v.z = c1.z - c1.value * (c2.z - c1.z) / (c2.value - c1.value); + } + //vnormal(function, & v, & n, delta); /* normal */ + n = Polygonizer.vnormal(function, v, n, delta); /* normal */ + //gvertices.push_back(v); /* save vertex */ + gvertices.add(v); + //gnormals.push_back(n); /* save vertex */ + gnormals.add(n); + vid = gvertices.size() - 1; + //edges.setedge(c1.i, c1.j, c1.k, c2.i, c2.j, c2.k, vid); + return vid; + } + + /**** Tetrahedral Polygonization ****/ + + + /* dotet: triangulate the tetrahedron + * b, c, d should appear clockwise when viewed from a + * return 0 if client aborts, 1 otherwise */ + + boolean dotet(CUBE cube, int c1, int c2, int c3, int c4) { + CORNER a = cube.corners[c1]; + CORNER b = cube.corners[c2]; + CORNER c = cube.corners[c3]; + CORNER d = cube.corners[c4]; + int index = 0, e1 = -1, e2 = -1, e3 = -1, e4 = -1, e5 = -1, e6 = -1; + boolean apos, bpos, cpos, dpos; + if (apos = (a.value > 0.0)) { + index += 8; + } + if (bpos = (b.value > 0.0)) { + index += 4; + } + if (cpos = (c.value > 0.0)) { + index += 2; + } + if (dpos = (d.value > 0.0)) { + index += 1; + } + /* index is now 4-bit number representing one of the 16 possible cases */ + if (apos != bpos) { + e1 = vertid(a, b); + } + if (apos != cpos) { + e2 = vertid(a, c); + } + if (apos != dpos) { + e3 = vertid(a, d); + } + if (bpos != cpos) { + e4 = vertid(b, c); + } + if (bpos != dpos) { + e5 = vertid(b, d); + } + if (cpos != dpos) { + e6 = vertid(c, d); + } + /* 14 productive tetrahedral cases (0000 and 1111 do not yield polygons */ + switch (index) { + case 1: + return triangle(e5, e6, e3); + case 2: + return triangle(e2, e6, e4); + case 3: + return triangle(e3, e5, e4) && + triangle(e3, e4, e2); + case 4: + return triangle(e1, e4, e5); + case 5: + return triangle(e3, e1, e4) && + triangle(e3, e4, e6); + case 6: + return triangle(e1, e2, e6) && + triangle(e1, e6, e5); + case 7: + return triangle(e1, e2, e3); + case 8: + return triangle(e1, e3, e2); + case 9: + return triangle(e1, e5, e6) && + triangle(e1, e6, e2); + case 10: + return triangle(e1, e3, e6) && + triangle(e1, e6, e4); + case 11: + return triangle(e1, e5, e4); + case 12: + return triangle(e3, e2, e4) && + triangle(e3, e4, e5); + case 13: + return triangle(e6, e2, e4); + case 14: + return triangle(e5, e3, e6); + } + return true; + } + + /* dotet: triangulate the tetrahedron + * b, c, d should appear clockwise when viewed from a + * return 0 if client aborts, 1 otherwise */ + + boolean dotet2(CUBE cube, int c1, int c2, int c3, int c4) { + CORNER a = cube.corners[c1]; + CORNER b = cube.corners[c2]; + CORNER c = cube.corners[c3]; + CORNER d = cube.corners[c4]; + int index = 0, e1 = -1, e2 = -1, e3 = -1, e4 = -1, e5 = -1, e6 = -1; + boolean apos, bpos, cpos, dpos; + if (apos = (a.value > 0.0)) { + index += 8; + } + if (bpos = (b.value > 0.0)) { + index += 4; + } + if (cpos = (c.value > 0.0)) { + index += 2; + } + if (dpos = (d.value > 0.0)) { + index += 1; + } + + // index is now 4-bit number representing one of the 16 possible cases + if (apos != bpos) { + e1 = vertid2(a, b); + } + if (apos != cpos) { + e2 = vertid2(a, c); + } + if (apos != dpos) { + e3 = vertid2(a, d); + } + if (bpos != cpos) { + e4 = vertid2(b, c); + } + if (bpos != dpos) { + e5 = vertid2(b, d); + } + if (cpos != dpos) { + e6 = vertid2(c, d); + } + /* 14 productive tetrahedral cases (0000 and 1111 do not yield polygons */ + switch (index) { + case 1: + + //((VERTEX)gvertices.get(e5)).rgb = greenColor; + //((VERTEX)gvertices.get(e6)).rgb = greenColor; + //((VERTEX)gvertices.get(e3)).rgb = greenColor; + return triangle(e5, e6, e3); + case 2: + + //((VERTEX)gvertices.get(e2)).rgb = greenColor; + //((VERTEX)gvertices.get(e6)).rgb = greenColor; + //((VERTEX)gvertices.get(e4)).rgb = greenColor; + return triangle(e2, e6, e4); + case 3: + return triangle(e3, e5, e4) && + triangle(e3, e4, e2); + case 4: + return triangle(e1, e4, e5); + case 5: + return triangle(e3, e1, e4) && + triangle(e3, e4, e6); + case 6: + return triangle(e1, e2, e6) && + triangle(e1, e6, e5); + case 7: + return triangle(e1, e2, e3); + case 8: + return triangle(e1, e3, e2); + case 9: + return triangle(e1, e5, e6) && + triangle(e1, e6, e2); + case 10: + return triangle(e1, e3, e6) && + triangle(e1, e6, e4); + case 11: + return triangle(e1, e5, e4); + case 12: + return triangle(e3, e2, e4) && + triangle(e3, e4, e5); + case 13: + return triangle(e6, e2, e4); + case 14: + return triangle(e5, e3, e6); + } + return true; + } + + /* docube: triangulate the cube directly, without decomposition */ + + boolean docube(CUBE cube) { + int index = 0; + for (int i = 0; i < 8; i++) { + if (cube.corners[i].value > 0.0) { + index += (1 << i); + } + } + + INTLISTS intlists = CUBETABLE.get_cubetable_entry(index); + //INTLISTS::const_iterator polys = intlists.begin(); + Iterator polys = intlists.iterator(); + //for (; polys != intlists.end(); ++polys) { + while (polys.hasNext()) { + //INTLIST::const_iterator edges = polys.begin(); + INTLIST intlist = (INTLIST) polys.next(); + Iterator edges = intlists.iterator(); + int a = -1, b = -1, count = 0; + //for (; edges != polys.end(); ++edges) { + while (edges.hasNext()) { + int edge = ( (Integer) edges.next()).intValue(); + //CORNER c1 = cube.corners[corner1[ ( * edges)]]; + //CORNER c2 = cube.corners[corner2[ ( * edges)]]; + CORNER c1 = cube.corners[CUBETABLE.corner1[edge]]; + CORNER c2 = cube.corners[CUBETABLE.corner2[edge]]; + int c = vertid(c1, c2); + if (++count > 2 && !triangle(a, b, c)) { + return false; + } + if (count < 3) { + a = b; + } + b = c; + } + } + return true; + } + + /**** An Implicit Surface Polygonizer ****/ + + + /* polygonize: polygonize the implicit surface function + * arguments are: + * ImplicitFunction + * the implicit surface function + * return negative for inside, positive for outside + * float size + * width of the partitioning cube + * float delta + * a small step - used for gradient computation + * int bounds + * max. range of cubes (+/- on the three axes) from first cube + * _gvertices, _gnormals, _gtriangles + * the data structures into which information is put. + */ + + public PROCESS(ImplicitFunctionInterface _function, float _size[], float _delta, + int _bounds[], List _gvertices, List _gnormals, List _gtriangles) { + function = _function; + size = _size; + delta = _delta; + bounds = _bounds; + centers = new ArrayList(Polygonizer.HASHSIZE); + corners = new ArrayList(Polygonizer.HASHSIZE); + for (int i = 0; i < Polygonizer.HASHSIZE; i++) { + corners.add(new CORNERLIST()); + centers.add(new CENTERLIST()); + } + + gvertices = _gvertices; + gnormals = _gnormals; + gtriangles = _gtriangles; + } + + void march(int mode, float x, float y, float z) throws Exception { + boolean noabort; + TEST in = new TEST(), out = new TEST(); + + /* find point on surface, beginning search at (x, y, z): */ + //srand(1); + //Math.random(); + in = find(1, x, y, z); + out = find(0, x, y, z); + //if (!in.ok || !out.ok) { + if (in.ok == 0 || out.ok == 0) { + throw new Exception("can't find starting point"); + } + + //converge( & in.p, & out.p, in.value, function, & start); + Polygonizer.converge(in.p, out.p, in.value, function, start); + + /* push initial cube on stack: */ + CUBE cube = new CUBE(); + cube.i = cube.j = cube.k = 0; + //cubes.push_front(cube); + cubes.add(0, cube); + + /* set corners of initial cube: */ + //for (int n = 0; n < 8; n++) { + // cubes.front().corners[n] = setcorner(BIT(n, 2), BIT(n, 1), BIT(n, 0)); + //} + CUBE cc = (CUBE) cubes.get(0); + for (int n = 0; n < 8; n++) { + cc.corners[n] = setcorner(BIT(n, 2), BIT(n, 1), BIT(n, 0)); + logger.info("n, i,j,k: " + n + " " + BIT(n, 2) + " " + + BIT(n, 1) + " " + BIT(n, 0) + " x,y,z, value: " + + cc.corners[n].x + " " + cc.corners[n].y + " " + + cc.corners[n].z + " " + cc.corners[n].value); + } + + Polygonizer.setcenter(centers, 0, 0, 0); + + while (cubes.size() != 0) { + /* process active cubes till none left */ + //CUBE c = cubes.front(); + CUBE c = (CUBE) cubes.get(0); + + noabort = mode == TET ? + /* either decompose into tetrahedra and polygonize: */ + dotet(c, CUBETABLE.LBN, CUBETABLE.LTN, CUBETABLE.RBN, CUBETABLE.LBF) && + dotet(c, CUBETABLE.RTN, CUBETABLE.LTN, CUBETABLE.LBF, CUBETABLE.RBN) && + dotet(c, CUBETABLE.RTN, CUBETABLE.LTN, CUBETABLE.LTF, CUBETABLE.LBF) && + dotet(c, CUBETABLE.RTN, CUBETABLE.RBN, CUBETABLE.LBF, CUBETABLE.RBF) && + dotet(c, CUBETABLE.RTN, CUBETABLE.LBF, CUBETABLE.LTF, CUBETABLE.RBF) && + dotet(c, CUBETABLE.RTN, CUBETABLE.LTF, CUBETABLE.RTF, CUBETABLE.RBF) + : + /* or polygonize the cube directly: */ + docube(c); + if (!noabort) { + throw new Exception("aborted"); + } + + /* pop current cube from stack */ + //cubes.pop_front(); + cubes.remove(0); + + /* test six face directions, maybe add to stack: */ + testface(c.i - 1, c.j, c.k, c, CUBETABLE.L, CUBETABLE.LBN, CUBETABLE.LBF, + CUBETABLE.LTN, CUBETABLE.LTF); + testface(c.i + 1, c.j, c.k, c, CUBETABLE.R, CUBETABLE.RBN, CUBETABLE.RBF, + CUBETABLE.RTN, CUBETABLE.RTF); + testface(c.i, c.j - 1, c.k, c, CUBETABLE.B, CUBETABLE.LBN, CUBETABLE.LBF, + CUBETABLE.RBN, CUBETABLE.RBF); + testface(c.i, c.j + 1, c.k, c, CUBETABLE.T, CUBETABLE.LTN, CUBETABLE.LTF, + CUBETABLE.RTN, CUBETABLE.RTF); + testface(c.i, c.j, c.k - 1, c, CUBETABLE.N, CUBETABLE.LBN, CUBETABLE.LTN, + CUBETABLE.RBN, CUBETABLE.RTN); + testface(c.i, c.j, c.k + 1, c, CUBETABLE.F, CUBETABLE.LBF, CUBETABLE.LTF, + CUBETABLE.RBF, CUBETABLE.RTF); + } + } + + void march3(int mode, float dataOrigin[], int numberOfVoxels[], + float xyz_step[]) throws Exception { + boolean noabort; + TEST in = new TEST(), out = new TEST(); + float origin[] = new float[3]; + + for (int ix = 0; ix < numberOfVoxels[0] - 2; ix++) { + for (int iy = 0; iy < numberOfVoxels[1] - 2; iy++) { + for (int iz = 0; iz < numberOfVoxels[2] - 2; iz++) { + + if (Polygonizer.setcenter(centers, ix, iy, iz)) { + continue; + } + + origin[0] = dataOrigin[0] + xyz_step[0] * ix; + origin[1] = dataOrigin[1] + xyz_step[1] * iy; + origin[2] = dataOrigin[2] + xyz_step[2] * iz; + + in = find2(1, origin, xyz_step); + out = find2(0, origin, xyz_step); + + if (in.ok == 0 || out.ok == 0) { + continue; + } + + Polygonizer.converge(in.p, out.p, in.value, function, start); + + CUBE cube = new CUBE(); + cube.i = cube.j = cube.k = 0; + cubes.add(0, cube); + + CUBE cc = (CUBE) cubes.get(0); + for (int n = 0; n < 8; n++) { + cc.corners[n] = setcorner(BIT(n, 2), BIT(n, 1), BIT(n, 0)); + } + + //Polygonizer.setcenter(centers, ix, iy, iz); + + while (cubes.size() != 0) { + /* process active cubes till none left */ + //CUBE c = cubes.front(); + CUBE c = (CUBE) cubes.get(0); + + noabort = mode == TET ? + /* either decompose into tetrahedra and polygonize: */ + dotet(c, CUBETABLE.LBN, CUBETABLE.LTN, CUBETABLE.RBN, + CUBETABLE.LBF) && + dotet(c, CUBETABLE.RTN, CUBETABLE.LTN, CUBETABLE.LBF, + CUBETABLE.RBN) && + dotet(c, CUBETABLE.RTN, CUBETABLE.LTN, CUBETABLE.LTF, + CUBETABLE.LBF) && + dotet(c, CUBETABLE.RTN, CUBETABLE.RBN, CUBETABLE.LBF, + CUBETABLE.RBF) && + dotet(c, CUBETABLE.RTN, CUBETABLE.LBF, CUBETABLE.LTF, + CUBETABLE.RBF) && + dotet(c, CUBETABLE.RTN, CUBETABLE.LTF, CUBETABLE.RTF, + CUBETABLE.RBF) + : + /* or polygonize the cube directly: */ + docube(c); + if (!noabort) { + throw new Exception("aborted"); + } + + cubes.remove(0); + + /* test six face directions, maybe add to stack: */ + testface(c.i - 1, c.j, c.k, c, CUBETABLE.L, CUBETABLE.LBN, + CUBETABLE.LBF, CUBETABLE.LTN, CUBETABLE.LTF); + testface(c.i + 1, c.j, c.k, c, CUBETABLE.R, CUBETABLE.RBN, + CUBETABLE.RBF, CUBETABLE.RTN, CUBETABLE.RTF); + testface(c.i, c.j - 1, c.k, c, CUBETABLE.B, CUBETABLE.LBN, + CUBETABLE.LBF, CUBETABLE.RBN, CUBETABLE.RBF); + testface(c.i, c.j + 1, c.k, c, CUBETABLE.T, CUBETABLE.LTN, + CUBETABLE.LTF, CUBETABLE.RTN, CUBETABLE.RTF); + testface(c.i, c.j, c.k - 1, c, CUBETABLE.N, CUBETABLE.LBN, + CUBETABLE.LTN, CUBETABLE.RBN, CUBETABLE.RTN); + testface(c.i, c.j, c.k + 1, c, CUBETABLE.F, CUBETABLE.LBF, + CUBETABLE.LTF, CUBETABLE.RBF, CUBETABLE.RTF); + } + + } + } + } + + return; + } + + void march2(int mode, float dataOrigin[], int numberOfVoxels[], float xyz_step[]) throws Exception { + boolean noabort; + TEST in = new TEST(), out = new TEST(); + float origin[] = new float[3]; + int count = 0; + + for (int ix = 0; ix < numberOfVoxels[0] - 2; ix++) { + for (int iy = 0; iy < numberOfVoxels[1] - 2; iy++) { + for (int iz = 0; iz < numberOfVoxels[2] - 2; iz++) { + + origin[0] = dataOrigin[0] + xyz_step[0] * ix; + origin[1] = dataOrigin[1] + xyz_step[1] * iy; + origin[2] = dataOrigin[2] + xyz_step[2] * iz; + + in = find2(1, origin, xyz_step); + out = find2(0, origin, xyz_step); + + if (in.ok == 0 || out.ok == 0) { + continue; + } + ++count; + + //Polygonizer.converge(in.p, out.p, in.value, function, start); + + CUBE cube = new CUBE(); + cube.i = ix; + cube.j = iy; + cube.k = iz; + //cubes.add(0, cube); + + /* + n, i,j,k: 0 0 0 0 + n, i,j,k: 1 0 0 1 + n, i,j,k: 2 0 1 0 + n, i,j,k: 3 0 1 1 + n, i,j,k: 4 1 0 0 + n, i,j,k: 5 1 0 1 + n, i,j,k: 6 1 1 0 + n, i,j,k: 7 1 1 1 + */ + + //CUBE cc = (CUBE) cubes.get(0); + for (int n = 0; n < 8; n++) { + cube.corners[n] = setcorner2(BIT(n, 2), BIT(n, 1), BIT(n, 0), ix, + iy, iz, + origin[0], origin[1], origin[2]); + //logger.info("n, i,j,k: " + n + " " + BIT(n, 2) + " " + + // BIT(n, 1) + " " + BIT(n, 0)); + if (ix == 0 && iy == 0 && iz == 0) { + logger.info("n, i,j,k: " + n + " " + BIT(n, 2) + " " + + BIT(n, 1) + " " + BIT(n, 0) + + " x,y,z, value: " + + cube.corners[n].x + " " + cube.corners[n].y + + " " + + cube.corners[n].z + " " + + cube.corners[n].value); + } + + } + + //Polygonizer.setcenter(centers, ix, iy, iz); + + noabort = mode == TET ? + /* either decompose into tetrahedra and polygonize: */ + dotet2(cube, CUBETABLE.LBN, CUBETABLE.LTN, CUBETABLE.RBN, + CUBETABLE.LBF) && + dotet2(cube, CUBETABLE.RTN, CUBETABLE.LTN, CUBETABLE.LBF, + CUBETABLE.RBN) && + dotet2(cube, CUBETABLE.RTN, CUBETABLE.LTN, CUBETABLE.LTF, + CUBETABLE.LBF) && + dotet2(cube, CUBETABLE.RTN, CUBETABLE.RBN, CUBETABLE.LBF, + CUBETABLE.RBF) && + dotet2(cube, CUBETABLE.RTN, CUBETABLE.LBF, CUBETABLE.LTF, + CUBETABLE.RBF) && + dotet2(cube, CUBETABLE.RTN, CUBETABLE.LTF, CUBETABLE.RTF, + CUBETABLE.RBF) + : + /* or polygonize the cube directly: */ + docube(cube); + if (!noabort) { + throw new Exception("aborted"); + } + + //cubes.remove(0); + + //logger.info("Cube: "+count+" new # trinangles: "+gtriangles.size()); + + // test six face directions, maybe add to stack: + /* + testface(cc.i - 1, cc.j, cc.k, cc, CUBETABLE.L, CUBETABLE.LBN, + CUBETABLE.LBF, CUBETABLE.LTN, CUBETABLE.LTF); + testface(cc.i + 1, cc.j, cc.k, cc, CUBETABLE.R, CUBETABLE.RBN, + CUBETABLE.RBF, CUBETABLE.RTN, CUBETABLE.RTF); + testface(cc.i, cc.j - 1, cc.k, cc, CUBETABLE.B, CUBETABLE.LBN, + CUBETABLE.LBF, CUBETABLE.RBN, CUBETABLE.RBF); + testface(cc.i, cc.j + 1, cc.k, cc, CUBETABLE.T, CUBETABLE.LTN, + CUBETABLE.LTF, CUBETABLE.RTN, CUBETABLE.RTF); + testface(cc.i, cc.j, cc.k - 1, cc, CUBETABLE.N, CUBETABLE.LBN, + CUBETABLE.LTN, CUBETABLE.RBN, CUBETABLE.RTN); + testface(cc.i, cc.j, cc.k + 1, cc, CUBETABLE.F, CUBETABLE.LBF, + CUBETABLE.LTF, CUBETABLE.RBF, CUBETABLE.RTF); + */ + } + } + } + logger.info("# cells to be polygomized: " + count); + return; + /* + // find point on surface, beginning search at (x, y, z): + in = find(1, x, y, z); + out = find(0, x, y, z); + if (in.ok == 0 || out.ok == 0) { + throw new Exception("can't find starting point"); + } + + Polygonizer.converge(in.p, out.p, in.value, function, start); + + // push initial cube on stack: + CUBE cube = new CUBE(); + cube.i = cube.j = cube.k = 0; + cubes.add(0, cube); + + // set corners of initial cube: + CUBE cc = (CUBE) cubes.get(0); + for (int n = 0; n < 8; n++) { + cc.corners[n] = setcorner(BIT(n, 2), BIT(n, 1), BIT(n, 0)); + } + + Polygonizer.setcenter(centers, 0, 0, 0); + + while (cubes.size() != 0) { + // process active cubes till none left + CUBE c = (CUBE) cubes.get(0); + + noabort = mode == TET ? + // either decompose into tetrahedra and polygonize: + dotet(c, CUBETABLE.LBN, CUBETABLE.LTN, CUBETABLE.RBN, CUBETABLE.LBF) && + dotet(c, CUBETABLE.RTN, CUBETABLE.LTN, CUBETABLE.LBF, CUBETABLE.RBN) && + dotet(c, CUBETABLE.RTN, CUBETABLE.LTN, CUBETABLE.LTF, CUBETABLE.LBF) && + dotet(c, CUBETABLE.RTN, CUBETABLE.RBN, CUBETABLE.LBF, CUBETABLE.RBF) && + dotet(c, CUBETABLE.RTN, CUBETABLE.LBF, CUBETABLE.LTF, CUBETABLE.RBF) && + dotet(c, CUBETABLE.RTN, CUBETABLE.LTF, CUBETABLE.RTF, CUBETABLE.RBF) + : + // or polygonize the cube directly: + docube(c); + if (!noabort) { + throw new Exception("aborted"); + } + + // pop current cube from stack + cubes.remove(0); + + // test six face directions, maybe add to stack: + testface(c.i - 1, c.j, c.k, c, CUBETABLE.L, CUBETABLE.LBN, CUBETABLE.LBF, + CUBETABLE.LTN, CUBETABLE.LTF); + testface(c.i + 1, c.j, c.k, c, CUBETABLE.R, CUBETABLE.RBN, CUBETABLE.RBF, + CUBETABLE.RTN, CUBETABLE.RTF); + testface(c.i, c.j - 1, c.k, c, CUBETABLE.B, CUBETABLE.LBN, CUBETABLE.LBF, + CUBETABLE.RBN, CUBETABLE.RBF); + testface(c.i, c.j + 1, c.k, c, CUBETABLE.T, CUBETABLE.LTN, CUBETABLE.LTF, + CUBETABLE.RTN, CUBETABLE.RTF); + testface(c.i, c.j, c.k - 1, c, CUBETABLE.N, CUBETABLE.LBN, CUBETABLE.LTN, + CUBETABLE.RBN, CUBETABLE.RTN); + testface(c.i, c.j, c.k + 1, c, CUBETABLE.F, CUBETABLE.LBF, CUBETABLE.LTF, + CUBETABLE.RBF, CUBETABLE.RTF); + } + */ + } + + /** + * find: search for point with value of given sign (0: neg, 1: pos) + * + */ + + TEST find2(int sign, float origin[], float range[]) { + boolean sign2 = sign != 0; + TEST test = new TEST(); + test.ok = 1; + + for (int ix = 0; ix < 2; ix++) { + for (int iy = 0; iy < 2; iy++) { + for (int iz = 0; iz < 2; iz++) { + test.p.x = origin[0] + range[0] * ix; + test.p.y = origin[1] + range[1] * iy; + test.p.z = origin[2] + range[2] * iz; + + test.value = (float) function.eval(test.p.x, test.p.y, test.p.z); + //if (sign == (test.value > 0.0)) { + if (sign2 && (test.value > 0.0)) { + return test; + } + else if ( (!sign2) && (! (test.value > 0.0))) { + return test; + } + } + } + } + + test.ok = 0; + return test; + } + +} diff --git a/src/main/java/cct/poly/Polygonizer.java b/src/main/java/cct/poly/Polygonizer.java new file mode 100644 index 0000000..b24523a --- /dev/null +++ b/src/main/java/cct/poly/Polygonizer.java @@ -0,0 +1,370 @@ +package cct.poly; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.logging.Logger; + +import cct.interfaces.ImplicitFunctionInterface; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * ********************************************************************* + + polygonizer.h + + This is Jules Bloomenthal's implicit surface polygonizer from GRAPHICS + GEMS IV. Bloomenthal's polygonizer is still used and the present code + is simply the original code morphed into C++. + + J. Andreas B�rentzen 2003. + + ********************************************************************* + + * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Polygonizer { + + static final Logger logger = Logger.getLogger(Polygonizer.class.getCanonicalName()); + static boolean dotet = true; + + static int TET = 0; // use tetrahedral decomposition + static int NOTET = 1; // no tetrahedral decomposition */ + + static int RES = 10; /* # converge iterations */ + + static int L = 0; /* left direction: -x, -i */ + static int R = 1; /* right direction: +x, +i */ + static int B = 2; /* bottom direction: -y, -j */ + static int T = 3; /* top direction: +y, +j */ + static int N = 4; /* near direction: -z, -k */ + static int F = 5; /* far direction: +z, +k */ + static int LBN = 0; /* left bottom near corner */ + static int LBF = 1; /* left bottom far corner */ + static int LTN = 2; /* left top near corner */ + static int LTF = 3; /* left top far corner */ + static int RBN = 4; /* right bottom near corner */ + static int RBF = 5; /* right bottom far corner */ + static int RTN = 6; /* right top near corner */ + static int RTF = 7; /* right top far corner */ + + /* the LBN corner of cube (i, j, k), corresponds with location + * (start.x+(i-.5)*size, start.y+(j-.5)*size, start.z+(k-.5)*size) */ + +//typedef POINT VERTEX; +//typedef POINT NORMAL; + + static int HASHBIT = 5; + + public static final int HASHSIZE = (1<< (3 * HASHBIT)); + + static int MASK = ( (1< gnormals; + List gnormals = new ArrayList(); + //std::vector gvertices; + List gvertices = new ArrayList(); + //std::vector gtriangles; + List gtriangles = new ArrayList(); + + ImplicitFunctionInterface func; + float size[] = null; + int bounds[] = null; + + /** Constructor of Polygonizer. The first argument is the ImplicitFunction + that we wish to polygonize. The second argument is the size of the + polygonizing cell. The final arg. is the limit to how far away we will + look for components of the implicit surface. */ + + + //Polygonizer(ImplicitFunction _func, float _size, int _bounds): + //func(_func), size(_size), bounds(_bounds) {} + + /** March erases the triangles gathered so far and builds a new + polygonization. The first argument indicates whether the primitive + cell is a tetrahedron (true) or a cube (fale). The final x,y,z + arguments indicate a point near the surface. */ + + /** Return number of triangles generated after the polygonization. + Call this function only when march has been called. */ + public int no_triangles() { + return gtriangles.size(); + } + + /** Return number of vertices generated after the polygonization. + Call this function only when march has been called. */ + int no_vertices() { + return gvertices.size(); + } + + /** Return number of normals generated after the polygonization. + Of course the result of calling this function is the same as + no_vertices. + Call this function only when march has been called. */ + int no_normals() { + return gnormals.size(); + } + + /// Return triangle with index i. + public TRIANGLE get_triangle(int i) { + //return (TRIANGLE) gtriangles[i]; + return (TRIANGLE) gtriangles.get(i); + } + + /// Return vertex with index i. + public VERTEX get_vertex(int i) { + //return (VERTEX) gvertices[i]; + return (VERTEX) gvertices.get(i); + } + + /// Return normal with index i. + public NORMAL get_normal(int i) { + return (NORMAL) gnormals.get(i); + } + + public Polygonizer(ImplicitFunctionInterface _func, float _size[], int _bounds[]) { + func = _func; + size = _size; + bounds = _bounds; + } + + /* + inline float RAND() + { + return (rand()&32767)/32767.0f; + } + */ + + + + public static int HASH(int i, int j, int k) { + return ( ( ( ( (i & MASK) << HASHBIT) | j & MASK) << HASHBIT) | k & MASK); + } + + int BIT(int i, int bit) { + return (i >> bit) & 1; + } + + // flip the given bit of i + public static int FLIP(int i, int bit) { + return i ^ 1 << bit; + } + + //struct TEST { /* test the function for a signed value */ + // POINT p; /* location of test */ + // float value; /* function value at p */ + // int ok; /* if value is of correct sign */ + //}; + + + + + + + //typedef list CENTERLIST; + List CENTERLIST = new ArrayList(); + + //typedef list CORNERLIST; + List CORNERLIST = new ArrayList(); + + //typedef list EDGELIST; + List EDGELIST = new ArrayList(); + //typedef list INTLIST; + List INTLIST = new ArrayList(); + + //typedef list INTLISTS; + List INTLISTS = new ArrayList(); + + //---------------------------------------------------------------------- + // Implicit surface evaluation functions + //---------------------------------------------------------------------- + + /* converge: from two points of differing sign, converge to zero crossing */ + + public static void converge(POINT p1, POINT p2, float v, + ImplicitFunctionInterface function, POINT p) { + int i = 0; + POINT pos = new POINT(), neg = new POINT(); + if (v < 0) { + pos.x = p2.x; + pos.y = p2.y; + pos.z = p2.z; + neg.x = p1.x; + neg.y = p1.y; + neg.z = p1.z; + } + else { + pos.x = p1.x; + pos.y = p1.y; + pos.z = p1.z; + neg.x = p2.x; + neg.y = p2.y; + neg.z = p2.z; + } + while (true) { + p.x = 0.5f * (pos.x + neg.x); + p.y = 0.5f * (pos.y + neg.y); + p.z = 0.5f * (pos.z + neg.z); + if (i++ == RES) { + return; + } + if ( (function.eval(p.x, p.y, p.z)) > 0.0) { + pos.x = p.x; + pos.y = p.y; + pos.z = p.z; + } + else { + neg.x = p.x; + neg.y = p.y; + neg.z = p.z; + } + } + } + + /* vnormal: compute unit length surface normal at point */ + + public static NORMAL vnormal(ImplicitFunctionInterface function, POINT point, NORMAL n, + float delta) { + float f = (float) function.eval(point.x, point.y, point.z); + n.x = (float) function.eval(point.x + delta, point.y, point.z) - f; + n.y = (float) function.eval(point.x, point.y + delta, point.z) - f; + n.z = (float) function.eval(point.x, point.y, point.z + delta) - f; + f = (float) Math.sqrt(n.x * n.x + n.y * n.y + n.z * n.z); + if (f != 0.0) { + n.x /= f; + n.y /= f; + n.z /= f; + } + return n; + } + + // ---------------------------------------------------------------------- + + + + + // ---------------------------------------------------------------------- + + + + /* setcenter: set (i,j,k) entry of table[] + return 1 if already set; otherwise, set and return 0 */ + //int setcenter(vector& table, + public static boolean setcenter(List table, int i, int j, int k) { + int index = HASH(i, j, k); + //CENTERLIST::const_iterator q = table[index].begin(); + CENTERLIST xxx = (CENTERLIST) table.get(index); + Iterator q = xxx.iterator(); + //for (; q != table[index].end(); ++q) { + while (q.hasNext()) { + CENTERELEMENT ce = (CENTERELEMENT) q.next(); + //if (q.i == i && q.j == j && q.k == k) { + if (ce.i == i && ce.j == j && ce.k == k) { + return true; + } + } + + CENTERELEMENT elem = new CENTERELEMENT(i, j, k); + //table[index].push_front(elem); + xxx.add(0, elem); + return false; + } + + INTLISTS get_cubetable_entry(int i) { + //static CUBETABLE c; + //return c.get_lists(i); + return CUBETABLE.get_lists(i); + } + + public void march(boolean tetra, float x, float y, float z) { + gvertices.clear(); + gnormals.clear(); + gtriangles.clear(); + PROCESS p = new PROCESS(func, size, size[0] / (RES * RES), bounds, // !!! Redo + gvertices, gnormals, gtriangles); + try { + p.march(tetra ? TET : NOTET, x, y, z); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + + public void march2(boolean tetra, float dataOrigin[], int numberOfVoxels[], + float xyz_step[]) { + gvertices.clear(); + gnormals.clear(); + gtriangles.clear(); + PROCESS p = new PROCESS(func, size, size[0] / (RES * RES), bounds, // !!! Redo + gvertices, gnormals, gtriangles); + try { + p.march2(tetra ? TET : NOTET, dataOrigin, numberOfVoxels, xyz_step); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + + public void march3(boolean tetra, float dataOrigin[], int numberOfVoxels[], + float xyz_step[]) { + gvertices.clear(); + gnormals.clear(); + gtriangles.clear(); + PROCESS p = new PROCESS(func, size, size[0] / (RES * RES), bounds, // !!! Redo + gvertices, gnormals, gtriangles); + try { + p.march3(tetra ? TET : NOTET, dataOrigin, numberOfVoxels, xyz_step); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static void main(String[] args) { + //Torus torus = new Torus(); + float size[] = { + .05f, .05f, .05f}; + int bounds[] = { + 30, 30, 30}; + Polygonizer polygonizer = new Polygonizer(new Torus(), size, bounds); + polygonizer.march(dotet, 0.f, 0.f, 0.f); + + logger.info("# triangles: " + polygonizer.no_triangles()); + for (int i = 0; i < polygonizer.no_triangles(); ++i) { + TRIANGLE t = polygonizer.get_triangle(i); + NORMAL n0 = polygonizer.get_normal(t.v0); + VERTEX v0 = polygonizer.get_vertex(t.v0); + + NORMAL n1 = polygonizer.get_normal(t.v1); + VERTEX v1 = polygonizer.get_vertex(t.v1); + + NORMAL n2 = polygonizer.get_normal(t.v2); + VERTEX v2 = polygonizer.get_vertex(t.v2); + } + + } + +} + +class Torus + implements ImplicitFunctionInterface { + public Torus() { + super(); + } + + @Override + public double eval(float x, float y, float z) { + float x2 = x * x, y2 = y * y, z2 = z * z; + float a = x2 + y2 + z2 + (0.5f * 0.5f) - (0.1f * 0.1f); + return - (a * a - 4.0f * (0.5f * 0.5f) * (y2 + z2)); + } +} diff --git a/src/main/java/cct/poly/TEST.java b/src/main/java/cct/poly/TEST.java new file mode 100644 index 0000000..08f13db --- /dev/null +++ b/src/main/java/cct/poly/TEST.java @@ -0,0 +1,23 @@ +package cct.poly; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class TEST { + /* test the function for a signed value */ + public POINT p = new POINT(); /* location of test */ + public float value; /* function value at p */ + public int ok; /* if value is of correct sign */ + + public TEST() { + } +} diff --git a/src/main/java/cct/poly/TRIANGLE.java b/src/main/java/cct/poly/TRIANGLE.java new file mode 100644 index 0000000..50449c9 --- /dev/null +++ b/src/main/java/cct/poly/TRIANGLE.java @@ -0,0 +1,19 @@ +package cct.poly; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class TRIANGLE { + public int v0, v1, v2; + public TRIANGLE() { + } +} diff --git a/src/main/java/cct/poly/VERTEX.java b/src/main/java/cct/poly/VERTEX.java new file mode 100644 index 0000000..d9c6a7a --- /dev/null +++ b/src/main/java/cct/poly/VERTEX.java @@ -0,0 +1,21 @@ +package cct.poly; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class VERTEX + extends POINT { + public float rgb[] = { + 0, 0, 0}; + public VERTEX() { + } +} diff --git a/src/main/java/cct/povray/Povray.java b/src/main/java/cct/povray/Povray.java new file mode 100644 index 0000000..cc759b8 --- /dev/null +++ b/src/main/java/cct/povray/Povray.java @@ -0,0 +1,878 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.povray; + +import java.awt.Color; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.prefs.Preferences; + +import javax.swing.JFileChooser; + +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; +import cct.interfaces.MoleculeInterface; +import cct.interfaces.Point3fInterface; +import cct.modelling.ChemicalElements; +import cct.tools.FileFilterImpl; +import cct.vecmath.FaceIndices; +import cct.vecmath.MeshObject; + +/** + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2007

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Povray { + + public static final String IMAGE_SEQ_INI_TEMPLATE_KEY = "povray.template.movie.ini"; + public static final String DEFAULT_IMAGE_SEQ_INI_FILENAME = "gen-img-seq.ini"; + public static final String DEFAULT_IMAGE_SEQ_INI_TEMPLATE + = "; Persistence Of Vision raytracer version 3.7 image sequence template file.\n" + + "Antialias=On\n" + + "\n" + + "Antialias_Threshold=0.1\n" + + "Antialias_Depth=2\n" + + "Input_File_Name=@@POVRAY-CONTROL-FILE@@\n" + + "\n" + + "Initial_Frame=1\n" + + "Final_Frame=@@FRAMES@@\n" + + "Initial_Clock=1\n" + + "Final_Clock=@@FRAMES@@\n" + + "\n" + + "Cyclic_Animation=on\n" + + "Pause_when_Done=off\n" + + "\n" + + "Output_File_Type=J\n" + + "Width=800\n" + + "Height=600\n"; + + public static final String IMAGE_SEQ_POV_TEMPLATE_KEY = "povray.template.movie.pov"; + public static final String DEFAULT_IMAGE_SEQ_POV_FILENAME = "gen-img-seq.pov"; + public static final String DEFAULT_IMAGE_SEQ_POV_TEMPLATE + = "#declare _DEBUG_ = true;\n" + + "#declare AnimationLength = 20.0;\n" + + "#declare AnimationClock = clock * AnimationLength;\n" + + "#declare file = concat(\"@@PREFIX@@\",str(frame_number,-6,0),\".pov\")\n" + + "#ifdef (_DEBUG_)\n" + + "#debug \"\\n\"\n" + + "#debug concat(\"clock = \", str(clock,7,3),\" Frame number: \",str(frame_number,0,0) , \"\\n\")\n" + + "#debug concat(\"AnimationClock = \", str(AnimationClock,7,3), \"\\n\")\n" + + "#debug concat(\"Rendering \", file, \"\\n\")\n" + + "#end\n" + + "#include file\n"; + + public static final String NUMBER_OF_FRAMES_TEMPLATE = "@@FRAMES@@"; + public static final String FILE_PREFIX_TEMPLATE = "@@PREFIX@@"; + public static final String POVRAY_CONTROL_FILE_NAME_TEMPLATE = "@@POVRAY-CONTROL-FILE@@"; + + private static String lastPWDKey = "lastPWD"; + private static String phongID = "phongValue"; + private static String meshPhongID = "meshPhongValue"; + private static String phongSizeID = "phongSizeValue"; + private static String meshPhongSizeID = "meshPhongSizeValue"; + private static String diffuseID = "diffuseValue"; + private static String meshDiffuseID = "meshDiffuseValue"; + private static String meshOpacityID = "meshOpacity"; + + private static float defaultPhongValue = 0.6f; + private static float defaultMeshPhongValue = 0.6f; + private static float defaultPhongSizeValue = 5.0f; + private static float defaultMeshPhongSizeValue = 5.0f; + private static float defaultDiffuseValue = 0.7f; + private static float defaultMeshDiffuseValue = 0.7f; + private static float defaulCylinerRadius = 0.01f; + + public static final int PARALLEL_PROJECTION = 0; + public static final int PERSPECTIVE_PROJECTION = 1; + + public static final double RADIANS_TO_DEGREES = 180.0 / Math.PI; + + float defaultAtomicRadius = 0.05f; + + int projectionPolicy = PERSPECTIVE_PROJECTION; + float fieldOfView = 60.0f; + float[] cameraLocation = { + 0, 0, 0}; + float[] transformMatrix = null; + MoleculeInterface molecule = null; + float[] backgroundColor = { + 0.0f, 0.0f, 0.0f}; + + Preferences prefs = Preferences.userNodeForPackage(getClass()); + File currentWorkingDirectory = null; + JFileChooser chooser = null; + FileFilterImpl filter = null; + + List meshObjects = null; + + public Povray() { + } + + public void settransformMatrix(float[] matrix) { + transformMatrix = new float[16]; + for (int i = 0; i < 16; i++) { + transformMatrix[i] = matrix[i]; + } + } + + public void setCameraLocation(float x, float y, float z) { + cameraLocation[0] = x; + cameraLocation[1] = y; + cameraLocation[2] = z; + } + + public void setMolecule(MoleculeInterface mol) { + molecule = mol; + } + + public void setFieldOfView(float angle) { + fieldOfView = angle; + } + + public void setProjectionPolicy(int policy) { + if (policy != PARALLEL_PROJECTION && policy != PERSPECTIVE_PROJECTION) { + System.err.println("setProjectionPolicy: wrong projection policy: set to perspective..."); + policy = PERSPECTIVE_PROJECTION; + } + projectionPolicy = policy; + } + + public static void main(String[] args) { + Povray povray = new Povray(); + } + + public void savePovrayFile() throws Exception { + if (chooser == null) { + chooser = new JFileChooser(); + filter = new FileFilterImpl(); + + String temp[] = { + "pov", "POV"}; // extensions.split(";"); + for (int i = 0; i < temp.length; i++) { + filter.addExtension(temp[i]); + } + filter.setDescription("Pov-Ray Files (*.pov)"); + chooser.setFileFilter(filter); + } + + chooser.setDialogTitle("Save as Pov-Ray File"); + chooser.setDialogType(JFileChooser.SAVE_DIALOG); + + if (currentWorkingDirectory != null) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } else { + String lastPWD = prefs.get(lastPWDKey, ""); + if (lastPWD.length() > 0) { + currentWorkingDirectory = new File(lastPWD); + if (currentWorkingDirectory.isDirectory() + && currentWorkingDirectory.exists()) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } + } + } + + int returnVal = JFileChooser.CANCEL_OPTION; + + returnVal = chooser.showSaveDialog(null); + + if (returnVal == JFileChooser.CANCEL_OPTION) { + return; + } + + if (returnVal == JFileChooser.APPROVE_OPTION) { + String fileName = chooser.getSelectedFile().getPath(); + if (fileName.endsWith(".")) { + fileName += "pov"; + } else if (!fileName.endsWith(".pov") && !fileName.endsWith(".POV")) { + fileName += ".pov"; + } + currentWorkingDirectory = chooser.getCurrentDirectory(); + try { + prefs.put(lastPWDKey, currentWorkingDirectory.getAbsolutePath()); + } catch (Exception ex) { + System.err.println("Cannot save cwd: " + ex.getMessage() + + " Ignored..."); + } + //logger.info("You chose to open this file: " + + // fileName); + + savePovrayFile(fileName); + } + + } + + public void setBackgroundColor(float red, float green, float blue) { + backgroundColor[0] = red; + backgroundColor[1] = green; + backgroundColor[2] = blue; + } + + public void savePovrayFile(String filename) throws Exception { + FileOutputStream out; + try { + out = new FileOutputStream(filename); + + out.write("// --- File is generated by Jamberoo (former JMolEditor)\n".getBytes()); + out.write("\n".getBytes()); + + out.write("global_settings { assumed_gamma 2.2 }\n".getBytes()); + out.write("\n".getBytes()); + out.write("#include \"colors.inc\"\n".getBytes()); + out.write("\n".getBytes()); + + // --- Writing camera parameters + out.write("camera {\n".getBytes()); + + if (projectionPolicy == PERSPECTIVE_PROJECTION) { + out.write(" perspective\n".getBytes()); + } + //else { + // out.write(" parallel\n".getBytes()); + //} + + //out.write(" perspective\n".getBytes()); + out.write((" location <" + String.valueOf(cameraLocation[0]) + ", " + String.valueOf(cameraLocation[1]) + ", " + + String.valueOf(cameraLocation[2]) + ">\n").getBytes()); + /* + perspective + location <0, 0, 0> + right <4/3, 0, 0> + up <0, 1, 0> + direction <0, -1, 0> + look_at <0, 0, -1> + angle 60 + */ + out.write(" right <4/3, 0, 0>\n".getBytes()); + out.write(" up <0, -1, 0>\n".getBytes()); + //out.write( "direction <0, -1, 0>\n".getBytes()); + out.write((" look_at <0, 0, -1>\n").getBytes()); + + out.write((" angle " + String.valueOf(fieldOfView) + "\n").getBytes()); + out.write(" }\n".getBytes()); + + // --- Light and background + out.write("\n".getBytes()); + out.write("light_source { < 50.000, 50.000, 50.000> colour Gray70 }\n".getBytes()); + out.write(("\n\n// --- Background color\n\n" + + "background { color red " + backgroundColor[0] + " green " + backgroundColor[1] + " blue " + backgroundColor[2] + + " }\n").getBytes()); + + // --- Setup transform matrix + if (transformMatrix != null) { + out.write("\n#declare transformMatrix =\n".getBytes()); + out.write(" transform {\n".getBytes()); + out.write(" matrix <\n".getBytes()); + out.write((" " + String.valueOf(transformMatrix[0]) + ", " + String.valueOf(transformMatrix[4]) + ", " + + String.valueOf(transformMatrix[8]) + ",\n").getBytes()); + out.write((" " + transformMatrix[1] + ", " + transformMatrix[5] + ", " + transformMatrix[9] + ",\n").getBytes()); + out.write((" " + transformMatrix[2] + ", " + transformMatrix[6] + ", " + transformMatrix[10] + ",\n").getBytes()); + out.write((" " + transformMatrix[3] + ", " + transformMatrix[7] + ", " + transformMatrix[11] + "\n").getBytes()); + out.write(" >\n".getBytes()); + out.write(" }\n".getBytes()); + } + + // --- Writing atoms + //sphere { < 13.354, -14.637, -11.758>, 1.450 + //pigment { color red 0.000 green 0.000 blue 1.000 } + //finish { ambient 0.3 diffuse 0.7 phong 1 } + //} + Map Colors = new HashMap(molecule.getNumberOfAtoms()); + + Map uniqueRadii = new LinkedHashMap(molecule.getNumberOfAtoms()); + Map uniqueColors = new LinkedHashMap(molecule.getNumberOfAtoms()); + Map uniqueAmbientColors = new LinkedHashMap(molecule.getNumberOfAtoms()); + Map uniqueColorID = new HashMap(molecule.getNumberOfAtoms()); + Map uniqueAmbientColorID = new HashMap(molecule.getNumberOfAtoms()); + List atomicRadii = new ArrayList(molecule.getNumberOfAtoms()); + List atomicColors = new ArrayList(molecule.getNumberOfAtoms()); + List atomicAmbientColors = new ArrayList(molecule.getNumberOfAtoms()); + + // --- First, find unique properties for atoms + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface atom = molecule.getAtomInterface(i); + + Object obj = atom.getProperty(AtomInterface.VISIBLE); + if (obj != null && obj instanceof Boolean) { + if (!(Boolean) obj) { + continue; + } + } + + float red = 0.5f, green = 0.5f, blue = 0.5f; + obj = atom.getProperty(AtomInterface.RGB_COLOR); + if (obj != null) { + if (obj instanceof Integer[]) { + red = (float) ((Integer[]) obj)[0] / 255.0f; + green = (float) ((Integer[]) obj)[1] / 255.0f; + blue = (float) ((Integer[]) obj)[2] / 255.0f; + + } + } + + float[] colors = { + red, green, blue}; + Colors.put(atom, colors); + + // --- Process Atomic Radii + obj = atom.getProperty(AtomInterface.GR_RADIUS); + Float radius = defaultAtomicRadius; + if (obj != null) { + if (obj instanceof Float) { + radius = (Float) obj; + } else if (obj instanceof Double) { + radius = ((Double) obj).floatValue(); + } + } + + String radiusID = ""; + if (!uniqueRadii.containsKey(radius)) { + radiusID = "atomicRadius_" + String.valueOf(uniqueRadii.size() + 1); + uniqueRadii.put(radius, radiusID); + } else { + radiusID = uniqueRadii.get(radius); + } + atomicRadii.add(radiusID); + + // --- Process atomic colors + processAtomColor(atom, AtomInterface.RGB_COLOR, uniqueColors, atomicColors, new float[]{0.5f, 0.5f, 0.5f}); + + // --- Process atomic Ambient colors (if any) + processAtomColor(atom, AtomInterface.AMBIENT_RGB_COLOR, uniqueAmbientColors, atomicAmbientColors, new float[]{0.3f, + 0.3f, 0.3f}); + } + + // --- Write unique atomic radii + out.write("\n// --- Unique atomic radii\n\n".getBytes()); + + Set set = uniqueRadii.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + Float value = (Float) me.getKey(); + String id = me.getValue().toString(); + out.write(("#declare " + id + "=" + value.floatValue() + ";\n").getBytes()); + } + + // --- Write unique atomic colors + out.write("\n// --- Unique atomic colors\n\n".getBytes()); + + int count = 0; + set = uniqueColors.entrySet(); + iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + Integer value = (Integer) me.getKey(); + Float[] color = (Float[]) me.getValue(); + ++count; + String id = "atomColor_" + count; + uniqueColorID.put(value, id); + out.write(("#declare " + id + " = " + "pigment { color red " + color[0] + " green " + color[1] + " blue " + color[2] + + " }\n").getBytes()); + } + + // --- Write unique atomic Ambient colors + out.write("\n// --- Unique atomic Ambient colors\n\n".getBytes()); + + count = 0; + set = uniqueAmbientColors.entrySet(); + iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + Integer value = (Integer) me.getKey(); + Float[] color = (Float[]) me.getValue(); + ++count; + String id = "atomAmbientColor_" + count; + uniqueAmbientColorID.put(value, id); + out.write(("#declare " + id + " = " + "< " + color[0] + ", " + color[1] + ", " + color[2] + " >;\n").getBytes()); + } + + // --- Second, find unique properties for bonds + Map uniqueBondRadii = new LinkedHashMap(molecule.getNumberOfBonds()); + Map uniqueBondColors = new LinkedHashMap(molecule.getNumberOfBonds()); + Map bondColorRef = new LinkedHashMap(molecule.getNumberOfBonds()); + List bondColors = new ArrayList(molecule.getNumberOfBonds()); + List bondRadii = new ArrayList(molecule.getNumberOfBonds()); + Map uniqueBondColorID = new HashMap(molecule.getNumberOfAtoms()); + float[] defaultBondColor = new float[]{ + 0.5f, 0.5f, 0.5f}; + + int bondRenderingStyle = BondInterface.CYLINDER_BICOLOR; + for (int i = 0; i < molecule.getNumberOfBonds(); i++) { + BondInterface bond = molecule.getBondInterface(i); + AtomInterface a1 = bond.getIAtomInterface(); + AtomInterface a2 = bond.getJAtomInterface(); + + float[] a1_color = Colors.get(a1); + float[] a2_color = Colors.get(a2); + + processColor(a1_color, uniqueBondColors, bondColors, defaultBondColor); + processColor(a2_color, uniqueBondColors, bondColors, defaultBondColor); + + Object obj = bond.getProperty(BondInterface.RENDERING_STYLE); + int bRendStyle = bondRenderingStyle; + if (obj instanceof Integer) { + bRendStyle = ((Integer) obj).intValue(); + } + + if (bRendStyle == BondInterface.CYLINDER_BICOLOR || bRendStyle == BondInterface.LINE_BICOLOR) { + bondColorRef.put(bond, new Integer[]{bondColors.get(2 * i), bondColors.get(2 * i + 1)}); + } + + // --- Process radius + Float R = (Float) bond.getProperty(BondInterface.CYLINDER_RADIUS); + if (R == null || bRendStyle == BondInterface.LINE_BICOLOR) { + R = defaulCylinerRadius; + } + + String radiusID = ""; + if (!uniqueBondRadii.containsKey(R)) { + radiusID = "bondRadius_" + String.valueOf(uniqueBondRadii.size() + 1); + uniqueBondRadii.put(R, radiusID); + } else { + radiusID = uniqueBondRadii.get(R); + } + bondRadii.add(radiusID); + + } + + // --- Write unique bond radii + out.write("\n// --- Unique bond radii\n\n".getBytes()); + + set = uniqueBondRadii.entrySet(); + iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + Float value = (Float) me.getKey(); + String id = me.getValue().toString(); + out.write(("#declare " + id + "=" + value.floatValue() + ";\n").getBytes()); + } + + // --- Write unique bond colors + out.write("\n// --- Unique bond colors\n\n".getBytes()); + + count = 0; + set = uniqueBondColors.entrySet(); + iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + Integer value = (Integer) me.getKey(); + Float[] color = (Float[]) me.getValue(); + ++count; + String id = "bondColor_" + count; + uniqueBondColorID.put(value, id); + out.write(("#declare " + id + " = " + "pigment { color red " + color[0] + " green " + color[1] + " blue " + color[2] + + " }\n").getBytes()); + } + + // --- Write other finishing parameters + out.write("\n// --- Finishing parameters\n\n".getBytes()); + + out.write(("// The " + phongID + " keyword controls the amount of the bright shiny spots\n").getBytes()); + out.write(("// on the object that are the color of the light source being reflected.\n").getBytes()); + out.write(("// " + phongID + "'s value is typically from 0.0 to 1.0,\n").getBytes()); + out.write(("// where 1.0 causes complete saturation to the light source's color\n").getBytes()); + out.write(("// at the brightest area (center) of the highlight. The value 0.0 gives no highlight.\n").getBytes()); + out.write("\n".getBytes()); + out.write(("#declare " + phongID + " = " + defaultPhongValue + ";\n").getBytes()); + + out.write("\n".getBytes()); + + out.write(("// The size of the highlight spot is defined by the " + phongSizeID + " value.\n").getBytes()); + out.write(("// The larger the phong size the tighter, or smaller, the highlight and the shinier the appearance.\n"). + getBytes()); + out.write(("// The smaller the phong size the looser, or larger, the highlight and the less glossy the appearance.\n"). + getBytes()); + out.write(("// Typical values range from 1.0 (very dull) to 250 (highly polished)\n").getBytes()); + out.write("\n".getBytes()); + out.write(("#declare " + phongSizeID + " = " + defaultPhongSizeValue + ";\n").getBytes()); + + out.write("\n".getBytes()); + + out.write(("// The value of " + diffuseID + " is used in a \"diffuse\" statement\n").getBytes()); + out.write(("// to control how much of the light coming directly from any light sources\n").getBytes()); + out.write(("// is reflected via diffuse reflection. For example, the value 0.7 means that 70% of the light seen\n"). + getBytes()); + out.write(("// comes from direct illumination from light sources.\n").getBytes()); + out.write("\n".getBytes()); + out.write(("#declare " + diffuseID + " = " + defaultDiffuseValue + ";\n").getBytes()); + + // --- Parameters for mesh objects + List meshTransparency = null; + if (meshObjects != null && meshObjects.size() > 0) { + + out.write("\n".getBytes()); + + out.write(("// Mesh parameters\n").getBytes()); + + out.write(("#declare " + meshDiffuseID + " = " + defaultMeshDiffuseValue + ";\n").getBytes()); + out.write(("#declare " + meshPhongID + " = " + defaultMeshPhongValue + ";\n").getBytes()); + out.write(("#declare " + meshPhongSizeID + " = " + defaultMeshPhongSizeValue + ";\n").getBytes()); + + out.write("\n".getBytes()); + meshTransparency = new ArrayList(meshObjects.size()); + for (int i = 0; i < meshObjects.size(); i++) { + String id = meshOpacityID + "_" + String.valueOf(i + 1); + meshTransparency.add(id); + out.write(("#declare " + id + " = " + meshObjects.get(i).getTransparency() + ";\n").getBytes()); + } + out.write("\n".getBytes()); + } + + // --- Finally start to write atoms + out.write("\n// --- Atomic spheres\n\n".getBytes()); + + out.write("union {\n".getBytes()); + + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface atom = molecule.getAtomInterface(i); + + Object obj = atom.getProperty(AtomInterface.VISIBLE); + if (obj != null && obj instanceof Boolean) { + if (!(Boolean) obj) { + continue; + } + } + + out.write("\n".getBytes()); + + String monomerName = molecule.getMonomerInterface(atom.getSubstructureNumber()).getName(); + + try { + out.write(("// Atom " + (i + 1) + " " + atom.getName() + "(" + ChemicalElements.getElementName(atom.getAtomicNumber()) + + ") " + monomerName + "-" + (atom.getSubstructureNumber() + 1) + "\n").getBytes()); + } catch (Exception ex) { + } + + out.write(("sphere { < " + atom.getX() + ", " + atom.getY() + ", " + atom.getZ() + ">, " + atomicRadii.get(i) + "\n"). + getBytes()); + //if (transformMatrix != null) { + // out.write(" transform { transformMatrix }\n".getBytes()); + //} + Integer colorHash = atomicColors.get(i); + String colorID = uniqueColorID.get(colorHash); + out.write((" texture { " + colorID + " }\n").getBytes()); + out.write(" finish { ".getBytes()); + + colorHash = atomicAmbientColors.get(i); + colorID = uniqueAmbientColorID.get(colorHash); + out.write((" ambient rgb " + colorID + " diffuse " + diffuseID + " phong " + phongID + " phong_size " + phongSizeID). + getBytes()); + out.write(" }\n".getBytes()); + + out.write("}\n".getBytes()); + } + + if (transformMatrix != null) { + out.write("\n transform { transformMatrix }\n".getBytes()); + } + out.write("}\n".getBytes()); + + // --- Writing bonds + //cylinder { < -5.244, 2.407, -18.493>, < -4.837, 2.627, -18.216>, 0.100 + //pigment { color red 0.000 green 1.000 blue 1.000 } + //finish { ambient 0.3 diffuse 0.7 phong 1 } + //} + for (int i = 0; i < molecule.getNumberOfBonds(); i++) { + BondInterface bond = molecule.getBondInterface(i); + AtomInterface a1 = bond.getIAtomInterface(); + AtomInterface a2 = bond.getJAtomInterface(); + + Object obj = bond.getProperty(BondInterface.RENDERING_STYLE); + int bRendStyle = bondRenderingStyle; + if (obj instanceof Integer) { + bRendStyle = ((Integer) obj).intValue(); + } + + Float R = (Float) bond.getProperty(BondInterface.CYLINDER_RADIUS); + if (R == null || bRendStyle == BondInterface.LINE_BICOLOR) { + R = defaulCylinerRadius; + } + + out.write("\n".getBytes()); + + try { + out.write(("// Bond : #" + (molecule.getAtomIndex(a1) + 1) + ":" + a1.getName() + "(" + + ChemicalElements.getElementName(a1.getAtomicNumber()) + + ") " + molecule.getMonomerInterface(a1.getSubstructureNumber()).getName() + "-" + + (a1.getSubstructureNumber() + 1) + " - #" + (molecule.getAtomIndex(a2) + 1) + ":" + a2.getName() + "(" + + ChemicalElements.getElementName(a2.getAtomicNumber()) + + ") " + molecule.getMonomerInterface(a2.getSubstructureNumber()).getName() + "-" + + (a2.getSubstructureNumber() + 1) + "\n").getBytes()); + } catch (Exception ex) { + } + + if (bRendStyle == BondInterface.CYLINDER_BICOLOR || bRendStyle == BondInterface.LINE_BICOLOR) { + + obj = bondColorRef.get(bond); + Integer[] colors = (Integer[]) obj; + + out.write(("cylinder { < " + a1.getX() + ", " + a1.getY() + ", " + a1.getZ() + ">,\n").getBytes()); + out.write((" < " + (0.5f * (a1.getX() + a2.getX())) + ", " + + (0.5f * (a1.getY() + a2.getY())) + ", " + (0.5f * (a1.getZ() + a2.getZ())) + ">, " + bondRadii.get(i) + + "\n").getBytes()); + if (transformMatrix != null) { + out.write(" transform { transformMatrix }\n".getBytes()); + } + String colorID = uniqueBondColorID.get(colors[0]); + out.write((" texture { " + colorID + " }\n").getBytes()); + //out.write( (" pigment { color red " + a1_color[0] + " green " + a1_color[1] + " blue " + a1_color[2] + "}\n"). + // getBytes()); + out.write(("finish { ambient 0.3 diffuse " + diffuseID + " phong " + phongID + " phong_size " + phongSizeID + + " }\n").getBytes()); + out.write("}\n".getBytes()); + + out.write("\n".getBytes()); + + out.write(("cylinder { < " + (0.5f * (a1.getX() + a2.getX())) + ", " + (0.5f * (a1.getY() + a2.getY())) + ", " + + (0.5f * (a1.getZ() + a2.getZ())) + ">,\n").getBytes()); + out.write((" < " + a2.getX() + ", " + a2.getY() + ", " + a2.getZ() + ">, " + bondRadii.get(i) + + "\n").getBytes()); + if (transformMatrix != null) { + out.write(" transform { transformMatrix }\n".getBytes()); + } + + colorID = uniqueBondColorID.get(colors[1]); + out.write((" texture { " + colorID + " }\n").getBytes()); + //out.write( (" pigment { color red " + a2_color[0] + " green " + a2_color[1] + " blue " + a2_color[2] + "}\n"). + // getBytes()); + out.write(("finish { ambient 0.3 diffuse " + diffuseID + " phong " + phongID + " phong_size " + phongSizeID + + " }\n").getBytes()); + out.write("}\n".getBytes()); + + } else if (bRendStyle == BondInterface.CYLINDER_MONOCOLOR) { + + } else if (bRendStyle == BondInterface.LINE_MONOCOLOR) { + + } + + } + + if (meshObjects != null && meshObjects.size() > 0) { + for (int i = 0; i < meshObjects.size(); i++) { + MeshObject mesh = meshObjects.get(i); + if (mesh.getObjectType() == MeshObject.TRIANGLES_MESH_OBJECT) { + out.write("mesh2 {\n".getBytes()); + + // --- Write vertices + Point3fInterface[] vertices = mesh.getVerticesAsArray(); + out.write(" vertex_vectors {\n".getBytes()); + out.write((" " + vertices.length + ",\n").getBytes()); + for (int j = 0; j < vertices.length / 3; j++) { + if (j != 0) { + out.write(",\n".getBytes()); + } + out.write((" <" + vertices[j * 3].getX() + ", " + vertices[j * 3].getY() + ", " + vertices[j * 3].getZ() + + ">, ").getBytes()); + out.write(("<" + vertices[j * 3 + 1].getX() + ", " + vertices[j * 3 + 1].getY() + ", " + vertices[j * 3 + + 1].getZ() + ">, ").getBytes()); + out.write(("<" + vertices[j * 3 + 2].getX() + ", " + vertices[j * 3 + 2].getY() + ", " + vertices[j * 3 + + 2].getZ() + ">").getBytes()); + } + out.write("\n }\n".getBytes()); + + // --- Write normals + List normals = mesh.getNormals(); + out.write(" normal_vectors {\n".getBytes()); + out.write((" " + normals.size() + ",\n").getBytes()); + for (int j = 0; j < normals.size() / 3; j++) { + if (j != 0) { + out.write(",\n".getBytes()); + } + out.write((" <" + normals.get(j * 3).getX() + ", " + normals.get(j * 3).getY() + ", " + + normals.get(j * 3).getZ() + + ">, ").getBytes()); + out.write(("<" + normals.get(j * 3 + 1).getX() + ", " + normals.get(j * 3 + 1).getY() + ", " + + normals.get(j * 3 + 1).getZ() + ">, ").getBytes()); + out.write(("<" + normals.get(j * 3 + 2).getX() + ", " + normals.get(j * 3 + 2).getY() + ", " + + normals.get(j * 3 + 2).getZ() + ">").getBytes()); + } + out.write("\n }\n".getBytes()); + + // -- Write colors + Color[] colors = mesh.getColorsAsArray(); + out.write(" texture_list {\n".getBytes()); + out.write((" " + colors.length + ",\n").getBytes()); + for (int j = 0; j < colors.length; j++) { + float red = ((float) colors[j].getRed()) / 255.0f; + float green = ((float) colors[j].getGreen()) / 255.0f; + float blue = ((float) colors[j].getBlue()) / 255.0f; + String ambient = " < " + (red * 0.2f) + ", " + (green * 0.2f) + ", " + (blue * 0.2f) + "> "; + out.write((" texture { pigment { rgbt <" + red + ", " + green + ", " + blue + ", " + + meshTransparency.get(i) + "> }\n").getBytes()); + out.write((" finish { ambient " + ambient + " diffuse " + meshDiffuseID + + " phong " + meshPhongID + " phong_size " + meshPhongSizeID + " }}\n").getBytes()); + } + out.write("\n }\n".getBytes()); + + // --- Write face indices + List faces = mesh.getFaceIndices(); + out.write(" face_indices {\n".getBytes()); + out.write((" " + faces.size() + ",\n").getBytes()); + for (int j = 0; j < faces.size(); j++) { + if (j != 0) { + out.write(",\n".getBytes()); + } + + FaceIndices face = faces.get(j); + out.write((" < " + face.i + ", " + face.j + ", " + face.k + ">, " + face.i + ", " + face.j + ", " + face.k). + getBytes()); + } + out.write("\n }\n".getBytes()); + + if (transformMatrix != null) { + out.write("\n transform { transformMatrix }\n".getBytes()); + } + + out.write("}\n".getBytes()); + } + + } + } + + out.close(); + } catch (IOException e) { + throw e; + } + + } + + private void processColor(Object colorInfo, Map uniqueColors, List atomicColors, float[] defaultColor) { + float red = defaultColor[0], green = defaultColor[1], blue = defaultColor[2]; + Integer colorHash = -1; + if (colorInfo != null) { + if (colorInfo instanceof Integer[]) { + Integer[] c = (Integer[]) colorInfo; + red = (float) c[0] / 255.0f; + green = (float) c[1] / 255.0f; + blue = (float) c[2] / 255.0f; + colorHash = this.getColorHash(c[0], c[1], c[2]); + } else if (colorInfo instanceof int[]) { + int[] c = (int[]) colorInfo; + red = (float) c[0] / 255.0f; + green = (float) c[1] / 255.0f; + blue = (float) c[2] / 255.0f; + colorHash = this.getColorHash(c[0], c[1], c[2]); + } else if (colorInfo instanceof Float[]) { + Float[] c = (Float[]) colorInfo; + red = c[0]; + green = c[1]; + blue = c[2]; + } else if (colorInfo instanceof float[]) { + float[] c = (float[]) colorInfo; + red = c[0]; + green = c[1]; + blue = c[2]; + } + + } + + if (colorHash < 0) { + colorHash = getColorHash(red, green, blue); + } + + //String pigment = ""; + if (!uniqueColors.containsKey(colorHash)) { + uniqueColors.put(colorHash, new Float[]{red, green, blue}); + //pigment = "pigment { color red "+red+" green "+green+" blue "+blue+" }"; + } + atomicColors.add(colorHash); + } + + private void processAtomColor(AtomInterface atom, String colorLabel, Map uniqueColors, List atomicColors, + float[] defaultColor) { + Object obj = atom.getProperty(colorLabel); + processColor(obj, uniqueColors, atomicColors, defaultColor); + + } + + Integer getColorHash(Integer red, Integer green, Integer blue) { + Integer colorHash = -1; + colorHash = red << 16 | green << 8 | blue; + return colorHash; + } + + Integer getColorHash(int red, int green, int blue) { + Integer colorHash = -1; + colorHash = red << 16 | green << 8 | blue; + return colorHash; + } + + Integer getColorHash(float red, float green, float blue) { + Integer colorHash = -1; + int r = (int) (red * 255.0f); + int g = (int) (green * 255.0f); + int b = (int) (blue * 255.0f); + colorHash = r << 16 | g << 8 | b; + return colorHash; + } + + Integer getColorHash(Float red, Float green, Float blue) { + Integer colorHash = -1; + int r = (int) (red * 255.0f); + int g = (int) (green * 255.0f); + int b = (int) (blue * 255.0f); + colorHash = r << 16 | g << 8 | b; + return colorHash; + } + + public void addMeshObject(MeshObject mesh) { + if (meshObjects == null) { + meshObjects = new ArrayList(); + } + meshObjects.add(mesh); + } +} diff --git a/src/main/java/cct/qchem/QChem.java b/src/main/java/cct/qchem/QChem.java new file mode 100644 index 0000000..a11f0cc --- /dev/null +++ b/src/main/java/cct/qchem/QChem.java @@ -0,0 +1,1026 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.qchem; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.ChemicalElements; + +/** + *

Title:

+ * + *

Description:

+ * Written based on version 3.1 manual + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class QChem { + + static final double ONE_BOHR = 0.529177249; // In Angstrom + static final float DEGREES_TO_RADIANS = (float) (Math.PI / 180.0); + + static final String batchSeparator = "@@@"; + + static final String endSection = "$END"; + static final String commentSection = "$COMMENT"; + static final String remSection = "$REM"; + static final String moleculeSection = "$MOLECULE"; + static final String basisSection = "$BASIS"; // User{de ned basis set information (see Chapter 7). + static final String ecpSection = "$ECP"; // User{de ned e ective core potentials (see Chapter 8). + static final String external_chargesSection = "$EXTERNAL_CHARGES"; // External charges and their positions. + static final String intraculeSection = "$INTRACULE"; // Intracule parameters (see Chapter 10). + static final String isotopesSection = "$ISOTOPES"; // Isotopic substitutions for vibrational calculations (see Chapter 10). + static final String multipole_fieldSection = "$MLTIPOLE_FIELD"; // Details of a multipole eld to apply. + static final String nboSection = "$NBO"; // Natural Bond Orbital package. + static final String occupiedSection = "$OCCUPIED"; // Guess orbitals to be occupied. + static final String optSection = "$OPT"; // Constraint de nitions for geometry optimizations. + static final String svpSection = "$SVP"; // Special parameters for the SS(V)PE module. + static final String svpirfSection = "$SVPIRF"; // Initial guess for SS(V)PE) module. + static final String plotsSection = "$PLOTS"; // Generate plotting information over a grid of points (see Chapter + static final String van_der_waalsSection = "$VAN_DER_WAALS"; // User{de ned atomic radii for Langevin dipoles solvation (see Chapter + static final String xcSection = "$XC"; // functional Details of user{de ned DFT exchange{correlation functionals. + + static final Set validSections = new HashSet (); + static final Logger logger = Logger.getLogger(QChem.class.getCanonicalName()); + + static { + validSections.add(endSection); + validSections.add(commentSection); + validSections.add(remSection); + validSections.add(moleculeSection); + validSections.add(basisSection); + validSections.add(ecpSection); + validSections.add(external_chargesSection); + validSections.add(intraculeSection); + validSections.add(isotopesSection); + validSections.add(multipole_fieldSection); + validSections.add(nboSection); + validSections.add(occupiedSection); + validSections.add(optSection); + validSections.add(svpSection); + validSections.add(svpirfSection); + validSections.add(plotsSection); + validSections.add(van_der_waalsSection); + validSections.add(xcSection); + + } + + boolean yesMoleculeSection = false; + boolean yesRemSection = false; + + int netCharge = 0; + int spinMultiplicity = 1; + boolean cartesianCoords = true; + List Atoms = new ArrayList (); + + Map remSectionParameters = new HashMap (); + + public QChem() { + } + + public void getMolecularInterface(MoleculeInterface molec) throws + Exception { + if (molec == null) { + throw new Exception(this.getClass().getCanonicalName() + + " : molec == null"); + } + if (Atoms.size() < 1) { + throw new Exception(this.getClass().getCanonicalName() + + " : no QChem atoms"); + } + + float factor = 1.0f; + if (remSectionParameters.containsKey("INPUT_BOHR")) { + String value = (String) remSectionParameters.get("INPUT_BOHR"); + try { + boolean bohr = Boolean.parseBoolean(value.toLowerCase()); + if (bohr) { + factor = (float) ONE_BOHR; + } + } + catch (Exception ex) { + + } + + } + + molec.addProperty(MoleculeInterface.ChargeProperty, new Integer(netCharge)); + molec.addProperty(MoleculeInterface.MultiplicityProperty, new Integer(spinMultiplicity)); + + molec.addMonomer("QChem"); + + for (int i = 0; i < Atoms.size(); i++) { + QChemAtom ga = Atoms.get(i); + AtomInterface atom = molec.getNewAtomInstance(); + atom.setName(ga.getName()); + atom.setAtomicNumber(ga.getAtomicNumber()); + atom.setXYZ(ga.getX() * factor, ga.getY() * factor, ga.getZ() * factor); + molec.addAtom(atom); + } + } + + public void parseQChemInput(String inputfile, int fileType) throws + Exception { + + String line; + BufferedReader in = null; + + if (fileType == 0) { // Read from file + try { + in = new BufferedReader(new FileReader(inputfile)); + } + catch (Exception ex) { + throw ex; + } + } + else if (fileType == 1) { // Read from String + in = new BufferedReader(new StringReader(inputfile)); + } + else { + throw new Exception( + "parseQChemInput: INTERNAL ERROR: Unknown file type"); + } + + try { + //BufferedReader in = new BufferedReader(new FileReader(filename)); + + while ( (line = in.readLine()) != null) { + line = line.trim(); + + if (line.length() < 1) { // Blank line + continue; + } + + if (line.startsWith(batchSeparator)) { + break; + } + + if (!line.startsWith("$")) { + continue; + } + + if (line.startsWith("$")) { // Get section + StringTokenizer st = new StringTokenizer(line, " \t=,"); + String sectionName = st.nextToken().toUpperCase(); + if (sectionName.equalsIgnoreCase(moleculeSection)) { + this.readMoleculeSection(in); + } + else if (sectionName.equalsIgnoreCase(remSection)) { + this.readRemSection(in); + } + else { + if (!validSections.contains(sectionName)) { + System.err.println("parseQChemInput: Error: Unknown input section " + sectionName + " Ignored..."); + } + readSection(in, sectionName); + } + } + else { + in.close(); + throw new Exception( + "parseQChemInput: Error: looking for section, got " + line); + } + + } + + in.close(); + } + catch (IOException e) { + throw e; + } + } + + void readRemSection(BufferedReader in) throws Exception { + String line; + while ( (line = in.readLine()) != null) { + line = line.trim().toUpperCase(); + if (line.startsWith(endSection)) { + return; + } + else if (line.startsWith("!") || line.length() < 1) { + continue; + } + + StringTokenizer st = new StringTokenizer(line, " \t=,"); + + if (st.countTokens() < 2) { + System.err.println("readRemSection: line should have at least two tokens. Got " + line + " Ignored..."); + continue; + } + + remSectionParameters.put(st.nextToken(), st.nextToken()); + + } + + throw new Exception( + "parseQChemInput: Error: din't find $end keyword for $rem section"); + } + + void readSection(BufferedReader in, String section) throws Exception { + String line; + if (section.equalsIgnoreCase(remSection)) { + yesRemSection = true; + } + + while ( (line = in.readLine()) != null) { + line = line.trim().toUpperCase(); + if (line.startsWith(endSection)) { + return; + } + } + throw new Exception( + "parseQChemInput: Error: din't find $end keyword for input section " + section); + } + + /** + * Reads $molecule section + * @param in BufferedReader + * @throws Exception + */ + void readMoleculeSection(BufferedReader in) throws Exception { + yesMoleculeSection = true; + boolean endSectionFound = false; + Map atomNames = new HashMap (100); + Map symbolicStrings = new HashMap (300); + + String line; + if ( (line = in.readLine()) == null) { + throw new Exception( + "Unexpected end-of-file while reading net charge and the spin multiplicity in $molecule section"); + } + + StringTokenizer st = new StringTokenizer(line, " \t=,"); + + String charge = ""; + if (st.countTokens() >= 1) { + charge = st.nextToken(); + if (charge.equalsIgnoreCase("READ")) { + throw new Exception( + "Cannot read molecular geometry from another file"); + } + } + + if (st.countTokens() < 1) { + throw new Exception( + "Expecting two integer numbers for net charge and the spin multiplicity in $molecule section. Got " + line); + } + + try { + netCharge = Integer.parseInt(charge); + spinMultiplicity = Integer.parseInt(st.nextToken()); + } + catch (Exception ex) { + throw new Exception( + "Error parsing net charge or the spin multiplicity in $molecule section.\n Expecting two integer numbers. Got " + line); + } + + // --- Start to read coordinates + + while ( (line = in.readLine()) != null) { + line = line.trim().toUpperCase(); + + if (line.length() < 1) { + break; // End of input + } + else if (line.startsWith(endSection)) { + endSectionFound = true; + break; + } + + st = new StringTokenizer(line, " \t,"); + + // --- for the first atom determine input format + + if (Atoms.size() == 0) { + if (st.countTokens() == 1) { // Z-matrix + cartesianCoords = false; + } + else if (st.countTokens() == 4) { // Cartesians + cartesianCoords = true; + } + else { + throw new Exception( + "Input line for the first atom should consist of either 1 or 4 tokens. Got " + line); + } + } + + // --- Error check + + if (cartesianCoords && st.countTokens() < 4) { + throw new Exception( + "Expecting at least 4 tokens for the " + (Atoms.size() + 1) + " atom. Got " + line); + } + else if (!cartesianCoords) { + if (Atoms.size() == 1 && st.countTokens() < 3) { + throw new Exception( + "Expecting at least 3 tokens for the " + (Atoms.size() + 1) + " atom. Got " + line); + } + else if (Atoms.size() == 2 && st.countTokens() < 5) { + throw new Exception( + "Expecting at least 5 tokens for the " + (Atoms.size() + 1) + " atom. Got " + line); + } + else if (Atoms.size() > 2 && st.countTokens() < 7) { + throw new Exception( + "Expecting at least 7 tokens for the " + (Atoms.size() + 1) + " atom. Got " + line); + } + } + + // --- Start to read atom + + QChemAtom atom = new QChemAtom(); + + String token = st.nextToken(); + + boolean isNumber = false; + int element = 0; + try { + element = Integer.parseInt(token); + isNumber = true; + } + catch (Exception ex) { + isNumber = false; + } + + atom.setName(token); + if (isNumber) { + atom.setAtomicNumber(element); + } + else { + atom.setAtomicNumber(getAtomicNumber(atom.getName())); + } + + // --- check atom name for uniqueness + + if (atomNames.containsKey(atom.getName())) { + // --- it's not unique + atomNames.put(atom.getName(), new Integer( -1)); + } + else { + atomNames.put(atom.getName(), new Integer(Atoms.size())); + } + + // --- Case for cartesian coordinates + + if (cartesianCoords) { + for (int i = 0; i < 3; i++) { + token = st.nextToken(); + + isNumber = true; + float value = 0; + + try { + value = Float.parseFloat(token); + } + catch (Exception ex) { + isNumber = false; + } + + // --- if it's a parameter + if (!isNumber) { + String symbolic = token; + if (token.startsWith("-")) { + symbolic = token.substring(1); + } + if (!symbolicStrings.containsKey(symbolic)) { + symbolicStrings.put(symbolic, null); + } + + switch (i) { + case 0: + atom.setBondLength(token); + break; + case 1: + atom.setAlpha(token); + break; + case 2: + atom.setBeta(token); + break; + } + } + else { + switch (i) { + case 0: + atom.setBondLength(value); + break; + case 1: + atom.setAlpha(value); + break; + case 2: + atom.setBeta(value); + break; + } + } + } + + Atoms.add(atom); + continue; + } + + // --- Code below only for Z-matrix input + + // --- Special case, Z-matrix, 1st atom + + if (!cartesianCoords && Atoms.size() == 0) { + Atoms.add(atom); + continue; + } + + // --- reading reference atom A + + token = st.nextToken(); + + // --- if it's atom's name + + isNumber = true; + int number = 0; + + try { + number = Integer.parseInt(token); + } + catch (Exception ex) { + isNumber = false; + } + + if (isNumber) { // --- If it's a number + if (number < 1 || number > Atoms.size()) { + throw new Exception("Wrong reference atom A value " + number + + " for " + (Atoms.size() + 1) + + " atom : it should be between 1 and " + + Atoms.size()); + } + atom.set_i1(number - 1); + } + else { // --- If it's an atom + if (atomNames.containsKey(token)) { + Integer i = atomNames.get(token); + atom.set_i1(i); + } + else { + throw new Exception("Wrong reference atom A value " + token + + " for " + (Atoms.size() + 1) + + " atom : no atom with such name was previously specified"); + } + } + + // --- Reading Bond Length + + if (!st.hasMoreTokens()) { + throw new Exception("Expecting bond length value"); + } + token = st.nextToken(); + + isNumber = true; + float value = 0; + + try { + value = Float.parseFloat(token); + } + catch (Exception ex) { + isNumber = false; + } + + // --- if it's a parameter + if (!isNumber) { + String symbolic = token; + if (token.startsWith("-")) { + symbolic = token.substring(1); + } + if (!symbolicStrings.containsKey(symbolic)) { + symbolicStrings.put(symbolic, null); + } + + atom.setBondLength(token); + } + else { + atom.setBondLength(value); + } + + // --- Special case, Z-matrix, 2nd atom + + if (Atoms.size() == 1) { + Atoms.add(atom); + continue; + } + + // --- Reading reference Atom B + + if (!st.hasMoreTokens()) { + throw new Exception("Expecting reference Atom B"); + } + token = st.nextToken(); + + // --- if it's atom's name + + isNumber = true; + + try { + number = Integer.parseInt(token); + } + catch (Exception ex) { + isNumber = false; + } + + if (isNumber) { // --- If it's a number + if (number < 1 || number > Atoms.size() || + number == atom.get_i1() + 1) { + throw new Exception("Wrong reference Atom B value " + number + " for " + + (Atoms.size() + 1) + + " atom : it should be between 1 and " + + Atoms.size() + " and not " + + (atom.get_i1() + 1)); + } + atom.set_i2(number - 1); + } + else { // --- If it's an atom + if (atomNames.containsKey(token)) { + Integer i = atomNames.get(token); + atom.set_i2(i); + } + else { + throw new Exception("Wrong reference Atom B value " + token + + " for " + (Atoms.size() + 1) + + " atom : no atom with such name was previously specified"); + } + } + + // --- Reading Angle + + if (!st.hasMoreTokens()) { + throw new Exception("Expecting angle value"); + } + token = st.nextToken(); + + isNumber = true; + + try { + value = Float.parseFloat(token); + } + catch (Exception ex) { + isNumber = false; + } + + // --- if it's a parameter + if (!isNumber) { + String symbolic = token; + if (token.startsWith("-")) { + symbolic = token.substring(1); + } + if (!symbolicStrings.containsKey(symbolic)) { + symbolicStrings.put(symbolic, null); + } + + atom.setAlpha(token); + } + else { + atom.setAlpha(value); + } + + if (Atoms.size() == 2) { + Atoms.add(atom); + continue; + } + + // --- Reading reference atom C + + if (!st.hasMoreTokens()) { + throw new Exception("Expecting reference atom C"); + } + token = st.nextToken(); + + // --- if it's atom's name + + isNumber = true; + + try { + number = Integer.parseInt(token); + } + catch (Exception ex) { + isNumber = false; + } + + // --- if it's atom's name + + if (!isNumber) { + if (atomNames.containsKey(token)) { + Integer i = atomNames.get(token); + atom.set_i3(i); + } + else { + throw new Exception("Wrong reference atom C value " + token + + " for " + (Atoms.size() + 1) + + " atom : no atom with such name was previously specified"); + } + } + // --- If it's a number + else { + if (number < 1 || number > Atoms.size() || + number == atom.get_i1() + 1 || + number == atom.get_i2() + 1) { + throw new Exception("Wrong reference atom C value " + number + + " for " + (Atoms.size() + 1) + + " atom : it should be between 1 and " + + Atoms.size() + " and not " + + (atom.get_i1() + 1) + " or " + + (atom.get_i2() + 1)); + } + atom.set_i3(number - 1); + } + + // --- Reading torsion angle + + if (!st.hasMoreTokens()) { + throw new Exception("Expecting torsion angle"); + } + token = st.nextToken(); + + isNumber = true; + + try { + value = Float.parseFloat(token); + } + catch (Exception ex) { + isNumber = false; + } + + // --- if it's a parameter + if (!isNumber) { + String symbolic = token; + if (token.startsWith("-")) { + symbolic = token.substring(1); + } + if (!symbolicStrings.containsKey(symbolic)) { + symbolicStrings.put(symbolic, null); + } + + atom.setBeta(token); + } + else { + atom.setBeta(value); + } + + Atoms.add(atom); + + } // --- End of while/ reading atoms + + // --- Resolve Parameters + + if (symbolicStrings.size() > 0) { + logger.info("Expecting " + symbolicStrings.size() + + " unique symbolic strings"); + if (endSectionFound) { + throw new Exception( + "Unexpected end of $molecule section. Excepting parameters"); + } + + // --- Start to read symbolic strings + + while ( (line = in.readLine()) != null) { + line = line.trim().toUpperCase(); + + st = new StringTokenizer(line, "=, \t"); + + if (st.countTokens() < 1) { + continue; + } + + String currentString = st.nextToken(); + + if (currentString.equalsIgnoreCase(endSection)) { + break; + } + + if (st.countTokens() < 1) { + throw new Exception( + "Expecting at least two values for symbolic strings"); + } + + // --- Read symbol + + if (!symbolicStrings.containsKey(currentString)) { + System.err.println( + "Warning: atom string parameters do not have string " + + currentString); + continue; + } + + // --- Read value + + String token = st.nextToken(); + try { + Float f = new Float(token); + symbolicStrings.put(currentString, f); + } + catch (Exception ex) { + throw new Exception("Wrong value for symbolic string " + token); + } + } + } + + if (symbolicStrings.size() > 0) { + try { + resolveSymbolicStrings(symbolicStrings, Atoms); + } + catch (Exception ex) { + throw ex; + } + } + + // --- Convert to cartesian coordinates + + if (cartesianCoords) { + for (int i = 0; i < Atoms.size(); i++) { + QChemAtom atom = Atoms.get(i); + atom.setX(atom.getBondLength()); + atom.setY(atom.getAlpha()); + atom.setZ(atom.getBeta()); + } + } + else { + fromZMatrixToCartesians(Atoms); + } + } + + /** + * Expects bond length in angstroms + * @param atoms ArrayList + * @throws Exception + */ + public static void fromZMatrixToCartesians(List atoms) throws + Exception { + int i, ii, jj, kk, ll; + int natoms = atoms.size(); + QChemAtom a, a1, a2, a3; + float xyz[] = new float[3], x1[], x2[], x3[]; + + double SIN2, COS2, SIN3, COS3, + VT[] = new double[3], V1[] = new double[3], + V2[] = new double[3]; + double R2, + V3[] = new double[3], VA1, VB1, VC1, R3, V[] = new double[3]; + + if (natoms < 1) { + return; + } + + float factor = 1.0f; + + // --- The first atom. Put it into the origin + + QChemAtom atom = atoms.get(0); + atom.setXYZ(0, 0, 0); + + if (natoms < 2) { + return; + } + + // --- ther second atom: put it along the X-axis + + atom = atoms.get(1); + atom.setXYZ(atom.getBondLength() * factor, 0, 0); + + if (natoms < 3) { + return; + } + + // --- Third atom (put it into the XOY plane + + a = atoms.get(2); + + //x1 = (float[]) cartesians.get(a.ijk[0] - 1); + x1 = new float[3]; + int index = a.get_i1(); + a1 = atoms.get(index); + x1[0] = a1.getX(); + x1[1] = a1.getY(); + x1[2] = a1.getZ(); + + xyz[2] = 0.0f; // Z-coordinate + + if (index == 0) { // Connected to the first atom + //logger.info("To the 1st"); + xyz[0] = a.getBondLength() * factor * + (float) Math.cos( (a.getAlpha() * DEGREES_TO_RADIANS)); // So, we put it along X-axis + xyz[1] = a.getBondLength() * factor * + (float) Math.sin( (double) (a.getAlpha() * DEGREES_TO_RADIANS)); + } + else { + //logger.info("To the 2nd"); + xyz[0] = x1[0] - + a.getBondLength() * factor * + (float) Math.cos( (double) (a.getAlpha() * DEGREES_TO_RADIANS)); // So, we put it along X-axis + xyz[1] = -a.getBondLength() * factor * + (float) Math.sin( (double) (a.getAlpha() * DEGREES_TO_RADIANS)); + } + + a.setXYZ(xyz[0], xyz[1], xyz[2]); + + // Other atoms + + for (i = 3; i < natoms; i++) { + + a = atoms.get(i); + + a1 = atoms.get(a.get_i1()); + a2 = atoms.get(a.get_i2()); + a3 = atoms.get(a.get_i3()); + + x1 = a1.xyz; + x2 = a2.xyz; + x3 = a3.xyz; + + SIN2 = Math.sin( (double) (a.getAlpha() * DEGREES_TO_RADIANS)); + COS2 = Math.cos( (double) (a.getAlpha() * DEGREES_TO_RADIANS)); + SIN3 = Math.sin( (double) (a.getBeta() * DEGREES_TO_RADIANS)); + COS3 = Math.cos( (double) (a.getBeta() * DEGREES_TO_RADIANS)); + + VT[0] = a.getBondLength() * factor * COS2; + VT[1] = a.getBondLength() * factor * SIN2 * SIN3; + VT[2] = a.getBondLength() * factor * SIN2 * COS3; + + V1[0] = x3[0] - x2[0]; + V1[1] = x3[1] - x2[1]; + V1[2] = x3[2] - x2[2]; + + V2[0] = x2[0] - x1[0]; + V2[1] = x2[1] - x1[1]; + V2[2] = x2[2] - x1[2]; + + R2 = Math.sqrt(V2[0] * V2[0] + V2[1] * V2[1] + V2[2] * V2[2]); + + V3[0] = V1[1] * V2[2] - V1[2] * V2[1]; + V3[1] = V1[2] * V2[0] - V1[0] * V2[2]; + V3[2] = V1[0] * V2[1] - V1[1] * V2[0]; + + R3 = Math.sqrt(V3[0] * V3[0] + V3[1] * V3[1] + V3[2] * V3[2]); + + V2[0] = V2[0] / R2; + V2[1] = V2[1] / R2; + V2[2] = V2[2] / R2; + + V3[0] = V3[0] / R3; + V3[1] = V3[1] / R3; + V3[2] = V3[2] / R3; + + V[0] = V2[1] * V3[2] - V2[2] * V3[1]; + V[1] = V2[2] * V3[0] - V2[0] * V3[2]; + V[2] = V2[0] * V3[1] - V2[1] * V3[0]; + + VA1 = V2[0] * VT[0] + V3[0] * VT[1] + V[0] * VT[2]; + VB1 = V2[1] * VT[0] + V3[1] * VT[1] + V[1] * VT[2]; + VC1 = V2[2] * VT[0] + V3[2] * VT[1] + V[2] * VT[2]; + + xyz[0] = x1[0] + (float) VA1; + xyz[1] = x1[1] + (float) VB1; + xyz[2] = x1[2] + (float) VC1; + + a.setXYZ(xyz); + } + } + + private void resolveSymbolicStrings(Map symbolicStrings, + List atoms) throws Exception { + + // --- Error check + + boolean error = false; + String Errors = ""; + Set set = symbolicStrings.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String string = me.getKey().toString(); + Object value = me.getValue(); + + if (value == null) { + error = true; + Errors += "No value for string " + string + "\n"; + } + else { + logger.info(me.getKey().toString() + "=" + + me.getValue().toString()); + } + } + + if (error) { + throw new Exception(Errors); + } + + // --- resolve strings + + int nsymbols = 0; + for (int i = 0; i < atoms.size(); i++) { + QChemAtom atom = atoms.get(i); + + String string = atom.getBondLengthPar(); + if (string != null) { + boolean negative = string.startsWith("-"); + if (negative) { + string = string.substring(1); + } + Float f = symbolicStrings.get(string); + if (negative) { + f = -f; + } + atom.setBondLength(f); + } + + string = atom.getAlphaPar(); + if (string != null) { + boolean negative = string.startsWith("-"); + if (negative) { + string = string.substring(1); + } + Float f = symbolicStrings.get(string); + if (negative) { + f = -f; + } + atom.setAlpha(f); + } + + string = atom.getBetaPar(); + if (string != null) { + boolean negative = string.startsWith("-"); + if (negative) { + string = string.substring(1); + } + Float f = symbolicStrings.get(string); + if (negative) { + f = -f; + } + atom.setBeta(f); + } + } + + } + + public static int getAtomicNumber(String symbol) { + byte[] chars = symbol.getBytes(); + String atom = ""; + + if (symbol.length() == 1) { + return ChemicalElements.getAtomicNumber(symbol); + } + else if (chars.length > 1 && chars[1] >= '0' && chars[1] <= '9') { + atom = symbol.substring(0, 1); + } + else { + atom = symbol.substring(0, 2); + } + + return ChemicalElements.getAtomicNumber(atom); + } + +} diff --git a/src/main/java/cct/qchem/QChemAtom.java b/src/main/java/cct/qchem/QChemAtom.java new file mode 100644 index 0000000..177066b --- /dev/null +++ b/src/main/java/cct/qchem/QChemAtom.java @@ -0,0 +1,217 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.qchem; + +import cct.interfaces.Point3fInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class QChemAtom { + String name; + int atomicNumber; + float xyz[] = new float[3]; + float bondLength, alpha, beta; + String bondLengthPar = null, alphaPar = null, betaPar = null; + int i1 = -1, i2 = -1, i3 = -1; + + public void setName(String _name) { + name = _name; + } + + public String getName() { + return name; + } + + public int getAtomicNumber() { + return atomicNumber; + } + + public void setAtomicNumber(int number) { + atomicNumber = number; + } + + public void setBondLength(float bond) { + bondLength = bond; + } + + public float getBondLength() { + return bondLength; + } + + public void setBondLength(String bond) { + bondLengthPar = bond; + } + + public String getBondLengthPar() { + return bondLengthPar; + } + + public void setAlpha(float a) { + alpha = a; + } + + public float getAlpha() { + return alpha; + } + + public void setAlpha(String a) { + alphaPar = a; + } + + public String getAlphaPar() { + return alphaPar; + } + + public void setBeta(float b) { + beta = b; + } + + public float getBeta() { + return beta; + } + + public void setBeta(String b) { + betaPar = b; + } + + public String getBetaPar() { + return betaPar; + } + + public void set_i1(int i1) { + this.i1 = i1; + } + + public int get_i1() { + return this.i1; + } + + public void set_i2(int i2) { + this.i2 = i2; + } + + public int get_i2() { + return this.i2; + } + + public void set_i3(int i3) { + this.i3 = i3; + } + + public int get_i3() { + return this.i3; + } + + public void setX(float x) { + xyz[0] = x; + } + + public void setX(double x) { + xyz[0] = (float) x; + } + + public void setY(float y) { + xyz[1] = y; + } + + public void setY(double y) { + xyz[1] = (float) y; + } + + public void setZ(float z) { + xyz[2] = z; + } + + public void setZ(double z) { + xyz[2] = (float) z; + } + + public float getX() { + return xyz[0]; + } + + public float getY() { + return xyz[1]; + } + + public float getZ() { + return xyz[2]; + } + + public double distanceTo(Point3fInterface point) { + return Math.sqrt( (xyz[0] - point.getX()) * (xyz[0] - point.getX()) + + (xyz[1] - point.getY()) * (xyz[1] - point.getY()) + + (xyz[2] - point.getZ()) * (xyz[2] - point.getZ())); + } + + public void setXYZ(float xx, float yy, float zz) { + xyz[0] = xx; + xyz[1] = yy; + xyz[2] = zz; + } + + public void setXYZ(float xx[]) { + xyz[0] = xx[0]; + xyz[1] = xx[1]; + xyz[2] = xx[2]; + } + + public void setXYZ(Point3fInterface xyz) { + this.xyz[0] = xyz.getX(); + this.xyz[1] = xyz.getY(); + this.xyz[2] = xyz.getZ(); + } + + public void subtract(Point3fInterface a1, Point3fInterface a2) { + xyz[0] = a1.getX() - a2.getX(); + xyz[1] = a1.getY() - a2.getY(); + xyz[2] = a1.getZ() - a2.getZ(); + + } + +} diff --git a/src/main/java/cct/qchem/QChemOutput.java b/src/main/java/cct/qchem/QChemOutput.java new file mode 100644 index 0000000..b43d5e7 --- /dev/null +++ b/src/main/java/cct/qchem/QChemOutput.java @@ -0,0 +1,354 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.qchem; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class QChemOutput { + + Map outputResume = new LinkedHashMap (); + boolean normalTermination = false; + + List Atoms = new ArrayList (); + + public QChemOutput() { + } + + public static void main(String[] args) { + QChemOutput qchemoutput = new QChemOutput(); + } + + public void parseQChemOutputFile(String filename, boolean update) throws Exception { + String line, token; + StringTokenizer st; + try { + BufferedReader in = new BufferedReader(new FileReader(filename)); + + while ( (line = in.readLine()) != null) { + + if (line.startsWith("User input:")) { + // --- User input ... + } + + else if (line.contains("Q-Chem") && line.contains("Version")) { + this.outputResume.put("Q_Chem version", line); + } + + else if (line.contains("Standard Nuclear Orientation (Angstroms)") || + line.contains("Nuclear coordinates and velocities (a.u.)")) { + float factor = 1.0f; + if (line.contains("(a.u.)")) { + factor = 0.529177249f; + } + int linesToSkip = 2; + if (line.contains("Nuclear coordinates and velocities (a.u.)")) { + linesToSkip = 3; + } + + // --- Skip n lines + for (int i = 0; i < linesToSkip; i++) { + if ( (line = in.readLine()) == null) { + break; + } + } + if (line == null) { + break; + } + + line = ""; + List atoms = new ArrayList (); // local array + while ( (line = in.readLine()) != null && (!line.contains("--------------------"))) { + + st = new StringTokenizer(line, " \t"); + if (st.countTokens() < 5) { + System.err.println("Reading Standard Nuclear Orientation : expecting 5 tokens, got " + line); + break; + } + + QChemAtom atom = new QChemAtom(); + + // --- skip the first token + st.nextToken(); + + // --- Atom name + + token = st.nextToken(); + atom.setName(token); + atom.setAtomicNumber(QChem.getAtomicNumber(token)); + + // --- x,y,z coordinates + + try { + token = st.nextToken(); + atom.setX(Float.parseFloat(token) * factor); + token = st.nextToken(); + atom.setY(Float.parseFloat(token) * factor); + token = st.nextToken(); + atom.setZ(Float.parseFloat(token) * factor); + + } + catch (Exception ex) { + System.err.println("Reading atom's coordinates in Standard Nuclear Orientation: error parsing coordinate: " + + line); + break; + } + + atoms.add(atom); + + } + + if (Atoms.size() == 0) { + Atoms = atoms; + } + else if (Atoms.size() == atoms.size()) { + Atoms = atoms; + } + + if (line == null) { + break; + } + } + + else if (line.contains("Molecular Point Group")) { + this.outputResume.put("Molecular Point Group", line); + } + else if (line.contains("Largest Abelian Subgroup")) { + this.outputResume.put("Largest Abelian Subgroup", line); + } + + else if (line.contains("There are") && line.contains("alpha and")) { + this.outputResume.put("electrons", line); + } + else if (line.contains("Requested basis set is")) { + this.outputResume.put("Requested basis set is", line); + } + + else if (line.contains("AB INITIO MOLECULAR DYNAMICS")) { + this.outputResume.put("AB INITIO MOLECULAR DYNAMICS 0", "======================================================="); + this.outputResume.put("AB INITIO MOLECULAR DYNAMICS 1", line); + this.outputResume.put("AB INITIO MOLECULAR DYNAMICS 2", "======================================================="); + } + + else if (line.contains("TIME STEPS COMPLETED")) { + this.outputResume.put("TIME STEPS COMPLETED", line); + } + + else if (line.contains("Step-to-Step energy fluctuations")) { + this.outputResume.put("Step-to-Step energy fluctuations", line); + if ( (line = in.readLine()) != null) { + this.outputResume.put("Step-to-Step energy fluctuations 1", line); + } + } + + else if (line.contains("Overall energy fluctuations")) { + this.outputResume.put("Overall energy fluctuations", line); + if ( (line = in.readLine()) != null) { + this.outputResume.put("Overall energy fluctuations 1", line); + } + } + + else if (line.contains("Kinetic energy fluctuations")) { + this.outputResume.put("Kinetic energy fluctuations", line); + if ( (line = in.readLine()) != null) { + this.outputResume.put("Kinetic energy fluctuations 1", line); + } + } + + else if (line.contains("Potential energy fluctuations")) { + this.outputResume.put("Potential energy fluctuations", line); + if ( (line = in.readLine()) != null) { + this.outputResume.put("Potential energy fluctuations 1", line); + } + } + + else if (line.contains("OPTIMIZATION CONVERGED")) { + outputResume.put("OPTIMIZATION CONVERGED 0", " ******************************"); + outputResume.put("OPTIMIZATION CONVERGED", line); + outputResume.put("OPTIMIZATION CONVERGED 1", " ******************************"); + } + + else if (line.contains("Mulliken Net Atomic Charges")) { + outputResume.put("Mulliken", "\n" + line); + if ( (line = in.readLine()) != null) { + outputResume.put("Mulliken a", line); + } + if ( (line = in.readLine()) != null) { + outputResume.put("Mulliken b", line); + } + if ( (line = in.readLine()) != null) { + outputResume.put("Mulliken c", line); + } + for (int i = 0; i < Atoms.size(); i++) { + if ( (line = in.readLine()) != null) { + outputResume.put("Mulliken " + String.valueOf(i), line); + } + } + if ( (line = in.readLine()) != null) { + outputResume.put("Mulliken d", line); + } + if ( (line = in.readLine()) != null) { + outputResume.put("Mulliken e", line + "\n"); + } + } + + else if (line.contains("Dipole Moment ")) { + outputResume.put("Dipole 0", line); + if ( (line = in.readLine()) != null) { + outputResume.put("Dipole 1", line); + } + if ( (line = in.readLine()) != null) { + outputResume.put("Dipole 2", line); + } + } + + else if (line.contains("Quadrupole Moments ")) { + outputResume.put("Quadrupole 0", line); + if ( (line = in.readLine()) != null) { + outputResume.put("Quadrupole 1", line); + } + if ( (line = in.readLine()) != null) { + outputResume.put("Quadrupole 2", line); + } + } + + else if (line.contains("Maximum Tolerance Cnvgd")) { + outputResume.put("Cnvgd 0", line); + if ( (line = in.readLine()) != null) { + outputResume.put("Cnvgd 1", line); + } + if ( (line = in.readLine()) != null) { + outputResume.put("Cnvgd 2", line); + } + if ( (line = in.readLine()) != null) { + outputResume.put("Cnvgd 3", line); + } + } + + else if (line.contains("Convergence criterion met")) { + outputResume.put("Energy cnv", line); + } + + else if (line.contains("Energy is")) { + outputResume.put("Energy is", line); + } + + else if (line.contains("Optimization Cycle")) { + outputResume.put("Cycle", line); + } + + else if (line.contains("Total job time")) { + this.outputResume.put("Total job time", line); + normalTermination = true; + break; // Don't read any further... + } + + } + } + catch (Exception ex) { + throw new Exception("Error reading QChem output: " + ex.getMessage()); + } + } + + public String getOutputResume() { + StringWriter sWriter = new StringWriter(); + Set set = outputResume.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String line = me.getValue().toString(); + sWriter.write(line + "\n"); + } + + if (!normalTermination) { + sWriter.write( + "\n***** !!!!! IT IS NOT A NORMAL TERMINATION of Q-Chem !!!!! *****"); + } + return sWriter.toString(); + } + + public void getMolecularInterface(MoleculeInterface molec) throws + Exception { + if (molec == null) { + throw new Exception(this.getClass().getCanonicalName() + + " : molec == null"); + } + if (Atoms.size() < 1) { + throw new Exception(this.getClass().getCanonicalName() + + " : no QChem atoms"); + } + + //molec.addProperty(MoleculeInterface.ChargeProperty, new Integer(netCharge)); + //molec.addProperty(MoleculeInterface.MultiplicityProperty, new Integer(spinMultiplicity)); + + molec.addMonomer("QChem"); + + for (int i = 0; i < Atoms.size(); i++) { + QChemAtom ga = Atoms.get(i); + AtomInterface atom = molec.getNewAtomInstance(); + atom.setName(ga.getName()); + atom.setAtomicNumber(ga.getAtomicNumber()); + atom.setXYZ(ga.getX(), ga.getY(), ga.getZ()); + molec.addAtom(atom); + } + } + +} diff --git a/src/main/java/cct/resources/.DS_Store b/src/main/java/cct/resources/.DS_Store new file mode 100644 index 0000000..564d777 Binary files /dev/null and b/src/main/java/cct/resources/.DS_Store differ diff --git a/src/main/java/cct/resources/._.DS_Store b/src/main/java/cct/resources/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/cct/resources/._.DS_Store differ diff --git a/src/main/java/cct/resources/Resources.java b/src/main/java/cct/resources/Resources.java new file mode 100644 index 0000000..d8dfd4a --- /dev/null +++ b/src/main/java/cct/resources/Resources.java @@ -0,0 +1,18 @@ +package cct.resources; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Resources { + public Resources() { + } +} diff --git a/src/main/java/cct/resources/images/ImageResources.java b/src/main/java/cct/resources/images/ImageResources.java new file mode 100644 index 0000000..7a92c74 --- /dev/null +++ b/src/main/java/cct/resources/images/ImageResources.java @@ -0,0 +1,18 @@ +package cct.resources.images; + +/** + *

Title: Gasussian Utility Classes

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class ImageResources { + public ImageResources() { + } +} diff --git a/src/main/java/cct/script-sample.txt b/src/main/java/cct/script-sample.txt new file mode 100644 index 0000000..a6b1f22 --- /dev/null +++ b/src/main/java/cct/script-sample.txt @@ -0,0 +1,41 @@ +#!/bin/csh + +#PBS -V + +### Job name +#PBS -N MyJobName + +### Join queuing system output and error files into a single output file +#PBS -j oe + +### Send email to user when job ends or aborts +#PBS -m ae + +### email address for user +#PBS -M vvv900@gmail.com + +### Queue name that job is submitted to +#PBS -q hydra + +### Request nodes NB THIS IS REQUIRED +####NOTE: ncpus=1-8 then progress to nodes=1-67 +#### after 8 cpus, you need to use nodes= instead of ncpus= +#PBS -l ncpus=1 +#PBS -l mem=1000mb,vmem=1000mb +####NOTE: need to specify in MB used to be able to use GB +#PBS -l walltime=1:00:00 + + +# This job's working directory +echo Working directory is $PBS_O_WORKDIR +cd $PBS_O_WORKDIR +echo Running on host `hostname` +echo Time is `date` + +#Load module(s) if required +#module load application_module +module load gaussian/G09 + +# Run the executable +@@EXECUTABLE@@ < @@INPUT@@ > @@OUTPUT@@ +###or g09 < ${PBS_JOBNAME}.gif > ${PBS_JOBNAME}.${PBS_JOBID}.log diff --git a/src/main/java/cct/sff/AngleParam.java b/src/main/java/cct/sff/AngleParam.java new file mode 100644 index 0000000..81b5dd0 --- /dev/null +++ b/src/main/java/cct/sff/AngleParam.java @@ -0,0 +1,61 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.sff; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class AngleParam { + public float Fk, Theta; + public AngleParam(float fk, float r0) { + Fk = fk; + Theta = r0; + } + + public AngleParam() { + } +} diff --git a/src/main/java/cct/sff/BondParam.java b/src/main/java/cct/sff/BondParam.java new file mode 100644 index 0000000..738562f --- /dev/null +++ b/src/main/java/cct/sff/BondParam.java @@ -0,0 +1,58 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.sff; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class BondParam { + public float Fk, R0; + public BondParam(float fk, float r0) { + Fk = fk; + R0 = r0; + } +} diff --git a/src/main/java/cct/sff/SFF.txt b/src/main/java/cct/sff/SFF.txt new file mode 100644 index 0000000..85266d1 --- /dev/null +++ b/src/main/java/cct/sff/SFF.txt @@ -0,0 +1,18 @@ + + C.4 C.4 310.0 1.526 Amber: CT-CT 310.0 1.526 JCC,7,(1986),230; AA, SUGARS + C.4 H 340.0 1.090 Amber: CT-HC 340.0 1.090 changed from 331 bsd on NMA nmodes; AA, SUGARS + O.4 H 553.0 0.9572 Amber: OW-HW 553.0 0.9572 ! TIP3P water + C.4 O.4 320.0 1.410 Amber: CT-OS 320.0 1.410 JCC,7,(1986),230; NUCLEIC ACIDS + C.3 C.3 469.0 1.400 Amber: CA-CA 469.0 1.400 JCC,7,(1986),230; BENZENE,PHE,TRP,TYR + C.3 C.4 317.0 1.510 Amber: CA-CT 317.0 1.510 JCC,7,(1986),230; PHE,TYR + C.3 H 367.0 1.080 Amber: CA-HA 367.0 1.080 changed from 340. bsd on C6H6 nmodes; PHE,TRP,TYR + C.3 O.4 450.0 1.364 Amber: CA-OH 450.0 1.364 substituted for C-OH in tyr + S.4 S.4 166.0 2.038 Amber: S -S 166.0 2.038 JCC,7,(1986),230; CYX (SCHERAGA) + + + H O.4 H 100. 104.52 Amber: HW-OW-HW 100. 104.52 TIP3P water + C.3 C.3 C.3 70. 120.0 + C.3 C.3 H 50. 120.0 + + +S1 3.851 0.105 diff --git a/src/main/java/cct/sff/SimpleForceField.java b/src/main/java/cct/sff/SimpleForceField.java new file mode 100644 index 0000000..e861e08 --- /dev/null +++ b/src/main/java/cct/sff/SimpleForceField.java @@ -0,0 +1,999 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.sff; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.ForceFieldInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.*; +import cct.vecmath.Point3f; + +/** + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2006

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class SimpleForceField implements ForceFieldInterface { + + static final public int SP_SP_TORSION = 1; + static final public int SP_SP2_TORSION = 2; + static final public int SP_SP3_TORSION = 3; + static final public int SP2_SP2_TORSION = 4; + static final public int SP2_SP3_TORSION = 5; + static final public int SP3_SP3_TORSION = 6; + protected Map bondStretchParams = null; + static protected Map angleBendParams = null; + static protected Map specificTorsionParams = null; + static protected Map generalTorsionParams = null; + protected Map surfaceParams = null; + static protected String ffName = "SFF"; + static protected boolean calculateElectrostatics = false; + static protected float dielectricConstant = 1.0f; + static protected int dielectricFunction = CONSTANT_DIELECTRIC_FUNCTION; + static protected boolean useNBCutoff = false; + static protected float nbCutoff = 10.0f; + static protected float oneFourVDWScale = 1.0f; + static protected float oneFourElsScale = 1.0f; + public static final float FK_GRAD_2_RAD_FACTOR = (float) (Point3f.RADIANS_TO_DEGREES * Point3f.RADIANS_TO_DEGREES); + final static String Default_SFF_File = "SFF.txt"; + static boolean Initialized = false; + static float defaultAngleFk = 50.0f; + static final Logger logger = Logger.getLogger(SimpleForceField.class.getCanonicalName()); + + public SimpleForceField() { + initializeSFF(); + } + + public boolean isInitialized() { + return Initialized; + } + + public void initializeSFF() { + Initialized = true; + URL sffFile = null; + InputStream is = null; + try { + ClassLoader cl = SimpleForceField.class.getClassLoader(); + //logger.info("Class loader: " + cl.toString()); + sffFile = cl.getResource("cct/sff/" + Default_SFF_File); + is = cl.getResourceAsStream("cct/sff/" + Default_SFF_File); + //readParametersAsASCII(sffFile.getFile()); + readParametersAsASCII(is); + } catch (Exception ex) { + System.err.println(" : " + ex.getMessage()); + } + + } + + public void readParametersAsASCII(InputStream is) throws Exception { + + String line; + int flag = -1; + Map residue = null; + String res_name = ""; + + try { + //DataInputStream in = new DataInputStream(is); + BufferedReader in = new BufferedReader(new InputStreamReader(is)); + + while ((line = in.readLine()) != null) { + line = line.trim(); + if (line.startsWith(";") || line.startsWith("#")) { + continue; // Comment + } + if (line.length() == 0) { + continue; // Empty line + } + + line = line.toUpperCase(); + + if (line.startsWith("")) { // Start to read bond stretch parameters + + bondStretchParams = new HashMap(); + + while ((line = in.readLine()) != null) { + line = line.trim(); + if (line.startsWith(";") || line.startsWith("#")) { + continue; + } + if (line.length() == 0) { + break; // End of input - empty line + } + line = line.toUpperCase(); + + StringTokenizer st = new StringTokenizer(line, " \t", false); + if (st.countTokens() < 4) { + in.close(); + throw new Exception( + "readParametersAsASCII: ERROR while reading bond stretch parameters: " + + line); + } + + String a1 = st.nextToken(); + String a2 = st.nextToken(); + String atString = ""; + + if (a1.compareTo(a2) == 0) { + atString = a1 + "-" + a2; + } else if (a1.compareTo(a2) < 0) { + atString = a1 + "-" + a2; + } else { + atString = a2 + "-" + a1; + } + + float fk, r0; + try { + fk = Float.parseFloat(st.nextToken()); + r0 = Float.parseFloat(st.nextToken()); + } catch (Exception ex) { + in.close(); + throw new Exception( + "readParametersAsASCII: ERROR while reading bond stretch parameters: " + + line + " : " + ex.getMessage()); + } + + BondParam bp = new BondParam(fk, r0); + + bondStretchParams.put(atString, bp); + + } + + logger.info("Number of Bond Stretch parameters: " + + bondStretchParams.size()); + Set set = bondStretchParams.entrySet(); + Iterator iter = set.iterator(); + int count = 0; + while (iter.hasNext()) { + ++count; + Map.Entry me = (Map.Entry) iter.next(); + String Key = me.getKey().toString(); + BondParam bp = (BondParam) me.getValue(); + logger.info(count + " : " + Key + " " + bp.Fk + " " + + bp.R0); + } + } else if (line.startsWith("")) { // Start to read angle bend parameters + readAngleBendParameters(in); + } else if (line.startsWith("")) { // Start to read angle bend parameters + readSurfaceParameters(in); + } + + } + + in.close(); + } catch (Exception ex) { + throw new Exception("readParametersAsASCII: ERROR: " + ex.getMessage()); + } + + } + + public void readParametersAsASCII(String filename) throws Exception { + String line; + BufferedReader in = null; + int flag = -1; + Map residue = null; + String res_name = ""; + + try { + in = new BufferedReader(new FileReader(filename)); + + while ((line = in.readLine()) != null) { + line = line.trim(); + if (line.startsWith(";") || line.startsWith("#")) { + continue; // Comment + } + if (line.length() == 0) { + continue; // Empty line + } + + line = line.toUpperCase(); + + if (line.startsWith("")) { // Start to read bond stretch parameters + + bondStretchParams = new HashMap(); + + while ((line = in.readLine()) != null) { + line = line.trim(); + if (line.startsWith(";") || line.startsWith("#")) { + continue; + } + if (line.length() == 0) { + break; // End of input - empty line + } + line = line.toUpperCase(); + + StringTokenizer st = new StringTokenizer(line, " \t", false); + if (st.countTokens() < 4) { + in.close(); + throw new Exception( + "readParametersAsASCII: ERROR while reading bond stretch parameters: " + + line); + } + + String a1 = st.nextToken(); + String a2 = st.nextToken(); + String atString = ""; + + if (a1.compareTo(a2) == 0) { + atString = a1 + "-" + a2; + } else if (a1.compareTo(a2) < 0) { + atString = a1 + "-" + a2; + } else { + atString = a2 + "-" + a1; + } + + float fk, r0; + try { + fk = Float.parseFloat(st.nextToken()); + r0 = Float.parseFloat(st.nextToken()); + } catch (Exception ex) { + in.close(); + throw new Exception( + "readParametersAsASCII: ERROR while reading bond stretch parameters: " + + line + " : " + ex.getMessage()); + } + + BondParam bp = new BondParam(fk, r0); + + bondStretchParams.put(atString, bp); + + } + + logger.info("Number of Bond Stretch parameters: " + + bondStretchParams.size()); + Set set = bondStretchParams.entrySet(); + Iterator iter = set.iterator(); + int count = 0; + while (iter.hasNext()) { + ++count; + Map.Entry me = (Map.Entry) iter.next(); + String Key = me.getKey().toString(); + BondParam bp = (BondParam) me.getValue(); + logger.info(count + " : " + Key + " " + bp.Fk + " " + + bp.R0); + } + } else if (line.startsWith("")) { // Start to read angle bend parameters + readAngleBendParameters(in); + } + + } + + in.close(); + } catch (Exception ex) { + if (in != null) { + in.close(); + } + throw new Exception("readParametersAsASCII: ERROR: " + ex.getMessage()); + } + + } + + /** + * Table contains angle bend parameters in the form: Fk - in kcal/(mol*grad^2), Theta0 - in grads, so a subroutine + * transforms Theta0 in radians, Fk - into kcal/(mol*rad^2) + * + * @param in BufferedReader + * @throws Exception + */ + public static void readAngleBendParameters(BufferedReader in) throws + Exception { + String line; + angleBendParams = new HashMap(); + + while ((line = in.readLine()) != null) { + line = line.trim(); + if (line.startsWith(";") || line.startsWith("#")) { + continue; + } + if (line.length() == 0) { + break; // End of input - empty line + } + line = line.toUpperCase(); + + StringTokenizer st = new StringTokenizer(line, " \t", false); + if (st.countTokens() < 5) { + in.close(); + throw new Exception( + "readAngleBendParameters: ERROR while reading angle bend parameters: " + + line); + } + + String a1 = st.nextToken(); + String a2 = st.nextToken(); + String a3 = st.nextToken(); + String atString = ""; + + if (a1.compareTo(a3) == 0) { + atString = a1 + "-" + a2 + "-" + a3; + } else if (a1.compareTo(a3) < 0) { + atString = a1 + "-" + a2 + "-" + a3; + } else { + atString = a3 + "-" + a2 + "-" + a1; + } + + float fk, r0; + try { + fk = Float.parseFloat(st.nextToken()); // * FK_GRAD_2_RAD_FACTOR; + r0 = Float.parseFloat(st.nextToken()) * (float) Point3f.DEGREES_TO_RADIANS; + } catch (Exception ex) { + throw new Exception( + "readAngleBendParameters: ERROR while reading angle bend parameters: " + + line + " : " + ex.getMessage()); + } + + AngleParam ap = new AngleParam(fk, r0); + + angleBendParams.put(atString, ap); + + } + + logger.info("Number of Angle Bend parameters: " + + angleBendParams.size()); + Set set = angleBendParams.entrySet(); + Iterator iter = set.iterator(); + int count = 0; + while (iter.hasNext()) { + ++count; + Map.Entry me = (Map.Entry) iter.next(); + String Key = me.getKey().toString(); + AngleParam bp = (AngleParam) me.getValue(); + logger.info(count + " : " + Key + " " + + (bp.Fk / FK_GRAD_2_RAD_FACTOR) + " " + + (bp.Theta * (float) Point3f.RADIANS_TO_DEGREES)); + } + + } + + public void getAngleBendParams(MoleculeInterface molec, AngleBendsArray angles) { + + if (!isInitialized()) { + initializeSFF(); + } + + for (int i = 0; i < angles.getSize(); i++) { + AngleBend ab = angles.getAngleBend(i); + + AtomInterface a1 = molec.getAtomInterface(ab.getI()); + AtomInterface a2 = molec.getAtomInterface(ab.getJ()); + AtomInterface a3 = molec.getAtomInterface(ab.getK()); + + String type_1 = (String) a1.getProperty(AtomInterface.CCT_ATOM_TYPE); + if (type_1 == null) { + type_1 = cct.modelling.Molecule.guessAtomType(a1, + AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } + + String type_2 = (String) a2.getProperty(AtomInterface.CCT_ATOM_TYPE); + if (type_2 == null) { + type_2 = cct.modelling.Molecule.guessAtomType(a2, + AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } + + String type_3 = (String) a3.getProperty(AtomInterface.CCT_ATOM_TYPE); + if (type_3 == null) { + type_3 = cct.modelling.Molecule.guessAtomType(a3, + AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } + + // --- Start to guess the parameters + // --- Lookup in the table + if (type_1 != null && type_2 != null && type_3 != null + && CCTAtomTypes.isValidCCTType(type_1) + && CCTAtomTypes.isValidCCTType(type_2) + && CCTAtomTypes.isValidCCTType(type_3) + && angleBendParams != null) { + + String atString = ""; + + if (type_1.compareTo(type_3) == 0) { + atString = type_1 + "-" + type_2 + "-" + type_3; + } else if (type_1.compareTo(type_3) < 0) { + atString = type_1 + "-" + type_2 + "-" + type_3; + } else { + atString = type_3 + "-" + type_2 + "-" + type_1; + } + + if (angleBendParams.containsKey(atString)) { + AngleParam ap = (AngleParam) angleBendParams.get(atString); + ab.setFk(ap.Fk); + ab.setTheta(ap.Theta); + } else { + float[] params = constructAngleBendParam(type_1, type_2, + type_3, a1, a2, a3, molec); + ab.setFk(params[0]); + ab.setTheta(params[1]); + } + } // --- Try to guess + else { + float[] params = constructAngleBendParam(type_1, type_2, + type_3, a1, a2, a3, molec); + ab.setFk(params[0]); + ab.setTheta(params[1]); + } + } + } + + public static float[] constructAngleBendParam(String a1, String a2, + String a3, + AtomInterface atom_1, + AtomInterface atom_2, + AtomInterface atom_3, + MoleculeInterface molec) { + float[] ab = new float[2]; + float theta = 0; + + if (a2 == null || (a1 == null && a2 == null && a3 == null) + || (!CCTAtomTypes.isValidCCTType(a2))) { + theta = Point3f.angleBetween(atom_1, atom_2, atom_3); + + ab[0] = defaultAngleFk; // * FK_GRAD_2_RAD_FACTOR; + ab[1] = theta; // Already in radians + } else { + CCTAtomTypes info = CCTAtomTypes.getAtomTypeInfo(a2); + int geom = info.getGeometry(); + if (geom == CCTAtomTypes.LINEAR) { + ab[0] = 70; // * FK_GRAD_2_RAD_FACTOR; + ab[1] = 180 * (float) Point3f.DEGREES_TO_RADIANS; + return ab; + } else if (geom == CCTAtomTypes.TETRAHEDRAL) { + ab[0] = 50; // * FK_GRAD_2_RAD_FACTOR; + ab[1] = 109.5f * (float) Point3f.DEGREES_TO_RADIANS; + return ab; + } + if (geom == CCTAtomTypes.TRIGONAL) { + ab[0] = 70; // * FK_GRAD_2_RAD_FACTOR; + ab[1] = 120 * (float) Point3f.DEGREES_TO_RADIANS; + return ab; + } else { + System.err.println("Unknown geometry type for atom " + a2); + theta = Point3f.angleBetween(atom_1, atom_2, atom_3); + + ab[0] = defaultAngleFk; // * FK_GRAD_2_RAD_FACTOR; + ab[1] = theta; // Already in radians + } + } + + logger.info("Setting " + atom_1.getName() + "(" + + molec.getAtomIndex(atom_1) + ")-" + + atom_2.getName() + "(" + molec.getAtomIndex(atom_2) + + ")-" + atom_3.getName() + "(" + + molec.getAtomIndex(atom_3) + + ") to its current value: " + + ab[1] * Point3f.RADIANS_TO_DEGREES + " Fk: " + + ab[0] + " Kcal/(mol*rad^2"); + return ab; + } + + public BondParam getBondStretchParam(String a1, String a2) throws Exception { + + if (a1 == null || a2 == null || a1.length() == 0 || a2.length() == 0) { + throw new Exception("getBondStretchParam: a1 == null || a2 == null || a1.length() == 0 || a2.length() == 0"); + } + + if (!isInitialized()) { + initializeSFF(); + } + + if (bondStretchParams == null || bondStretchParams.size() < 1) { + return guessBondStretchParam(a1, a2); + } + + String atString = ""; + + if (a1.compareTo(a2) == 0) { + atString = a1 + "-" + a2; + } else if (a1.compareTo(a2) < 0) { + atString = a1 + "-" + a2; + } else { + atString = a2 + "-" + a1; + } + + if (bondStretchParams.containsKey(atString)) { + BondParam bp = (BondParam) bondStretchParams.get(atString); + return new BondParam(bp.Fk, bp.R0); + } + + return guessBondStretchParam(a1, a2); + } + + public static BondParam guessBondStretchParam(String a1, String a2) { + if (!CCTAtomTypes.isValidCCTType(a1)) { + System.err.println(a1 + " is not a valid CCT atom type"); + return new BondParam(0, 0); + } + if (!CCTAtomTypes.isValidCCTType(a2)) { + System.err.println(a2 + " is not a valid CCT atom type"); + return new BondParam(0, 0); + } + + String atString = ""; + + if (a1.compareTo(a2) == 0) { + atString = a1 + "-" + a2; + } else if (a1.compareTo(a2) < 0) { + atString = a1 + "-" + a2; + } else { + atString = a2 + "-" + a1; + } + + CCTAtomTypes info = CCTAtomTypes.getAtomTypeInfo(a1); + float r1 = info.getCovalentRadius(); + info = CCTAtomTypes.getAtomTypeInfo(a2); + float r2 = info.getCovalentRadius(); + + return new BondParam(300.0f, (float) Math.sqrt(r1 + r2)); + } + + public static float guessCovalentBondLength(String a1, String a2) { + if (!CCTAtomTypes.isValidCCTType(a1) || !CCTAtomTypes.isValidCCTType(a2)) { + System.err.println(a2 + " or/and " + a1 + " is/are not valid CCT atom type"); + return 0; + } + + CCTAtomTypes info = CCTAtomTypes.getAtomTypeInfo(a1); + float r1 = info.getCovalentRadius(); + info = CCTAtomTypes.getAtomTypeInfo(a2); + float r2 = info.getCovalentRadius(); + + /* + * String atString = ""; if (a1.compareTo(a2) == 0) { atString = a1 + "-" + a2; } else if (a1.compareTo(a2) < 0) { atString = a1 + * + "-" + a2; } else { atString = a2 + "-" + a1; } + * + * if (!isInitialized()) { initializeSFF(); } + * + * if (bondStretchParams.containsKey(atString)) { BondParam bp = (BondParam) bondStretchParams.get(atString); return bp.R0; } + */ + return (float) Math.sqrt(r1 + r2); + } + + public static void setupNonbondedParams(MoleculeInterface molec, List nonbonded) { + int element; + for (int i = 0; i < nonbonded.size(); i++) { + NonbondedPair nb = (NonbondedPair) nonbonded.get(i); + AtomInterface atom_1 = molec.getAtomInterface(nb.getI()); + AtomInterface atom_2 = molec.getAtomInterface(nb.getJ()); + + String type_1 = (String) atom_1.getProperty(AtomInterface.CCT_ATOM_TYPE); + if (type_1 == null) { + type_1 = cct.modelling.Molecule.guessAtomType(atom_1, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } + + String type_2 = (String) atom_2.getProperty(AtomInterface.CCT_ATOM_TYPE); + if (type_2 == null) { + type_2 = cct.modelling.Molecule.guessAtomType(atom_2, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } + + float Di = 0, Dj = 0, Ri = 0, Rj = 0; + + // For atom i + if (!CCTAtomTypes.isValidCCTType(type_1)) { + System.err.println(type_1 + " is not a valid CCT atom type"); + element = atom_1.getAtomicNumber(); + Ri = ChemicalElements.getUFFRadius(element); + Di = ChemicalElements.getUFFWellDepth(element); + System.err.println("Di and Ri are set for corresponding element: " + Di + " " + Ri); + } else { + CCTAtomTypes info = CCTAtomTypes.getAtomTypeInfo(type_1); + Ri = info.getVDWDIstance(); + Di = info.getVDWWellDepth(); + } + + // For atom j + if (!CCTAtomTypes.isValidCCTType(type_2)) { + System.err.println(type_1 + " is not a valid CCT atom type"); + element = atom_2.getAtomicNumber(); + Rj = ChemicalElements.getUFFRadius(element); + Dj = ChemicalElements.getUFFWellDepth(element); + System.err.println("Di and Ri are set for corresponding element: " + Dj + " " + Rj); + } else { + CCTAtomTypes info = CCTAtomTypes.getAtomTypeInfo(type_2); + Rj = info.getVDWDIstance(); + Dj = info.getVDWWellDepth(); + } + + // --- Construct Aij and Cij for nonbonded pair + // using geometric mean + double Dij = Math.sqrt(Di * Dj); + double Rij = Ri * Ri * Ri * Rj * Rj * Rj; + + nb.setA(Dij * Rij * Rij); + nb.setC(2.0 * Dij * Rij); + } + + } + + public static void setupNonbondedParams(MoleculeInterface mol, MolecularPlane plane) { + int element; + float Dj = (float) plane.getSurfaceParameter().getW(), Rj = (float) plane.getSurfaceParameter().getR(); + List list = plane.getAtomList(); + list.clear(); + + for (int i = 0; i < mol.getNumberOfAtoms(); i++) { + AtomInterface atom = mol.getAtomInterface(i); + + String type_1 = (String) atom.getProperty(AtomInterface.CCT_ATOM_TYPE); + if (type_1 == null) { + type_1 = cct.modelling.Molecule.guessAtomType(atom, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } + + float Di = 0, Ri = 0; + + // For atom i + if (!CCTAtomTypes.isValidCCTType(type_1)) { + System.err.println(type_1 + " is not a valid CCT atom type"); + element = atom.getAtomicNumber(); + Ri = ChemicalElements.getUFFRadius(element); + Di = ChemicalElements.getUFFWellDepth(element); + System.err.println("Di and Ri are set for corresponding element: " + Di + " " + Ri); + } else { + CCTAtomTypes info = CCTAtomTypes.getAtomTypeInfo(type_1); + Ri = info.getVDWDIstance(); + Di = info.getVDWWellDepth(); + } + + // --- Construct Aij and Cij for nonbonded pair + // using geometric mean + double Dij = Math.sqrt(Di * Dj); + double Rij = Ri * Ri * Ri * Rj * Rj * Rj; + + AtomSurfaceEntity nb = new AtomSurfaceEntity(atom, Dij * Rij * Rij, 2.0 * Dij * Rij); + list.add(nb); + //nb.setA(Dij * Rij * Rij); + //nb.setC(2.0 * Dij * Rij); + } + + } + + public List getTorsionParams(MoleculeInterface molec, List torsions) { + + if (!isInitialized()) { + initializeSFF(); + } + + List tPars = new ArrayList(); + + for (int i = 0; i < torsions.size(); i++) { + Torsion tor = (Torsion) torsions.get(i); + boolean foundParam = false; + + AtomInterface a1 = molec.getAtomInterface(tor.ijkl[0]); + AtomInterface a2 = molec.getAtomInterface(tor.ijkl[1]); + AtomInterface a3 = molec.getAtomInterface(tor.ijkl[2]); + AtomInterface a4 = molec.getAtomInterface(tor.ijkl[3]); + + String type_1 = (String) a1.getProperty(AtomInterface.CCT_ATOM_TYPE); + if (type_1 == null) { + type_1 = cct.modelling.Molecule.guessAtomType(a1, + AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } + + String type_2 = (String) a2.getProperty(AtomInterface.CCT_ATOM_TYPE); + if (type_2 == null) { + type_2 = cct.modelling.Molecule.guessAtomType(a2, + AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } + + String type_3 = (String) a3.getProperty(AtomInterface.CCT_ATOM_TYPE); + if (type_3 == null) { + type_3 = cct.modelling.Molecule.guessAtomType(a3, + AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } + + String type_4 = (String) a4.getProperty(AtomInterface.CCT_ATOM_TYPE); + if (type_4 == null) { + type_4 = cct.modelling.Molecule.guessAtomType(a4, + AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + } + + // --- Start to guess the parameters + // --- Lookup in the table with the SPECIFIC parameters + if (type_1 != null && type_2 != null && type_3 != null && type_4 != null + && CCTAtomTypes.isValidCCTType(type_1) + && CCTAtomTypes.isValidCCTType(type_2) + && CCTAtomTypes.isValidCCTType(type_3) + && CCTAtomTypes.isValidCCTType(type_4) + && specificTorsionParams != null) { + + String atString = ""; + + if (type_1.compareTo(type_4) == 0) { + atString = type_1 + "-" + type_2 + "-" + type_3 + "-" + type_4; + } else if (type_1.compareTo(type_4) < 0) { + atString = type_1 + "-" + type_2 + "-" + type_3 + "-" + type_4; + } else { + atString = type_4 + "-" + type_3 + "-" + type_2 + "-" + type_1; + } + + if (specificTorsionParams.containsKey(atString)) { + List serie = (List) specificTorsionParams.get(atString); + TorsionParameter tpar = new TorsionParameter(tor, serie); + tPars.add(tpar); + foundParam = true; + } + } + + if (foundParam) { + continue; + } + + // --- Lookup in the table with the GENERAL parameters + if (type_2 != null && type_3 != null + && CCTAtomTypes.isValidCCTType(type_2) + && CCTAtomTypes.isValidCCTType(type_3) + && generalTorsionParams != null) { + + String atString = ""; + + if (type_2.compareTo(type_3) == 0) { + atString = type_2 + "-" + type_3; + } else if (type_2.compareTo(type_3) < 0) { + atString = type_2 + "-" + type_3; + } else { + atString = type_3 + "-" + type_2; + } + + if (generalTorsionParams.containsKey(atString)) { + List serie = (List) generalTorsionParams.get(atString); + TorsionParameter tpar = new TorsionParameter(tor, serie); + tPars.add(tpar); + foundParam = true; + } + } + + if (foundParam) { + continue; + } + + // --- Try to guess + List serie = guessTorsionParam(a2, a3, type_2, type_3); + TorsionParameter tpar = new TorsionParameter(tor, serie); + tPars.add(tpar); + + } + + return tPars; + } + + public static List guessTorsionParam(AtomInterface a2, AtomInterface a3, String type_2, String type_3) { + List serie = new ArrayList(); + + int bond_type = SP3_SP3_TORSION; + boolean bothTrigonal = false; + boolean bothTetrahedral = true; + boolean trigonalAndTetrahedral = false; + + if (type_2 != null && type_3 != null + && CCTAtomTypes.isValidCCTType(type_2) + && CCTAtomTypes.isValidCCTType(type_3)) { + + CCTAtomTypes info2 = CCTAtomTypes.getAtomTypeInfo(type_2); + CCTAtomTypes info3 = CCTAtomTypes.getAtomTypeInfo(type_3); + + bothTrigonal = info2.getGeometry() == CCTAtomTypes.TRIGONAL + && info3.getGeometry() == CCTAtomTypes.TRIGONAL; + bothTetrahedral = info2.getGeometry() == CCTAtomTypes.TETRAHEDRAL + && info3.getGeometry() == CCTAtomTypes.TETRAHEDRAL; + trigonalAndTetrahedral = (info2.getGeometry() + == CCTAtomTypes.TETRAHEDRAL + && info3.getGeometry() == CCTAtomTypes.TRIGONAL) + || (info2.getGeometry() == CCTAtomTypes.TRIGONAL + && info3.getGeometry() == CCTAtomTypes.TETRAHEDRAL); + + } + + if (bothTetrahedral) { + TorsionTerm tt = new TorsionTerm(0.15f, 3, 0.0f); // Amber: HC-CT-CT-HC 1 0.15 0.0 3. Junmei et al, 1999 + serie.add(tt); + } else if (bothTrigonal) { + TorsionTerm tt = new TorsionTerm(3.625f, 2, + (float) (180.0 + * Point3f.DEGREES_TO_RADIANS)); // Amber: X -CA-CA-X 4 14.50 180.0 2. intrpol.bsd.on C6H6 + serie.add(tt); + } else if (trigonalAndTetrahedral) { + TorsionTerm tt = new TorsionTerm(0.0f, 3, 0.0f); + serie.add(tt); + } else { + TorsionTerm tt = new TorsionTerm(0.0f, 3, 0.0f); + serie.add(tt); + + } + + return serie; + } + + public static void main(String[] args) { + SimpleForceField simpleforcefield = new SimpleForceField(); + } + + public void enableCalculateElectrostatics(boolean enable) { + calculateElectrostatics = enable; + } + + public void enableUseNBCutoff(boolean enable) { + useNBCutoff = enable; + } + + public float get14ElsScale() { + return oneFourElsScale; + } + + public float get14NBScale() { + return oneFourVDWScale; + } + + public float getDielectricConstant() { + return dielectricConstant; + } + + public int getDielectricFunction() { + return dielectricFunction; + } + + public String getName() { + return ffName; + } + + public float getNBCutoff() { + return nbCutoff; + } + + public boolean isCalculateElectrostatics() { + return calculateElectrostatics; + } + + public boolean isUseNBCutoff() { + return useNBCutoff; + } + + public void set14ElsScale(float scne) { + oneFourElsScale = scne; + } + + public void set14NBScale(float scnb) { + oneFourVDWScale = scnb; + } + + public void setDielectricConstant(float diel) { + dielectricConstant = diel; + } + + public void setDielectricFunction(int func) { + if (func != CONSTANT_DIELECTRIC_FUNCTION + && func != DISTANCE_DIELECTRIC_FUNCTION) { + System.err.println("Unknown dielectric function. Ignored..."); + return; + } + dielectricFunction = func; + } + + public void setNBCutoff(float cutoff) { + nbCutoff = cutoff; + } + + public void readSurfaceParameters(BufferedReader in) throws Exception { + String line; + surfaceParams = new HashMap(); + + while ((line = in.readLine()) != null) { + line = line.trim(); + if (line.startsWith(";") || line.startsWith("#")) { + continue; + } + if (line.length() == 0) { + break; // End of input - empty line + } + line = line.toUpperCase(); + + StringTokenizer st = new StringTokenizer(line, " \t", false); + if (st.countTokens() < 3) { + in.close(); + throw new Exception("readSurfaceParameters: ERROR while reading surface parameters: " + line); + } + + String a1 = st.nextToken(); + String a2 = st.nextToken(); + String a3 = st.nextToken(); + + float R, W; + try { + R = Float.parseFloat(a2); + W = Float.parseFloat(a3); + } catch (Exception ex) { + throw new Exception("readSurfaceParameters: ERROR while reading surface parameters: " + line + " : " + ex.getMessage()); + } + + SurfaceParameter sp = new SurfaceParameter(R, W); + + surfaceParams.put(a1, sp); + } + + logger.info("Number of Angle Bend parameters: " + + angleBendParams.size()); + Set set = angleBendParams.entrySet(); + Iterator iter = set.iterator(); + int count = 0; + while (iter.hasNext()) { + ++count; + Map.Entry me = (Map.Entry) iter.next(); + String Key = me.getKey().toString(); + AngleParam bp = (AngleParam) me.getValue(); + logger.info(count + " : " + Key + " " + + (bp.Fk / FK_GRAD_2_RAD_FACTOR) + " " + + (bp.Theta * (float) Point3f.RADIANS_TO_DEGREES)); + } + } + + public void getSurfaceParam(MolecularPlane mPlane) throws Exception { + + if (!isInitialized()) { + initializeSFF(); + } + + SurfaceParameter sp = surfaceParams.get(mPlane.getName()); + + if (sp == null) { + throw new Exception("No Surface parameter for surface type " + mPlane.getName()); + } + + mPlane.setSurfaceParameter(sp.getR(), sp.getW()); + + } +} diff --git a/src/main/java/cct/siesta/.DS_Store b/src/main/java/cct/siesta/.DS_Store new file mode 100644 index 0000000..a051e41 Binary files /dev/null and b/src/main/java/cct/siesta/.DS_Store differ diff --git a/src/main/java/cct/siesta/._.DS_Store b/src/main/java/cct/siesta/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/cct/siesta/._.DS_Store differ diff --git a/src/main/java/cct/siesta/AtomicCoordinatesFormat.java b/src/main/java/cct/siesta/AtomicCoordinatesFormat.java new file mode 100644 index 0000000..0a1544d --- /dev/null +++ b/src/main/java/cct/siesta/AtomicCoordinatesFormat.java @@ -0,0 +1,54 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.siesta; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public enum AtomicCoordinatesFormat { + Bohr, NotScaledCartesianBohr, Ang, NotScaledCartesianAng, /*ScaledCartesian,*/ Fractional, ScaledByLatticeVectors +} diff --git a/src/main/java/cct/siesta/ChemicalSpeciesLabel.java b/src/main/java/cct/siesta/ChemicalSpeciesLabel.java new file mode 100644 index 0000000..3e4cc4a --- /dev/null +++ b/src/main/java/cct/siesta/ChemicalSpeciesLabel.java @@ -0,0 +1,70 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.siesta; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class ChemicalSpeciesLabel { + Integer number; + int atomicNumber; + String label; + + public ChemicalSpeciesLabel(Integer number, int atomicNumber, String label) { + this.number = number; + this.atomicNumber = atomicNumber; + this.label = label; + } + + public int getAtomicNumber() { + return atomicNumber; + } + + public String getSpeciesLabel() { + return label; + } +} diff --git a/src/main/java/cct/siesta/Siesta.java b/src/main/java/cct/siesta/Siesta.java new file mode 100644 index 0000000..4d03892 --- /dev/null +++ b/src/main/java/cct/siesta/Siesta.java @@ -0,0 +1,170 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.siesta; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.ChemicalElements; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class Siesta { + protected Siesta() { + } + + public static AtomicCoordinatesFormat getDefaultAtomicCoordinatesFormat() { + return AtomicCoordinatesFormat.NotScaledCartesianBohr; + } + + /** + * Creates a new set of ChemicalSpeciesLabels + * @param molec MoleculeInterface - molecule + * @return Map - ChemicalSpeciesLabels + */ + public static Map formChemicalSpeciesLabels(MoleculeInterface molec) { + Map chemicalSpeciesLabels = new HashMap (); + Map labels = new HashMap (); + + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface atom = molec.getAtomInterface(i); + int element = atom.getAtomicNumber(); + String symbol = ChemicalElements.getElementSymbol(element); + + atom.setProperty(SiestaInterface.SIESTA_SPECIES_LABEL, symbol); + if (labels.containsKey(symbol)) { + atom.setProperty(SiestaInterface.SIESTA_SPECIES_NUMBER, labels.get(symbol)); + continue; + } + + Integer number = chemicalSpeciesLabels.size() + 1; + atom.setProperty(SiestaInterface.SIESTA_SPECIES_NUMBER, number); + ChemicalSpeciesLabel species = new ChemicalSpeciesLabel(number, element, symbol); + chemicalSpeciesLabels.put(number, species); + labels.put(symbol, number); + } + + labels = null; + return chemicalSpeciesLabels; + } + + public static Map updateChemicalSpeciesLabels(MoleculeInterface molec, Map chemicalSpeciesLabels) { + + Map labels = new HashMap (); + Set set = chemicalSpeciesLabels.entrySet(); + Iterator iter = set.iterator(); + + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + Integer number = (Integer) me.getKey(); + ChemicalSpeciesLabel species = (ChemicalSpeciesLabel) me.getValue(); + labels.put(species.label, number); + } + + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface atom = molec.getAtomInterface(i); + + Object obj = atom.getProperty(SiestaInterface.SIESTA_SPECIES_LABEL); + int element = atom.getAtomicNumber(); + + if (obj == null) { + + String symbol = ChemicalElements.getElementSymbol(element); + if (labels.containsKey(symbol)) { + + } + else { + + Integer number = getUniqueLabelNumber(labels.values().toArray()); + labels.put(symbol, number); + ChemicalSpeciesLabel species = new ChemicalSpeciesLabel(number, element, symbol); + chemicalSpeciesLabels.put(number, species); + } + atom.setProperty(SiestaInterface.SIESTA_SPECIES_LABEL, symbol); + atom.setProperty(SiestaInterface.SIESTA_SPECIES_NUMBER, labels.get(symbol)); + continue; + } + + String symbol = obj.toString(); + if (labels.containsKey(symbol)) { + + } + else { + Integer number = getUniqueLabelNumber(labels.values().toArray()); + labels.put(symbol, number); + ChemicalSpeciesLabel species = new ChemicalSpeciesLabel(number, element, symbol); + chemicalSpeciesLabels.put(number, species); + } + + atom.setProperty(SiestaInterface.SIESTA_SPECIES_LABEL, symbol); + atom.setProperty(SiestaInterface.SIESTA_SPECIES_NUMBER, labels.get(symbol)); + } + + labels = null; + return chemicalSpeciesLabels; + } + + private static Integer getUniqueLabelNumber(Object[] integers) { + Arrays.sort(integers); + if (integers == null) { + return 1; + } + for (int i = 1; i <= integers.length; i++) { + if (i == (Integer) integers[i]) { + return i; + } + } + return integers.length + 1; + } +} diff --git a/src/main/java/cct/siesta/SiestaInput.java b/src/main/java/cct/siesta/SiestaInput.java new file mode 100644 index 0000000..80b0c3b --- /dev/null +++ b/src/main/java/cct/siesta/SiestaInput.java @@ -0,0 +1,1002 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.siesta; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; + +import cct.Constants; +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.math.Crystal; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ + +public class SiestaInput + implements SiestaInterface { + // --- based on Siesta 2.0 + public final static String BLOCK_TOKEN = "%block"; + + private String systemName = ""; + private String systemLabel = "siesta"; + // Number of different atomic species in the simulation. Atoms of the same species, but with a different pseudopotential or basis set are counted as different species + private int numberOfSpecies = 0; // + // Number of atoms in the simulation. + private int numberOfAtoms = 0; + // Specify the net charge of the system + private float netCharge = 0; + // attice constant. This is just to define the scale of the lattice vectors. + private double latticeConstant = 1.0; + + // --- The cell vectors are read in units of the lattice constant defined above. They are read as a matrix CELL(ixyz,ivector), each vector being one line + private double latticeVectors[][] = { + { + 1.0, 0.0, 0.0}, { + 0.0, 1.0, 0.0}, { + 0.0, 0.0, 1.0} + }; + + // --- Crystallographic way of specifying the lattice vectors, by giving six real numbers: the three vector modules, $a$, $b$, and $c$, and the three angles + private double latticeParameters[] = { + 1.0, 1.0, 1.0, 90., 90., 90.}; + private boolean useLatticeParameters = true; + private boolean defaultLatticeParameters = true; + + private Map chemicalSpeciesLabels = new HashMap (); + private List atoms = new ArrayList (); + private List otherOptions = new ArrayList (); + + // Character string to specify the format of the atomic positions in input. + private AtomicCoordinatesFormat atomicCoordinatesFormat = AtomicCoordinatesFormat.NotScaledCartesianBohr; + + public SiestaInput() { + } + + public static void main(String[] args) { + SiestaInput siestainput = new SiestaInput(); + } + + public double[][] getLatticeVectors() { + if (useLatticeParameters) { + return latticeVectors; + } + else { + double latticeVect[][] = new double[3][3]; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + latticeVect[i][j] = latticeVectors[i][j] * latticeConstant; + } + } + return latticeVect; + } + } + + public void setLatticeConstant(double latticeConst) { + latticeConstant = latticeConst; + } + + public void getMolecularInterface(MoleculeInterface molec) throws + Exception { + if (molec == null) { + throw new Exception(this.getClass().getCanonicalName() + " : molec == null"); + } + if (atoms.size() < 1) { + throw new Exception(this.getClass().getCanonicalName() + " : no SIESTA atoms"); + } + + molec.addMonomer("SIESTA"); + + float[][] coords = null; + if (useLatticeParameters) { + coords = calcAbsoluteCoordinates(atoms, latticeVectors); + molec.addProperty(MoleculeInterface.LATTICE_VECTORS, latticeVectors); + } + else { + double latticeVect[][] = new double[3][3]; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + latticeVect[i][j] = latticeVectors[i][j] * latticeConstant; + } + } + coords = calcAbsoluteCoordinates(atoms, latticeVect); + molec.addProperty(MoleculeInterface.LATTICE_VECTORS, latticeVect); + } + + for (int i = 0; i < atoms.size(); i++) { + SiestaAtom ga = atoms.get(i); + AtomInterface atom = molec.getNewAtomInstance(); + atom.setName(ga.label); + atom.setAtomicNumber(ga.element); + + atom.setXYZ(coords[i][0], coords[i][1], coords[i][2]); + + ChemicalSpeciesLabel label = chemicalSpeciesLabels.get(ga.species); + atom.setProperty(SiestaInterface.SIESTA_SPECIES_LABEL, label.label); + atom.setProperty(SiestaInterface.SIESTA_SPECIES_NUMBER, ga.species); + + molec.addAtom(atom); + } + + if (systemName.length() > 0) { + molec.setName(systemName); + } + else { + molec.setName(systemLabel); + } + + if (!defaultLatticeParameters) { + molec.addProperty(MoleculeInterface.LATTICE_PARAMETERS, latticeParameters); + } + + molec.addProperty(MoleculeInterface.ChargeProperty, new Float(netCharge)); + molec.addProperty(SiestaInterface.SIESTA_INTERFACE, this); + } + + public float[][] calcAbsoluteCoordinates(List atoms, double vectors[][]) throws Exception { + + if (atoms.size() < 1) { + return null; + } + float[][] coords = new float[atoms.size()][3]; + + for (int i = 0; i < atoms.size(); i++) { + SiestaAtom ga = atoms.get(i); + switch (atomicCoordinatesFormat) { + case Fractional: + case ScaledByLatticeVectors: + + /* + coords[i][0] = (float) (ga.xyz[0] * vectors[0][0] + ga.xyz[1] * vectors[0][1] + ga.xyz[2] * vectors[0][2]); + coords[i][1] = (float) (ga.xyz[0] * vectors[1][0] + ga.xyz[1] * vectors[1][1] + ga.xyz[2] * vectors[1][2]); + coords[i][2] = (float) (ga.xyz[0] * vectors[2][0] + ga.xyz[1] * vectors[2][1] + ga.xyz[2] * vectors[2][2]); + */ + coords[i][0] = (float) (ga.xyz[0] * vectors[0][0] + ga.xyz[1] * vectors[1][0] + ga.xyz[2] * vectors[2][0]); + coords[i][1] = (float) (ga.xyz[0] * vectors[0][1] + ga.xyz[1] * vectors[1][1] + ga.xyz[2] * vectors[2][1]); + coords[i][2] = (float) (ga.xyz[0] * vectors[0][2] + ga.xyz[1] * vectors[1][2] + ga.xyz[2] * vectors[2][2]); + break; + + case Ang: + case NotScaledCartesianAng: + coords[i][0] = (float) ga.xyz[0]; + coords[i][1] = (float) ga.xyz[1]; + coords[i][2] = (float) ga.xyz[2]; + break; + case Bohr: + case NotScaledCartesianBohr: + coords[i][0] = (float) (ga.xyz[0] * Constants.ONE_BOHR); + coords[i][1] = (float) (ga.xyz[1] * Constants.ONE_BOHR); + coords[i][2] = (float) (ga.xyz[2] * Constants.ONE_BOHR); + break; + + } + /* + if (ga.Cartesians != null) { + ga.Xyz[0] = ga.Cartesians[0] * norm_vectors[0][0] + ga.Cartesians[1] * norm_vectors[0][1] + + ga.Cartesians[2] * norm_vectors[0][2]; + ga.Xyz[1] = ga.Cartesians[0] * norm_vectors[1][0] + ga.Cartesians[1] * norm_vectors[1][1] + + ga.Cartesians[2] * norm_vectors[1][2]; + ga.Xyz[2] = ga.Cartesians[0] * norm_vectors[2][0] + ga.Cartesians[1] * norm_vectors[2][1] + + ga.Cartesians[2] * norm_vectors[2][2]; + } + else if (ga.Fractional != null) { + ga.Xyz[0] = ga.Fractional[0] * vectors[0][0] + ga.Fractional[1] * vectors[0][1] + ga.Fractional[2] * vectors[0][2]; + ga.Xyz[1] = ga.Fractional[0] * vectors[1][0] + ga.Fractional[1] * vectors[1][1] + ga.Fractional[2] * vectors[1][2]; + ga.Xyz[2] = ga.Fractional[0] * vectors[2][0] + ga.Fractional[1] * vectors[2][1] + ga.Fractional[2] * vectors[2][2]; + } + else { + throw new Exception("Neither cartesian nor fractional coordinates are set for " + (i + 1) + " atoms"); + } + */ + } + + return coords; + } + + public void parseFDF(String filename, int fileType) throws Exception { + String line, label; + StringTokenizer st; + + BufferedReader in = null; + + if (fileType == 0) { // Read from file + try { + in = new BufferedReader(new FileReader(filename)); + } + catch (java.io.FileNotFoundException e) { + throw new Exception("Error opening file " + filename + ": " + e.getMessage()); + } + } + else if (fileType == 1) { // Read from String + in = new BufferedReader(new StringReader(filename)); + } + else { + throw new Exception("Implementation error: unknown file type"); + } + + while ( (line = in.readLine()) != null) { + line = line.trim(); + + st = new StringTokenizer(line, " \t"); + if (st.countTokens() < 1) { + continue; + } + + label = st.nextToken(); + + // --- Read block of data + if (label.equalsIgnoreCase(BLOCK_TOKEN)) { // block data + if (!st.hasMoreTokens()) { + throw new Exception("Unexpected end of line while reading %block, got " + line); + } + label = st.nextToken(); + + if (label.equalsIgnoreCase("ChemicalSpeciesLabel")) { + parseChemicalSpeciesLabel(in); + } + else if (label.equalsIgnoreCase("LatticeVectors")) { + parseLatticeVectors(in); + } + else if (label.equalsIgnoreCase("LatticeParameters")) { + parseLatticeParameters(in); + } + else if (label.equalsIgnoreCase("AtomicCoordinatesAndAtomicSpecies")) { + parseAtomicCoordinatesAndAtomicSpecies(in); + } + + else { // just skip the block + otherOptions.add(line); + while ( (line = in.readLine()) != null) { + otherOptions.add(line); + line = line.trim().toLowerCase(); + if (line.startsWith("%endblock")) { + break; + } + } + if (line == null) { + break; // end of file, exit main loop + } + } + } + + // --- Test for different labels... + else if (label.equalsIgnoreCase("SystemName")) { + int n = line.indexOf(" "); + if (n == -1) { + continue; + } + systemName = line.substring(n).trim(); + } + + else if (label.equalsIgnoreCase("SystemLabel")) { + int n = line.indexOf(" "); + if (n == -1) { + continue; + } + systemLabel = line.substring(n).trim(); + } + + else if (label.equalsIgnoreCase("NumberOfSpecies")) { + if (!st.hasMoreTokens()) { + throw new Exception("Unexpected end of line while reading NumberOfSpecies, got " + line); + } + try { + numberOfSpecies = Integer.parseInt(st.nextToken()); + } + catch (Exception ex) { + throw new Exception("Error while parsing NumberOfSpecies, got " + line); + } + } + + else if (label.equalsIgnoreCase("NumberOfAtoms")) { + if (!st.hasMoreTokens()) { + throw new Exception("Unexpected end of line while reading NumberOfAtoms, got " + line); + } + try { + numberOfAtoms = Integer.parseInt(st.nextToken()); + if (atoms instanceof ArrayList) { + ( (ArrayList) atoms).ensureCapacity(numberOfAtoms); + } + } + catch (Exception ex) { + throw new Exception("Error while parsing NumberOfAtoms, got " + line); + } + } + + else if (label.equalsIgnoreCase("LatticeConstant")) { + if (!st.hasMoreTokens()) { + throw new Exception("Unexpected end of line while reading LatticeConstant, got " + line); + } + try { + latticeConstant = Float.parseFloat(st.nextToken()); + } + catch (Exception ex) { + throw new Exception("Error while parsing LatticeConstant, got " + line); + } + } + + else if (label.equalsIgnoreCase("AtomicCoordinatesFormat")) { + if (!st.hasMoreTokens()) { + throw new Exception("Unexpected end of line while reading AtomicCoordinatesFormat, got " + line); + } + + label = st.nextToken(); + + if (label.equalsIgnoreCase("Bohr")) { + atomicCoordinatesFormat = AtomicCoordinatesFormat.Bohr; + } + else if (label.equalsIgnoreCase("NotScaledCartesianBohr")) { + atomicCoordinatesFormat = AtomicCoordinatesFormat.NotScaledCartesianBohr; + } + else if (label.equalsIgnoreCase("Ang")) { + atomicCoordinatesFormat = AtomicCoordinatesFormat.Ang; + } + else if (label.equalsIgnoreCase("NotScaledCartesianAng")) { + atomicCoordinatesFormat = AtomicCoordinatesFormat.NotScaledCartesianAng; + } + //else if (label.equalsIgnoreCase("ScaledCartesian")) { + // atomicCoordinatesFormat = AtomicCoordinatesFormat.ScaledCartesian; + //} + else if (label.equalsIgnoreCase("Fractional")) { + atomicCoordinatesFormat = AtomicCoordinatesFormat.Fractional; + } + else if (label.equalsIgnoreCase("ScaledByLatticeVectors")) { + atomicCoordinatesFormat = AtomicCoordinatesFormat.ScaledByLatticeVectors; + } + else { + throw new Exception("Unknown AtomicCoordinatesFormat: " + line); + } + } + + else { // Line to ignore + otherOptions.add(line); + } + } // --- End of main while + + } + + public void parseAtomicCoordinatesAndAtomicSpecies(String text) throws Exception { + BufferedReader in = new BufferedReader(new StringReader(text)); + parseAtomicCoordinatesAndAtomicSpecies(in); + } + + public void parseAtomicCoordinatesAndAtomicSpecies(BufferedReader in) throws Exception { + String line, label; + StringTokenizer st; + double[] xyz = new double[3]; + + while ( (line = in.readLine()) != null) { + line = line.trim(); + if (line.length() < 1) { + continue; + } + + st = new StringTokenizer(line, " \t"); + label = st.nextToken().toLowerCase(); + if (label.equals("%endblock")) { + return; + } + + if (st.countTokens() < 3) { + throw new Exception("Expected at least 4 tokens to read AtomicCoordinatesAndAtomicSpecies, got " + line); + } + + // --- Parse coordinates + try { + for (int i = 0; i < 3; i++) { + if (i == 0) { + xyz[i] = Double.parseDouble(label); + } + else { + xyz[i] = Double.parseDouble(st.nextToken()); + } + } + } + catch (Exception ex) { + throw new Exception("Error while parsing AtomicCoordinatesAndAtomicSpecies coordinate, got " + line); + } + + // --- Parse species number + Integer number; + try { + number = Integer.parseInt(st.nextToken()); + } + catch (Exception ex) { + throw new Exception("Error while parsing AtomicCoordinatesAndAtomicSpecies number, got " + line); + } + + if (!chemicalSpeciesLabels.containsKey(number)) { + throw new Exception("There is no Chemical Species number " + number); + } + + ChemicalSpeciesLabel species = chemicalSpeciesLabels.get(number); + SiestaAtom atom = new SiestaAtom(species.atomicNumber, species.label, xyz[0], xyz[1], xyz[2], species.number); + atoms.add(atom); + } + } + + private void parseLatticeParameters(BufferedReader in) throws Exception { + String line, label; + StringTokenizer st; + + if ( (line = in.readLine()) == null) { + throw new Exception("Unexpected end of file while reading LatticeParameters"); + } + st = new StringTokenizer(line, " \t"); + if (st.countTokens() < 6) { + throw new Exception("Expected at least 6 tokens to read LatticeParameters, got " + line); + } + for (int j = 0; j < 6; j++) { + try { + latticeParameters[j] = Double.parseDouble(st.nextToken()); + } + catch (Exception ex) { + throw new Exception("Error while parsing LatticeParameters, got " + line); + } + } + + Crystal.validateLatticeParameters(latticeParameters[0], latticeParameters[1], latticeParameters[2], latticeParameters[3], + latticeParameters[4], latticeParameters[5]); + + // --- Read until end of block + + while (true) { + if ( (line = in.readLine()) == null) { + throw new Exception("Unexpected end of file while looking for end of block"); + } + line = line.trim().toLowerCase(); + if (line.startsWith("%endblock ")) { + break; + } + } + + defaultLatticeParameters = false; + useLatticeParameters = true; + + // --- Calculate lattice verctors + + buildLatticeVectors(latticeParameters[0] * latticeConstant, latticeParameters[1] * latticeConstant, + latticeParameters[2] * latticeConstant, latticeParameters[3], + latticeParameters[4], latticeParameters[5]); + } + + private void buildLatticeVectors(double a, double b, double c, double alpha, double beta, double gamma) { + alpha *= Constants.DEGREES_TO_RADIANS; + beta *= Constants.DEGREES_TO_RADIANS; + gamma *= Constants.DEGREES_TO_RADIANS; + + double factor = Math.sqrt(1.0 - Math.cos(alpha) * Math.cos(alpha) - Math.cos(beta) * Math.cos(beta) - + Math.cos(gamma) * Math.cos(gamma) + 2.0 * Math.cos(alpha) * Math.cos(beta) * Math.cos(gamma)); + /* + latticeVectors[0][0] = a; + latticeVectors[0][1] = b * Math.cos(gamma); + latticeVectors[0][2] = c * Math.cos(beta); + + latticeVectors[1][0] = 0; + latticeVectors[1][1] = b * Math.sin(gamma); + latticeVectors[1][2] = c * (Math.cos(alpha) - Math.cos(beta) * Math.cos(gamma)) / Math.sin(gamma); + + latticeVectors[2][0] = 0; + latticeVectors[2][1] = 0; + latticeVectors[2][2] = c * factor / Math.sin(gamma); + */ + + latticeVectors[0][0] = a; + latticeVectors[0][1] = 0; + latticeVectors[0][2] = 0; + + latticeVectors[1][0] = b * Math.cos(gamma); + latticeVectors[1][1] = b * Math.sin(gamma); + latticeVectors[1][2] = 0; + + latticeVectors[2][0] = c * Math.cos(beta); + latticeVectors[2][1] = c * (Math.cos(alpha) - Math.cos(beta) * Math.cos(gamma)) / Math.sin(gamma); + latticeVectors[2][2] = c * factor / Math.sin(gamma); + } + + private void parseLatticeVectors(BufferedReader in) throws Exception { + String line, label; + StringTokenizer st; + + for (int i = 0; i < 3; i++) { + if ( (line = in.readLine()) == null) { + throw new Exception("Unexpected end of file while reading " + (i + 1) + " LatticeVectors"); + } + st = new StringTokenizer(line, " \t"); + if (st.countTokens() < 3) { + throw new Exception("Expected at least 3 tokens to read parseLatticeVector, got " + line); + } + for (int j = 0; j < 3; j++) { + try { + latticeVectors[i][j] = Double.parseDouble(st.nextToken()); + } + catch (Exception ex) { + throw new Exception("Error while parsing LatticeVectors, got " + line); + } + + } + } + useLatticeParameters = false; + } + + public void parseChemicalSpeciesLabel(String text) throws Exception { + BufferedReader in = new BufferedReader(new StringReader(text)); + parseChemicalSpeciesLabel(in); + } + + public void parseChemicalSpeciesLabel(BufferedReader in) throws Exception { + String line, label; + StringTokenizer st; + while ( (line = in.readLine()) != null) { + line = line.trim(); + if (line.length() < 1) { + continue; + } + + st = new StringTokenizer(line, " \t"); + label = st.nextToken().toLowerCase(); + if (label.equals("%endblock")) { + return; + } + + if (st.countTokens() < 2) { + throw new Exception("Expected at least 3 tokens to read Chemical Species Labels, got " + line); + } + + Integer number; + try { + number = Integer.parseInt(label); + } + catch (Exception ex) { + throw new Exception("Error while parsing Chemical Species number, got " + line); + } + + if (chemicalSpeciesLabels.containsKey(number)) { + throw new Exception("Duplicate definition for Chemical Species number " + number + " Got " + line); + } + + int atomicNumber = 0; + try { + atomicNumber = Integer.parseInt(st.nextToken()); + } + catch (Exception ex) { + throw new Exception("Error while parsing Chemical Species atomic number, got " + line); + } + + ChemicalSpeciesLabel species = new ChemicalSpeciesLabel(number, atomicNumber, st.nextToken()); + chemicalSpeciesLabels.put(number, species); + } + } + + public void setLatticeParameters(float a, float b, float c, float alpha, float beta, float gamma) { + latticeParameters[0] = a; + latticeParameters[1] = b; + latticeParameters[2] = c; + latticeParameters[3] = alpha; + latticeParameters[4] = beta; + latticeParameters[5] = gamma; + + defaultLatticeParameters = false; + useLatticeParameters = true; + + // --- Calculate lattice verctors + + buildLatticeVectors(latticeParameters[0] * latticeConstant, latticeParameters[1] * latticeConstant, + latticeParameters[2] * latticeConstant, latticeParameters[3], + latticeParameters[4], latticeParameters[5]); + } + + public void setLatticeParameters(double a, double b, double c, double alpha, double beta, double gamma) { + latticeParameters[0] = a; + latticeParameters[1] = b; + latticeParameters[2] = c; + latticeParameters[3] = alpha; + latticeParameters[4] = beta; + latticeParameters[5] = gamma; + + defaultLatticeParameters = false; + useLatticeParameters = true; + + // --- Calculate lattice verctors + + buildLatticeVectors(latticeParameters[0] * latticeConstant, latticeParameters[1] * latticeConstant, + latticeParameters[2] * latticeConstant, latticeParameters[3], + latticeParameters[4], latticeParameters[5]); + } + + public void setSystemLabel(String name) { + systemLabel = name; + } + + public void setSystemName(String name) { + systemName = name; + } + + public void setAtomicCoordinatesFormat(AtomicCoordinatesFormat format) { + atomicCoordinatesFormat = format; + } + + public void setChemicalSpeciesLabels(Map speciesLabels) { + chemicalSpeciesLabels.clear(); + if (speciesLabels == null || speciesLabels.size() < 1) { + return; + } + chemicalSpeciesLabels.putAll(speciesLabels); + } + + public void setOtherOptions(List other) { + otherOptions.clear(); + if (other == null || other.size() < 1) { + return; + } + otherOptions.addAll(other); + } + + public void setOtherOptions(String other) { + otherOptions.clear(); + if (other == null || other.length() < 1) { + return; + } + + String line; + try { + BufferedReader in = new BufferedReader(new StringReader(other)); + while ( (line = in.readLine()) != null) { + otherOptions.add(line); + } + in.close(); + } + catch (Exception ex) { + System.err.println("setOtherOptions(String other): " + ex.getMessage()); + } + } + + public String getOtherOptionsAsString() { + if (otherOptions.size() < 1) { + return "\n"; + } + StringWriter sWriter = new StringWriter(); + for (int i = 0; i < otherOptions.size(); i++) { + sWriter.write(otherOptions.get(i) + "\n"); + } + return sWriter.toString(); + } + + public String getSpeciesLabelsAsString() { + if (chemicalSpeciesLabels == null || chemicalSpeciesLabels.size() < 1) { + return "\n"; + } + Object[] ints = chemicalSpeciesLabels.keySet().toArray(); + Arrays.sort(ints); + StringWriter sWriter = new StringWriter(); + for (int i = 0; i < ints.length; i++) { + Integer number = (Integer) ints[i]; + ChemicalSpeciesLabel label = chemicalSpeciesLabels.get(number); + sWriter.write(String.format(" %3d %2d %s\n", number, label.getAtomicNumber(), label.getSpeciesLabel())); + } + return sWriter.toString(); + } + + public String getAtomicCoordinatesAsString() { + if (atoms == null || atoms.size() < 1) { + + } + StringWriter sWriter = new StringWriter(1024); + for (int i = 0; i < atoms.size(); i++) { + SiestaAtom ga = atoms.get(i); + ChemicalSpeciesLabel label = chemicalSpeciesLabels.get(ga.species); + sWriter.write(String.format(" %12.6f %12.6f %12.6f %3d %4d %2s\n", ga.getCoordinates()[0], ga.getCoordinates()[1], + ga.getCoordinates()[2], ga.species, (i + 1), ga.getLabel())); + } + + return sWriter.toString(); + } + + public String getAtomicCoordinatesAsString(MoleculeInterface molec) { + if (molec == null || molec.getNumberOfAtoms() < 1) { + return "\n"; + } + + // --- Resolve species labels + + chemicalSpeciesLabels = Siesta.updateChemicalSpeciesLabels(molec, chemicalSpeciesLabels); + + // --- Print out coordinates + + float factor = 1.0f; + if (atomicCoordinatesFormat == AtomicCoordinatesFormat.Bohr || + atomicCoordinatesFormat == AtomicCoordinatesFormat.NotScaledCartesianBohr) { + factor = (float) (1.0 / Constants.ONE_BOHR); + } + + float[][] matrix = null; + if (atomicCoordinatesFormat == AtomicCoordinatesFormat.Fractional || + atomicCoordinatesFormat == AtomicCoordinatesFormat.ScaledByLatticeVectors) { + double[][] m = Crystal.getCartesianToFractionalTransMatrix(latticeParameters); + matrix = new float[3][3]; + for (int i = 0; i < 3; i++) { + matrix[i][0] = (float) m[i][0]; + matrix[i][1] = (float) m[i][1]; + matrix[i][2] = (float) m[i][2]; + } + } + + Object obj; + StringWriter sWriter = new StringWriter(1024); + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface atom = molec.getAtomInterface(i); + obj = atom.getProperty(SiestaInterface.SIESTA_SPECIES_NUMBER); + Integer number = (Integer) obj; + obj = atom.getProperty(SiestaInterface.SIESTA_SPECIES_LABEL); + switch (atomicCoordinatesFormat) { + case Fractional: + case ScaledByLatticeVectors: + float[] frac = getFractionalCoordinates(atom.getX(), atom.getY(), atom.getZ(), matrix); + sWriter.write(String.format(" %12.6f %12.6f %12.6f %3d %4d %2s\n", frac[0], frac[1], frac[2], number, (i + 1), + obj.toString())); + break; + + case Ang: + case NotScaledCartesianAng: + case Bohr: + case NotScaledCartesianBohr: + + sWriter.write(String.format(" %12.6f %12.6f %12.6f %3d %4d %2s\n", atom.getX() * factor, + atom.getY() * factor, atom.getZ() * factor, number, (i + 1), obj.toString())); + break; + } + } + return sWriter.toString(); + } + + public String getInputAsString() throws Exception { + if (atoms.size() < 1) { + throw new Exception("No atoms in SIESTA input"); + } + StringWriter sWriter = new StringWriter(); + + sWriter.write("SystemName " + systemName + "\n"); + sWriter.write("SystemLabel " + systemLabel + "\n"); + sWriter.write("\n"); + + sWriter.write("NumberOfSpecies " + chemicalSpeciesLabels.size() + "\n"); + sWriter.write("%block ChemicalSpeciesLabel\n"); + sWriter.append(this.getSpeciesLabelsAsString()); + sWriter.write("%endblock ChemicalSpeciesLabel\n"); + sWriter.write("\n"); + + sWriter.write("LatticeConstant " + latticeConstant + "\n"); + sWriter.write("%block LatticeParameters\n"); + sWriter.write(" " + latticeParameters[0] + " " + latticeParameters[1] + " " + latticeParameters[2] + " " + + latticeParameters[3] + " " + latticeParameters[4] + " " + latticeParameters[5] + "\n"); + sWriter.write("%endblock LatticeParameters\n"); + sWriter.write("\n"); + + sWriter.write("AtomicCoordinatesFormat " + atomicCoordinatesFormat.toString() + "\n"); + sWriter.write("NumberOfAtoms " + atoms.size() + "\n"); + sWriter.write("%block AtomicCoordinatesAndAtomicSpecies\n"); + sWriter.append(this.getAtomicCoordinatesAsString()); + sWriter.write("%endblock AtomicCoordinatesAndAtomicSpecies\n"); + sWriter.write("\n"); + + for (int i = 0; i < otherOptions.size(); i++) { + sWriter.write(otherOptions.get(i) + "\n"); + } + return sWriter.toString(); + } + + public static void centerContentsInCell(double[][] fracCoord, int nCenters) { + double x = 0, y = 0, z = 0; + for (int i = 0; i < nCenters; i++) { + x += fracCoord[i][0]; + y += fracCoord[i][1]; + z += fracCoord[i][2]; + } + + x = -x / (double) nCenters + 0.5; + y = -y / (double) nCenters + 0.5; + z = -z / (double) nCenters + 0.5; + + for (int i = 0; i < nCenters; i++) { + fracCoord[i][0] += x; + fracCoord[i][1] += y; + fracCoord[i][2] += z; + } + } + + public void centerContentsInCell() throws Exception { + double factor = 1.0; + switch (atomicCoordinatesFormat) { + case Fractional: + case ScaledByLatticeVectors: + double[][] fracCoord = new double[atoms.size()][3]; + for (int i = 0; i < atoms.size(); i++) { + SiestaAtom ga = atoms.get(i); + fracCoord[i][0] = ga.xyz[0]; + fracCoord[i][1] = ga.xyz[1]; + fracCoord[i][2] = ga.xyz[2]; + } + centerContentsInCell(fracCoord, atoms.size()); + + for (int i = 0; i < atoms.size(); i++) { + SiestaAtom ga = atoms.get(i); + ga.xyz[0] = fracCoord[i][0]; + ga.xyz[1] = fracCoord[i][1]; + ga.xyz[2] = fracCoord[i][2]; + } + + break; + + case Bohr: + case NotScaledCartesianBohr: + factor = 1.0 / Constants.ONE_BOHR; + case Ang: + case NotScaledCartesianAng: + double[][] m = Crystal.getCartesianToFractionalTransMatrix(latticeParameters); + double[][] frac = getFractionalCoordinates(m); + centerContentsInCell(frac, atoms.size()); + double[][] cartesian = Crystal.getCartesianFromFractional(frac, atoms.size(), latticeVectors); + for (int i = 0; i < atoms.size(); i++) { + SiestaAtom ga = atoms.get(i); + ga.xyz[0] = cartesian[i][0] * factor; + ga.xyz[1] = cartesian[i][1] * factor; + ga.xyz[2] = cartesian[i][2] * factor; + } + break; + } + } + + public double[][] getFractionalCoordinates(double[][] transMatrix) { + + double factor = 1.0; + double[][] frac = new double[atoms.size()][3]; + + switch (atomicCoordinatesFormat) { + case Fractional: + case ScaledByLatticeVectors: + for (int i = 0; i < atoms.size(); i++) { + SiestaAtom ga = atoms.get(i); + frac[i][0] = ga.getX(); + frac[i][1] = ga.getY(); + frac[i][2] = ga.getZ(); + } + break; + + case Bohr: + case NotScaledCartesianBohr: + factor = Constants.ONE_BOHR; + case Ang: + case NotScaledCartesianAng: + for (int i = 0; i < atoms.size(); i++) { + SiestaAtom ga = atoms.get(i); + frac[i][0] = (ga.getX() * transMatrix[0][0] + ga.getY() * transMatrix[1][0] + ga.getZ() * transMatrix[2][0]) * + factor; + frac[i][1] = (ga.getX() * transMatrix[0][1] + ga.getY() * transMatrix[1][1] + ga.getZ() * transMatrix[2][1]) * + factor; + frac[i][2] = (ga.getX() * transMatrix[0][2] + ga.getY() * transMatrix[1][2] + ga.getZ() * transMatrix[2][2]) * + factor; + } + break; + } + + return frac; + } + + public static float[] getFractionalCoordinates(float x, float y, float z, float[][] transMatrix) { + float[] frac = new float[3]; + frac[0] = x * transMatrix[0][0] + y * transMatrix[1][0] + z * transMatrix[2][0]; + frac[1] = x * transMatrix[0][1] + y * transMatrix[1][1] + z * transMatrix[2][1]; + frac[2] = x * transMatrix[0][2] + y * transMatrix[1][2] + z * transMatrix[2][2]; + return frac; + } + + class SiestaAtom { + private double[] xyz = new double[3]; + int element = 0; + private Integer species = 0; + private String label; + + public SiestaAtom(int el, String label, double x, double y, double z, Integer species) { + xyz[0] = x; + xyz[1] = y; + xyz[2] = z; + element = el; + this.species = species; + this.label = label; + } + + public double getX() { + return xyz[0]; + } + + public double getY() { + return xyz[1]; + } + + public double getZ() { + return xyz[2]; + } + + public Integer getSpecies() { + return species; + } + + public void setSpecies(Integer species) { + this.species = species; + } + + public String getLabel() { + return label; + } + + public double[] getCoordinates() { + return xyz; + } + + } + + public String getSystemLabel() { + return systemLabel; + } + + public Map getChemicalSpeciesLabels() { + return chemicalSpeciesLabels; + } + + public List getOtherOptions() { + return otherOptions; + } +} diff --git a/src/main/java/cct/siesta/SiestaInterface.java b/src/main/java/cct/siesta/SiestaInterface.java new file mode 100644 index 0000000..4a30cf0 --- /dev/null +++ b/src/main/java/cct/siesta/SiestaInterface.java @@ -0,0 +1,63 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.siesta; + +import java.util.List; +import java.util.Map; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public interface SiestaInterface { + String SIESTA_INTERFACE = "_Siesta Interface"; + String SIESTA_SPECIES_LABEL = "_Siesta Species Label"; + String SIESTA_SPECIES_NUMBER = "_Siesta Species Number"; + + Map getChemicalSpeciesLabels(); + List getOtherOptions(); + String getSystemLabel(); +} diff --git a/src/main/java/cct/siesta/ui/SaveSiestaInputDialog.java b/src/main/java/cct/siesta/ui/SaveSiestaInputDialog.java new file mode 100644 index 0000000..f55a641 --- /dev/null +++ b/src/main/java/cct/siesta/ui/SaveSiestaInputDialog.java @@ -0,0 +1,178 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.siesta.ui; + +import java.awt.BorderLayout; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JOptionPane; +import javax.swing.JPanel; + +import cct.interfaces.MoleculeInterface; +import cct.j3d.Java3dUniverse; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class SaveSiestaInputDialog + extends JDialog { + private JPanel panel1 = new JPanel(); + private BorderLayout borderLayout1 = new BorderLayout(); + private SiestaPanel siestaPanel1 = new SiestaPanel(); + private JPanel jPanel1 = new JPanel(); + private JButton cancelButton = new JButton(); + private JButton validateButton = new JButton(); + private JButton okButton = new JButton(); + private JButton saveEditButton = new JButton(); + + public SaveSiestaInputDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public SaveSiestaInputDialog() { + this(new Frame(), "SaveSiestaInputDialog", false); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + cancelButton.setToolTipText("Cancel & hide Dialog"); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + cancelButton_actionPerformed(e); + } + }); + validateButton.setToolTipText(""); + validateButton.setText("Validate Data"); + validateButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + jButton2_actionPerformed(e); + } + }); + okButton.setToolTipText(""); + okButton.setText(" Save "); + okButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + okButton_actionPerformed(e); + } + }); + saveEditButton.setToolTipText(""); + saveEditButton.setText("Edit & Save"); + saveEditButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + saveEditButton_actionPerformed(e); + } + }); + this.setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); + getContentPane().add(panel1); + panel1.add(siestaPanel1, BorderLayout.CENTER); + panel1.add(jPanel1, BorderLayout.SOUTH); + jPanel1.add(okButton); + jPanel1.add(saveEditButton); + jPanel1.add(validateButton); + jPanel1.add(cancelButton); + } + + public void setMolecularInterface(MoleculeInterface molec) { + siestaPanel1.setMolecularInterface(molec); + } + + public void cancelButton_actionPerformed(ActionEvent e) { + setVisible(false); + } + + public void setJava3dUniverse(Java3dUniverse j3dU) { + siestaPanel1.setJava3dUniverse(j3dU); + } + + public void okButton_actionPerformed(ActionEvent e) { + try { + siestaPanel1.validateData(); + siestaPanel1.saveData(false); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error saving file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + setVisible(false); + } + + public void jButton2_actionPerformed(ActionEvent e) { + try { + siestaPanel1.validateData(); + JOptionPane.showMessageDialog(this, "OK", "No errors found", JOptionPane.INFORMATION_MESSAGE); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error in data: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + } + + public void saveEditButton_actionPerformed(ActionEvent e) { + try { + siestaPanel1.validateData(); + siestaPanel1.saveData(true); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error saving data: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + } +} diff --git a/src/main/java/cct/siesta/ui/SiestaPanel.java b/src/main/java/cct/siesta/ui/SiestaPanel.java new file mode 100644 index 0000000..8c72fe1 --- /dev/null +++ b/src/main/java/cct/siesta/ui/SiestaPanel.java @@ -0,0 +1,635 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.siesta.ui; + +import java.awt.BorderLayout; +import java.awt.FileDialog; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.SystemColor; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.text.NumberFormat; +import java.util.Map; +import java.util.prefs.Preferences; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFormattedTextField; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTabbedPane; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.border.TitledBorder; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.j3d.Java3dUniverse; +import cct.j3d.UnitCellGraphics; +import cct.math.Crystal; +import cct.modelling.CCTAtomTypes; +import cct.modelling.Molecule; +import cct.siesta.AtomicCoordinatesFormat; +import cct.siesta.ChemicalSpeciesLabel; +import cct.siesta.Siesta; +import cct.siesta.SiestaInput; +import cct.siesta.SiestaInterface; +import cct.tools.FileUtilities; +import cct.tools.IOUtils; +import cct.tools.ui.JShowText; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class SiestaPanel + extends JPanel { + + private static String FontNameKey = "FontName"; + private static String FontSizeKey = "FontSize"; + private static String FontStyleKey = "FontStyle"; + private static String defaultFontName = "default"; + + private NumberFormat aFormat = NumberFormat.getNumberInstance(); + private NumberFormat bFormat = NumberFormat.getNumberInstance(); + private NumberFormat cFormat = NumberFormat.getNumberInstance(); + private NumberFormat alphaFormat = NumberFormat.getNumberInstance(); + private NumberFormat betaFormat = NumberFormat.getNumberInstance(); + private NumberFormat gammaFormat = NumberFormat.getNumberInstance(); + private NumberFormat lcConst = NumberFormat.getNumberInstance(); + + private BorderLayout borderLayout1 = new BorderLayout(); + private JPanel mainPanel = new JPanel(); + private BorderLayout borderLayout2 = new BorderLayout(); + private JPanel jPanel1 = new JPanel(); + private JPanel jPanel2 = new JPanel(); + private JPanel jPanel3 = new JPanel(); + private BorderLayout borderLayout3 = new BorderLayout(); + private JLabel jLabel1 = new JLabel(); + private FlowLayout flowLayout1 = new FlowLayout(); + private JLabel jLabel2 = new JLabel(); + private FlowLayout flowLayout2 = new FlowLayout(); + private JTextField systemNameTextField = new JTextField(); + private JTextField systemLabelTextField = new JTextField(); + private JPanel speciesPanel = new JPanel(); + private JScrollPane jScrollPane1 = new JScrollPane(); + private JTextArea speciesTextArea = new JTextArea(); + private BorderLayout borderLayout4 = new BorderLayout(); + private JPanel coordPanel = new JPanel(); + private JScrollPane jScrollPane2 = new JScrollPane(); + private JTextArea coordTextArea = new JTextArea(); + private BorderLayout borderLayout5 = new BorderLayout(); + private JTabbedPane jTabbedPane1 = new JTabbedPane(); + private JPanel otherPanel = new JPanel(); + private JScrollPane jScrollPane3 = new JScrollPane(); + private JTextArea otherTextArea = new JTextArea(); + private BorderLayout borderLayout6 = new BorderLayout(); + private JPanel jPanel4 = new JPanel(); + private BorderLayout borderLayout7 = new BorderLayout(); + private JPanel jPanel5 = new JPanel(); + private BorderLayout borderLayout8 = new BorderLayout(); + private JPanel jPanel6 = new JPanel(); + private JPanel latticePanel = new JPanel(); + private BorderLayout borderLayout9 = new BorderLayout(); + private JLabel jLabel3 = new JLabel(); + private JLabel jLabel4 = new JLabel(); + private JFormattedTextField latticeConstantTextField = new JFormattedTextField(lcConst); + private JComboBox formatComboBox = new JComboBox(); + private JLabel jLabel6 = new JLabel(); + private JLabel jLabel7 = new JLabel(); + private JLabel jLabel8 = new JLabel(); + private JLabel jLabel9 = new JLabel(); + private JLabel jLabel10 = new JLabel(); + private JFormattedTextField betaTextField = new JFormattedTextField(betaFormat); + private JFormattedTextField alphaTextField = new JFormattedTextField(alphaFormat); + private JFormattedTextField cTextField = new JFormattedTextField(cFormat); + private JFormattedTextField bTextField = new JFormattedTextField(bFormat); + private JFormattedTextField aTextField = new JFormattedTextField(aFormat); + private JFormattedTextField gammaTextField = new JFormattedTextField(gammaFormat); + private JPanel jPanel7 = new JPanel(); + private JPanel auxPanel = new JPanel(); + private GridBagLayout gridBagLayout1 = new GridBagLayout(); + private JLabel jLabel11 = new JLabel(); + private GridBagLayout gridBagLayout2 = new GridBagLayout(); + + private MoleculeInterface molecule = null; + private Preferences prefs; + private AtomicCoordinatesFormat atomicCoordinatesFormat; + private SiestaInput siestaInput = null; + private String defaultFileName = "siesta.fdf"; + private Java3dUniverse j3d = null; + private JButton centerMolButton = new JButton(); + private FlowLayout flowLayout3 = new FlowLayout(); + + public SiestaPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + mainPanel.setLayout(borderLayout2); + jPanel1.setLayout(borderLayout3); + jLabel1.setToolTipText(""); + jLabel1.setText("System Label:"); + jPanel3.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + jLabel2.setToolTipText(""); + jLabel2.setText("System Name:"); + jPanel2.setLayout(flowLayout2); + flowLayout2.setAlignment(FlowLayout.LEFT); + systemLabelTextField.setToolTipText(""); + systemLabelTextField.setText("siesta"); + systemLabelTextField.setColumns(20); + systemNameTextField.setColumns(20); + speciesPanel.setLayout(borderLayout4); + speciesPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder(SystemColor.controlDkShadow, 1), + "%block ChemicalSpeciesLabel")); + coordPanel.setLayout(borderLayout5); + coordPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder(SystemColor.controlDkShadow, 1), + "%block AtomicCoordinatesAndAtomicSpecies")); + otherPanel.setLayout(borderLayout6); + otherTextArea.setToolTipText(""); + coordTextArea.setToolTipText(""); + coordTextArea.setRows(10); + jPanel4.setLayout(borderLayout7); + jPanel5.setLayout(borderLayout8); + jPanel6.setLayout(borderLayout9); + jLabel3.setToolTipText(""); + jLabel3.setText("Atomic Coordinates Format:"); + latticePanel.setLayout(gridBagLayout1); + jLabel4.setToolTipText(""); + jLabel4.setText("Lattice Constant:"); + latticeConstantTextField.setValue(new Double(1.0)); + latticeConstantTextField.setColumns(10); + jLabel6.setToolTipText(""); + jLabel6.setText("beta:"); + jLabel7.setToolTipText(""); + jLabel7.setText("a:"); + jLabel8.setToolTipText(""); + jLabel8.setText("b:"); + jLabel9.setToolTipText(""); + jLabel9.setText("c:"); + jLabel10.setToolTipText(""); + jLabel10.setText("gamma:"); + betaTextField.setValue(new Double(90.0)); + alphaTextField.setValue(new Double(90.0)); + cTextField.setValue(new Double(1.0)); + bTextField.setValue(new Double(1.0)); + aTextField.setValue(new Double(1.0)); + gammaTextField.setValue(new Double(90.0)); + jLabel11.setToolTipText(""); + jLabel11.setText("alpha:"); + jPanel7.setLayout(gridBagLayout2); + speciesTextArea.setRows(5); + jPanel7.setBorder(new TitledBorder(BorderFactory.createLineBorder(SystemColor.controlDkShadow, 1), "Lattice Parameters")); + formatComboBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + formatComboBox_actionPerformed(e); + } + }); + otherTextArea.setRows(20); + centerMolButton.setToolTipText("Center Molecule in Cell"); + centerMolButton.setText("Center"); + centerMolButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + centerMolButton_actionPerformed(e); + } + }); + auxPanel.setLayout(flowLayout3); + jPanel2.add(jLabel2); + jPanel2.add(systemNameTextField); + jScrollPane3.getViewport().add(otherTextArea); + + jPanel3.add(jLabel1); + jPanel3.add(systemLabelTextField); + jPanel1.add(jPanel2, BorderLayout.NORTH); + jPanel1.add(jPanel3, BorderLayout.CENTER); + + mainPanel.add(jPanel4, BorderLayout.NORTH); + jPanel4.add(jPanel5, BorderLayout.NORTH); + speciesPanel.add(jScrollPane1, BorderLayout.CENTER); + jPanel5.add(jPanel6, BorderLayout.NORTH); + jScrollPane1.getViewport().add(speciesTextArea); + mainPanel.add(coordPanel, BorderLayout.CENTER); + jScrollPane2.getViewport().add(coordTextArea); + this.add(jTabbedPane1, BorderLayout.CENTER); + jTabbedPane1.add(mainPanel, "Basic Options"); + jTabbedPane1.add(otherPanel, "Other"); + otherPanel.add(jScrollPane3, BorderLayout.CENTER); + coordPanel.add(jScrollPane2, BorderLayout.CENTER); + jPanel5.add(speciesPanel, BorderLayout.SOUTH); + jPanel6.add(jPanel1, BorderLayout.NORTH); + jPanel6.add(latticePanel, BorderLayout.CENTER); + latticePanel.add(jLabel4, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + latticePanel.add(jPanel7, new GridBagConstraints(0, 2, 2, 1, 1.0, 1.0 + , GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(2, 2, 2, 2), 0, 0)); + jPanel7.add(aTextField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0)); + jPanel7.add(bTextField, new GridBagConstraints(3, 0, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0)); + jPanel7.add(cTextField, new GridBagConstraints(5, 0, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0)); + jPanel7.add(alphaTextField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0)); + jPanel7.add(betaTextField, new GridBagConstraints(3, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0)); + jPanel7.add(gammaTextField, new GridBagConstraints(5, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0)); + jPanel7.add(jLabel7, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + + jPanel7.add(jLabel11, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + jPanel7.add(jLabel8, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + jPanel7.add(jLabel6, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + jPanel7.add(jLabel9, new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + jPanel7.add(jLabel10, new GridBagConstraints(4, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + latticePanel.add(latticeConstantTextField, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + latticePanel.add(formatComboBox, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + latticePanel.add(jLabel3, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); + jPanel7.add(auxPanel, new GridBagConstraints(0, 2, 6, 1, 1.0, 0.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0)); + auxPanel.add(centerMolButton); + jTabbedPane1.setSelectedComponent(mainPanel); + + AtomicCoordinatesFormat[] formats = AtomicCoordinatesFormat.values(); + formatComboBox.removeAllItems(); + for (int i = 0; i < formats.length; i++) { + formatComboBox.addItem(formats[i]); + } + atomicCoordinatesFormat = Siesta.getDefaultAtomicCoordinatesFormat(); + formatComboBox.setSelectedItem(atomicCoordinatesFormat); + + Font currentFont = speciesTextArea.getFont(); + int size = currentFont.getSize(); + int style = currentFont.getStyle(); + String fontName = currentFont.getFontName(); + + try { + prefs = Preferences.userNodeForPackage(this.getClass()); + fontName = prefs.get(FontNameKey, currentFont.getFontName()); + size = prefs.getInt(FontSizeKey, 12); + style = prefs.getInt(FontStyleKey, 0); + } + catch (Exception ex) { + //System.err.println("Error retrieving Font Preferences: " + ex.getMessage()); + //return; + } + + Font newFont = new Font(fontName, style, size); + speciesTextArea.setFont(newFont); + coordTextArea.setFont(newFont); + otherTextArea.setFont(newFont); + + aFormat.setMaximumFractionDigits(6); + bFormat.setMaximumFractionDigits(6); + cFormat.setMaximumFractionDigits(6); + alphaFormat.setMaximumFractionDigits(6); + betaFormat.setMaximumFractionDigits(6); + gammaFormat.setMaximumFractionDigits(6); + } + + public void setJava3dUniverse(Java3dUniverse j3dU) { + j3d = j3dU; + } + + private void setLatticeParameters(double[] latticeParameters) { + aTextField.setValue(new Double(latticeParameters[0])); + bTextField.setValue(new Double(latticeParameters[1])); + cTextField.setValue(new Double(latticeParameters[2])); + alphaTextField.setValue(new Double(latticeParameters[3])); + betaTextField.setValue(new Double(latticeParameters[4])); + gammaTextField.setValue(new Double(latticeParameters[5])); + siestaInput.setLatticeParameters(latticeParameters[0], latticeParameters[1], latticeParameters[2], latticeParameters[3], + latticeParameters[4], latticeParameters[5]); + } + + public void setMolecularInterface(MoleculeInterface molec) { + molecule = molec; + systemNameTextField.setText(molecule.getName()); + + siestaInput = new SiestaInput(); + siestaInput.setSystemName(molecule.getName()); + + Object obj = molec.getProperty(MoleculeInterface.LATTICE_PARAMETERS); + boolean no_cell_params = true; + if (obj != null) { + if (obj instanceof float[]) { + float[] latticeParameters = (float[]) obj; + aTextField.setValue(new Double(latticeParameters[0])); + bTextField.setValue(new Double(latticeParameters[1])); + cTextField.setValue(new Double(latticeParameters[2])); + alphaTextField.setValue(new Double(latticeParameters[3])); + betaTextField.setValue(new Double(latticeParameters[4])); + gammaTextField.setValue(new Double(latticeParameters[5])); + siestaInput.setLatticeParameters(latticeParameters[0], latticeParameters[1], latticeParameters[2], latticeParameters[3], + latticeParameters[4], latticeParameters[5]); + no_cell_params = false; + } + else if (obj instanceof double[]) { + double[] latticeParameters = (double[]) obj; + setLatticeParameters(latticeParameters); + no_cell_params = false; + } + else { + JOptionPane.showMessageDialog(this, "Unknown container(class) for lattice parameters: " + + obj.getClass().getCanonicalName(), "Error", JOptionPane.ERROR_MESSAGE); + obj = null; + } + } + + // --- try to work with lattice vectors + + if (obj == null) { + obj = molec.getProperty(MoleculeInterface.LATTICE_VECTORS); + if (obj != null) { + double[][] latticeVectors = (double[][]) obj; + double[] latticeParameters = Crystal.latticeParamFromLatticeVectors(latticeVectors); + setLatticeParameters(latticeParameters); + } + else { // == null + double[] latticeParameters = Crystal.getDefaultLatticeParameters(molec, 0.25); + setLatticeParameters(latticeParameters); + setLatticeParameters(latticeParameters); + } + } + + // --- Set format + atomicCoordinatesFormat = AtomicCoordinatesFormat.NotScaledCartesianAng; + formatComboBox.setEnabled(false); + formatComboBox.setSelectedItem(atomicCoordinatesFormat); + formatComboBox.setEnabled(true); + siestaInput.setAtomicCoordinatesFormat(atomicCoordinatesFormat); + + // --- Resolve species labels + + Map chemicalSpeciesLabels = null; + SiestaInterface siesta = null; + obj = molecule.getProperty(SiestaInterface.SIESTA_INTERFACE); + if (obj != null) { + if (! (obj instanceof SiestaInterface)) { + JOptionPane.showMessageDialog(this, "Unknown container(class) for siesta interface: " + + obj.getClass().getCanonicalName(), "Error", JOptionPane.ERROR_MESSAGE); + } + else { // use siesta info + siesta = (SiestaInterface) obj; + chemicalSpeciesLabels = siesta.getChemicalSpeciesLabels(); + java.util.List otherOptions = siesta.getOtherOptions(); + siestaInput.setOtherOptions(otherOptions); + } + } + else { // Default options + chemicalSpeciesLabels = Siesta.formChemicalSpeciesLabels(molecule); + } + + siestaInput.setChemicalSpeciesLabels(chemicalSpeciesLabels); + + // --- Setup species + + speciesTextArea.setText(siestaInput.getSpeciesLabelsAsString()); + speciesTextArea.setCaretPosition(0); + + // --- Setup coordinates + + coordTextArea.setText(siestaInput.getAtomicCoordinatesAsString(molecule)); + coordTextArea.setCaretPosition(0); + + // --- Setup other options + + otherTextArea.setText(siestaInput.getOtherOptionsAsString()); + otherTextArea.setCaretPosition(0); + + if (j3d != null) { + UnitCellGraphics siestaUC = new UnitCellGraphics("Siesta Unit Cell"); + j3d.addGraphics(siestaUC.getCellGraphicsObject(siestaInput.getLatticeVectors())); + } + + } + + public void formatComboBox_actionPerformed(ActionEvent e) { + if (!formatComboBox.isEnabled()) { + return; + } + + if (molecule == null) { + return; + } + + AtomicCoordinatesFormat format = (AtomicCoordinatesFormat) formatComboBox.getSelectedItem(); + siestaInput.setAtomicCoordinatesFormat(format); + + switch (format) { + case Fractional: + case ScaledByLatticeVectors: + if (atomicCoordinatesFormat == AtomicCoordinatesFormat.Fractional || + atomicCoordinatesFormat == AtomicCoordinatesFormat.ScaledByLatticeVectors) { + return; + } + break; + + case Ang: + case NotScaledCartesianAng: + if (atomicCoordinatesFormat == AtomicCoordinatesFormat.Ang || + atomicCoordinatesFormat == AtomicCoordinatesFormat.NotScaledCartesianAng) { + return; + } + break; + + case Bohr: + case NotScaledCartesianBohr: + if (atomicCoordinatesFormat == AtomicCoordinatesFormat.Bohr || + atomicCoordinatesFormat == AtomicCoordinatesFormat.NotScaledCartesianBohr) { + return; + } + break; + + } + coordTextArea.setText(siestaInput.getAtomicCoordinatesAsString(molecule)); + coordTextArea.setCaretPosition(0); + atomicCoordinatesFormat = format; + } + + public void validateData() throws Exception { + SiestaInput siestaInput = createSiestaObject(); + updateScene(siestaInput); + } + + private SiestaInput createSiestaObject() throws Exception { + //if (siestaInput == null) { + SiestaInput siesta = new SiestaInput(); + //} + siesta.setSystemName(systemNameTextField.getText()); + siesta.setSystemLabel(systemLabelTextField.getText()); + + double lC = ( (Number) latticeConstantTextField.getValue()).doubleValue(); + if (lC <= 0.0) { + throw new Exception("Lattice Constant cannot be less than 0. Got " + lC); + } + siesta.setLatticeConstant(lC); + + AtomicCoordinatesFormat atomicCoordinatesFormat = (AtomicCoordinatesFormat) formatComboBox.getSelectedItem(); + siesta.setAtomicCoordinatesFormat(atomicCoordinatesFormat); + + double a = ( (Number) aTextField.getValue()).doubleValue(); + double b = ( (Number) bTextField.getValue()).doubleValue(); + double c = ( (Number) cTextField.getValue()).doubleValue(); + + double alpha = ( (Number) alphaTextField.getValue()).doubleValue(); + double beta = ( (Number) betaTextField.getValue()).doubleValue(); + double gamma = ( (Number) gammaTextField.getValue()).doubleValue(); + + Crystal.validateLatticeParameters(a, b, c, alpha, beta, gamma); + + siesta.setLatticeParameters(a, b, c, alpha, beta, gamma); + + siesta.parseChemicalSpeciesLabel(speciesTextArea.getText()); + + siesta.parseAtomicCoordinatesAndAtomicSpecies(coordTextArea.getText()); + + siesta.setOtherOptions(otherTextArea.getText()); + return siesta; + } + + private void updateScene(SiestaInput siestaInput) { + if (j3d == null) { + return; + } + try { + molecule = molecule.getInstance(); + siestaInput.getMolecularInterface(molecule); + Molecule.guessCovalentBonds(molecule); + Molecule.guessAtomTypes(molecule, AtomInterface.CCT_ATOM_TYPE, CCTAtomTypes.getElementMapping()); + + j3d.setMolecule(molecule); + UnitCellGraphics siestaUC = new UnitCellGraphics("Siesta Unit Cell"); + j3d.addGraphics(siestaUC.getCellGraphicsObject(siestaInput.getLatticeVectors())); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Cannot render scene: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + } + + public void saveData(boolean withEditing) throws Exception { + if (withEditing) { + JShowText editSave = new JShowText("SIESTA Input Data"); + editSave.setDefaultFileName(defaultFileName); + editSave.setActionButton(JShowText.QUIT_WITH_SAVING); + editSave.enableTextEditing(false); + editSave.setLocationRelativeTo(this); + editSave.setText(getInputAsString()); + editSave.pack(); + editSave.setSize(600, 640); + editSave.setVisible(true); + } + else { + String text = getInputAsString(); + FileDialog fd = new FileDialog(new Frame(), "Save File", FileDialog.SAVE); + fd.setFile(defaultFileName); + fd.setVisible(true); + if (fd.getFile() != null) { + String fileName = fd.getFile(); + String name = FileUtilities.getFileName(fileName); + if (name.indexOf(".") == -1) { + fileName += ".fdf"; + } + + String workingDirectory = fd.getDirectory(); + try { + IOUtils.saveStringIntoFile(text, workingDirectory + fileName); + } + catch (Exception ex) { + throw new Exception("Error Saving file: " + ex.getMessage()); + } + } + } + } + + public String getInputAsString() throws Exception { + if (siestaInput == null) { + siestaInput = new SiestaInput(); + } + return siestaInput.getInputAsString(); + } + + public void centerMolButton_actionPerformed(ActionEvent e) { + try { + siestaInput = createSiestaObject(); + siestaInput.centerContentsInCell(); + coordTextArea.setText(siestaInput.getAtomicCoordinatesAsString()); + coordTextArea.setCaretPosition(0); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error in data: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + if (j3d == null) { + return; + } + updateScene(siestaInput); + } +} diff --git a/src/main/java/cct/ssh/J2SSHTest.java b/src/main/java/cct/ssh/J2SSHTest.java new file mode 100644 index 0000000..40a6a24 --- /dev/null +++ b/src/main/java/cct/ssh/J2SSHTest.java @@ -0,0 +1,358 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.ssh; + +import java.awt.Frame; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.List; +import java.util.logging.Logger; + +import com.sshtools.common.authentication.PasswordAuthenticationDialog; +import com.sshtools.j2ssh.SftpClient; +import com.sshtools.j2ssh.SshClient; +import com.sshtools.j2ssh.authentication.AuthenticationProtocolState; +import com.sshtools.j2ssh.authentication.KBIAuthenticationClient; +import com.sshtools.j2ssh.authentication.KBIPrompt; +import com.sshtools.j2ssh.authentication.KBIRequestHandler; +import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient; +import com.sshtools.j2ssh.configuration.ConfigurationLoader; +import com.sshtools.j2ssh.connection.ChannelState; +import com.sshtools.j2ssh.io.IOStreamConnector; +import com.sshtools.j2ssh.session.SessionChannelClient; +import com.sshtools.j2ssh.sftp.SftpFile; +import com.sshtools.j2ssh.transport.IgnoreHostKeyVerification; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class J2SSHTest { + private static BufferedReader reader = + new BufferedReader(new InputStreamReader(System.in)); + static final Logger logger = Logger.getLogger(J2SSHTest.class.getCanonicalName()); + public J2SSHTest() { + + String username = "vvv900"; + + try { + ConfigurationLoader.initialize(false); + + // Further code will be added here + SshClient ssh = new SshClient(); + + System.out.print("Host to connect: "); + + String hostname = "ac.anu.edu.au"; + + // Making the initial connection + + ssh.connect(hostname, new IgnoreHostKeyVerification()); + + logger.info("System banner:\n" + ssh.getAuthenticationBanner(500)); + + // Retrieving the available authentication Methods + +// It is possible at any time after the connection has been established +// and before authentication has been completed to request a list of authentication methods that can be used. +// The getAvailableAuthMethods method returns a list of authentication method names. + + List available = ssh.getAvailableAuthMethods(username); + + logger.info("Available Authentication Methods:"); + for (int i = 0; i < available.size(); i++) { + logger.info(available.get(i).toString()); + } + + int result = AuthenticationProtocolState.FAILED; + + if (available.contains("password")) { + PasswordAuthenticationClient pwd = new PasswordAuthenticationClient(); + + PasswordAuthenticationDialog dialog = new PasswordAuthenticationDialog(new + Frame()); + //dialog.setVisible(true); + + pwd.setAuthenticationPrompt(dialog); // ??? + + //System.out.print("Username: "); + //String username = reader.readLine(); + pwd.setUsername(username); + + //System.out.print("Password: "); + //String password = reader.readLine(); + pwd.setPassword("xxx"); + + result = ssh.authenticate(pwd); + + } + else if (available.contains("keyboard-interactive")) { + /* + * Create the keyboard-interactive instance + */ + KBIAuthenticationClient kbi = new KBIAuthenticationClient(); + // Get the users name + System.out.print("Username? "); + // Read the password + username = reader.readLine(); + kbi.setUsername(username); + + // Set the callback interface + kbi.setKBIRequestHandler(new KBIRequestHandler() { + @Override + public void showPrompts(String name, String instructions, + KBIPrompt[] prompts) { + logger.info(name); + logger.info(instructions); + String response; + if (prompts != null) { + for (int i = 0; i < prompts.length; i++) { + System.out.print(prompts[i].getPrompt() + ": "); + try { + response = reader.readLine(); + prompts[i].setResponse(response); + } + catch (IOException ex) { + prompts[i].setResponse(""); + ex.printStackTrace(); + } + } + } + } + }); + + // Try the authentication + result = ssh.authenticate(kbi); + } + +//It should be noted that the SSH specification allows the server to return authentication methods that are not valid +//for the user. + + + // In the default implementation of the connect method, J2SSH reads the $HOME/.ssh/known_hosts file + // to determines to which hosts connections may be allowed. + // This is provided by the class ConsoleKnownHostsKeyVerification and the + // default behavior can be emulated by the following code: + + //import com.sshtools.j2ssh.transport.ConsoleKnownHostsKeyVerification; + + + // ssh.connect("firestar", new ConsoleKnownHostsKeyVerification()); + + // When the connect method returns, the protocol has been negotiated and key exchange has taken place, + // leaving the connection ready for authenticating the user. + + // Authenticating the user + + // Once the connection has been completed the user is required to provide a set of credentials for authentication. + // All client side authentication methods are implemented using the abstract class: + + // import com.sshtools.j2ssh.authentication.SshAuthenticationClient. + + // To perform authentication, the SshClient class provides the following method: + + // public int authenticate(SshAuthenticationClient auth); + + // There are currently five authentication methods implemented by J2SSH, 'password', 'publickey', + // 'keyboard-interactive' and 'hostbased'. With an extra agent authentication method + // that performs public key authentication using the J2SSH key agent. + + /** + * Create a PasswordAuthenticationClient instance, set the properties + * and pass to the SessionClient to authenticate + */ + + + // The Authentication Result + + // When the authentication method completes it returns the result of the authentication. This integer value can be any + // of the following three values defined in the class: + + if (result == AuthenticationProtocolState.FAILED) { + logger.info("The authentication failed"); + } + + if (result == AuthenticationProtocolState.PARTIAL) { + logger.info("The authentication succeeded but another" + + "authentication is required"); + } + + if (result == AuthenticationProtocolState.COMPLETE) { + logger.info("The authentication is complete"); + + SessionChannelClient session = ssh.openSessionChannel(); + if (!session.requestPseudoTerminal("vt100", 80, 24, 0, 0, "")) { + logger.info("Failed to allocate a pseudo terminal"); + } + if (session.startShell()) { + IOStreamConnector input = + new IOStreamConnector(); + IOStreamConnector output = + new IOStreamConnector(); + IOStreamConnector error = + new IOStreamConnector(); + output.setCloseOutput(false); + input.setCloseInput(false); + error.setCloseOutput(false); + input.connect(System.in, session.getOutputStream()); + output.connect(session.getInputStream(), System.out); + error.connect(session.getStderrInputStream(), System.out); + session.getState().waitForState(ChannelState.CHANNEL_CLOSED); + } + else { + logger.info("Failed to start the users shell"); + } + ssh.disconnect(); + + } + + // SFTP + + SftpClient sftp = ssh.openSftpClient(); + List fileList = sftp.ls(); + + logger.info("Remote Directory List:"); + for (int i = 0; i < fileList.size(); i++) { + SftpFile file = (SftpFile) fileList.get(i); + + logger.info(file.getFilename() + " " + file.getAbsolutePath()); + } + + // The session channel provides an inputstream and outputstream for reading/writing, + // but before we can do this we need to setup the channel for our command. + // First we open the channel itself by calling the SshClient method: + + + SessionChannelClient session = ssh.openSessionChannel(); + + // Now that we have a session instance we need to configure it for our command, + // there are several options that can be set before we invoke one of the methods that will start the session. + + // Setting Environment Variables + + // public boolean setEnvironmentVariable(String name, String value); + + // Requesting a Pseudo Terminal + + // A pseudo terminal is a device that imitates a terminal. Rather than being connected to an actual terminal, + // a pseudo-terminal (or pty) is connected to a process. If the command you are executing is expecting a terminal + // (such as a shell command) you can request that a pseudo terminal be attached to the process by calling the requestPseudoTerminal method. + + logger.info("Opening pseudoterminal..."); + session.requestPseudoTerminal("ansi", 80, 25, 0, 0, ""); + logger.info("Opened pseudoterminal"); + + // Invoking a command + + //After the above operations have been performed you can then request that the session + // either start the user's shell, execute a specific command or start an SSH subsystem (such as SFTP). + // You should not invoke a subsystem unless you are able to read/write the subsystem protocol, + // there are many additional utilities within J2SSH that provide for the available subsystems. + + //session.startShell(); + + logger.info("Issuing command..."); + session.executeCommand("z01"); + session.executeCommand("date"); + logger.info("Issued command"); + + // Handling Session Data + + // Once the session has been configured and a command or shell has been started, you can begin to + // transfer data to and from the remote computer using the sessions IO streams. These streams provide you with a + // standardized interface for reading and writing the data. + + // The Session Channel's OutputStream + // The format of writing data varies according to how you configured the session, for example if you executed the + // users shell then the data should be written as if the user had entered the commands interactively. + + + /** Writing to the session OutputStream */ + /* + OutputStream out = session.getOutputStream(); + String cmd = "ls\n"; + out.write(cmd.getBytes()); + */ + + // The Session Channel's InputStream + + /** + * Reading from the session InputStream + */ + InputStream in = session.getInputStream(); + byte buffer[] = new byte[255]; + int read; + while ( (read = in.read(buffer)) > 0) { + String outstr = new String(buffer, 0, read); + logger.info(outstr); + } + + // Reading from stderr + // The session also provides the stderr data provided by the remote session. Again an InputStream is provided. + + //public InputStream session.getStderrInputStream(); + + // Closing the Session + + // The session can be closed using the following method: + + session.close(); + + ssh.disconnect(); + } + + catch (Exception e) { + e.printStackTrace(); + } + + } + + public static void main(String[] args) { + J2SSHTest j2sshtest = new J2SSHTest(); + } +} diff --git a/src/main/java/cct/ssh/KBIConnect.java b/src/main/java/cct/ssh/KBIConnect.java new file mode 100644 index 0000000..9242018 --- /dev/null +++ b/src/main/java/cct/ssh/KBIConnect.java @@ -0,0 +1,136 @@ +package cct.ssh; + +/* + * Sshtools - Java SSH2 API + * + * Copyright (C) 2002 Lee David Painter. + * + * Written by: 2002 Lee David Painter + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library 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 Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.logging.Logger; + +import com.sshtools.j2ssh.SshClient; +import com.sshtools.j2ssh.authentication.AuthenticationProtocolState; +import com.sshtools.j2ssh.authentication.KBIAuthenticationClient; +import com.sshtools.j2ssh.authentication.KBIPrompt; +import com.sshtools.j2ssh.authentication.KBIRequestHandler; +import com.sshtools.j2ssh.configuration.ConfigurationLoader; +import com.sshtools.j2ssh.configuration.SshConnectionProperties; +import com.sshtools.j2ssh.io.IOStreamConnector; +import com.sshtools.j2ssh.io.IOStreamConnectorState; +import com.sshtools.j2ssh.session.SessionChannelClient; + +/*import java.util.logging.FileHandler; + import java.util.logging.Handler; + import java.util.logging.Level; + import java.util.logging.Logger; + import java.util.logging.SimpleFormatter;*/ +/** + * Demonstrates a simple password connection to an SSH server. + * + * @author Lee David Painter + * @version $Id: KBIConnect.java,v 1.8 2003/07/16 10:42:07 t_magicthize Exp $ + * + * @created 20 December 2002 + */ +public class KBIConnect { + private static BufferedReader reader = + new BufferedReader(new InputStreamReader(System.in)); + static final Logger logger = Logger.getLogger(KBIConnect.class.getCanonicalName()); + /** + * The main program for the PasswordConnect class + * + * @param args The command line arguments + */ + public static void main(String args[]) { + try { + // Setup a logfile + /*Handler fh = new FileHandler("example.log"); + fh.setFormatter(new SimpleFormatter()); + Logger.getLogger("com.sshtools").setUseParentHandlers(false); + Logger.getLogger("com.sshtools").addHandler(fh); + Logger.getLogger("com.sshtools").setLevel(Level.ALL);*/ + // Configure J2SSH (This will attempt to install the bouncycastle provider + // under jdk 1.3.1) + ConfigurationLoader.initialize(false); + System.out.print("Connect to host? "); + System.out.print("Connect to host? "); + String hostname = reader.readLine(); + // Make a client connection + SshClient ssh = new SshClient(); + SshConnectionProperties properties = new SshConnectionProperties(); + properties.setHost(hostname); + // Connect to the host + ssh.connect(properties); + // Create a password authentication instance + KBIAuthenticationClient kbi = new KBIAuthenticationClient(); + // Get the users name + System.out.print("Username? "); + // Read the password + String username = reader.readLine(); + kbi.setUsername(username); + kbi.setKBIRequestHandler(new KBIRequestHandler() { + @Override + public void showPrompts(String name, String instructions, + KBIPrompt[] prompts) { + logger.info(name); + logger.info(instructions); + String response; + if (prompts != null) { + for (int i = 0; i < prompts.length; i++) { + System.out.print(prompts[i].getPrompt() + ": "); + try { + response = reader.readLine(); + prompts[i].setResponse(response); + } + catch (IOException ex) { + prompts[i].setResponse(""); + ex.printStackTrace(); + } + } + } + } + }); + // Try the authentication + int result = ssh.authenticate(kbi); + // Evaluate the result + if (result == AuthenticationProtocolState.COMPLETE) { + // The connection is authenticated we can now do some real work! + SessionChannelClient session = ssh.openSessionChannel(); + if (!session.requestPseudoTerminal("vt100", 80, 24, 0, 0, "")) { + logger.info("Failed to allocate a pseudo terminal"); + } + if (session.startShell()) { + IOStreamConnector input = + new IOStreamConnector(System.in, session.getOutputStream()); + IOStreamConnector output = + new IOStreamConnector(session.getInputStream(), System.out); + output.getState().waitForState(IOStreamConnectorState.CLOSED); + } + else { + logger.info("Failed to start the users shell"); + } + ssh.disconnect(); + } + } + catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/cct/ssh/PasswordConnect.java b/src/main/java/cct/ssh/PasswordConnect.java new file mode 100644 index 0000000..9c53556 --- /dev/null +++ b/src/main/java/cct/ssh/PasswordConnect.java @@ -0,0 +1,126 @@ +package cct.ssh; + +/* + * Sshtools - Java SSH2 API + * + * Copyright (C) 2002 Lee David Painter. + * + * Written by: 2002 Lee David Painter + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library 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 Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.logging.Logger; + +import com.sshtools.j2ssh.SshClient; +import com.sshtools.j2ssh.authentication.AuthenticationProtocolState; +import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient; +import com.sshtools.j2ssh.configuration.ConfigurationLoader; +import com.sshtools.j2ssh.configuration.SshConnectionProperties; +import com.sshtools.j2ssh.connection.ChannelState; +import com.sshtools.j2ssh.io.IOStreamConnector; +import com.sshtools.j2ssh.session.SessionChannelClient; + +// JDK > 1.4 ONLY +/*import java.util.logging.FileHandler; + import java.util.logging.Handler; + import java.util.logging.Level; + import java.util.logging.Logger; + import java.util.logging.SimpleFormatter;*/ +/** + * Demonstrates a simple password connection to an SSH server. + * + * @author Lee David Painter + * @version $Id: PasswordConnect.java,v 1.12 2003/07/16 10:42:07 t_magicthize Exp $ + * + * @created 20 December 2002 + */ +public class PasswordConnect { + + static final Logger logger = Logger.getLogger(PasswordConnect.class.getCanonicalName()); + /** + * The main program for the PasswordConnect class + * + * @param args The command line arguments + */ + public static void main(String args[]) { + try { + // JDK > 1.4 ONLY + /*Handler fh = new FileHandler("example.log"); + fh.setFormatter(new SimpleFormatter()); + Logger.getLogger("com.sshtools").setUseParentHandlers(false); + Logger.getLogger("com.sshtools").addHandler(fh); + Logger.getLogger("com.sshtools").setLevel(Level.ALL);*/ + // Configure J2SSH (This will attempt to install the bouncycastle provider + // under jdk 1.3.1) + ConfigurationLoader.initialize(false); + BufferedReader reader = + new BufferedReader(new InputStreamReader(System.in)); + System.out.print("Connect to host? "); + String hostname = reader.readLine(); + // Make a client connection + SshClient ssh = new SshClient(); + ssh.setSocketTimeout(30000); + SshConnectionProperties properties = new SshConnectionProperties(); + properties.setHost(hostname); + properties.setPrefPublicKey("ssh-dss"); + // Connect to the host + ssh.connect(properties); + // Create a password authentication instance + PasswordAuthenticationClient pwd = new PasswordAuthenticationClient(); + // Get the users name + System.out.print("Username? "); + // Read the password + String username = reader.readLine(); + pwd.setUsername(username); + // Get the password + System.out.print("Password? "); + String password = reader.readLine(); + pwd.setPassword(password); + // Try the authentication + int result = ssh.authenticate(pwd); + // Evaluate the result + if (result == AuthenticationProtocolState.COMPLETE) { + // The connection is authenticated we can now do some real work! + SessionChannelClient session = ssh.openSessionChannel(); + if (!session.requestPseudoTerminal("vt100", 80, 24, 0, 0, "")) { + logger.info("Failed to allocate a pseudo terminal"); + } + if (session.startShell()) { + IOStreamConnector input = + new IOStreamConnector(); + IOStreamConnector output = + new IOStreamConnector(); + IOStreamConnector error = + new IOStreamConnector(); + output.setCloseOutput(false); + input.setCloseInput(false); + error.setCloseOutput(false); + input.connect(System.in, session.getOutputStream()); + output.connect(session.getInputStream(), System.out); + error.connect(session.getStderrInputStream(), System.out); + session.getState().waitForState(ChannelState.CHANNEL_CLOSED); + } + else { + logger.info("Failed to start the users shell"); + } + ssh.disconnect(); + } + } + catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/cct/ssh/PortForwarding.java b/src/main/java/cct/ssh/PortForwarding.java new file mode 100644 index 0000000..cbed855 --- /dev/null +++ b/src/main/java/cct/ssh/PortForwarding.java @@ -0,0 +1,99 @@ +package cct.ssh; + +/* + * Sshtools - Java SSH2 API + * + * Copyright (C) 2002 Lee David Painter. + * + * Written by: 2002 Lee David Painter + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library 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 Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ +import java.io.BufferedReader; +import java.io.InputStreamReader; + +import com.sshtools.j2ssh.SshClient; +import com.sshtools.j2ssh.authentication.AuthenticationProtocolState; +import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient; +import com.sshtools.j2ssh.configuration.ConfigurationLoader; +import com.sshtools.j2ssh.forwarding.ForwardingClient; +import com.sshtools.j2ssh.transport.TransportProtocolState; + +/*import java.util.logging.FileHandler; + import java.util.logging.Handler; + import java.util.logging.Level; + import java.util.logging.Logger; + import java.util.logging.SimpleFormatter;*/ +/** + * Demonstrates a starting both a local and remote forwarding configuration. + * + * @author Lee David Painter + * @version $Id: PortForwarding.java,v 1.9 2003/07/16 10:42:07 t_magicthize Exp $ + * + * @created 20 December 2002 + */ +public class PortForwarding { + /** + * The main program for the PortForwarding class + * + * @param args The command line arguments + */ + public static void main(String args[]) { + try { + // Setup a logfile + /*Handler fh = new FileHandler("example.log"); + fh.setFormatter(new SimpleFormatter()); + Logger.getLogger("com.sshtools").setUseParentHandlers(false); + Logger.getLogger("com.sshtools").addHandler(fh); + Logger.getLogger("com.sshtools").setLevel(Level.ALL);*/ + // Configure J2SSH (This will attempt to install the bouncycastle provider + // under jdk 1.3.1) + ConfigurationLoader.initialize(false); + BufferedReader reader = + new BufferedReader(new InputStreamReader(System.in)); + System.out.print("Connect to host? "); + String hostname = reader.readLine(); + // Make a client connection + SshClient ssh = new SshClient(); + // Connect to the hos + ssh.connect(hostname); + // Create a password authentication instance + PasswordAuthenticationClient pwd = new PasswordAuthenticationClient(); + // Get the users name + System.out.print("Username? "); + String username = reader.readLine(); + pwd.setUsername(username); + // Get the password + System.out.print("Password? "); + String password = reader.readLine(); + pwd.setPassword(password); + // Try the authentication + int result = ssh.authenticate(pwd); + // Evaluate the result + if (result == AuthenticationProtocolState.COMPLETE) { + ForwardingClient forwarding = ssh.getForwardingClient(); + forwarding.addLocalForwarding("Test Local", "0.0.0.0", 8081, + "127.0.0.1", 80); + forwarding.startLocalForwarding("Test Local"); + forwarding.addRemoteForwarding("Test Remote", "0.0.0.0", 8081, + "127.0.0.1", 8080); + forwarding.startRemoteForwarding("Test Remote"); + } + ssh.getConnectionState().waitForState(TransportProtocolState.DISCONNECTED); + } + catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/cct/ssh/PublicKeyConnect.java b/src/main/java/cct/ssh/PublicKeyConnect.java new file mode 100644 index 0000000..8e4237f --- /dev/null +++ b/src/main/java/cct/ssh/PublicKeyConnect.java @@ -0,0 +1,134 @@ +package cct.ssh; + +/* + * Sshtools - Java SSH2 API + * + * Copyright (C) 2002 Lee David Painter. + * + * Written by: 2002 Lee David Painter + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library 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 Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.util.logging.Logger; + +import com.sshtools.j2ssh.SshClient; +import com.sshtools.j2ssh.authentication.AuthenticationProtocolState; +import com.sshtools.j2ssh.authentication.PublicKeyAuthenticationClient; +import com.sshtools.j2ssh.configuration.ConfigurationLoader; +import com.sshtools.j2ssh.io.IOStreamConnector; +import com.sshtools.j2ssh.io.IOStreamConnectorState; +import com.sshtools.j2ssh.session.SessionChannelClient; +import com.sshtools.j2ssh.transport.publickey.SshPrivateKey; +import com.sshtools.j2ssh.transport.publickey.SshPrivateKeyFile; + +/*import java.util.logging.FileHandler; + import java.util.logging.Handler; + import java.util.logging.Level; + import java.util.logging.Logger; + import java.util.logging.SimpleFormatter;*/ +/** + * Demonstrates a public key authentication connection to an SSH server. + * + * @author Lee David Painter + * @version $Id: PublicKeyConnect.java,v 1.8 2003/07/16 10:42:08 t_magicthize Exp $ + * + * @created 20 December 2002 + */ +public class PublicKeyConnect { + + static final Logger logger = Logger.getLogger(PublicKeyConnect.class.getCanonicalName()); + /** + * The main program for the PublicKeyConnect class + * + * @param args The command line arguments + */ + public static void main(String args[]) { + try { + // Setup a logfile + /*Handler fh = new FileHandler("example.log"); + fh.setFormatter(new SimpleFormatter()); + Logger.getLogger("com.sshtools").setUseParentHandlers(false); + Logger.getLogger("com.sshtools").addHandler(fh); + Logger.getLogger("com.sshtools").setLevel(Level.ALL);*/ + // Configure J2SSH (This will attempt to install the bouncycastle provider + // under jdk 1.3.1) + ConfigurationLoader.initialize(false); + BufferedReader reader = + new BufferedReader(new InputStreamReader(System.in)); + System.out.print("Connect to host? "); + String hostname = reader.readLine(); + // Make a client connection + SshClient ssh = new SshClient(); + // Connect to the host + ssh.connect(hostname); + PublicKeyAuthenticationClient pk = new PublicKeyAuthenticationClient(); + // Get the users name + System.out.print("Username? "); + String username = reader.readLine(); + pk.setUsername(username); + // Get the private key file + System.out.print("Path to private key file? "); + String filename = reader.readLine(); + // Open up the private key file + SshPrivateKeyFile file = + SshPrivateKeyFile.parse(new File(filename)); + // If the private key is passphrase protected then ask for the passphrase + String passphrase = null; + if (file.isPassphraseProtected()) { + System.out.print("Enter passphrase? "); + passphrase = reader.readLine(); + } + // Get the key + SshPrivateKey key = file.toPrivateKey(passphrase); + pk.setKey(key); + // Try the authentication + int result = ssh.authenticate(pk); + // Evaluate the result + if (result == AuthenticationProtocolState.COMPLETE) { + // The connection is authenticated we can now do some real work! + SessionChannelClient session = ssh.openSessionChannel(); + if (!session.requestPseudoTerminal("vt100", 80, 24, 0, 0, "")) { + logger.info("Failed to allocate a pseudo terminal"); + } + if (session.startShell()) { + InputStream in = session.getInputStream(); + OutputStream out = session.getOutputStream(); + IOStreamConnector input = + new IOStreamConnector(System.in, session.getOutputStream()); + IOStreamConnector output = + new IOStreamConnector(session.getInputStream(), System.out); + output.getState().waitForState(IOStreamConnectorState.CLOSED); + } + else { + logger.info("Failed to start the users shell"); + } + ssh.disconnect(); + } + if (result == AuthenticationProtocolState.PARTIAL) { + logger.info("Further authentication requried!"); + } + if (result == AuthenticationProtocolState.FAILED) { + logger.info("Authentication failed!"); + } + } + catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/cct/ssh/SFTPFileStaging.java b/src/main/java/cct/ssh/SFTPFileStaging.java new file mode 100644 index 0000000..53a9294 --- /dev/null +++ b/src/main/java/cct/ssh/SFTPFileStaging.java @@ -0,0 +1,123 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.ssh; + +import java.util.logging.Logger; + +import cct.grid.JobDescription; +import cct.tools.filebrowser.SFTPBrowser; + +import com.sshtools.j2ssh.SftpClient; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class SFTPFileStaging { + static final Logger logger = Logger.getLogger(SFTPFileStaging.class.getCanonicalName()); + + public SFTPFileStaging() { + } + + public void fileStageIn(JobDescription job, boolean modal) throws Exception { + + // --- Setting local directory + + String localDirectory = ""; + if (job.getLocalDirectory() != null && + job.getLocalDirectory().trim().length() > 0) { + localDirectory = job.getLocalDirectory(); + if (localDirectory.endsWith("/")) { + localDirectory = localDirectory.substring(0, + localDirectory.length() - 1); + } + } + + // --- Setting remote directory + + String remoteDirectory = ""; + if (job.getRemoteDirectory() != null && + job.getRemoteDirectory().trim().length() > 0) { + remoteDirectory = job.getRemoteDirectory().trim(); + if (remoteDirectory.endsWith("/")) { + remoteDirectory = remoteDirectory.substring(0, + remoteDirectory.length() - 1); + } + } + + SFTPBrowser sftp = (SFTPBrowser) job.getTaskProviderObject(); + SftpClient sftp_client = null; + try { + sftp_client = sftp.getSftpClient(); + } + catch (Exception ex) { + throw new Exception("Failed to open sftp client: " + ex.getMessage()); + } + + try { + sftp.setRemoteDirectory(remoteDirectory); + } + catch (Exception ex) { + throw new Exception("Failed setting remote directory: " + ex.getMessage()); + } + + // --- Start file staging + + for (int i = 0; i < job.getFileStageInCount(); i++) { + //fileTranferCompleted = false; + String[] files = job.getFileStageIn(i); + String localFile = job.getLocalDirectory() + "/" + files[1]; + logger.info("Transfering: " + localFile); + try { + sftp_client.put(localFile); + } + catch (Exception ex) { + throw new Exception(localFile + " : " + ex.getMessage()); + } + } + } + +} diff --git a/src/main/java/cct/ssh/SSHPanel.java b/src/main/java/cct/ssh/SSHPanel.java new file mode 100644 index 0000000..d8f9509 --- /dev/null +++ b/src/main/java/cct/ssh/SSHPanel.java @@ -0,0 +1,816 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.ssh; + +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.logging.Logger; +import java.util.prefs.Preferences; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.ListSelectionModel; + +import cct.interfaces.FileBrowserInterface; +import cct.interfaces.FileChooserInterface; +import cct.tools.filebrowser.FileChooserDialog; +import cct.tools.filebrowser.SFTPBrowser; + +import com.sshtools.j2ssh.SshClient; +import com.sshtools.j2ssh.transport.IgnoreHostKeyVerification; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class SSHPanel + extends JPanel implements FileChooserInterface { + + static final String DIVIDER = "@"; + static final String DEFAULT_HOST = "defaultHost"; + static final String HOST_EDITABLE = "hostEditable"; + JLabel jLabel1 = new JLabel(); + JComboBox hostComboBox = new JComboBox(); + JLabel jLabel2 = new JLabel(); + JComboBox userComboBox = new JComboBox(); + JButton connectButton = new JButton(); + FileChooserDialog fileChooserDialog = null; + private Preferences userPrefs = Preferences.userNodeForPackage(getClass()); + final static String SSHHostKey = "ssh-host"; + final static String SSHUserKey = "ssh-user"; + private Set hosts = new HashSet(); + private Set users = new HashSet(); + private Map sshClients = new HashMap(); + private JButton removeHostButton = new JButton(); + private JTextField jTextField1 = new JTextField(); + private JLabel jLabel3 = new JLabel(); + private JButton removeUserButton = new JButton(); + private GridBagLayout gridBagLayout1 = new GridBagLayout(); + static final Logger logger = Logger.getLogger(SSHPanel.class.getCanonicalName()); + + public SSHPanel() { + try { + jbInit(); + this.validate(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + + this.setMinimumSize(new Dimension(500, 100)); + this.setPreferredSize(new Dimension(500, 100)); + + this.setLayout(gridBagLayout1); + jLabel1.setToolTipText(""); + jLabel1.setText("Remote Host: "); + jLabel2.setToolTipText(""); + jLabel2.setText(" User Name:"); + connectButton.setToolTipText("Connect to Host"); + connectButton.setText("Connect"); + connectButton.addActionListener(new SSHPanel_connectButton_actionAdapter(this)); + hostComboBox.setPreferredSize(new Dimension(100, 19)); + hostComboBox.setToolTipText("Enter Host and Press Enter"); + hostComboBox.setEditable(true); + hostComboBox.addActionListener(new SSHPanel_hostComboBox_actionAdapter(this)); + userComboBox.setPreferredSize(new Dimension(100, 19)); + userComboBox.setToolTipText("Enter username and Press Enter"); + userComboBox.setEditable(true); + userComboBox.addActionListener(new SSHPanel_userComboBox_actionAdapter(this)); + removeHostButton.setToolTipText("Remove Host from the List"); + removeHostButton.setText("Remove"); + removeHostButton.addActionListener(new SSHPanel_removeHostButton_actionAdapter(this)); + jTextField1.setEnabled(false); + jTextField1.setToolTipText(""); + jTextField1.setText("22"); + jTextField1.setColumns(6); + jLabel3.setToolTipText(""); + jLabel3.setText("Port: "); + removeUserButton.setToolTipText("Remove User from the List"); + removeUserButton.setText("Remove"); + removeUserButton.addActionListener(new SSHPanel_removeUserButton_actionAdapter(this)); + this.add(jLabel1, + new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 0, 0), + 0, 0)); + this.add(hostComboBox, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(removeHostButton, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(jLabel3, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(jTextField1, new GridBagConstraints(4, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(jLabel2, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(userComboBox, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(removeUserButton, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(connectButton, new GridBagConstraints(3, 1, 2, 1, 0.0, 1.0, GridBagConstraints.NORTH, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + + // --- Reading Hosts + + hostComboBox.setEnabled(false); + hostComboBox.addItem(""); + for (int i = 0; i < 1000; i++) { + String value = userPrefs.get(SSHHostKey + i, null); + if (value == null) { + break; + } + + if (hosts.contains(value)) { + continue; + } + hosts.add(value); + + //String tokens[] = value.split("@"); + + //hostComboBox.addItem(tokens[1]); + //userComboBox.addItem(tokens[0]); + + hostComboBox.addItem(value); + } + hostComboBox.setEnabled(true); + + // --- Reading users + + userComboBox.setEnabled(false); + userComboBox.addItem(""); + for (int i = 0; i < 1000; i++) { + String value = userPrefs.get(SSHUserKey + i, null); + if (value == null) { + break; + } + + if (users.contains(value)) { + continue; + } + users.add(value); + + userComboBox.addItem(value); + } + userComboBox.setEnabled(true); + + // --- + + String className = this.getClass().getCanonicalName(); + try { + + Properties props = cct.GlobalSettings.getCustomProperties(); + + if (props != null) { + + + //--- Default host + + String defHost = props.getProperty(className + DIVIDER + DEFAULT_HOST); + if (defHost != null) { + hostComboBox.setSelectedItem(defHost); + if (!hosts.contains(defHost)) { + hosts.add(defHost); + } + } + + String hostEditable = props.getProperty(className + DIVIDER + HOST_EDITABLE); + if (hostEditable != null) { + Boolean editable; + try { + editable = Boolean.parseBoolean(hostEditable); + hostComboBox.setEditable(editable); + } catch (Exception exx) { + } + } + + } + + } catch (Exception ex) { + logger.warning("Cannot open custom properties file" + cct.GlobalSettings.getCustomPropertiesURL() + " : " + + ex.getMessage()); + } + } + + public String getHost() { + return hostComboBox.getSelectedItem().toString(); + } + + public String getUserName() { + return userComboBox.getSelectedItem().toString(); + } + + public int getPort() throws Exception { + int port = 22; + try { + port = Integer.parseInt(jTextField1.getText().trim()); + } catch (Exception ex) { + System.err.println(this.getClass().getCanonicalName() + " : wrong port value: " + jTextField1.getText().trim() + + " Using default value " + port); + } + return port; + } + + @Override + public String pwd() { + if (fileChooserDialog == null || fileChooserDialog.getPressedKey() == FileChooserDialog.CANCEL) { + return null; + } + return fileChooserDialog.pwd(); + } + + @Override + public void setFileChooserVisible(boolean enable) throws Exception { + FileBrowserInterface browser = null; + if (fileChooserDialog == null) { + try { + checkConnection(); + Object obj = getSSHProvider(); + browser = (FileBrowserInterface) obj; + browser.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + } catch (Exception ex) { + String host = hostComboBox.getSelectedItem().toString(); + String user = userComboBox.getSelectedItem().toString(); + //JOptionPane.showMessageDialog(null, + // "Unable to connect Host " + host + + // " as " + user + + // " : " + ex.getMessage(), + // "Error",JOptionPane.ERROR_MESSAGE); + //return; + throw new Exception("Unable to connect Host " + host + " as " + user + + " : " + ex.getMessage()); + } + + fileChooserDialog = new FileChooserDialog(new Frame(), + "Choose Remote File", true, + browser); + fileChooserDialog.setFileBrowser(browser); + fileChooserDialog.setLocationRelativeTo(this.getParent()); + fileChooserDialog.setAlwaysOnTop(true); + fileChooserDialog.setSize(-1, 450); + fileChooserDialog.repaint(); + fileChooserDialog.pack(); + } + + // --- + + if (enable) { + fileChooserDialog.setVisible(true); + } else { + fileChooserDialog.setVisible(false); + } + } + + @Override + public String getDirectory() { + if (fileChooserDialog == null || fileChooserDialog.getPressedKey() == FileChooserDialog.CANCEL) { + return null; + } + + String[] files = fileChooserDialog.getSelectedFolders(); + + if (files == null) { + return null; + } + + if (files.length == 1) { + return files[0]; + } + + JOptionPane.showMessageDialog(null, + "INTERNAL ERROR: Multiple files are selected!", + "Error", + JOptionPane.ERROR_MESSAGE); + + return null; + } + + @Override + public String getFile() { + if (fileChooserDialog == null || fileChooserDialog.getPressedKey() == FileChooserDialog.CANCEL) { + return null; + } + + String[] files = fileChooserDialog.getSelectedFiles(); + + if (files == null) { + return null; + } + + if (files.length == 1) { + return files[0]; + } + + JOptionPane.showMessageDialog(null, + "INTERNAL ERROR: Multiple files are selected!", + "Error", + JOptionPane.ERROR_MESSAGE); + + return null; + } + + @Override + public String[] getFiles() { + if (fileChooserDialog.getPressedKey() == FileChooserDialog.CANCEL) { + return null; + } + + String[] files = fileChooserDialog.getSelectedFiles(); + + if (files == null) { + return null; + } + + return files; + } + + @Override + public String[] getDirectories() { + if (fileChooserDialog.getPressedKey() == FileChooserDialog.CANCEL) { + return null; + } + + String[] files = fileChooserDialog.getSelectedFolders(); + + if (files == null) { + return null; + } + + return files; + } + + public void checkConnection() throws Exception { + String host = hostComboBox.getSelectedItem().toString(); + + if (host.length() < 0) { + throw new Exception("Hostname is not set"); + } + + String user = userComboBox.getSelectedItem().toString(); + + if (user.length() < 0) { + throw new Exception("Username is not set"); + } + + Object obj = getSSHProvider(); + if (obj == null) { + SFTPBrowser sftp = new SFTPBrowser(); + try { + sftp.connect(host, user); + sshClients.put(user + "@" + host, sftp); + SSHServiceProvider.addHost(host, sftp); + /* + JOptionPane.showMessageDialog(null, + "Connection to Host " + host + + " as " + user + + " is established successfully", + "Success", + JOptionPane.INFORMATION_MESSAGE); + */ + + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, "Unable to connect Host " + host + " as " + user + + " : " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + + } else { + SFTPBrowser sftp = (SFTPBrowser) obj; + if (!sftp.isAuthenticated()) { + try { + sftp.reconnect(); + } catch (Exception ex) { + throw new Exception("Unable to reconnect to Host " + host + + "as " + user + " : " + ex.getMessage()); + } + } + } + } + + public Object getSSHProvider() { + String host = hostComboBox.getSelectedItem().toString(); + String user = userComboBox.getSelectedItem().toString(); + if (!sshClients.containsKey(user + "@" + host)) { + System.err.println("no " + user + "@" + host + " in list"); + return null; + } + SFTPBrowser sftp = (SFTPBrowser) sshClients.get(user + "@" + host); + if (!sftp.isAuthenticated()) { + System.err.println(user + "@" + host + " is not autenticated"); + return null; + } + return sftp; + } + + private void saveHosts(Set gk) { + Iterator i = gk.iterator(); + String newValue = ""; + int count = 0; + while (i.hasNext()) { + newValue = (String) i.next(); + try { + userPrefs.put(SSHHostKey + count, newValue); + } catch (Exception ex) { + System.err.println("Warning: unable to save host list: " + + ex.getMessage()); + } + } + } + + private void saveUsers(Set gk) { + Iterator i = gk.iterator(); + String newValue = ""; + int count = 0; + while (i.hasNext()) { + newValue = (String) i.next(); + try { + userPrefs.put(SSHUserKey + count, newValue); + } catch (Exception ex) { + System.err.println("Warning: unable to save user list: " + + ex.getMessage()); + } + } + } + + public void hostComboBox_actionPerformed(ActionEvent e) { + if (!hostComboBox.isEnabled()) { + return; + } + + hostComboBox.setEnabled(false); + + int n = hostComboBox.getSelectedIndex(); + String host = null; + Object obj = hostComboBox.getEditor().getItem(); + if (obj != null) { + host = obj.toString(); + } + + if (n == -1 || n == 0) { + if (obj == null) { + hostComboBox.setEnabled(true); + return; + } + } else { + Object item = hostComboBox.getSelectedItem(); + host = item.toString().trim(); + } + + if (host.length() < 1) { + hostComboBox.setEnabled(true); + return; + } + + if (hosts.contains(host)) { + /* + JOptionPane.showMessageDialog(null, + "Host " + host + " is already in the list", + "Warning", + JOptionPane.WARNING_MESSAGE); + GatekeeperComboBox.setEnabled(true); + */ + hostComboBox.setEnabled(true); + return; + } + + hostComboBox.addItem(host); + hostComboBox.setSelectedIndex(hostComboBox.getItemCount() - 1); + hosts.add(host); + + saveHosts(hosts); + + hostComboBox.setEnabled(true); + + } + + public void userComboBox_actionPerformed(ActionEvent e) { + if (!userComboBox.isEnabled()) { + return; + } + + userComboBox.setEnabled(false); + + String user = null; + Object obj = userComboBox.getEditor().getItem(); + if (obj != null) { + user = obj.toString(); + } + int n = userComboBox.getSelectedIndex(); + + if (n == -1 || n == 0) { + if (obj == null) { + userComboBox.setEnabled(true); + return; + } + } else { + Object item = userComboBox.getSelectedItem(); + user = item.toString().trim(); + } + + if (user.length() < 1) { + userComboBox.setEnabled(true); + return; + } + + if (users.contains(user)) { + /* + JOptionPane.showMessageDialog(null, + "Host " + host + " is already in the list", + "Warning", + JOptionPane.WARNING_MESSAGE); + GatekeeperComboBox.setEnabled(true); + */ + userComboBox.setEnabled(true); + return; + } + + userComboBox.addItem(user); + userComboBox.setSelectedIndex(userComboBox.getItemCount() - 1); + users.add(user); + + this.saveUsers(users); + + userComboBox.setEnabled(true); + + } + + public void connectButton_actionPerformed(ActionEvent e) { + + if (hostComboBox.getItemCount() < 1) { + return; + } + + if (!connectButton.isEnabled()) { + return; + } + connectButton.setEnabled(false); + hostComboBox.setEnabled(false); + userComboBox.setEnabled(false); + + String host = hostComboBox.getSelectedItem().toString().trim(); + if (host.length() > 1) { + String user = ""; + if (userComboBox.getItemCount() > 0) { + user = userComboBox.getSelectedItem().toString().trim(); + } + //SFTPBrowser + if (user.length() < 1) { // Just ping a host + try { + //ConfigurationLoader.initialize(false); + //SshConnectionProperties properties = new SshConnectionProperties(); + //properties.setHost("hostname"); + //properties.setPort(22); + SshClient ssh = new SshClient(); + //ssh.connect(properties); + ssh.connect(host, 22, new IgnoreHostKeyVerification()); + logger.info("System banner:\n" + ssh.getAuthenticationBanner(500)); + JOptionPane.showMessageDialog(null, host + " : Connection established successfully", + "Success", JOptionPane.INFORMATION_MESSAGE); + + if (!hosts.contains(host)) { + hosts.add(host); + this.saveHosts(hosts); + } + } catch (java.io.IOException ex) { + //System.err.println(); + //ex.printStackTrace(); + JOptionPane.showMessageDialog(null, "Unable to connect Host " + host + " : " + ex.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE); + } + } else if (sshClients.containsKey(user + "@" + host)) { + SFTPBrowser sftp = (SFTPBrowser) sshClients.get(user + "@" + host); + if (sftp.isAuthenticated()) { + JOptionPane.showMessageDialog(null, + "Connection to Host " + host + " as " + user + " is already authenticated", + "Success", JOptionPane.INFORMATION_MESSAGE); + } else { // !!! code here for reconnection + try { + sftp.reconnect(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, "Unable to reconnect to Host " + + host + "as " + user + " : " + ex.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE); + } + } + } else { // Make a connection + SFTPBrowser sftp = new SFTPBrowser(); + + try { + sftp.connect(host, user); + sshClients.put(user + "@" + host, sftp); + SSHServiceProvider.addHost(host, sftp); + JOptionPane.showMessageDialog(null, + "Connection to Host " + host + " as " + user + " is established successfully", + "Success", JOptionPane.INFORMATION_MESSAGE); + + if (!hosts.contains(host)) { + hosts.add(host); + this.saveHosts(hosts); + } + + if (!users.contains(user)) { + users.add(user); + this.saveUsers(users); + } + + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, "Unable to connect Host " + host + + " as " + user + " : " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + } + } + + } + + hostComboBox.setEnabled(true); + userComboBox.setEnabled(true); + connectButton.setEnabled(true); + } + + public void removeHostButton_actionPerformed(ActionEvent e) { + int n = hostComboBox.getSelectedIndex(); + Object item = hostComboBox.getSelectedItem(); + String host = item.toString().trim(); + + if (host.length() < 1) { + return; + } + + hostComboBox.setEnabled(false); + + hosts.remove(host); + hostComboBox.removeItemAt(n); + if (n < hostComboBox.getItemCount()) { + hostComboBox.setSelectedIndex(n); + } else if (n > 0 && hostComboBox.getItemCount() > 0) { + hostComboBox.setSelectedIndex(hostComboBox.getItemCount() - 1); + } + + saveHosts(hosts); + + hostComboBox.setEnabled(true); + } + + public void removeUserButton_actionPerformed(ActionEvent e) { + int n = userComboBox.getSelectedIndex(); + Object item = userComboBox.getSelectedItem(); + String user = item.toString().trim(); + + if (user.length() < 1) { + return; + } + + userComboBox.setEnabled(false); + users.remove(user); + userComboBox.removeItemAt(n); + if (n < userComboBox.getItemCount()) { + userComboBox.setSelectedIndex(n); + } else if (n > 0 && userComboBox.getItemCount() > 0) { + userComboBox.setSelectedIndex(userComboBox.getItemCount() - 1); + } + + saveUsers(users); + userComboBox.setEnabled(true); + } + + private class SSHPanel_removeUserButton_actionAdapter + implements ActionListener { + + private SSHPanel adaptee; + + SSHPanel_removeUserButton_actionAdapter(SSHPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.removeUserButton_actionPerformed(e); + } + } + + private class SSHPanel_removeHostButton_actionAdapter + implements ActionListener { + + private SSHPanel adaptee; + + SSHPanel_removeHostButton_actionAdapter(SSHPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.removeHostButton_actionPerformed(e); + } + } + + private class SSHPanel_hostComboBox_actionAdapter + implements ActionListener { + + private SSHPanel adaptee; + + SSHPanel_hostComboBox_actionAdapter(SSHPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.hostComboBox_actionPerformed(e); + } + } + + private class SSHPanel_userComboBox_actionAdapter + implements ActionListener { + + private SSHPanel adaptee; + + SSHPanel_userComboBox_actionAdapter(SSHPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.userComboBox_actionPerformed(e); + } + } + + private class SSHPanel_connectButton_actionAdapter + implements ActionListener { + + private SSHPanel adaptee; + + SSHPanel_connectButton_actionAdapter(SSHPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.connectButton_actionPerformed(e); + } + } + + public static void main(String[] args) { + JDialog diag = new JDialog(new Frame(), "Test SSHPanel", true); + SSHPanel panel = new SSHPanel(); + diag.add(panel); + diag.setSize(640, 200); + diag.pack(); + diag.setVisible(true); + System.exit(0); + } +} diff --git a/src/main/java/cct/ssh/SSHServiceProvider.java b/src/main/java/cct/ssh/SSHServiceProvider.java new file mode 100644 index 0000000..e672509 --- /dev/null +++ b/src/main/java/cct/ssh/SSHServiceProvider.java @@ -0,0 +1,853 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.ssh; + +import java.awt.Component; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.StringReader; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.prefs.Preferences; + +import javax.swing.JOptionPane; + +import cct.grid.CheckPoint; +import cct.grid.CheckPointInterface; +import cct.grid.GridProviderInterface; +import cct.grid.JobDescription; +import cct.grid.OperationalSystems; +import cct.grid.PBSJobStatus; +import cct.grid.TaskProvider; +import cct.interfaces.FileChooserInterface; +import cct.tools.filebrowser.SFTPBrowser; + +import com.sshtools.j2ssh.SftpClient; +import com.sshtools.j2ssh.SshClient; +import com.sshtools.j2ssh.connection.ChannelInputStream; +import com.sshtools.j2ssh.io.IOStreamConnector; +import com.sshtools.j2ssh.io.IOStreamConnectorState; +import com.sshtools.j2ssh.session.SessionChannelClient; + +/** + *

Title: SSH Service Provider

+ * + *

Description: How to use SSH Service Provider

+ * Could be customized using custom.properties file: + * cct.ssh.SSHServiceProvider@jobKillCommand = bash --login -c 'qdel -F %s' + * cct.ssh.SSHServiceProvider@jobSubmitCommand = bash --login -c 'qsub %s' + * cct.ssh.SSHServiceProvider@jobStatusCommand = bash --login -c 'qstat -f %s' + * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class SSHServiceProvider + implements GridProviderInterface { + + static final String SSH2_HOST = "ssh2Host"; + static final String SSH2_PORT = "ssh2Port"; + static final String SSH2_USER_NAME = "ssh2UserName"; + static final String DIVIDER = "@"; + static final String JOB_KILL_COMMAND = "jobKillCommand"; + static final String JOB_SUBMIT_COMMAND = "jobSubmitCommand"; + static final String JOB_STATUS_COMMAND = "jobStatusCommand"; + //cct.ssh.SSHServiceProvider@jobKillCommand = bash --login -c 'qdel -F %s' + //cct.ssh.SSHServiceProvider@jobSubmitCommand = bash --login -c 'qsub %s' + //cct.ssh.SSHServiceProvider@jobStatusCommand = bash --login -c 'qstat -f %s' + Preferences prefs = Preferences.userNodeForPackage(getClass()); + private String jobHandle; + private int jobID = -1; + private static Map hosts = new HashMap(); + protected SSHPanel nativeDialog = new SSHPanel(); + static String jobKillCommand = "bash --login -c 'qdel -F %s'"; + static String jobSubmitCommand = "bash --login -c 'qsub %s'"; + static String jobStatusCommand = "bash --login -c 'qstat -f %s'"; + static final Logger logger = Logger.getLogger(SSHServiceProvider.class.getCanonicalName()); + + public SSHServiceProvider() { + + String className = this.getClass().getCanonicalName(); + try { + Properties props = cct.GlobalSettings.getCustomProperties(); + + if (props != null) { + + //--- Get custom kill command + + String customCommand = props.getProperty(className + DIVIDER + JOB_KILL_COMMAND); + if (customCommand != null) { + jobKillCommand = customCommand; + } + + //--- Get custom submit command + + customCommand = props.getProperty(className + DIVIDER + JOB_SUBMIT_COMMAND); + if (customCommand != null) { + jobSubmitCommand = customCommand; + } + + //--- Get custom status command + + customCommand = props.getProperty(className + DIVIDER + + JOB_STATUS_COMMAND); + if (customCommand != null) { + jobStatusCommand = customCommand; + } + } + } catch (Exception ex) { + } + + } + + /** + * Submits job using ssh + * @param job JobDescription + * @throws Exception in case of any error(s) + */ + public void submitJob(JobDescription job) throws Exception { + + // Error check + + if (job.getLocalDirectory() == null) { + throw new Exception("Local directory is not set"); + } else if (job.getExecutable() == null) { + throw new Exception("Executable is not set"); + } + + //job.getExecutable()); + //job.getRemoteDirectory()); + + + /* + if (job.getRemoteDirectory() != null && job.getJobName() != null) { + sWriter.write(""); + sWriter.write(job.getRemoteDirectory() + "/" + job.getJobName() + + ".stdout"); + sWriter.write("\n"); + } + + if (job.getRemoteDirectory() != null && job.getJobName() != null) { + sWriter.write(""); + sWriter.write(job.getRemoteDirectory() + "/" + job.getJobName() + + ".stderr"); + sWriter.write("\n"); + } + */ + + //SFTPBrowser sftp = (SFTPBrowser) job.getTaskProviderObject(); + SFTPBrowser sftp = (SFTPBrowser) nativeDialog.getSSHProvider(); + + if (job.getFileStageInCount() > 0) { + job.setTaskProviderObject(sftp); + SFTPFileStaging fileTransfer = new SFTPFileStaging(); + try { + fileTransfer.fileStageIn(job, true); + } catch (Exception ex) { + throw new Exception("File staging-in failed: " + ex.getMessage()); + } + + } + + // Remember the host and username + + String host = sftp.getHost(); + //String user = sftp.getUsername(); + if (!hosts.containsKey(host)) { + hosts.put(host, sftp); + } + + // --- Create SSH client + + SshClient ssh_client = sftp.getSshClient(); + + // Submitting job + + SessionChannelClient session = ssh_client.openSessionChannel(); + + //StringWriter outWriter = new StringWriter(); + //StringWriter errWriter = new StringWriter(); + + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + ByteArrayOutputStream errStream = new ByteArrayOutputStream(); + + IOStreamConnector output = new IOStreamConnector(); + IOStreamConnector error = new IOStreamConnector(); + output.setCloseOutput(false); + error.setCloseOutput(false); + + output.connect(session.getInputStream(), outStream); + //output.connect(session.getInputStream(), System.out); + + //error.connect(session.getStderrInputStream(), System.out); + error.connect(session.getStderrInputStream(), errStream); + + /* try { + logger.info("Executing: cd " + job.getRemoteDirectory()); + session.executeCommand("cd " + job.getRemoteDirectory()); + String out = errStream.toString(); + if (out != null && out.length() > 0) { + throw new Exception("Failed to switch to remote directory: " + out); + } + logger.info("Out: "+outStream.toString()); + } + catch (Exception ex) { + throw new Exception("Failed to switch to remote directory: " + + ex.getMessage()); + } + */ + + /* + outStream.reset(); + errStream.reset(); + + output = new IOStreamConnector(); + error = new IOStreamConnector(); + output.setCloseOutput(false); + error.setCloseOutput(false); + + //output.connect(session.getInputStream(), System.out ); + output.connect(session.getInputStream(), outStream); + error.connect(session.getStderrInputStream(), errStream); + */ + + try { + String cmd = "cd " + job.getRemoteDirectory() + "; " + + String.format(jobSubmitCommand, job.getExecutable()); + //"; bash --login -c 'qsub " + + //job.getExecutable() + "'"; + //String cmd = "qsub " + job.getExecutable(); + + logger.info("Executing: " + cmd); + ChannelInputStream in = session.getInputStream(); + session.executeCommand(cmd); + //session.getState().waitForState(ChannelState.CHANNEL_CLOSED); + + output.getState().waitForState(IOStreamConnectorState.CLOSED); + error.getState().waitForState(IOStreamConnectorState.CLOSED); + + //InputStream err = session.getStderrInputStream(); + //session.close(); + String out = ""; + + out = errStream.toString(); + if (out != null && out.length() > 0) { + throw new Exception("Failed to submit a job: " + out); + } + + byte buffer[] = new byte[255]; + int read; + + /* + String errors = ""; + while ( (read = err.read(buffer)) > 0) { + out = new String(buffer, 0, read); + errors += out; + System.err.println(out); + } + + if (errors.length() > 0) { + throw new Exception("Failed to submit a job:\n" + errors); + } + */ + + /* + while ( (read = in.read(buffer)) > 0) { + out = new String(buffer, 0, read); + logger.info(out); + StringTokenizer st = new StringTokenizer(out, " .", true); + // Look for a number + while (st.hasMoreTokens()) { + try { + int number = Integer.parseInt(st.nextToken()); + jobHandle = String.valueOf(number); + jobID = number; + logger.info("Job handle: " + jobHandle); + return; + } + catch (Exception ex) {} + } + + throw new Exception("Cannot get job handle"); + } + */ + + + + session.close(); + logger.info("Output state: " + output.getState()); + logger.info("Output bytes: " + output.getBytes()); + logger.info("Out: Size: " + outStream.size() + " : " + + outStream.toString()); + + jobHandle = outStream.toString().trim(); + logger.info("Job handle: " + jobHandle); + // Look for a number + + /* + try { + int number = Integer.parseInt(jobHandle); + jobID = number; + + return; + } + catch (Exception ex) {} + */ + } catch (Exception ex) { + throw new Exception("Failed to submit job: " + ex.getMessage()); + } + + /* + if (!session.requestPseudoTerminal("vt100", 80, 24, 0, 0, "")) { + logger.info("Failed to allocate a pseudo terminal"); + } + if (session.startShell()) { + IOStreamConnector input = + new IOStreamConnector(); + IOStreamConnector output = + new IOStreamConnector(); + IOStreamConnector error = + new IOStreamConnector(); + output.setCloseOutput(false); + input.setCloseInput(false); + error.setCloseOutput(false); + input.connect(System.in, session.getOutputStream()); + output.connect(session.getInputStream(), System.out); + error.connect(session.getStderrInputStream(), System.out); + session.getState().waitForState(ChannelState.CHANNEL_CLOSED); + } + else { + logger.info("Failed to start the users shell"); + } + */ + //ssh.disconnect(); + } + + /** + * Returns job handle of a submitted job (in the case of success) + * @return String + */ + public String getJobHandle() { + return jobHandle; + } + + /** + * Returns current job status of a job + * @param chkp CheckPoint + * @return String + * @throws Exception + */ + public String getJobStatus(CheckPoint chkp) throws Exception { + if (!chkp.containsKey(CheckPointInterface.statusTag)) { + return null; + } + + /* + if (!chkp.containsKey(providerTag)) { + return null; + } + */ + + String status = chkp.getJobStatus(); + if (status.equalsIgnoreCase(CheckPointInterface.JOB_STATUS_DONE)) { + return status; + } + + String handle = chkp.getJobHandle(); + if (handle == null) { + throw new Exception("No job handle in the checkpoint"); + } + + String host = chkp.getServiceTag(SSH2_HOST); + if (host == null) { + throw new Exception("No host name in the checkpoint"); + } + + SFTPBrowser sftp; + try { + logger.log(Level.INFO, "Connecting to {0}...", host); + sftp = getConnection(host); + logger.log(Level.INFO, "Connection to {0} established", host); + } catch (Exception ex) { + logger.log(Level.SEVERE, "Error connecting to {0} : {1}", new Object[]{host, ex.getMessage()}); + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return CheckPointInterface.JOB_STATUS_UNKNOWN; + } + + // --- Check whether we still connected + + if (!sftp.isAuthenticated()) { + try { + logger.log(Level.INFO, "Authenticating to host {0}...", host); + sftp.reconnect(); + } catch (Exception ex) { + logger.severe("Unable to reconnect to host " + sftp.getHost() + " as " + sftp.getUsername() + " : " + ex.getMessage()); + return CheckPointInterface.JOB_STATUS_UNKNOWN; + } + } else { + logger.info("Connection to host " + host + " is already authenticated"); + } + + // --- Send a command + + SshClient ssh_client = sftp.getSshClient(); + SessionChannelClient session = ssh_client.openSessionChannel(); + + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + ByteArrayOutputStream errStream = new ByteArrayOutputStream(); + + IOStreamConnector output = new IOStreamConnector(); + IOStreamConnector error = new IOStreamConnector(); + output.setCloseOutput(false); + error.setCloseOutput(false); + + output.connect(session.getInputStream(), outStream); + error.connect(session.getStderrInputStream(), errStream); + + try { + String cmd = String.format(jobStatusCommand, handle); + //"bash --login -c 'qstat -f " + handle + "'"; + + logger.info("Executing command '" + cmd + "' on host " + host + "..."); + session.executeCommand(cmd); + + output.getState().waitForState(IOStreamConnectorState.CLOSED); + error.getState().waitForState(IOStreamConnectorState.CLOSED); + session.close(); + + String out = ""; + + out = errStream.toString(); + logger.info("Stderr from the host " + host + ":\n" + out); + //logger.info("Stderr: " + out); + if (out != null && out.length() > 0) { + //System.err.println("Failed to query a job: " +handle+" : " + out); + //throw new Exception("Failed to submit a job: " + out); + return CheckPointInterface.JOB_STATUS_DONE; + } + + logger.info("Stdout from the host " + host + ":\n" + outStream.toString()); + //logger.info("Stdout: " + outStream.toString()); + BufferedReader in = new BufferedReader(new StringReader(outStream.toString())); + + PBSJobStatus pbs_status = new PBSJobStatus(); + + try { + status = pbs_status.parsePBSJobStatus(in); + Map rused = pbs_status.getResourcesUsed(); + chkp.setResourcesUsed(rused); + if (status == null) { + System.err.println("Unable to get job statusfor job: " + handle + + " : qstat output is empty"); + return CheckPointInterface.JOB_STATUS_UNKNOWN; + } + + if (status.equalsIgnoreCase("E")) { + return "EXITING AFTER HAVING RUN"; + } else if (status.equalsIgnoreCase("H")) { + return "HELD"; + } else if (status.equalsIgnoreCase("Q")) { + return "QUEUED"; + } else if (status.equalsIgnoreCase("R")) { + return "ACTIVE"; + } else if (status.equalsIgnoreCase("T")) { + return "BEING MOVED"; + } else if (status.equalsIgnoreCase("W")) { + return "WAITING"; + } else if (status.equalsIgnoreCase("S")) { + return "SUSPENDED"; + } + + return status; + + } catch (Exception ex) { + logger.severe("Unable to get job status for a job: " + handle + + " from the host " + host + ": " + ex.getMessage()); + return CheckPointInterface.JOB_STATUS_UNKNOWN; + } + + } catch (Exception ex) { + //throw new Exception("Failed to submit job: " + ex.getMessage()); + logger.severe("Failed to query a job: " + handle + " on the host " + host + ": " + + ex.getMessage()); + return CheckPointInterface.JOB_STATUS_UNKNOWN; + } + + //return JOB_STATUS_UNKNOWN; + } + + /* + public boolean transferFile(String source, String destination) throws Exception { + + // --- Define direction of the file transfer + + if (source.indexOf("/") == -1) { + throw new Exception("Wrong Source " + source); + } + String host = source.substring(0, source.indexOf("/")); + String remoteFile = source.substring(source.indexOf("/")); + + // --- Now we need to process a situation whether file is in root directory + // (//File) or in default user's one (/File) + + if (remoteFile.startsWith("//")) { + remoteFile = remoteFile.substring(1); + } + else if (remoteFile.substring(1).indexOf("/") == -1) { + remoteFile = remoteFile.substring(1); + } + + SFTPBrowser sftp = null; + try { + sftp = getConnection(host); + } + catch (Exception ex) { + throw ex; + } + + SftpClient sftp_client = null; + try { + sftp_client = sftp.getSftpClient(); + } + catch (Exception ex) { + throw new Exception("Failed to open sftp client: " + ex.getMessage()); + } + + logger.info("Transfering: " + source + " -> " + destination); + try { + sftp_client.get(remoteFile, destination); + } + catch (Exception ex) { + throw new Exception(ex.getMessage()); + } + + return true; + } + */ + /** + * Transfers file assuming that "source" is a remote file while "destination" is a local + * @param source String + * @param destination String + * @param chkp CheckPoint + * @return boolean + * @throws Exception + */ + public boolean transferFile(String source, String destination, CheckPoint chkp) throws Exception { + // --- Define direction of the file transfer + + String host = chkp.getComputer(); + if (host == null || host.length() < 1) { + throw new Exception("SSH Service provider: host is not set: " + source); + } + + String remoteDir = ""; + if (chkp.getRemoteDirectory() == null) { + remoteDir += "/"; + } else { + remoteDir = chkp.getRemoteDirectory(); + if (!remoteDir.endsWith("/")) { + remoteDir += "/"; + } + } + + String remoteFile = remoteDir + source; + + // --- Now we need to process a situation whether file is in root directory + // (//File) or in default user's one (/File) + + if (remoteFile.startsWith("//")) { + remoteFile = remoteFile.substring(1); + } else if (remoteFile.substring(1).indexOf("/") == -1) { + remoteFile = remoteFile.substring(1); + } + + SFTPBrowser sftp = null; + try { + sftp = getConnection(host); + } catch (Exception ex) { + throw ex; + } + + SftpClient sftp_client = null; + try { + sftp_client = sftp.getSftpClient(); + } catch (Exception ex) { + throw new Exception("Failed to open sftp client: " + ex.getMessage()); + } + + logger.info("Transfering: " + source + " -> " + destination); + try { + sftp_client.get(remoteFile, destination); + } catch (Exception ex) { + throw new Exception(ex.getMessage()); + } + + return true; + + } + + public static SFTPBrowser getConnection(String host) throws Exception { + SFTPBrowser sftp = null; + if (!hosts.containsKey(host)) { // Make a connection + sftp = new SFTPBrowser(); + hosts.put(host, sftp); + try { + logger.info("Connecting to " + host); + sftp.connect(host); + } catch (Exception ex) { + logger.severe("Cannot connect to " + host + ": " + ex.getMessage()); + throw new Exception("Unable to connect to Host " + host + " as " + sftp.getUsername() + " : " + ex.getMessage()); + } + } else { // Get connection + logger.info(host + " is already in the hosts pool... Retrieving..."); + sftp = (SFTPBrowser) hosts.get(host); + } + return sftp; + } + + public void killJob(CheckPoint chkp) throws Exception { + + // --- Error check + + String host = chkp.getComputer(); + if (host == null) { + throw new Exception("No Host in checkpoint file"); + } + + if (chkp.getTaskProvider() != null + && !chkp.getTaskProvider().equalsIgnoreCase(TaskProvider.SSH_PROVIDER)) { + throw new Exception("Checkpoint file is not for " + + TaskProvider.SSH_PROVIDER + " task provider: " + + chkp.getTaskProvider()); + } + + if (chkp.getJobStatus() != null + && chkp.getJobStatus().equalsIgnoreCase(CheckPointInterface.JOB_STATUS_DONE)) { + return; // It's already finished + } + + String handle = chkp.getJobHandle(); + + if (handle == null) { + throw new Exception("Checkpoint file does not have job handle"); + } + + // --- Getting provider + + SFTPBrowser sftp = null; + try { + sftp = getConnection(host); + } catch (Exception ex) { + throw ex; + } + + // --- Send a command + + SshClient ssh_client = sftp.getSshClient(); + SessionChannelClient session = ssh_client.openSessionChannel(); + + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + ByteArrayOutputStream errStream = new ByteArrayOutputStream(); + + IOStreamConnector output = new IOStreamConnector(); + IOStreamConnector error = new IOStreamConnector(); + output.setCloseOutput(false); + error.setCloseOutput(false); + + output.connect(session.getInputStream(), outStream); + error.connect(session.getStderrInputStream(), errStream); + + try { + //String cmd = "bash --login -c 'qdel -F " + handle + "'"; + String cmd = String.format(jobKillCommand, handle); + + logger.info("Executing: " + cmd); + session.executeCommand(cmd); + + output.getState().waitForState(IOStreamConnectorState.CLOSED); + error.getState().waitForState(IOStreamConnectorState.CLOSED); + session.close(); + + String out = ""; + + out = errStream.toString(); + logger.info("Stderr: " + out); + if (out != null && out.length() > 0) { + if (out.indexOf("Unknown") != -1 && out.indexOf("Job") != -1) { + return; + } + System.err.println("Failed to kill a job: " + handle + " : " + out); + throw new Exception("Failed to kill a job: " + handle + " on " + + host + + " : " + out); + } + + logger.info("Stdout: " + outStream.toString()); + } catch (Exception ex) { + System.err.println("Failed to kill a job: " + handle + " on " + host + + " : " + + ex.getMessage()); + throw new Exception("Failed to kill a job: " + handle + " on " + host + + " : " + + ex.getMessage()); + } + + } + + public static void addHost(String host, SFTPBrowser sftp) { + hosts.put(host, sftp); + } + + /** + * + * @param sftp SFTPBrowser + * @param command String + * @return String[] + * @throws Exception + */ + public String[] executeCommand(SFTPBrowser sftp, String command) throws + Exception { + + // Error check + + if (command == null || command.length() < 1) { + throw new Exception("Command is not set"); + } + + // --- Create SSH client + + SshClient ssh_client = sftp.getSshClient(); + + // Submitting job + + SessionChannelClient session = ssh_client.openSessionChannel(); + + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + ByteArrayOutputStream errStream = new ByteArrayOutputStream(); + + IOStreamConnector output = new IOStreamConnector(); + IOStreamConnector error = new IOStreamConnector(); + output.setCloseOutput(false); + error.setCloseOutput(false); + + output.connect(session.getInputStream(), outStream); + + error.connect(session.getStderrInputStream(), errStream); + + try { + logger.info("Executing: " + command); + ChannelInputStream in = session.getInputStream(); + session.executeCommand(command); + + output.getState().waitForState(IOStreamConnectorState.CLOSED); + error.getState().waitForState(IOStreamConnectorState.CLOSED); + + String[] return_value = new String[2]; + return_value[0] = outStream.toString(); + return_value[1] = errStream.toString(); + + return return_value; + } catch (Exception ex) { + throw new Exception("Failed to execute command: " + ex.getMessage()); + } + + } + + // implementation of GridProviderInterface functions + public String getName() { + return "ssh"; + } + + public Component getVisualComponent() { + return nativeDialog; + } + + public FileChooserInterface getRemoteFileChooser() { + return nativeDialog; + } + + public String getRemoteHost() { + return nativeDialog.getHost(); + } + + public boolean isPassOptionsToScheduler() { + return true; + } + + public String submitTask(JobDescription job) throws Exception { + nativeDialog.checkConnection(); + submitJob(job); + return jobHandle; + } + + public String getCommandsAsString() { + return "#!sh\n"; + } + + public OperationalSystems getOS() { + return OperationalSystems.Linux; // !!! + } + + public String getGatekeeper() { + return null; + } + + public boolean isRemoteDirectorySelectable() { + return true; + } + + public CheckPointInterface setCheckPoint(CheckPointInterface checkp) { + try { + checkp.setServiceTag(CheckPointInterface.providerTag, getName(), true); + checkp.setServiceTag(SSH2_HOST, nativeDialog.getHost(), true); + checkp.setServiceTag(SSH2_PORT, String.valueOf(nativeDialog.getPort()), true); + checkp.setServiceTag(SSH2_USER_NAME, nativeDialog.getUserName(), true); + } catch (Exception ex) { + } + return checkp; + } + + public GridProviderInterface newInstance() { + return new SSHServiceProvider(); + } +} diff --git a/src/main/java/cct/ssh/SftpConnect.java b/src/main/java/cct/ssh/SftpConnect.java new file mode 100644 index 0000000..b9ccedf --- /dev/null +++ b/src/main/java/cct/ssh/SftpConnect.java @@ -0,0 +1,122 @@ +package cct.ssh; + +/* + * Sshtools - Java SSH2 API + * + * Copyright (C) 2002 Lee David Painter. + * + * Written by: 2002 Lee David Painter + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library 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 Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.logging.Logger; + +import com.sshtools.j2ssh.SftpClient; +import com.sshtools.j2ssh.SshClient; +import com.sshtools.j2ssh.authentication.AuthenticationProtocolState; +import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient; +import com.sshtools.j2ssh.configuration.ConfigurationLoader; + +/*import java.util.logging.FileHandler; + import java.util.logging.Handler; + import java.util.logging.Level; + import java.util.logging.Logger; + import java.util.logging.SimpleFormatter;*/ +/** + * Demonstrates a simple password connection to an SSH server. + * + * @author Lee David Painter + * @version $Id: SftpConnect.java,v 1.8 2003/07/16 10:42:08 t_magicthize Exp $ + * + * @created 20 December 2002 + */ +public class SftpConnect { + static final Logger logger = Logger.getLogger(SftpConnect.class.getCanonicalName()); + + /** + * The main program for the PasswordConnect class + * + * @param args The command line arguments + */ + public static void main(String args[]) { + try { + // Setup a logfile + /*Handler fh = new FileHandler("example.log"); + fh.setFormatter(new SimpleFormatter()); + Logger.getLogger("com.sshtools").setUseParentHandlers(false); + Logger.getLogger("com.sshtools").addHandler(fh); + Logger.getLogger("com.sshtools").setLevel(Level.ALL);*/ + // Configure J2SSH (This will attempt to install the bouncycastle provider + // under jdk 1.3.1) + ConfigurationLoader.initialize(false); + BufferedReader reader = + new BufferedReader(new InputStreamReader(System.in)); + System.out.print("Connect to host? "); + String hostname = reader.readLine(); + // Make a client connection + SshClient ssh = new SshClient(); + // Connect to the host + ssh.connect(hostname); + // Create a password authentication instance + PasswordAuthenticationClient pwd = new PasswordAuthenticationClient(); + // Get the users name + System.out.print("Username? "); + String username = reader.readLine(); + pwd.setUsername(username); + // Get the password + System.out.print("Password? "); + String password = reader.readLine(); + pwd.setPassword(password); + // Try the authentication + int result = ssh.authenticate(pwd); + // Evaluate the result + if (result == AuthenticationProtocolState.COMPLETE) { + // The connection is authenticated we can now do some real work! + SftpClient sftp = ssh.openSftpClient(); + // Make a directory + try { + sftp.mkdir("j2ssh"); + } + catch (IOException ex) { + } + // Change directory + sftp.cd("j2ssh"); + logger.info(sftp.pwd()); + // Change the mode + sftp.chmod(0777, "j2ssh"); + sftp.lcd("c:/"); + // Upload a file + sftp.put("system.gif"); + // Change the local directory + sftp.lcd("localdir"); + // Download a file + sftp.get("somefile.txt", "anotherfile.txt"); + // Remove a directory or file + sftp.rm("j2ssh"); + // Quit + sftp.quit(); + ssh.disconnect(); + } + } + catch (Exception e) { + e.printStackTrace(); + } + finally { + System.exit(0); + } + } +} diff --git a/src/main/java/cct/testStarter.java b/src/main/java/cct/testStarter.java new file mode 100644 index 0000000..69a69cf --- /dev/null +++ b/src/main/java/cct/testStarter.java @@ -0,0 +1,76 @@ +package cct; + +import cct.dialogs.Frame1; + +import javax.swing.*; +import java.awt.*; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class testStarter { + boolean packFrame = false; + + /** + * Construct and show the application. + */ + public testStarter() { + JFrame.setDefaultLookAndFeelDecorated(true); + Frame1 frame = new Frame1(); + + //frame.addMenuItem("File", new JMenuItem("Get Geometry")); + + // Validate frames that have preset sizes + // Pack frames that have useful preferred size info, e.g. from their layout + if (packFrame) { + frame.pack(); + } + else { + frame.validate(); + } + + // Center the window + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension frameSize = frame.getSize(); + if (frameSize.height > screenSize.height) { + frameSize.height = screenSize.height; + } + if (frameSize.width > screenSize.width) { + frameSize.width = screenSize.width; + } + frame.setLocation( (screenSize.width - frameSize.width) / 2, + (screenSize.height - frameSize.height) / 2); + frame.setVisible(true); + } + + /** + * Application entry point. + * + * @param args String[] + */ + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } + catch (Exception exception) { + exception.printStackTrace(); + } + + new testStarter(); + + } + }); + } +} diff --git a/src/main/java/cct/tools/.DS_Store b/src/main/java/cct/tools/.DS_Store new file mode 100644 index 0000000..c4dc425 Binary files /dev/null and b/src/main/java/cct/tools/.DS_Store differ diff --git a/src/main/java/cct/tools/._.DS_Store b/src/main/java/cct/tools/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/cct/tools/._.DS_Store differ diff --git a/src/main/java/cct/tools/CCTParser.java b/src/main/java/cct/tools/CCTParser.java new file mode 100644 index 0000000..9f6706d --- /dev/null +++ b/src/main/java/cct/tools/CCTParser.java @@ -0,0 +1,1732 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStreamWriter; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.ResourceBundle; +import java.util.Set; +import java.util.logging.Logger; + +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; + +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; +import org.xml.sax.helpers.DefaultHandler; + +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.AtomicSet; +import cct.modelling.AtomicSets; +import cct.modelling.Molecule; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class CCTParser + extends DefaultHandler { + + static boolean Debug = false; + static private String NO_PROPERTY_SIGN = "&!"; + static final String INTERNAL_PROPERTY = "_"; + + List molecules = new ArrayList(); + List atoms = new ArrayList(); + List bonds = new ArrayList(); + static final Logger logger = Logger.getLogger(CCTParser.class.getCanonicalName()); + + AtomicSets atomicSets = new AtomicSets(); + String atomSetName = "ATOM_SET"; + + boolean finish_parsing = false; + boolean yes_cct = false; + boolean yes_many_molecules = false; + boolean yes_many_monomers = false; + boolean yes_many_atoms = false; + boolean yes_molecule = false; + boolean unrecoverableError = false; + int parseLevel = -1; + String currentTag = null; + String fullString = ""; + MoleculeInterface currentMolecule = null; + + StringReader sReader = null; + StringWriter sWriter = null; + + private String propertyID = ""; + private String propertyType = ""; + private String propertyFormat = ""; + private String propertyClass = ""; + private String propertyValue = ""; + + ResourceBundle resources; + + static private Writer out; + + public CCTParser(MoleculeInterface molecule) { + currentMolecule = molecule; + try { + resources = ResourceBundle.getBundle("cct.cct"); + String text = + resources.getString(this.getClass().getName() + ".debug"); + if (text.equalsIgnoreCase("true")) { + Debug = true; + } + else if (text.equalsIgnoreCase("false")) { + Debug = false; + } + else { + logger.info("Warning: wrong value for " + + this.getClass().getName() + ".debug" + " : " + + text); + } + } + catch (Exception ex) { + System.err.println(ex.getMessage()); + if (resources == null) { + System.err.println("Resources for class " + this.getClass().getName() + + " not found"); + } + } + } + + /** + * + * @param file_name String + * @param molecule MoleculeInterface + * @return List + */ + public List parseCCTFile(Object inputSource, MoleculeInterface molecule) { + DefaultHandler handler = new CCTParser(molecule); + // Use the default (non-validating) parser + SAXParserFactory factory = SAXParserFactory.newInstance(); + + try { + // Set up output stream + out = new OutputStreamWriter(System.out, "UTF8"); + + // Parse the input + SAXParser saxParser = factory.newSAXParser(); + + if (inputSource instanceof String) { + saxParser.parse(new File( (String) inputSource), handler); + } + else if (inputSource instanceof InputStream) { + saxParser.parse( (InputStream) inputSource, handler); + } + else { + System.err.println("parseCCTFile: Unknown input source: " + + inputSource.getClass().getCanonicalName()); + return null; + } + + } + catch (Throwable t) { + //logger.error("Parsing error " + t.getMessage()); + t.printStackTrace(); + return null; + } + + CCTParser parser = (CCTParser) handler; + List mols = parser.getMolecules(); + return mols; + } + + public static void saveCCTFile(MoleculeInterface molec, String fileName) throws + Exception { + List mols = new ArrayList(); + mols.add(molec); + try { + saveCCTFile(mols, fileName); + } + catch (Exception ex) { + throw ex; + } + } + + public static void saveCCTFile(List mols, String fileName) throws + Exception { + //Message = ""; + + FileOutputStream out; + try { + out = new FileOutputStream(fileName); + } + catch (Exception ex) { + System.err.println("Error opening FileOutputStream: " + ex.getMessage()); + throw ex; + } + + //StringWriter sWriter = new StringWriter(); + + StreamResult streamResult = new StreamResult(out); + SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory. + newInstance(); + + // SAX2.0 ContentHandler. + TransformerHandler hd = null; + try { + hd = tf.newTransformerHandler(); + } + catch (TransformerConfigurationException e) { + System.err.println("Error geting newTransformerHandler: " + + e.getMessage()); + throw e; + } + + Transformer serializer = hd.getTransformer(); + //serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); + //serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "users.dtd"); + serializer.setOutputProperty(OutputKeys.INDENT, "yes"); + hd.setResult(streamResult); + try { + hd.startDocument(); + AttributesImpl atts = new AttributesImpl(); + atts.addAttribute("", "", "version", "CDATA", "0.1"); + //atts.addAttribute("","","TYPE","CDATA",type[i]); + + // CCT tag. + hd.startElement("", "", CCTParserEnum.CCT_TAG.toString(), atts); + + if (mols.size() > 1) { + atts.clear(); + atts.addAttribute("", "", "number", "CDATA", + String.valueOf(mols.size())); + hd.startElement("", "", CCTParserEnum.MANY_MOLECULES_TAG.toString(), + atts); + } + + for (int i = 0; i < mols.size(); i++) { + MoleculeInterface molec = (MoleculeInterface) mols.get(i); + atts.clear(); + atts.addAttribute("", "", "name", "CDATA", molec.getName()); + atts.addAttribute("", "", "atoms", "CDATA", + String.valueOf(molec.getNumberOfAtoms())); + atts.addAttribute("", "", "bonds", "CDATA", + String.valueOf(molec.getNumberOfBonds())); + hd.startElement("", "", CCTParserEnum.MOLECULE_TAG.toString(), atts); + + // --- Monomers ******************* + List substr = molec.getMolecularSubstructure(); + + atts.clear(); + atts.addAttribute("", "", "number", "CDATA", + String.valueOf(substr.size())); + hd.startElement("", "", CCTParserEnum.MANY_MONOMERS_TAG.toString(), + atts); + //hd.startCDATA(); + + hd.characters("\n".toCharArray(), 0, 1); + + Iterator iter = substr.iterator(); + while (iter.hasNext()) { + String data = (String) iter.next(); + if (data == null) { + data = "NONAME\n"; + } + else { + data += "\n"; + } + hd.characters(data.toCharArray(), 0, data.length()); + //hd.startEntity(data); + //out.write(data.getBytes()); + //hd.endEntity(""); + } + + //hd.endCDATA(); + hd.endElement("", "", CCTParserEnum.MANY_MONOMERS_TAG.toString()); + // --- End of monomers ******************** + + // --- Atoms ******************* + + writeAtoms(hd, molec); + + // --- end of atoms ************* + + // --- Bonds ******************** + + writeBonds(hd, molec); + + // --- end of Bonds ************* + + // --- Start to print Properties + + writeProperties(hd, molec); + + // --- End of Properties + + hd.endElement("", "", CCTParserEnum.MOLECULE_TAG.toString()); + } + + if (mols.size() > 1) { + hd.endElement("", "", CCTParserEnum.MANY_MOLECULES_TAG.toString()); + } + + hd.endElement("", "", CCTParserEnum.CCT_TAG.toString()); + hd.endDocument(); + + } + catch (SAXException e) { + //Message = e.getMessage(); + System.err.println(e.getMessage()); + throw e; + //return null; + } + + try { + out.close(); + } + catch (Exception ex) { + throw ex; + } + + } + + public static void writeBonds(TransformerHandler hd, + MoleculeInterface molec) throws + SAXException { + AttributesImpl atts = new AttributesImpl(); + try { + atts.clear(); + atts.addAttribute("", "", "number", "CDATA", + String.valueOf(molec.getNumberOfBonds())); + hd.startElement("", "", CCTParserEnum.MANY_BONDS_TAG.toString(), + atts); + //hd.startCDATA(); + + hd.characters("\n".toCharArray(), 0, 1); + + for (int j = 0; j < molec.getNumberOfBonds(); j++) { + BondInterface bond = molec.getBondInterface(j); + AtomInterface a_i = bond.getIAtomInterface(); + AtomInterface a_j = bond.getJAtomInterface(); + + String data = molec.getAtomIndex(a_i) + "," + + molec.getAtomIndex(a_j) + "\n"; + hd.characters(data.toCharArray(), 0, data.length()); + } + + //hd.endCDATA(); + hd.endElement("", "", CCTParserEnum.MANY_BONDS_TAG.toString()); + + } + catch (SAXException e) { + System.err.println("Error Writing Bonds : " + e.getMessage()); + throw e; + } + + } + + public static void writeAtoms(TransformerHandler hd, + MoleculeInterface molec) throws + SAXException { + AttributesImpl atts = new AttributesImpl(); + try { + atts.clear(); + atts.addAttribute("", "", "number", "CDATA", + String.valueOf(molec.getNumberOfAtoms())); + hd.startElement("", "", CCTParserEnum.MANY_ATOMS_TAG.toString(), + atts); + //hd.startCDATA(); + + hd.characters("\n".toCharArray(), 0, 1); + + for (int j = 0; j < molec.getNumberOfAtoms(); j++) { + AtomInterface atom = molec.getAtomInterface(j); + String data = atom.getAtomicNumber() + "," + atom.getName() + + "," + atom.getX() + "," + atom.getY() + "," + atom.getZ() + + "," + atom.getSubstructureNumber() + "\n"; + hd.characters(data.toCharArray(), 0, data.length()); + } + + //hd.endCDATA(); + hd.endElement("", "", CCTParserEnum.MANY_ATOMS_TAG.toString()); + + } + catch (SAXException e) { + System.err.println("Error Writing Atoms: " + e.getMessage()); + throw e; + } + + } + + public static void writeAtomSets(TransformerHandler hd, MoleculeInterface molec, AtomicSets sets) throws SAXException { + + AttributesImpl atts = new AttributesImpl(); + Molecule.validateSets(molec); + + Set set2 = sets.entrySet(); + Iterator iter = set2.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String setName = me.getKey().toString(); + Object obj = me.getValue(); + if (! (obj instanceof AtomicSet)) { + System.err.println("! (obj instanceof AtomicSet). Ignored..."); + continue; + } + AtomicSet aset = (AtomicSet) obj; + + atts.clear(); + atts.addAttribute("", "", "name", "CDATA", aset.getName()); + atts.addAttribute("", "", "type", "CDATA", "atoms"); + atts.addAttribute("", "", "number", "CDATA", String.valueOf(aset.size())); + atts.addAttribute("", "", "comment", "CDATA", "type attribute is not currently used"); + + hd.startElement("", "", CCTParserEnum.ATOM_SET_TAG.toString(), atts); + + hd.characters("\n".toCharArray(), 0, 1); + + for (int j = 0; j < aset.size(); j++) { + AtomInterface atom = aset.get(j); + int index = molec.getAtomIndex(atom); + if (j != 0) { + hd.characters(",".toCharArray(), 0, 1); + } + String data = String.valueOf(index); + hd.characters(data.toCharArray(), 0, data.length()); + } + hd.characters("\n".toCharArray(), 0, 1); + + hd.endElement("", "", CCTParserEnum.ATOM_SET_TAG.toString()); + } + + } + + public static void writeProperties(TransformerHandler hd, MoleculeInterface molec) throws SAXException { + + AttributesImpl atts = new AttributesImpl(); + + Map molProps = molec.getProperties(); + + Set set = molProps.entrySet(); + Iterator iter = set.iterator(); + try { + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String propName = me.getKey().toString(); + if (Debug) { + logger.info("Writing molecular property: " + propName); + } + + Object prop = molec.getProperty(propName); + + // --- If there are many properties + if (propName.equals(MoleculeInterface.AtomicSets)) { // Atomic sets + if (! (prop instanceof AtomicSets)) { + System.err.println("!(prop instanceof AtomicSets). Ignored..."); + continue; + } + writeAtomSets(hd, molec, (AtomicSets) prop); + } + + else if (prop instanceof List) { + List properties = (List) prop; + for (int i = 0; i < properties.size(); i++) { + Object obj = properties.get(i); + String propFormat = obj.getClass().getSimpleName(); + + atts.clear(); + atts.addAttribute("", "", "id", "CDATA", propName); + atts.addAttribute("", "", "type", "CDATA", "molecule"); + atts.addAttribute("", "", "class", "CDATA", propFormat); + + String data = getObjectAsString(obj); + + atts.addAttribute("", "", "value", "CDATA", data); + hd.startElement("", "", CCTParserEnum.PROPERTY_TAG.toString(), + atts); + hd.endElement("", "", CCTParserEnum.PROPERTY_TAG.toString()); + } + } + + // --- if there is only one property entry + else { + + atts.clear(); + atts.addAttribute("", "", "id", "CDATA", propName); + atts.addAttribute("", "", "type", "CDATA", "molecule"); + //Object prop = molec.getProperty(propName); + String propFormat = prop.getClass().getSimpleName(); + atts.addAttribute("", "", "class", "CDATA", propFormat); + + //String data = prop.toString(); + String data = getObjectAsString(prop); + atts.addAttribute("", "", "value", "CDATA", data); + + hd.startElement("", "", CCTParserEnum.PROPERTY_TAG.toString(), + atts); + + //hd.characters("\n".toCharArray(), 0, 1); + + //String data = prop.toString() + "\n"; + //hd.characters(data.toCharArray(), 0, data.length()); + + hd.endElement("", "", CCTParserEnum.PROPERTY_TAG.toString()); + } + + } + } + catch (SAXException e) { + //Message = e.getMessage(); + System.err.println("Error Writing properties: " + e.getMessage()); + throw e; + //return null; + } + + // --- Write Atomic properties + + // --- First count number of unique atom properties + + + Map props = new HashMap (); + Map propsFormat = new HashMap(); + for (int j = 0; j < molec.getNumberOfAtoms(); j++) { + AtomInterface atom = molec.getAtomInterface(j); + Map p = atom.getProperties(); + set = p.entrySet(); + Iterator iter2 = set.iterator(); + while (iter2.hasNext()) { + Map.Entry me = (Map.Entry) iter2.next(); + String propName = me.getKey().toString(); + + // --- We don't save properties which starts from INTERNAL_PROPERTY symbol + if (propName.startsWith(INTERNAL_PROPERTY)) { + continue; + } + + Object obj = me.getValue(); + if (props.containsKey(propName)) { + int count = props.get(propName).intValue(); + ++count; + props.put(propName, new Integer(count)); + } + else { // Found new property + Integer count = new Integer(1); + props.put(propName, count); + propsFormat.put(propName, obj.getClass().getSimpleName()); + } + } + } + + logger.info("There are " + props.size() + + " unique atomic properties"); + + // --- Printing + + set = props.entrySet(); + iter = set.iterator(); + try { + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String propName = me.getKey().toString(); + Integer count = (Integer) me.getValue(); + if (Debug) { + logger.info("Writing property: " + propName + + " number: " + count.intValue()); + } + + atts.clear(); + atts.addAttribute("", "", "id", "CDATA", propName); + atts.addAttribute("", "", "type", "CDATA", "atom"); + AtomInterface atom = molec.getAtomInterface(0); + Object prop = atom.getProperty(propName); + String propFormat = (String) propsFormat.get(propName); + atts.addAttribute("", "", "class", "CDATA", propFormat); + boolean indexed = false; + if (count.intValue() > molec.getNumberOfAtoms() / 2) { + atts.addAttribute("", "", "format", "CDATA", "all"); + indexed = false; + } + else { + atts.addAttribute("", "", "format", "CDATA", "indexed"); + indexed = true; + } + hd.startElement("", "", CCTParserEnum.PROPERTY_TAG.toString(), + atts); + hd.characters("\n".toCharArray(), 0, 1); + + for (int j = 0; j < molec.getNumberOfAtoms(); j++) { + atom = molec.getAtomInterface(j); + prop = atom.getProperty(propName); + + if (indexed) { + if (prop == null) { + continue; + } + String data = j + "," + getObjectAsString(prop) + "\n"; + hd.characters(data.toCharArray(), 0, data.length()); + } + else { + String data; + if (prop == null) { + data = NO_PROPERTY_SIGN + "\n"; + } + else { + data = getObjectAsString(prop) + "\n"; + } + hd.characters(data.toCharArray(), 0, data.length()); + } + } + + hd.endElement("", "", CCTParserEnum.PROPERTY_TAG.toString()); + } + } + catch (SAXException e) { + //Message = e.getMessage(); + System.err.println("Error Writing properties: " + e.getMessage()); + throw e; + //return null; + } + + // --- Write Bond properties + + // --- First count number of unique bond properties + + props.clear(); + propsFormat.clear(); + for (int j = 0; j < molec.getNumberOfBonds(); j++) { + BondInterface bond = molec.getBondInterface(j); + Map p = bond.getProperties(); + set = p.entrySet(); + Iterator iter2 = set.iterator(); + while (iter2.hasNext()) { + Map.Entry me = (Map.Entry) iter2.next(); + String propName = me.getKey().toString(); + + // --- We don't save properties which starts from INTERNAL_PROPERTY symbol + if (propName.startsWith(INTERNAL_PROPERTY)) { + continue; + } + + Object obj = me.getValue(); + if (props.containsKey(propName)) { + Integer count = props.get(propName); + ++count; + props.put(propName, count); + //int count = ( (Integer) props.get(propName)).intValue(); + //++count; + //props.put(propName, new Integer(count)); + } + else { // Found new property + Integer count = new Integer(1); + props.put(propName, count); + propsFormat.put(propName, obj.getClass().getSimpleName()); + } + } + } + + logger.info("There are " + props.size() + + " unique bond properties"); + + // --- Printing + + set = props.entrySet(); + iter = set.iterator(); + try { + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String propName = me.getKey().toString(); + Integer count = (Integer) me.getValue(); + if (Debug) { + logger.info("Writing property: " + propName + + " number: " + count.intValue()); + } + + atts.clear(); + atts.addAttribute("", "", "id", "CDATA", propName); + atts.addAttribute("", "", "type", "CDATA", "bond"); + //BondInterface bond = molec.getBondInterface(0); + //Object prop = bond.getProperty(propName); + String propFormat = (String) propsFormat.get(propName); + atts.addAttribute("", "", "class", "CDATA", propFormat); + boolean indexed = false; + if (count.intValue() > molec.getNumberOfBonds() / 2) { + atts.addAttribute("", "", "format", "CDATA", "all"); + indexed = false; + } + else { + atts.addAttribute("", "", "format", "CDATA", "indexed"); + indexed = true; + } + hd.startElement("", "", CCTParserEnum.PROPERTY_TAG.toString(), + atts); + hd.characters("\n".toCharArray(), 0, 1); + + for (int j = 0; j < molec.getNumberOfBonds(); j++) { + BondInterface bond = molec.getBondInterface(j); + Object prop = bond.getProperty(propName); + + if (indexed) { + if (prop == null) { + continue; + } + String data = j + "," + getObjectAsString(prop) + "\n"; + hd.characters(data.toCharArray(), 0, data.length()); + } + else { + String data; + if (prop == null) { + data = NO_PROPERTY_SIGN + "\n"; + } + else { + data = getObjectAsString(prop) + "\n"; + } + hd.characters(data.toCharArray(), 0, data.length()); + } + } + + hd.endElement("", "", CCTParserEnum.PROPERTY_TAG.toString()); + } + } + catch (SAXException e) { + //Message = e.getMessage(); + System.err.println("Error Writing properties: " + e.getMessage()); + throw e; + //return null; + } + + } + + public int getMoleculesCount() { + return molecules.size(); + } + + public List getMolecules() { + return molecules; + } + + public void startDocument() throws SAXException { + if (Debug) { + emit(""); + nl(); + } + } + + public void endDocument() throws SAXException { + try { + nl(); + out.flush(); + + } + catch (IOException e) { + throw new SAXException("I/O error", e); + } + } + + public void startElement(String namespaceURI, + String lName, // local name + String qName, // qualified name + Attributes attrs) throws SAXException { + + if (unrecoverableError) { + throw new SAXException("Unrecoverable error"); + } + + if (finish_parsing) { + return; + } + + String eName = lName; // element name + if ("".equals(eName)) { + eName = qName; // namespaceAware = false + } + if (Debug) { + emit("<" + eName); + } + if (attrs != null) { + for (int i = 0; i < attrs.getLength(); i++) { + String aName = attrs.getLocalName(i); // Attr name + if ("".equals(aName)) { + aName = attrs.getQName(i); + } + if (Debug) { + emit(" "); + emit(aName + "=\"" + attrs.getValue(i) + "\""); + } + } + } + if (Debug) { + emit(">"); + } + // Parse elements... + + currentTag = eName; + + if (CCTParserEnum.CCT_TAG.equalsIgnoreCase(eName)) { + yes_cct = true; + parseLevel = CCTParserEnum.CCT_TAG.getEnum(); + return; + } + if (!yes_cct) { + return; // Don't find tag yet... + } + + if (CCTParserEnum.MANY_MOLECULES_TAG.equalsIgnoreCase(eName)) { + if (Debug) { + logger.info("Starting parsing molecules..."); + } + parseLevel = CCTParserEnum.MANY_MOLECULES_TAG.getEnum(); + yes_many_molecules = true; + return; + } + + if (CCTParserEnum.MOLECULE_TAG.equalsIgnoreCase(eName)) { + if (Debug) { + logger.info("Starting parsing molecule..."); + } + parseLevel = CCTParserEnum.MOLECULE_TAG.getEnum(); + yes_molecule = true; + + // --- Init new molecule + if (molecules.size() != 0) { + currentMolecule = currentMolecule.getInstance(); + } + atoms.clear(); + bonds.clear(); + return; + } + + if (!yes_many_molecules && !yes_molecule) { + return; // Don't find or tag yet... + } + + if (CCTParserEnum.MANY_MONOMERS_TAG.equalsIgnoreCase(eName)) { + if (Debug) { + logger.info("Starting parsing monomers..."); + } + parseLevel = CCTParserEnum.MANY_MONOMERS_TAG.getEnum(); + yes_many_monomers = true; + sWriter = new StringWriter(); + return; + } + + if (CCTParserEnum.MANY_ATOMS_TAG.equalsIgnoreCase(eName)) { + if (Debug) { + logger.info("Starting parsing atoms..."); + } + parseLevel = CCTParserEnum.MANY_ATOMS_TAG.getEnum(); + yes_many_atoms = true; + sWriter = new StringWriter(); + return; + } + + if (CCTParserEnum.MANY_BONDS_TAG.equalsIgnoreCase(eName)) { + if (Debug) { + logger.info("Starting parsing bonds..."); + } + parseLevel = CCTParserEnum.MANY_BONDS_TAG.getEnum(); + sWriter = new StringWriter(); + return; + } + + if (CCTParserEnum.ATOM_SET_TAG.equalsIgnoreCase(eName)) { + if (Debug) { + logger.info("Starting parsing atom set..."); + } + parseLevel = CCTParserEnum.ATOM_SET_TAG.getEnum(); + atomSetName = attrs.getValue("name"); + sWriter = new StringWriter(); + return; + } + + if (CCTParserEnum.PROPERTY_TAG.equalsIgnoreCase(eName)) { + if (attrs == null) { + System.err.println("Error: no attributes for property"); + unrecoverableError = true; + return; + } + // --- Reset property attributes + propertyID = ""; + propertyType = "atom"; + propertyFormat = "all"; + propertyClass = "String"; + + for (int i = 0; i < attrs.getLength(); i++) { + String aName = attrs.getLocalName(i); // Attr name + if ("".equals(aName)) { + aName = attrs.getQName(i); + } + + if (aName.equalsIgnoreCase("id")) { + propertyID = attrs.getValue(i); + } + else if (aName.equalsIgnoreCase("type")) { + propertyType = attrs.getValue(i); + } + else if (aName.equalsIgnoreCase("format")) { + propertyFormat = attrs.getValue(i); + } + else if (aName.equalsIgnoreCase("class")) { + propertyClass = attrs.getValue(i); + } + else if (aName.equalsIgnoreCase("value")) { + propertyValue = attrs.getValue(i); + } + else { + System.err.println("Warning: unknown attribute name: " + aName + + " Ignored..."); + } + + if (propertyID.length() == 0) { + System.err.println( + "Error: No property ID attribute in property tag"); + unrecoverableError = true; + return; + } + + } + + if (Debug) { + logger.info("Starting parsing property..."); + } + parseLevel = CCTParserEnum.PROPERTY_TAG.getEnum(); + sWriter = new StringWriter(); + return; + } + + } + + public void endElement(String namespaceURI, + String sName, // simple name + String qName // qualified name + ) throws SAXException { + + if (unrecoverableError) { + throw new SAXException("Unrecoverable error"); + } + + if (finish_parsing) { + return; + } + + String eName = sName; // element name + if ("".equals(eName)) { + eName = qName; // namespaceAware = false + } + + if (Debug) { + emit(""); + } + // --- Parsing + + if (CCTParserEnum.CCT_TAG.equalsIgnoreCase(eName)) { + finish_parsing = true; + yes_cct = false; + return; + } + + if (CCTParserEnum.MANY_MOLECULES_TAG.equalsIgnoreCase(eName)) { + if (Debug) { + logger.info("Finish parsing molecules..."); + } + parseLevel = CCTParserEnum.CCT_TAG.getEnum(); + yes_many_molecules = false; + yes_molecule = false; + return; + } + + if (CCTParserEnum.MOLECULE_TAG.equalsIgnoreCase(eName)) { + if (Debug) { + logger.info("Finish parsing molecule: monomers: " + currentMolecule.getMolecularSubstructure().size() + " atoms: " + + currentMolecule.getNumberOfAtoms() + " bonds: " + currentMolecule.getNumberOfBonds()); + } + if (yes_many_molecules) { + parseLevel = CCTParserEnum.MANY_MOLECULES_TAG.getEnum(); + } + else { + parseLevel = CCTParserEnum.CCT_TAG.getEnum(); + } + + if (atomicSets.size() > 0) { + Map prop = currentMolecule.getProperties(); + prop.put(MoleculeInterface.AtomicSets, atomicSets); + } + molecules.add(currentMolecule); + yes_molecule = false; + return; + } + + if (CCTParserEnum.MANY_MONOMERS_TAG.equalsIgnoreCase(eName)) { + if (Debug) { + logger.info("Finish parsing monomers..."); + } + parseLevel = CCTParserEnum.MOLECULE_TAG.getEnum(); + yes_many_monomers = false; + try { + readMonomers(sWriter.toString(), currentMolecule); + sWriter.close(); + } + catch (Exception ex) { + logger.info("Finish parsing monomers: " + ex.getMessage()); + } + + return ; + } + + if (CCTParserEnum.MANY_ATOMS_TAG.equalsIgnoreCase(eName)) { + if (Debug) { + logger.info("Finish parsing atoms..."); + } + parseLevel = CCTParserEnum.MOLECULE_TAG.getEnum(); + yes_many_atoms = false; + try { + atoms = readAtoms(sWriter.toString(), currentMolecule); + sWriter.close(); + } + catch (Exception ex) { + logger.info("Finish parsing atoms: " + ex.getMessage()); + } + return ; + } + + if (CCTParserEnum.MANY_BONDS_TAG.equalsIgnoreCase(eName)) { + if (Debug) { + logger.info("Finish parsing bonds..."); + } + parseLevel = CCTParserEnum.MOLECULE_TAG.getEnum(); + //yes_many_atoms = false; + try { + bonds = readBonds(sWriter.toString(), currentMolecule); + sWriter.close(); + } + catch (Exception ex) { + System.err.println("Error: parsing bonds: " + ex.getMessage()); + } + return ; + } + + if (CCTParserEnum.ATOM_SET_TAG.equalsIgnoreCase(eName)) { + if (Debug) { + logger.info("Finish parsing atom set..."); + } + parseLevel = CCTParserEnum.MOLECULE_TAG.getEnum(); + try { + AtomicSet aset = readAtomSet(sWriter.toString(), currentMolecule); + sWriter.close(); + if (aset.size() > 0) { + this.atomicSets.put(aset.getName(), aset); + } + } + catch (Exception ex) { + System.err.println("Error: parsing atom set: " + ex.getMessage()); + } + return ; + } + + if (CCTParserEnum.PROPERTY_TAG.equalsIgnoreCase(eName)) { + if (Debug) { + logger.info("Finish parsing property..."); + } + parseLevel = CCTParserEnum.MOLECULE_TAG.getEnum(); + + if (propertyType.equalsIgnoreCase("molecule")) { + try { + Object objType = getObjectClass(propertyValue, propertyClass); + currentMolecule.addProperty(propertyID, objType); + } + catch (Exception ex) { + System.err.println("Error parsing molecule property: " + propertyID + " : " + ex.getMessage()); + System.err.println(" Property value: " + propertyValue + " Ignored... "); + } + + return ; + } + + try { + bonds = readProperty(sWriter.toString(), propertyID, propertyType, propertyFormat, propertyClass, currentMolecule); + sWriter.close(); + } + catch (Exception ex) { + System.err.println("Error: parsing property: " + ex.getMessage()); + } + return ; + } + + } + + public void characters(char buf[], int offset, int len) throws + SAXException { + + if (unrecoverableError) { + throw new SAXException("Unrecoverable error"); + } + String s = null; + //logger.info("BUF: " + offset+" "+len); + if (Debug) { + s = new String(buf, offset, len); + emit(s); + } + + // --- Parsing atom info + + if (yes_many_atoms) { + if (parseLevel == CCTParserEnum.MANY_ATOMS_TAG.getEnum()) { + sWriter.write(buf, offset, len); + } + } + + else if (parseLevel == CCTParserEnum.PROPERTY_TAG.getEnum()) { + sWriter.write(buf, offset, len); + if (Debug) { + logger.info("Adding property: " + s); + } + } + + else if (parseLevel == CCTParserEnum.MANY_MONOMERS_TAG.getEnum()) { + sWriter.write(buf, offset, len); + if (Debug) { + logger.info("Adding monomer: " + s); + } + //currentMolecule.addMonomer(fullString.substring(0, + // fullString.indexOf(",")).trim()); + } + + else if (parseLevel == CCTParserEnum.MANY_BONDS_TAG.getEnum()) { + sWriter.write(buf, offset, len); + if (Debug) { + logger.info("Adding bond: " + s); + } + } + + else if (parseLevel == CCTParserEnum.ATOM_SET_TAG.getEnum()) { + sWriter.write(buf, offset, len); + if (Debug) { + logger.info("Adding atom set member: " + s); + } + } + + //fullString = ""; + } + + //=========================================================== + // Utility Methods ... + //=========================================================== + + // Wrap I/O exceptions in SAX exceptions, to + // suit handler signature requirements + private void emit(String s) throws SAXException { + try { + //logger.info(s); + //if ( true ) return; + out.write("CHARS:" + s); + out.flush(); + } + catch (IOException e) { + throw new SAXException("I/O error", e); + } + } + + /* + private void emit(String s) throws SAXException { + try { + out.write(s); + out.flush(); + } + catch (IOException e) { + throw new SAXException("I/O error", e); + } + } + */ + // Start a new line + private void nl() throws SAXException { + String lineEnd = System.getProperty("line.separator"); + try { + out.write(lineEnd); + } + catch (IOException e) { + throw new SAXException("I/O error", e); + } + } + + /* + class tasksEndException + extends Exception { + + } + */ + + public static List readBonds(String bondsAsString, + MoleculeInterface molec) throws + Exception { + List bonds = new ArrayList(); + + BufferedReader in = null; + in = new BufferedReader(new StringReader(bondsAsString)); + + String line; + try { + while ( (line = in.readLine()) != null) { + if (line.trim().length() == 0) { + continue; // Ignore empty lines + } + //logger.info("Adding bond: " + line); + try { + String tokens[] = line.trim().split(","); + if (tokens.length < 2) { + System.err.println("Error: uncomplete data for " + + bonds.size() + + " bond: " + line); + } + + int a_index = Integer.parseInt(tokens[0]); + int b_index = Integer.parseInt(tokens[1]); + + AtomInterface a_i = molec.getAtomInterface(a_index); + AtomInterface a_j = molec.getAtomInterface(b_index); + + BondInterface b = molec.getNewBondInstance(a_i, a_j); + molec.addBond(b); + } + catch (Exception ex) { + System.err.println("Error: " + ex.getMessage()); + throw new Exception(ex.getMessage()); + } + + } + + in.close(); + } + catch (Exception ex) { + throw new Exception(ex.getMessage()); + } + + return bonds; + } + + public AtomicSet readAtomSet(String atomSetAsString, MoleculeInterface molec) throws + Exception { + AtomicSet aset = new AtomicSet(atomSetName); + + BufferedReader in = null; + in = new BufferedReader(new StringReader(atomSetAsString)); + + String line; + String tokens[]; + try { + while ( (line = in.readLine()) != null) { + line = line.trim(); + if (line.length() == 0) { + continue; // Ignore empty lines + } + //logger.info("Adding bond: " + line); + try { + tokens = line.split("[, ]"); + if (tokens.length < 1) { + continue; + } + } + catch (Exception ex) { + System.err.println("readAtomSet: Error: " + ex.getMessage()); + throw new Exception(ex.getMessage()); + } + + for (int i = 0; i < tokens.length; i++) { + try { + int index = Integer.parseInt(tokens[i]); + if (index < 0 || index >= molec.getNumberOfAtoms()) { + System.err.println("readAtomSet: index < 0 || index >= molec.getNumberOfAtoms(): Ignored..."); + continue; + } + AtomInterface atom = molec.getAtomInterface(index); + aset.add(atom); + } + catch (Exception ex) { + System.err.println("readAtomSet: Error while parsing atom index: " + tokens[i] + " Ignored..."); + } + } + } + + in.close(); + } + catch (Exception ex) { + throw new Exception(ex.getMessage()); + } + + return aset; + } + + public static List readProperty(String propertyAsString, String ID, + String Type, + String Format, String Class, + MoleculeInterface molec) throws + Exception { + List props = new ArrayList(); + + BufferedReader in = null; + in = new BufferedReader(new StringReader(propertyAsString)); + + boolean indexed = Format.equalsIgnoreCase("indexed"); + boolean atomProp = Type.equalsIgnoreCase("atom"); + boolean bondProp = Type.equalsIgnoreCase("bond"); + boolean moleculeProp = Type.equalsIgnoreCase("molecule"); + + if (Debug) { + logger.info("Parsing property: " + ID); + } + + String line; + try { + + if (indexed) { // Indexed property + while ( (line = in.readLine()) != null) { + if (line.trim().length() == 0) { + continue; // Ignore empty lines + } + logger.info("Parsing line: " + line); + + String tokens[] = line.trim().split(","); + if (tokens.length < 2) { + System.err.println("Error: uncomplete data for " + + props.size() + " indexed property: " + + line); + throw new Exception("Error: uncomplete data for " + + props.size() + " indexed property: " + + line); + } + + int index = Integer.parseInt(tokens[0]); + String token = line.substring(line.indexOf(",") + 1, line.length()); + + Object objType = getObjectClass(token, Class); + logger.info("Index: " + index + " property: " + token + + " class: " + objType.getClass().getSimpleName()); + + if (atomProp) { + AtomInterface atom = molec.getAtomInterface(index); + atom.setProperty(ID, objType); + } + else if (bondProp) { + BondInterface bond = molec.getBondInterface(index); + bond.setProperty(ID, objType); + } + else if (moleculeProp) { + molec.addProperty(ID, objType); + } + else { + throw new Exception("ERROR: Read property: Unknown type: " + + Type); + } + + //props.add(line.trim()); + } + + } + + else { // Property for all entities + int count = 0; + while ( (line = in.readLine()) != null) { + if (line.trim().length() == 0) { + continue; // Ignore empty lines + } + + String token = line.trim(); + if (token.equals(NO_PROPERTY_SIGN)) { + ++count; + continue; + } + + Object objType = getObjectClass(token, Class); + if (Debug) { + logger.info("Obj type: " + + objType.getClass().getSimpleName() + + " value: " + objType); + } + + if (atomProp) { + AtomInterface atom = molec.getAtomInterface(count); + atom.setProperty(ID, objType); + } + else if (bondProp) { + BondInterface bond = molec.getBondInterface(count); + bond.setProperty(ID, objType); + } + else if (moleculeProp) { + molec.addProperty(ID, objType); + } + else { + throw new Exception("ERROR: Read property: Unknown type: " + + Type); + } + ++count; + } + + //props.add(line.trim()); + } + + in.close(); + } + catch (Exception ex) { + throw new Exception("Parsing property: " + ID + " : " + ex.getMessage()); + } + + return props; + } + + public static String getObjectAsString(Object data) { + // String + if (data instanceof String) { + return (String) data; + } + // --- String[] + else if (data instanceof String[]) { + String str[] = (String[]) data; + + String Str = ""; + for (int i = 0; i < str.length; i++) { + if (i > 0) { + Str += ","; + } + Str += str[i]; + } + return Str; + + } + // --- Integer + else if (data instanceof Integer) { + Integer i = (Integer) data; + return i.toString(); + } + // --- Integer[] + else if (data instanceof Integer[]) { + Integer ia[] = (Integer[]) data; + + String str = ""; + for (int i = 0; i < ia.length; i++) { + if (i > 0) { + str += ","; + } + str += ia[i].toString(); + } + return str; + } + // --- Float + else if (data instanceof Float) { + Float f = (Float) data; + return f.toString(); + } + // --- Float[] + else if (data instanceof Float[]) { + Float ia[] = (Float[]) data; + String str = ""; + for (int i = 0; i < ia.length; i++) { + if (i > 0) { + str += ","; + } + str += ia[i].toString(); + } + return str; + } + // --- Double + else if (data instanceof Double) { + Double f = (Double) data; + return f.toString(); + } + // --- Double[] + else if (data instanceof Double[]) { + Double ia[] = (Double[]) data; + String str = ""; + for (int i = 0; i < ia.length; i++) { + if (i > 0) { + str += ","; + } + str += ia[i].toString(); + } + return str; + } + + // --- Boolean + else if (data instanceof Boolean) { + Boolean f = (Boolean) data; + return f.toString(); + } + // --- Boolean[] + else if (data instanceof Boolean[]) { + Boolean ia[] = (Boolean[]) data; + String str = ""; + for (int i = 0; i < ia.length; i++) { + if (i > 0) { + str += ","; + } + str += ia[i].toString(); + } + return str; + } + + return data.toString(); + } + + public static Object getObjectClass(String data, String dataClass) throws + Exception { + if (dataClass.equalsIgnoreCase("String") || + dataClass.endsWith(".String")) { + return data; + } + // --- Integer values + else if (dataClass.equalsIgnoreCase("Integer") || + dataClass.endsWith(".Integer")) { + try { + int n = Integer.parseInt(data); + Integer i = new Integer(n); + return i; + } + catch (Exception ex) { + System.err.println("ERROR: Wrong integer value: " + data); + throw ex; + } + } + // --- Integer array values + else if (dataClass.equalsIgnoreCase("Integer[]") || + dataClass.endsWith(".Integer[]")) { + String tokens[] = data.split(","); + Integer ia[] = new Integer[tokens.length]; + for (int i = 0; i < tokens.length; i++) { + try { + ia[i] = new Integer(tokens[i]); + } + catch (Exception ex) { + System.err.println("ERROR: Wrong integer value: " + tokens[i]); + throw ex; + } + } + return ia; + } + // --- Boolean values + else if (dataClass.equalsIgnoreCase("Boolean") || + dataClass.endsWith(".Boolean")) { + try { + Boolean i = new Boolean(data); + return i; + } + catch (Exception ex) { + System.err.println("ERROR: Wrong Boolean value: " + data); + throw ex; + } + } + // --- Boolean array values + else if (dataClass.equalsIgnoreCase("Boolean[]") || + dataClass.endsWith(".Boolean[]")) { + String tokens[] = data.split(","); + Boolean ia[] = new Boolean[tokens.length]; + for (int i = 0; i < tokens.length; i++) { + try { + ia[i] = new Boolean(tokens[i]); + } + catch (Exception ex) { + System.err.println("ERROR: Wrong Boolean value: " + tokens[i]); + throw ex; + } + } + return ia; + } + + // --- Float value + else if (dataClass.equalsIgnoreCase("Float") || + dataClass.endsWith(".Float")) { + try { + Float f = new Float(data); + return f; + } + catch (Exception ex) { + System.err.println("ERROR: Wrong float value: " + data); + throw ex; + } + } + // --- Float array values + else if (dataClass.equalsIgnoreCase("Float[]") || + dataClass.endsWith(".Float[]")) { + String tokens[] = data.split(","); + Float ia[] = new Float[tokens.length]; + for (int i = 0; i < tokens.length; i++) { + try { + ia[i] = new Float(tokens[i]); + } + catch (Exception ex) { + System.err.println("ERROR: Wrong float value: " + tokens[i]); + throw ex; + } + } + return ia; + } + // --- Double value + else if (dataClass.equalsIgnoreCase("Double") || + dataClass.endsWith(".Double")) { + try { + Double f = new Double(data); + return f; + } + catch (Exception ex) { + System.err.println("ERROR: Wrong double value: " + data); + throw ex; + } + } + // --- Double array values + else if (dataClass.equalsIgnoreCase("Double[]") || + dataClass.endsWith(".Double[]")) { + String tokens[] = data.split(","); + Double ia[] = new Double[tokens.length]; + for (int i = 0; i < tokens.length; i++) { + try { + ia[i] = new Double(tokens[i]); + } + catch (Exception ex) { + System.err.println("ERROR: Wrong double value: " + tokens[i]); + throw ex; + } + } + return ia; + } + + return data; + } + + public static List readAtoms(String bondsAsString, MoleculeInterface molec) throws + Exception { + List at = new ArrayList(); + BufferedReader in = null; + in = new BufferedReader(new StringReader(bondsAsString)); + + String line; + try { + while ( (line = in.readLine()) != null) { + if (line.trim().length() == 0) { + continue; + } + //logger.info("Adding atom: " + line); + try { + String tokens[] = line.trim().split(","); + if (tokens.length < 5) { + System.err.println("Error: uncomplete data for " + at.size() + " atom: " + line); + } + AtomInterface atom = molec.getNewAtomInstance(); + atom.setAtomicNumber(Integer.parseInt(tokens[0])); + atom.setName(tokens[1]); + atom.setXYZ(Float.parseFloat(tokens[2]), Float.parseFloat(tokens[3]), Float.parseFloat(tokens[4])); + if (tokens.length >= 6) { + atom.setSubstructureNumber(Integer.parseInt(tokens[5])); + } + if (tokens.length >= 7) { + atom.setProperty(AtomInterface.ATOMIC_CHARGE, new Float(tokens[6])); + } + at.add(atom); + } + catch (Exception ex) { + System.err.println("Error: " + ex.getMessage()); + throw ex; + } + + } + + in.close(); + } + catch (Exception ex) { + throw ex; + } + + for (int i = 0; i < at.size(); i++) { + AtomInterface atom = (AtomInterface) at.get(i); + molec.addAtom(atom, atom.getSubstructureNumber()); + } + + return at; + } + + /** + * Reads list of monomers + * @param monomersAsString String + * @param molec MoleculeInterface + * @return List + * @throws Exception + */ + public static List readMonomers(String monomersAsString, MoleculeInterface molec) throws + Exception { + List monomers = new ArrayList(); + BufferedReader in = null; + in = new BufferedReader(new StringReader(monomersAsString)); + + String line; + try { + while ( (line = in.readLine()) != null) { + if (line.trim().length() == 0) { + continue; + } + //logger.info("Adding monomer: " + line); + molec.addMonomer(line); + monomers.add(line); + } + + in.close(); + } + catch (Exception ex) { + throw ex; + } + + return monomers; + } + +} diff --git a/src/main/java/cct/tools/CCTParserEnum.java b/src/main/java/cct/tools/CCTParserEnum.java new file mode 100644 index 0000000..d126ae8 --- /dev/null +++ b/src/main/java/cct/tools/CCTParserEnum.java @@ -0,0 +1,104 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +// Ordinal-based typesafe enum +public class CCTParserEnum + implements Comparable { + private final String name; + // Ordinal of next suit to be created + private static int nextOrdinal = 0; + // Assign an ordinal to this suit + private final int ordinal = nextOrdinal++; + private CCTParserEnum(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } + + @Override + public int compareTo(Object o) { + return ordinal - ( (CCTParserEnum) o).ordinal; + } + + public int compareTo(String str) { + return this.toString().compareTo(str); + } + + public int compareToIgnoreCase(String str) { + return this.toString().compareToIgnoreCase(str); + } + + public boolean equalsIgnoreCase(String str) { + return this.toString().equalsIgnoreCase(str); + } + + public int getEnum() { + return ordinal; + } + + // CCT Tags + + public static final CCTParserEnum CCT_TAG = new CCTParserEnum("cct"); + public static final CCTParserEnum MANY_MOLECULES_TAG = new CCTParserEnum("molecules"); + public static final CCTParserEnum MOLECULE_TAG = new CCTParserEnum("molecule"); + public static final CCTParserEnum MANY_MONOMERS_TAG = new CCTParserEnum("monomers"); + public static final CCTParserEnum MONOMER_TAG = new CCTParserEnum("monomer"); + public static final CCTParserEnum MANY_ATOMS_TAG = new CCTParserEnum("atoms"); + public static final CCTParserEnum ATOM_TAG = new CCTParserEnum("atom"); + public static final CCTParserEnum MANY_BONDS_TAG = new CCTParserEnum("bonds"); + public static final CCTParserEnum BOND_TAG = new CCTParserEnum("bond"); + public static final CCTParserEnum PROPERTY_TAG = new CCTParserEnum("property"); + public static final CCTParserEnum ATOM_SET_TAG = new CCTParserEnum("atomSet"); + +} diff --git a/src/main/java/cct/tools/Crystal.java b/src/main/java/cct/tools/Crystal.java new file mode 100644 index 0000000..95fbadc --- /dev/null +++ b/src/main/java/cct/tools/Crystal.java @@ -0,0 +1,199 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.Molecule; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Crystal { + public float a[] = { + 0, 0, 5.2065f}; + public float b[] = { + 0, 5.7088f, 0}; + public float c[] = { + 4.9440f, 2.8544f, 0}; + public float d[] = { + -4.9440f, 2.8544f, 0}; + + public Crystal() { + } + + public static void main(String[] args) { + Crystal crystal = new Crystal(); + MoleculeInterface m = new Molecule(); + try { + XMolXYZ xMolXYZ = new XMolXYZ(); + m = xMolXYZ.parseXMolXYZ(args[0], m); + } + catch (Exception ex) { + //JOptionPane.showMessageDialog(null, + // ex.getMessage(), + // "Error", + // JOptionPane.ERROR_MESSAGE); + System.err.println(ex.getMessage()); + System.exit(1); + } + + MoleculeInterface refMol = m.getInstance(); + refMol.appendMolecule(m); + + for (int i = -2; i <= 2; i++) { + + for (int k = -1; k <= 1; k++) { + if (i == 0 && k == 0) { + continue; + } + MoleculeInterface newMol = m.getInstance(); + newMol.appendMolecule(refMol); + + for (int j = 0; j < newMol.getNumberOfAtoms(); j++) { + AtomInterface atom = newMol.getAtomInterface(j); + atom.setX(atom.getX() + i * crystal.a[0] + + k * crystal.b[0]); + atom.setY(atom.getY() + i * crystal.a[1] + + k * crystal.b[1]); + atom.setZ(atom.getZ() + i * crystal.a[2] + + k * crystal.b[2]); + } + m.appendMolecule(newMol); + + } + + for (int k = -1; k <= 1; k++) { + if (k == 0) { + continue; + } + MoleculeInterface newMol = m.getInstance(); + newMol.appendMolecule(refMol); + + for (int j = 0; j < newMol.getNumberOfAtoms(); j++) { + AtomInterface atom = newMol.getAtomInterface(j); + atom.setX(atom.getX() + i * crystal.a[0] + + k * crystal.c[0]); + atom.setY(atom.getY() + i * crystal.a[1] + + k * crystal.c[1]); + atom.setZ(atom.getZ() + i * crystal.a[2] + + k * crystal.c[2]); + } + m.appendMolecule(newMol); + + } + + for (int k = -1; k <= 1; k++) { + if (k == 0) { + continue; + } + MoleculeInterface newMol = m.getInstance(); + newMol.appendMolecule(refMol); + + for (int j = 0; j < newMol.getNumberOfAtoms(); j++) { + AtomInterface atom = newMol.getAtomInterface(j); + atom.setX(atom.getX() + i * crystal.a[0] + + k * crystal.d[0]); + atom.setY(atom.getY() + i * crystal.a[1] + + k * crystal.d[1]); + atom.setZ(atom.getZ() + i * crystal.a[2] + + k * crystal.d[2]); + } + m.appendMolecule(newMol); + + } + + /* + for (int k = -1; k <= 1; k++) { + + for (int k2 = -1; k2 <= 1; k2++) { + for (int k3 = -1; k3 <= 1; k3++) { + if (i == 0 && k == 0 && k2 == 0 && k3 == 0) { + continue; + } + MoleculeInterface newMol = m.getInstance(); + newMol.appendMolecule(refMol); + + for (int j = 0; j < newMol.getNumberOfAtoms(); j++) { + AtomInterface refAtom = m.getAtomInterface(j); + AtomInterface atom = newMol.getAtomInterface(j); + atom.setX(atom.getX() + (float) i * crystal.\u0441[0] + + (float) k * crystal.\u04301[0] + + (float) k2 * crystal.\u04302[0] + + (float) k3 * crystal.\u04303[0]); + atom.setY(atom.getY() + (float) i * crystal.\u0441[1] + + (float) k * crystal.\u04301[1] + + (float) k2 * crystal.\u04302[1] + + (float) k3 * crystal.\u04303[1]); + atom.setZ(atom.getZ() + (float) i * crystal.\u0441[2] + + (float) k * crystal.\u04301[2] + + (float) k2 * crystal.\u04302[2] + + (float) k3 * crystal.\u04303[2]); + } + m.appendMolecule(newMol); + } + } + } + */ + + } + + Molecule.guessCovalentBonds(m); + try { + CCTParser.saveCCTFile(m, args[1]); + } + catch (Exception ex) { + //JOptionPane.showMessageDialog(null, + // ex.getMessage(), + // "Error", + // JOptionPane.ERROR_MESSAGE); + System.err.println(ex.getMessage()); + System.exit(1); + } + + } +} diff --git a/src/main/java/cct/tools/DXData.java b/src/main/java/cct/tools/DXData.java new file mode 100644 index 0000000..557c6d2 --- /dev/null +++ b/src/main/java/cct/tools/DXData.java @@ -0,0 +1,148 @@ +package cct.tools; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.util.StringTokenizer; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2009 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ + +enum DX_KEYWORDS { + TITLE, XUNITS, YUNITS, XFACTOR, YFACTOR, NPOINTS, DELTAX +} + +public class DXData { + private String title = "No title"; + private double xFactor = 1.0, yFactor = 1.0; + private int nPoints = 0; + private double[] x, y; + + public DXData() { + } + + public int countItems() { + return nPoints; + } + + public double[] getXData() { + return x; + } + + public double[] getYData() { + return y; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getTitle() { + return this.title; + } + + public void parseDXFile(String fileName) throws Exception { + BufferedReader in = new BufferedReader(new FileReader(fileName)); + parseDXFile(in); + in.close(); + } + + public void parseDXFile(BufferedReader in) throws Exception { + String line; + int nLines = 0; + while ( (line = in.readLine()) != null) { + line = line.trim(); + + if (line.startsWith("##XYDATA=")) { + break; + } + + if (line.startsWith("##")) { + String keyword = line.substring(2, line.indexOf("=")).trim(); + String value = ""; + if (line.indexOf("=") + 1 < line.length()) { + value = line.substring(line.indexOf("=") + 1).trim(); + } + + DX_KEYWORDS key = null; + try { + key = DX_KEYWORDS.valueOf(keyword); + } + catch (Exception ex) { + continue; + } + + switch (key) { + case TITLE: + title = value; + break; + case XFACTOR: + xFactor = Double.parseDouble(value); + break; + case YFACTOR: + yFactor = Double.parseDouble(value); + break; + case NPOINTS: + nLines = Integer.parseInt(value); + break; + + } + } + } + + // --- Read data + + if (nLines < 1) { + throw new Exception("Didn't find NPOINTS keyword"); + } + + x = new double[nLines]; + y = new double[nLines]; + StringTokenizer st; + String token; + int i; + for (nPoints = 0, i = 0; i < nLines; i++, nPoints++) { + line = in.readLine(); + if (line == null) { + System.err.println("Warning: Expected " + nLines + " lines of data, got " + (i + 1)); + break; + } + + if (line.startsWith("##END")) { + break; + } + + st = new StringTokenizer(line, " "); + if (st.countTokens() < 2) { + throw new Exception("Expected at least 2 tokens while reading lines of data, got: " + line); + } + + token = st.nextToken(); + try { + x[i] = Double.parseDouble(token) * xFactor; + } + catch (Exception ex) { + throw new Exception("Error while parsing X value in line: " + line + " : " + ex.getMessage()); + } + + token = st.nextToken(); + try { + y[i] = Double.parseDouble(token) * yFactor; + } + catch (Exception ex) { + throw new Exception("Error while parsing Y value in line: " + line + " : " + ex.getMessage()); + } + } + + } + +} diff --git a/src/main/java/cct/tools/DataSets.java b/src/main/java/cct/tools/DataSets.java new file mode 100644 index 0000000..442adf9 --- /dev/null +++ b/src/main/java/cct/tools/DataSets.java @@ -0,0 +1,501 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.tools; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; + +/** + * + * @author Vlad + */ +public abstract class DataSets { + + public static final String DATA_ROW_NUMBER = "Row Number"; + + private Set descriptors = new LinkedHashSet(); + private Map data = new LinkedHashMap(); + static final Logger logger = Logger.getLogger(DataSets.class.getCanonicalName()); + + public DataSets() { + descriptors.add(DATA_ROW_NUMBER); + } + + public abstract void parseData(BufferedReader in) throws Exception; + + public void parseData(String filename) throws Exception { + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(filename)); + } catch (Exception e) { + throw new Exception("Error opening file " + filename + " : " + e.getMessage()); + } + + try { + parseData(in); + } catch (Exception e) { + try { + in.close(); + } catch (Exception ex) { + } + throw new Exception("Error while parsing data in file " + filename + " : " + e.getMessage()); + } + try { + in.close(); + } catch (Exception ex) { + } + } + + public void addData(String dataLabel, Object object) { + if (dataLabel.equals(DATA_ROW_NUMBER)) { + return; + } + if (!data.containsKey(dataLabel)) { + List list = new ArrayList(); + data.put(dataLabel, list); + descriptors.add(dataLabel); + } + data.get(dataLabel).add(object); + } + + public void addData(String dataLabel, String string) { + if (dataLabel.equals(DATA_ROW_NUMBER)) { + return; + } + if (!data.containsKey(dataLabel)) { + List list = new ArrayList(); + data.put(dataLabel, list); + descriptors.add(dataLabel); + } + data.get(dataLabel).add(string); + } + + public void addData(String dataLabel, double number) { + if (dataLabel.equals(DATA_ROW_NUMBER)) { + return; + } + if (!data.containsKey(dataLabel)) { + List list = new ArrayList(); + data.put(dataLabel, list); + descriptors.add(dataLabel); + } + data.get(dataLabel).add(number); + } + + public void addData(String dataLabel, float number) { + if (dataLabel.equals(DATA_ROW_NUMBER)) { + return; + } + if (!data.containsKey(dataLabel)) { + List list = new ArrayList(); + data.put(dataLabel, list); + descriptors.add(dataLabel); + } + data.get(dataLabel).add(number); + } + + public void addData(String dataLabel, int number) { + if (dataLabel.equals(DATA_ROW_NUMBER)) { + return; + } + if (!data.containsKey(dataLabel)) { + List list = new ArrayList(); + data.put(dataLabel, list); + descriptors.add(dataLabel); + } + data.get(dataLabel).add(number); + } + + public Object getData(String dataLabel, int index) { + if (dataLabel.equals(DATA_ROW_NUMBER)) { + return getData(index); + } + if (!data.containsKey(dataLabel)) { + return null; + } + + List list = data.get(dataLabel); + if (index < 0 || index >= list.size()) { + return null; + } + return list.get(index); + } + + private Object getData(int index) { + if (index < 0 || index >= this.getDataSize()) { + return null; + } + return new Integer(index + 1); + } + + public String getDataAsString(String dataLabel, int index) { + if (dataLabel.equals(DATA_ROW_NUMBER)) { + return getDataAsString(index); + } + if (!data.containsKey(dataLabel)) { + return null; + } + + List list = data.get(dataLabel); + if (index < 0 || index >= list.size()) { + return null; + } + return list.get(index).toString(); + } + + private String getDataAsString(int index) { + if (index < 0 || index >= this.getDataSize()) { + return null; + } + return String.valueOf(index + 1); + } + + public Double getDataAsDouble(String dataLabel, int index) { + if (dataLabel.equals(DATA_ROW_NUMBER)) { + return getDataAsDouble(index); + } + if (!data.containsKey(dataLabel)) { + return null; + } + + List list = data.get(dataLabel); + if (index < 0 || index >= list.size()) { + return null; + } + if (list.get(index) instanceof Number) { + return ((Number) list.get(index)).doubleValue(); + } + if (list.get(index) instanceof String) { + try { + return Double.parseDouble(list.get(index).toString()); + } catch (Exception ex) { + logger.severe("Error parsing " + list.get(index).toString() + " as a double value"); + return null; + } + } + return null; + } + + private Double getDataAsDouble(int index) { + if (index < 0 || index >= this.getDataSize()) { + return null; + } + return new Double(index + 1); + } + + public Float getDataAsFloat(String dataLabel, int index) { + if (dataLabel.equals(DATA_ROW_NUMBER)) { + return getDataAsFloat(index); + } + if (!data.containsKey(dataLabel)) { + return null; + } + + List list = data.get(dataLabel); + if (index < 0 || index >= list.size()) { + return null; + } + if (list.get(index) instanceof Number) { + return ((Number) list.get(index)).floatValue(); + } + if (list.get(index) instanceof String) { + try { + return Float.parseFloat(list.get(index).toString()); + } catch (Exception ex) { + logger.severe("Error parsing " + list.get(index).toString() + " as a float value"); + return null; + } + } + return null; + } + + private Float getDataAsFloat(int index) { + if (index < 0 || index >= this.getDataSize()) { + return null; + } + return new Float(index + 1); + } + + public Integer getDataAsInteger(String dataLabel, int index) { + if (dataLabel.equals(DATA_ROW_NUMBER)) { + return getDataAsInteger(index); + } + if (!data.containsKey(dataLabel)) { + return null; + } + + List list = data.get(dataLabel); + if (index < 0 || index >= list.size()) { + return null; + } + if (list.get(index) instanceof Number) { + return ((Number) list.get(index)).intValue(); + } + if (list.get(index) instanceof String) { + try { + return Integer.parseInt(list.get(index).toString()); + } catch (Exception ex) { + logger.severe("Error parsing " + list.get(index).toString() + " as a integer value"); + return null; + } + } + return null; + } + + private Integer getDataAsInteger(int index) { + if (index < 0 || index >= this.getDataSize()) { + return null; + } + return new Integer(index + 1); + } + + public Object getLastData(String dataLabel) { + if (!data.containsKey(dataLabel)) { + return null; + } + return this.getData(dataLabel, data.get(dataLabel).size() - 1); + } + + public String geLastDataAsString(String dataLabel) { + if (!data.containsKey(dataLabel)) { + return null; + } + return this.getDataAsString(dataLabel, data.get(dataLabel).size() - 1); + } + + public Double getLastDataAsDouble(String dataLabel) { + if (!data.containsKey(dataLabel)) { + return null; + } + return this.getDataAsDouble(dataLabel, data.get(dataLabel).size() - 1); + } + + public Float getLastDataAsFloat(String dataLabel) { + if (!data.containsKey(dataLabel)) { + return null; + } + return this.getDataAsFloat(dataLabel, data.get(dataLabel).size() - 1); + } + + public Integer getLastDataAsInteger(String dataLabel) { + if (!data.containsKey(dataLabel)) { + return null; + } + return this.getDataAsInteger(dataLabel, data.get(dataLabel).size() - 1); + } + + /** + * Clears dataset + */ + public void clearData() { + for (String key : data.keySet()) { + data.get(key).clear(); + //data.put(key, null); + } + data.clear(); + } + + /** + * Returns A COPY of original Map + * + * @return A COPY of original Map + */ + public Map getData() { + return new LinkedHashMap(data); + } + + public Set getDescriptors() { + return new LinkedHashSet(descriptors); + } + + public boolean hasDescriptor(String descr) { + return descriptors.contains(descr); + } + + public void addDescriptor(String descr) { + descriptors.add(descr); + } + + public void clearDescriptors() { + descriptors.clear(); + descriptors.add(DATA_ROW_NUMBER); + this.clearData(); + } + + public int getDataSize() { + if (descriptors.size() < 1) { + return 0; + } + int size = 0; + for (String key : descriptors) { + if (data.get(key) == null) { + continue; + } + if (data.get(key).size() > size) { + size = data.get(key).size(); + } + } + return size; + } + + public double[] getRowNumberAsDouble() { + double[] dbl = new double[this.getDataSize()]; + double value = 1.0; + for (int i = 0; i < getDataSize(); i++, value += 1.0) { + dbl[i] = value; + } + return dbl; + } + + public float[] getRowNumberAsFloat() { + float[] dbl = new float[this.getDataSize()]; + float value = 1.0f; + for (int i = 0; i < getDataSize(); i++, value += 1.0) { + dbl[i] = value; + } + return dbl; + } + + public double[] getDataAsDouble(String descriptor) { + if (descriptor.equals(DATA_ROW_NUMBER)) { + return getRowNumberAsDouble(); + } + List list = data.get(descriptor); + if (list == null) { + return null; + } + + double[] dbl = new double[list.size()]; + + if (list.get(0) instanceof Double) { + List dblList = list; + if (list.get(0) instanceof Double) { + for (int i = 0; i < dbl.length; i++) { + dbl[i] = dblList.get(i); + } + return dbl; + } + } + + // --- + if (list.get(0) instanceof Float) { + List fltList = list; + for (int i = 0; i < dbl.length; i++) { + dbl[i] = fltList.get(i).doubleValue(); + } + return dbl; + } + // --- + + if (list.get(0) instanceof Integer) { + List intList = list; + for (int i = 0; i < dbl.length; i++) { + dbl[i] = intList.get(i).doubleValue(); + } + return dbl; + } + + // --- + dbl = null; + return dbl; + } + + public float[] getDataAsFloat(String descriptor) { + if (descriptor.equals(DATA_ROW_NUMBER)) { + return getRowNumberAsFloat(); + } + List list = data.get(descriptor); + if (list == null) { + return null; + } + + float[] dbl = new float[list.size()]; + for (int i = 0; i < dbl.length; i++) { + dbl[i] = (Float) list.get(i); + } + return dbl; + } + + public int[] getRowNumberAsInteger() { + int[] dbl = new int[this.getDataSize()]; + + for (int i = 0; i < getDataSize(); i++) { + dbl[i] = i + 1; + } + return dbl; + } + + public int[] getDataAsInteger(String descriptor) { + if (descriptor.equals(DATA_ROW_NUMBER)) { + return getRowNumberAsInteger(); + } + List list = data.get(descriptor); + if (list == null) { + return null; + } + + int[] dbl = new int[list.size()]; + for (int i = 0; i < dbl.length; i++) { + dbl[i] = (Integer) list.get(i); + } + return dbl; + } + + public String[] getRowNumberAsString() { + String[] dbl = new String[this.getDataSize()]; + + for (int i = 0; i < getDataSize(); i++) { + dbl[i] = String.valueOf(i + 1); + } + return dbl; + } + + public String[] getDataAsString(String descriptor) { + if (descriptor.equals(DATA_ROW_NUMBER)) { + return getRowNumberAsString(); + } + List list = data.get(descriptor); + if (list == null) { + return null; + } + + String[] dbl = new String[list.size()]; + for (int i = 0; i < dbl.length; i++) { + dbl[i] = list.get(i).toString(); + } + return dbl; + } + + public Object[] getDataAsObject(String descriptor) { + List list = data.get(descriptor); + if (list == null) { + return null; + } + return list.toArray(); + } + + public void printDataSets() { + System.out.println("\nData Set(s) Contents:\nDescriptor(s) and Data:\n"); + int count = 0, n = 0; + for (String d : descriptors) { + System.out.println(String.format("%6d", ++count) + " " + d + ":"); + n = 0; + if (!d.equals(DATA_ROW_NUMBER)) { + for (Object o : data.get(d)) { + System.out.println(String.format("%6d", ++n) + " " + o.toString()); + } + } + } + System.out.println("===== End of Data Set(s) =====\n"); + } +} diff --git a/src/main/java/cct/tools/Experimental.java b/src/main/java/cct/tools/Experimental.java new file mode 100644 index 0000000..25fcce3 --- /dev/null +++ b/src/main/java/cct/tools/Experimental.java @@ -0,0 +1,143 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStreamReader; +import java.net.URI; +import java.net.URL; +import java.util.logging.Logger; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Experimental { + static final Logger logger = Logger.getLogger(Experimental.class.getCanonicalName()); + public Experimental() { + } + + public static void main(String[] args) { + Experimental experimental = new Experimental(); + + try { + File file = new File("E:/Java/Tests/PDB/pdb1cfm.ent.Z"); + //URL url = file.toURL(); + //URL url = new URL("ftp://ftp.rcsb.org/pub/pdb/data/structures/divided/pdb/cf/pdb1cfm.ent.Z"); + URL url = new URL("ftp://ftp.rcsb.org/pub/pdb/data/structures/divided/pdp/ka/pdb1kas.ent.Z"); + UncompressInputStream uis = new UncompressInputStream(url.openStream()); + + //Inflater inf = new Inflater(false); + //InflaterInputStream iis = new InflaterInputStream(url.openStream(), inf); + + //GZIPInputStream gzip = new GZIPInputStream(url.openStream()); + //ZipInputStream zis = new ZipInputStream(url.openStream()); + + //DataInputStream dis = new DataInputStream( iis ); + BufferedReader in = new BufferedReader(new InputStreamReader(uis)); + + String line; + while ( (line = in.readLine()) != null) { + + } + + // crude code to unpack a zip file into element files. + FileInputStream fis = new FileInputStream(new File( + "E:/Java/Tests/PDB/pdb1cfm.zip")); + ZipInputStream zip = new ZipInputStream(fis); + + // loop for each entry + while (true) { + ZipEntry entry = zip.getNextEntry(); + // relative name with slashes to separate dirnames. + String elementName = entry.getName(); + File elementFile = new File("targetdir", elementName); + // checking that subdirs exist for elementname is not shown. + + // This code won't work if ZipOutputStream + // was used to create the zip file. ZipEntry.getSize will + // return -1. You will have to read the element in chunks + // or estimate a biggest possible size. + // See http://mindprod.com/products.html#FILETRANSFER + // Filetransfer.copy will handle the chunking and does + // not need to know the length in advance. + int fileLength = (int) entry.getSize(); + + byte[] wholeFile = new byte[fileLength]; + int bytesRead = zip.read(wholeFile, 0, fileLength); + // checking bytesRead, and repeating if you don't get it all is not shown. + FileOutputStream fos = new FileOutputStream(elementFile); + fos.write(wholeFile, 0, fileLength); + fos.close(); + elementFile.setLastModified(entry.getTime()); + zip.closeEntry(); + } + + //zip.close(); + } + catch (Exception e) { + e.printStackTrace(); + } + + try { + URL url = new URL( + "http://sf.anu.edu.au/~vvv900/cct/appl/jmoleditor/download/JMolEditor.jar"); + URI uri = new URI( + "http://sf.anu.edu.au/~vvv900/cct/appl/jmoleditor/download/JMolEditor.jar"); + File file = new File(uri); + + logger.info("Last modified " + file.lastModified()); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } +} diff --git a/src/main/java/cct/tools/Face.java b/src/main/java/cct/tools/Face.java new file mode 100644 index 0000000..ef0377f --- /dev/null +++ b/src/main/java/cct/tools/Face.java @@ -0,0 +1,27 @@ +package cct.tools; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class Face { + int Nv = 0; // # vertices on this face + int v[] = null; // vertex indices + int r, g, b, a = 255; //3 or 4 integers: RGB[A] values 0..255 + float rf, gf, bf, af = 1; // # 3 or 4 floats: RGB[A] values 0..1 + public Face() { + } + + public Face(int _v[]) { + v = _v; + Nv = v.length; + } +} diff --git a/src/main/java/cct/tools/FileFilterImpl.java b/src/main/java/cct/tools/FileFilterImpl.java new file mode 100644 index 0000000..02f302f --- /dev/null +++ b/src/main/java/cct/tools/FileFilterImpl.java @@ -0,0 +1,174 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ + +import java.io.File; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class FileFilterImpl + extends javax.swing.filechooser.FileFilter { + protected String Description = ""; + protected List Extensions = new ArrayList(); + + //Accept all directories and all specified files. + @Override + public boolean accept(File f) { + if (f.isDirectory()) { + return true; + } + + String extension = getExtension(f); + if (extension != null) { + for (int i = 0; i < Extensions.size(); i++) { + String ext = (String) Extensions.get(i); + if (extension.equals(ext)) { + return true; + } + } + } + else { + return false; + } + + return false; + } + + //Accept all directories and all specified files. + public boolean accept(String fileName, boolean isDirectory) { + if (isDirectory) { + return true; + } + + String extension = getExtension(fileName); + if (extension != null) { + for (int i = 0; i < Extensions.size(); i++) { + String ext = (String) Extensions.get(i); + if (ext.equals("*")) { + return true; + } + if (extension.equals(ext)) { + return true; + } + } + } + else { + return false; + } + + return false; + } + +//The description of this filter + @Override + public String getDescription() { + return Description; + } + + public void setDescription(String descr) { + Description = descr; + } + + public static String getExtension(File f) { + return getExtension(f.getName()); + } + + public static String getExtension(String file_name) { + String ext = null; + int i = file_name.lastIndexOf('.'); + + if (i > 0 && i < file_name.length() - 1) { + ext = file_name.substring(i + 1).toLowerCase(); + } + return ext; + } + + /** + * Builds file filter implementations using HaspMap + * @param fileFormats LinkedHashMap + * @return FileFilterImpl[] + */ + public static javax.swing.filechooser.FileFilter[] getFileFilters(Map fileFormats) { + if (fileFormats == null || fileFormats.size() < 1) { + return null; + } + FileFilterImpl[] filters = new FileFilterImpl[fileFormats.size()]; + + int count = 0; + Set set = fileFormats.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String description = me.getKey().toString(); + String ext = me.getValue().toString(); + + filters[count] = new FileFilterImpl(); + String temp[] = ext.split(";"); + for (int i = 0; i < temp.length; i++) { + filters[count].addExtension(temp[i]); + } + filters[count].setDescription(description); + ++count; + } + + //for (int i=0; i (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools; + +import javax.swing.*; +import java.net.URL; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; +import java.util.ResourceBundle; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class FileUtilities { + + static String defaultProperiesFile_16x16 = "cct.tools.FileTypeIcons16x16"; + static String defaultProperiesFile_32x32 = "cct.tools.FileTypeIcons32x32"; + private static ResourceBundle resources; + private static String icons_16x16_base = "/cct/images/icons16x16"; + private static String icons_32x32_base = "/cct/images/icons32x32"; + private static boolean isInitialized_16x16 = false; + private static boolean isInitialized_32x32 = false; + + static String icons_16x16_postfix = "_16x16"; + static String icons_32x32_postfix = "_32x32"; + + final static ImageIcon folder = new ImageIcon(cct.resources.Resources.class. + getResource( + "/cct/images/icons16x16/folder.png")); + + final static ImageIcon folder_32x32 = new ImageIcon(cct.resources.Resources.class. + getResource( + "/cct/images/icons32x32/folder_closed.png")); + + final static ImageIcon multipleItems_32x32 = new ImageIcon(cct.resources. + Resources.class. + getResource( + "/cct/images/icons32x32/folder_window.png")); + + final static ImageIcon document = new ImageIcon(cct.resources.Resources.class. + getResource( + "/cct/images/icons16x16/document.png")); + + final static ImageIcon document_32x32 = new ImageIcon(cct.resources. + Resources.class. + getResource( + "/cct/images/icons32x32/document_plain.png")); + + final static ImageIcon gaussianImage = new ImageIcon(cct.resources.Resources.class. + getResource( + "/cct/images/icons16x16/gaussian-16x16.png")); + + final static ImageIcon triposImage = new ImageIcon(cct.resources.Resources.class. + getResource("/cct/images/icons16x16/tripos-transp-16x16.png")); + + static ImageIcon mdlImage = new ImageIcon(cct.resources.Resources.class. + getResource( + "/cct/images/icons16x16/MDL-16x16.png")); + + static ImageIcon imageFileImage = new ImageIcon(cct.resources.Resources.class. + getResource( + "/cct/images/icons16x16/image-file.png")); + + static ImageIcon javaFileImage = new ImageIcon(cct.resources.Resources.class. + getResource( + "/cct/images/icons16x16/java-file.png")); + + static ImageIcon htmlFileImage = new ImageIcon(cct.resources.Resources.class. + getResource( + "/cct/images/icons16x16/html-file.png")); + + static ImageIcon audioFileImage = new ImageIcon(cct.resources.Resources.class. + getResource( + "/cct/images/icons16x16/audio-file.png")); + + //static HashMap icons16x16 = new HashMap (); + static Map icons16x16 = new HashMap(); + //static HashMap extensions16x16 = new HashMap (); + static Map extensions16x16 = new HashMap(); + + //static HashMap icons32x32 = new HashMap (); + static Map icons32x32 = new HashMap(); + //static HashMap extensions32x32 = new HashMap (); + static Map extensions32x32 = new HashMap(); + + static { + extensions16x16.put("cct/html", htmlFileImage); + extensions16x16.put("htm", htmlFileImage); + + extensions16x16.put("java", javaFileImage); + extensions16x16.put("class", javaFileImage); + + extensions16x16.put("gjf", gaussianImage); + extensions16x16.put("g03", gaussianImage); + extensions16x16.put("mol2", triposImage); + extensions16x16.put("mol", mdlImage); + + extensions16x16.put("jpe", imageFileImage); + extensions16x16.put("jpg", imageFileImage); + extensions16x16.put("jpeg", imageFileImage); + extensions16x16.put("gif", imageFileImage); + extensions16x16.put("png", imageFileImage); + extensions16x16.put("tif", imageFileImage); + extensions16x16.put("tiff", imageFileImage); + } + + private FileUtilities() { + } + + /** + * Returns image icon + * @param filename String + * @return ImageIcon + */ + static public ImageIcon getIcon16x16(String filename) { + if (!isInitialized_16x16) { + initializeIcons_16x16(defaultProperiesFile_16x16); + } + + String ext = getFileExtension(filename).toLowerCase(); + if (ext.length() < 1) { + return document; + } + + if (extensions16x16.containsKey(ext)) { + return (ImageIcon) extensions16x16.get(ext); + } + + return document; + } + + /** + * Returns image icon + * @param filename String + * @return ImageIcon + */ + static public ImageIcon getIcon32x32(String filename) { + if (!isInitialized_32x32) { + initializeIcons_32x32(defaultProperiesFile_32x32); + } + + String ext = getFileExtension(filename).toLowerCase(); + if (ext.length() < 1) { + return document_32x32; + } + + if (extensions32x32.containsKey(ext)) { + return (ImageIcon) extensions32x32.get(ext); + } + + return document_32x32; + } + + static public ImageIcon getFolderIcon32x32() { + return folder_32x32; + } + + static public ImageIcon getMultipleItemsIcon32x32() { + return multipleItems_32x32; + } + + /** + * Returns file extension + * @param filename String - [path]/file name + * @return String File extension + */ + static public String getFileExtension(String filename) { + + int n = filename.lastIndexOf("."); + if (n == -1) { + return ""; + } + + int m = filename.lastIndexOf("/"); + if (m != -1 && m > n) { + return ""; + } + if (filename.endsWith(".")) { + return ""; + } + return filename.substring(filename.lastIndexOf(".") + 1, filename.length()); + } + + /** + * Initializes 16x16 icons + * @param propertiesName String + */ + static public void initializeIcons_16x16(String propertiesName) { + + try { + resources = ResourceBundle.getBundle(propertiesName); + } + catch (Exception ex) { + System.err.println(ex.getMessage()); + if (resources == null) { + System.err.println("Resources " + propertiesName + + " are not found"); + return; + } + } + + // --- First get 16x16 Icons + //for (Enumeration keys = resources.getKeys(); keys.hasMoreElements(); ) { + for (Enumeration keys = resources.getKeys(); keys.hasMoreElements(); ) { + String key = (String) keys.nextElement(); + if (!key.endsWith(icons_16x16_postfix)) { + continue; + } + String iconName = resources.getString(key); + //String iconName = key.substring(0, key.lastIndexOf(icons_16x16_postfix)); + URL resource = cct.resources.Resources.class. + getResource(icons_16x16_base + "/" + iconName); + + if (resource == null) { + System.err.println("Cannot find icon: " + icons_16x16_base + "/" + + iconName); + continue; + } + + ImageIcon icon = new ImageIcon(resource); + + //ImageIcon icon = new ImageIcon(cct.resources.Resources.class. + // getResource(icons_16x16_base + + // File.separator + iconName)); + //logger.info("Adding icon: " + icons_16x16_base + "/" + + // iconName); + icons16x16.put(key, icon); + } + + // -- Now go through file extensions + + //for (Enumeration keys = resources.getKeys(); keys.hasMoreElements(); ) { + for (Enumeration keys = resources.getKeys(); keys.hasMoreElements(); ) { + String key = (String) keys.nextElement(); + if (key.endsWith(icons_16x16_postfix)) { // It's an icon decription + continue; + } + String icon = resources.getString(key); + + if (!icons16x16.containsKey(icon)) { + System.err.println("Error: No icon " + icon + " for extension: " + + key); + continue; + } + + ImageIcon imageIcon = (ImageIcon) icons16x16.get(icon); + extensions16x16.put(key, imageIcon); + + } + + isInitialized_16x16 = true; + } + + /** + * Initializes 32x32 icons + * @param propertiesName String + */ + static public void initializeIcons_32x32(String propertiesName) { + + try { + resources = ResourceBundle.getBundle(propertiesName); + } + catch (Exception ex) { + System.err.println(ex.getMessage()); + if (resources == null) { + System.err.println("Resources " + propertiesName + + " are not found"); + return; + } + } + + // --- First get 32x32 Icons + //for (Enumeration keys = resources.getKeys(); keys.hasMoreElements(); ) { + for (Enumeration keys = resources.getKeys(); keys.hasMoreElements(); ) { + String key = (String) keys.nextElement(); + if (!key.endsWith(icons_32x32_postfix)) { + continue; + } + String iconName = resources.getString(key); + //String iconName = key.substring(0, key.lastIndexOf(icons_16x16_postfix)); + try { + ImageIcon icon = new ImageIcon(cct.resources.Resources.class. + getResource(icons_32x32_base + + "/" + iconName)); + //logger.info("Adding icon: " + icons_32x32_base + + // "/" + + // iconName); + icons32x32.put(key, icon); + } + catch (Exception ex) { + System.err.println("Cannot add icon: " + icons_32x32_base + + "/" + iconName); + + } + } + + // -- Now go through file extensions + + //for (Enumeration keys = resources.getKeys(); keys.hasMoreElements(); ) { + for (Enumeration keys = resources.getKeys(); keys.hasMoreElements(); ) { + String key = (String) keys.nextElement(); + if (key.endsWith(icons_32x32_postfix)) { // It's an icon decription + continue; + } + String icon = resources.getString(key); + + if (!icons32x32.containsKey(icon)) { + System.err.println("Error: No icon " + icon + " for extension: " + + key); + continue; + } + + ImageIcon imageIcon = (ImageIcon) icons32x32.get(icon); + extensions32x32.put(key, imageIcon); + + } + + isInitialized_32x32 = true; + } + + public static String getFileName(String path) { + String filename = null; + if (path.contains("/")) { + filename = path.substring(path.lastIndexOf("/") + 1); + } + else if (path.contains("\\")) { + filename = path.substring(path.lastIndexOf("\\") + 1); + } + else { + return path; + } + return filename; + } + +} diff --git a/src/main/java/cct/tools/FortranNamelist.java b/src/main/java/cct/tools/FortranNamelist.java new file mode 100644 index 0000000..01b8d8a --- /dev/null +++ b/src/main/java/cct/tools/FortranNamelist.java @@ -0,0 +1,379 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.io.StringWriter; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +public class FortranNamelist { + static final int READY_FOR_NEW_OPTION = 0; + static final int WAITING_FOR_VALUE = 1; + protected Map Vars = null; + String Name = null; + String Key = null, Value = null; + int Status = READY_FOR_NEW_OPTION; + static final Logger logger = Logger.getLogger(FortranNamelist.class.getCanonicalName()); + + public FortranNamelist() { + } + + void clear() { + if (Vars == null) { + Vars = new HashMap(); + } + if (!Vars.isEmpty()) { + Vars.clear(); + } + if (Name != null) { + Name = null; + } + Status = READY_FOR_NEW_OPTION; + } + + public Map getVariables() { + return Vars; + } + + /** + * + * @param filename String + * @param nm_name String + * @return String + */ + public String findAndParseFortranNamelist(String filename, String nm_name) { + clear(); + String line, bufer; + String namelist = "&" + nm_name.toUpperCase(); + logger.info("Looking for namelist: " + namelist); + try { + BufferedReader in = new BufferedReader(new FileReader(filename)); + // --- Look for beginning of namelist input + while ( (line = in.readLine()) != null) { + //line.trim(); + bufer = (line.trim()).toUpperCase(); + logger.info("Reading line: #" + bufer + "#"); + if (bufer.compareToIgnoreCase(namelist) == 0) { + String message = parseFortranNamelist(in, bufer); + in.close(); + return message; + } + + } // --- End of while + in.close(); + + } + catch (IOException e) { + String error = "parseFortranNamelist: " + e.getMessage(); + logger.info(error); + return error; + } + + return "Ok"; + } + + /** + * + * @param in BufferedReader + * @param nm_name String + * @return String + */ + public String findAndParseFortranNamelist(BufferedReader in, String nm_name) { + clear(); + String line, bufer; + String namelist = "&" + nm_name.toUpperCase(); + try { + // --- Look for end of namelist input + while ( (line = in.readLine()) != null) { + bufer = (line.trim()).toUpperCase(); + logger.info("Reading line: #" + bufer + "#"); + if (bufer.startsWith(namelist)) { + return parseFortranNamelist(in, bufer); + } + + } // --- End of while + + } + catch (IOException e) { + String error = "parseFortranNamelist: " + e.getMessage(); + logger.info(error); + return error; + } + + return "Ok"; + } + + /** + * + * @param filename String + * @return String + */ + public String parseFortranNamelist(String filename) { + clear(); + String line; + try { + BufferedReader in = new BufferedReader(new FileReader(filename)); + // --- Look for beginning of namelist input + while ( (line = in.readLine()) != null) { + line = line.trim(); + if (line.startsWith("&") || line.startsWith("$")) { + return parseFortranNamelist(in, line); + } + + } // --- End of while + + } + catch (IOException e) { + String error = "parseFortranNamelist: " + e.getMessage(); + logger.info(error); + return error; + } + + return "Ok"; + } + + /** + * + * @param in BufferedReader + * @param line String + * @return String + */ + public String parseFortranNamelist(BufferedReader in, String line) { + clear(); + String message = parseLine(line); + //if (message != null && message.contentEquals("end")) { // Java 1.5 + if (message != null && message.equalsIgnoreCase("end")) { + return "Ok"; + } + else if (message != null) { + return message; + } + + try { + // --- Look for end of namelist input + while ( (line = in.readLine()) != null) { + line = line.trim(); + message = parseLine(line); + //if (message != null && message.contentEquals("end")) { // Java 1.5 + if (message != null && message.equalsIgnoreCase("end")) { + logger.info("End-of-namelist"); + return "Ok"; + } + else if (message != null) { + return message; + } + } // --- End of while + + } + catch (IOException e) { + String error = "parseFortranNamelist: " + e.getMessage(); + logger.info(error); + return error; + } + + return "Ok"; + } + + /** + * + * @param line String + * @return String + */ + public String parseLine(String line) { + String token, opts = line.toUpperCase(); + opts = opts.trim(); + logger.info("Parsing line: " + opts); + if (opts.length() == 0) { + return null; + } + + StringTokenizer subtoken, tokens = new StringTokenizer(opts, " ,"); + + // --- Special case for the first line in namelist input + + if (opts.startsWith("&") || opts.startsWith("$")) { + if (opts.startsWith("&END") || opts.startsWith("$END")) { + return "end"; + } + if (Name != null) { + return "Start of a new namelist"; + } + token = tokens.nextToken(); + subtoken = new StringTokenizer(token, "&$"); + token = subtoken.nextToken(); + Name = token; + logger.info("Namelist name: " + Name); + } + + // --- Go through tokens + + while (tokens.hasMoreTokens()) { + token = tokens.nextToken(); + if (token == null) { + return null; + } + logger.info("Parsing token: " + token); + + // --- Simple cases of end-of-namelist + + if (token.startsWith("&END") || token.startsWith("$END")) { + return "end"; + } + else if (token.startsWith("/") && token.length() == 1) { + return "end"; + } + + // --- Case: taup=0.2 + + //if (Status == READY_FOR_NEW_OPTION && token.contains("=") && // Java 1.5 + if (Status == READY_FOR_NEW_OPTION && token.indexOf("=") != -1 && + (token.indexOf('=') < token.length() - 1)) { + subtoken = new StringTokenizer(token, "="); + Key = subtoken.nextToken(); + if (Vars.containsKey(Key)) { + return "Already contains key " + Key; + } + Value = subtoken.nextToken(); + Vars.put(Key, Value); + Status = READY_FOR_NEW_OPTION; + } + + // --- Case: taup= 0.2 + + //else if (Status == READY_FOR_NEW_OPTION && token.contains("=") && // Java 1.5 + else if (Status == READY_FOR_NEW_OPTION && token.indexOf("=") != -1 && + (token.indexOf('=') == token.length() - 1)) { + subtoken = new StringTokenizer(token, "="); + Key = subtoken.nextToken(); + if (Vars.containsKey(Key)) { + return "Already contains key " + Key; + } + Status = WAITING_FOR_VALUE; + } + + // --- Case: taup =0.2 + + //else if (Status == READY_FOR_NEW_OPTION && !token.contains("=")) { // Java 1.5 + else if (Status == READY_FOR_NEW_OPTION && token.indexOf("=") == -1) { + Key = token; + if (Vars.containsKey(Key)) { + return "Already contains key " + Key; + } + Status = WAITING_FOR_VALUE; + } + + // --- Case: =0.2 + + else if (Status == WAITING_FOR_VALUE && token.indexOf("=") == 0 && + token.length() > 1) { + subtoken = new StringTokenizer(token, "="); + Value = subtoken.nextToken(); + Vars.put(Key, Value); + Status = READY_FOR_NEW_OPTION; + } + + // --- Case: = + + else if (Status == WAITING_FOR_VALUE && token.indexOf("=") == 0 && + token.length() == 1) { + Status = WAITING_FOR_VALUE; + } + + // --- Case: 0.2 + + //else if (Status == WAITING_FOR_VALUE && !token.contains("=")) { // Java 1.5 + else if (Status == WAITING_FOR_VALUE && token.indexOf("=") == -1) { + Value = token; + Vars.put(Key, Value); + Status = READY_FOR_NEW_OPTION; + } + + } + + return null; + } + + /** + * + * @param line String + * @param nm_name String + * @return boolean + */ + static public boolean hasNamelistStart(String line, String nm_name) { + String namelist = "&" + nm_name.toUpperCase(); + String bufer = (line.trim()).toUpperCase(); + + return bufer.startsWith( namelist ); + + } + + /** + * + * @param line String + * @return boolean + */ + static public boolean hasNamelistEnd(String line) { + String bufer = (line.trim()).toUpperCase(); + return bufer.endsWith( "&END" ) || bufer.endsWith( "$END" ) || bufer.endsWith( " /" ); + } + + static public void writeNamelistBody(StringWriter sWriter, String namelistName, Map Vars) { + + sWriter.write(" &" + namelistName + "\n"); + + Set set = Vars.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String option = me.getKey().toString(); + String value = me.getValue().toString(); + + sWriter.write(" " + option + " = " + value + "\n"); + } + + sWriter.write(" &end\n"); + } + +} diff --git a/src/main/java/cct/tools/FragmentDictionaryParser.java b/src/main/java/cct/tools/FragmentDictionaryParser.java new file mode 100644 index 0000000..52cb887 --- /dev/null +++ b/src/main/java/cct/tools/FragmentDictionaryParser.java @@ -0,0 +1,703 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStreamWriter; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; +import java.net.URI; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Result; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.Comment; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +import cct.interfaces.MoleculeInterface; +import cct.modelling.Molecule; + +/** + *

Title:

+ * + *

Description:

+ * + * + * + * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class FragmentDictionaryParser + extends DefaultHandler { + + static boolean Debug = true; + + Map dictionaryTree = new LinkedHashMap(); + List dicStack = new ArrayList(); + + static final String INPUT_SOURCE_TAG = "inputSource"; + static final String DICTIONARY_TAG = "fragmentDictionary"; + static final String VERSION_TAG = "version"; + static final String FRAGMENT_TAG = "fragment"; + + boolean yes_dictionary = false; + boolean finish_parsing = false; + + boolean unrecoverableError = false; + String currentTag = null; + + StringReader sReader = null; + StringWriter sWriter = null; + + static private Writer out; + private InputStream is = null; + String fragContext = null; + URL fragmentDictionary = null; + Map fragmentsReferences = new HashMap(); + static final Logger logger = Logger.getLogger(FragmentDictionaryParser.class.getCanonicalName()); + + public FragmentDictionaryParser() { + + } + + public MoleculeInterface loadFragment(String specification) throws Exception { + + InputStream is = getInputStream(specification); + + MoleculeInterface m = new Molecule(); + CCTParser cctParser = new CCTParser(m); + List mols = cctParser.parseCCTFile(is, m); + m = (MoleculeInterface) mols.get(0); + logger.info("Number of atoms: " + m.getNumberOfAtoms()); + + return m; + } + + public InputStream getInputStream(String specification) throws Exception { + String urlAddress = fragContext + specification; + URL url = null; + try { + url = new URL(urlAddress); + } + catch (java.net.MalformedURLException ex) { + throw new Exception("Error Loading fragment: " + specification + " : " + ex.getMessage()); + } + + InputStream is = null; + try { + is = url.openStream(); + } + catch (IOException ex) { + throw new Exception("Error Loading fragment: " + specification + " : " + ex.getMessage()); + } + return is; + } + + /* + public FragmentDictionaryParser(MoleculeInterface molecule) { + currentMolecule = molecule; + try { + resources = ResourceBundle.getBundle("cct.cct"); + String text = + resources.getString(this.getClass().getName() + ".debug"); + if (text.equalsIgnoreCase("true")) { + Debug = true; + } + else if (text.equalsIgnoreCase("false")) { + Debug = false; + } + else { + logger.info("Warning: wrong value for " + + this.getClass().getName() + ".debug" + " : " + + text); + } + } + catch (Exception ex) { + System.err.println(ex.getMessage()); + if (resources == null) { + System.err.println("Resources for class " + this.getClass().getName() + + " not found"); + } + } + } + */ + + public static Map parseFragmentDictionary(Object inputSource) { + DefaultHandler handler = new FragmentDictionaryParser(); + // Use the default (non-validating) parser + SAXParserFactory factory = SAXParserFactory.newInstance(); + + try { + // Set up output stream + out = new OutputStreamWriter(System.out, "UTF8"); + + // Parse the input + SAXParser saxParser = factory.newSAXParser(); + + if (inputSource instanceof URL) { + URL file_name_location = (URL) inputSource; + + URI uri = new URI(file_name_location.getPath()); // file_name_location.toURI(); + uri.normalize(); + logger.info("URI: " + uri.toASCIIString()); + saxParser.parse(new File(uri), handler); + } + else if (inputSource instanceof InputStream) { + InputStream is = (InputStream) inputSource; + saxParser.parse(is, handler); + } + } + catch (Throwable t) { + //logger.error("Parsing error " + t.getMessage()); + t.printStackTrace(); + } + + FragmentDictionaryParser parser = (FragmentDictionaryParser) handler; + parser.setInputSource(inputSource); + + return parser.getDictionaryTree(); + } + + private static void saveCCTFile(List mols, String fileName) throws + Exception { + //Message = ""; + + FileOutputStream out; + try { + out = new FileOutputStream(fileName); + } + catch (Exception ex) { + System.err.println("Error opening FileOutputStream: " + ex.getMessage()); + throw ex; + } + + /* + //StringWriter sWriter = new StringWriter(); + + StreamResult streamResult = new StreamResult(out); + SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory. + newInstance(); + + // SAX2.0 ContentHandler. + TransformerHandler hd = null; + try { + hd = tf.newTransformerHandler(); + } + catch (TransformerConfigurationException e) { + System.err.println("Error geting newTransformerHandler: " + + e.getMessage()); + throw e; + } + + Transformer serializer = hd.getTransformer(); + //serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); + //serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "users.dtd"); + serializer.setOutputProperty(OutputKeys.INDENT, "yes"); + hd.setResult(streamResult); + try { + hd.startDocument(); + AttributesImpl atts = new AttributesImpl(); + atts.addAttribute("", "", "version", "CDATA", "0.1"); + //atts.addAttribute("","","TYPE","CDATA",type[i]); + + // CCT tag. + hd.startElement("", "", CCTParserEnum.CCT_TAG.toString(), atts); + + if (mols.size() > 1) { + atts.clear(); + atts.addAttribute("", "", "number", "CDATA", + String.valueOf(mols.size())); + hd.startElement("", "", CCTParserEnum.MANY_MOLECULES_TAG.toString(), + atts); + } + + for (int i = 0; i < mols.size(); i++) { + MoleculeInterface molec = (MoleculeInterface) mols.get(i); + atts.clear(); + atts.addAttribute("", "", "name", "CDATA", molec.getName()); + atts.addAttribute("", "", "atoms", "CDATA", + String.valueOf(molec.getNumberOfAtoms())); + atts.addAttribute("", "", "bonds", "CDATA", + String.valueOf(molec.getNumberOfBonds())); + hd.startElement("", "", CCTParserEnum.MOLECULE_TAG.toString(), atts); + + // --- Monomers ******************* + ArrayList substr = molec.getMolecularSubstructure(); + + atts.clear(); + atts.addAttribute("", "", "number", "CDATA", + String.valueOf(substr.size())); + hd.startElement("", "", CCTParserEnum.MANY_MONOMERS_TAG.toString(), + atts); + //hd.startCDATA(); + + hd.characters("\n".toCharArray(), 0, 1); + + Iterator iter = substr.iterator(); + while (iter.hasNext()) { + String data = (String) iter.next() + "\n"; + hd.characters(data.toCharArray(), 0, data.length()); + //hd.startEntity(data); + //out.write(data.getBytes()); + //hd.endEntity(""); + } + + //hd.endCDATA(); + hd.endElement("", "", CCTParserEnum.MANY_MONOMERS_TAG.toString()); + // --- End of monomers ******************** + + // --- Atoms ******************* + + writeAtoms(hd, molec); + + // --- end of atoms ************* + + // --- Bonds ******************** + + writeBonds(hd, molec); + + // --- end of Bonds ************* + + // --- Start to print Properties + + writeProperties(hd, molec); + + // --- End of Properties + + hd.endElement("", "", CCTParserEnum.MOLECULE_TAG.toString()); + } + + if (mols.size() > 1) { + hd.endElement("", "", CCTParserEnum.MANY_MOLECULES_TAG.toString()); + } + + hd.endElement("", "", CCTParserEnum.CCT_TAG.toString()); + hd.endDocument(); + + } + catch (org.xml.sax.SAXException e) { + //Message = e.getMessage(); + System.err.println(e.getMessage()); + throw e; + //return null; + } + + try { + out.close(); + } + catch (Exception ex) { + throw ex; + } + */ + + } + + public Map getDictionaryTree() { + return dictionaryTree; + } + + public void setInputSource(Object inputSource) { + dictionaryTree.put(INPUT_SOURCE_TAG, inputSource); + } + + @Override + public void startDocument() throws SAXException { + if (Debug) { + emit(""); + nl(); + } + } + + @Override + public void endDocument() throws SAXException { + try { + nl(); + out.flush(); + } + catch (IOException e) { + throw new SAXException("I/O error", e); + } + } + + @Override + public void startElement(String namespaceURI, + String lName, // local name + String qName, // qualified name + Attributes attrs) throws SAXException { + + if (unrecoverableError) { + throw new SAXException("Unrecoverable error"); + } + + if (finish_parsing) { + return; + } + + String eName = lName; // element name + if ("".equals(eName)) { + eName = qName; // namespaceAware = false + } + if (Debug) { + emit("<" + eName); + } + if (attrs != null) { + for (int i = 0; i < attrs.getLength(); i++) { + String aName = attrs.getLocalName(i); // Attr name + if ("".equals(aName)) { + aName = attrs.getQName(i); + } + if (Debug) { + emit(" "); + emit(aName + "=\"" + attrs.getValue(i) + "\""); + } + } + } + if (Debug) { + emit(">"); + } + // Parse elements... + + currentTag = eName; + + if (DICTIONARY_TAG.equalsIgnoreCase(eName)) { + yes_dictionary = true; + if (Debug) { + logger.info("Starting parsing fragment dictionary..."); + } + Map oneMoreDic = new LinkedHashMap(); + if (dicStack.size() == 0) { // Root + dicStack.add(oneMoreDic); + } + else { + Map parent = (Map) dicStack.get(dicStack.size() - + 1); // Get last dic + String dicName = attrs.getValue("name"); + if (dicName == null) { // Error + + } + parent.put(dicName, oneMoreDic); + dicStack.add(oneMoreDic); + } + return; + } + + if (!yes_dictionary) { + return; // Don't find tag yet... + } + + if (FRAGMENT_TAG.equalsIgnoreCase(eName)) { + if (Debug) { + logger.info("Starting parsing fragment info"); + } + String fragName = attrs.getValue("name"); + String fragURL = attrs.getValue("url"); + + if (fragName == null) { // Error + + } + if (fragURL == null) { // Error + + } + + Map currentDic = (Map) dicStack.get(dicStack.size() - 1); + currentDic.put(fragName, fragURL); + } + } + + @Override + public void endElement(String namespaceURI, + String sName, // simple name + String qName // qualified name + ) throws SAXException { + + if (unrecoverableError) { + throw new SAXException("Unrecoverable error"); + } + + if (finish_parsing) { + return; + } + + String eName = sName; // element name + if ("".equals(eName)) { + eName = qName; // namespaceAware = false + } + + if (Debug) { + emit(""); + } + // --- Parsing + + if (DICTIONARY_TAG.equalsIgnoreCase(eName)) { + if (Debug) { + logger.info("Finish parsing dictionary..."); + } + if (dicStack.size() == 1) { + finish_parsing = true; + this.dictionaryTree = (Map) dicStack.get(0); + } + dicStack.remove(dicStack.size() - 1); // Remove last dictionary in stack + return; + } + + if (FRAGMENT_TAG.equalsIgnoreCase(eName)) { + if (Debug) { + logger.info("Finish parsing fragment..."); + } + return; + } + + } + + @Override + public void characters(char buf[], int offset, int len) throws + SAXException { + + if (unrecoverableError) { + throw new SAXException("Unrecoverable error"); + } + String s = null; + //logger.info("BUF: " + offset+" "+len); + if (Debug) { + s = new String(buf, offset, len); + emit(s); + } + + /* + if (yes_many_atoms) { + if (parseLevel == CCTParserEnum.MANY_ATOMS_TAG.getEnum()) { + sWriter.write(buf, offset, len); + } + } + */ + + } + + //=========================================================== + // Utility Methods ... + //=========================================================== + + // Wrap I/O exceptions in SAX exceptions, to + // suit handler signature requirements + private void emit(String s) throws SAXException { + try { + //logger.info(s); + //if ( true ) return; + out.write("CHARS:" + s); + out.flush(); + } + catch (IOException e) { + throw new SAXException("I/O error", e); + } + } + + /* + private void emit(String s) throws SAXException { + try { + out.write(s); + out.flush(); + } + catch (IOException e) { + throw new SAXException("I/O error", e); + } + } + */ + // Start a new line + private void nl() throws SAXException { + String lineEnd = System.getProperty("line.separator"); + try { + out.write(lineEnd); + } + catch (IOException e) { + throw new SAXException("I/O error", e); + } + } + + /* + class tasksEndException + extends Exception { + + } + */ + + public void setFragmentDictionary(URL fragmentDic) throws Exception { + + fragmentDictionary = fragmentDic; + fragmentsReferences.clear(); + + if (fragmentDic.getProtocol().equalsIgnoreCase("jar") || fragmentDic.getProtocol().equalsIgnoreCase("zip")) { + fragContext = fragmentDic.toString(); + fragContext = fragContext.substring(0, fragContext.indexOf("!/") + 2); + } + else { + throw new Exception("setFragmentsBaseDirectory: don't know how to work with protocol: " + fragmentDic.getProtocol()); + } + + logger.info("Protocol: " + fragmentDic.getProtocol() + " Context: " + fragContext); + } + + public void saveFragmentDictionary(Map fragTree, String fileName) throws Exception { + + Object obj = fragTree.get(INPUT_SOURCE_TAG); + if (obj instanceof InputStream) { + is = (InputStream) obj; + } + else { + throw new Exception("Cannot handle InputSource " + obj.getClass().getCanonicalName()); + } + + if (!fileName.endsWith(".dic") && !fileName.endsWith(".DIC")) { + fileName += ".dic"; + } + + FileOutputStream fos = new FileOutputStream(fileName); + ZipOutputStream zos = new ZipOutputStream(fos); + + // --- Create dictionary descriptor + + //Create instance of DocumentBuilderFactory + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + //Get the DocumentBuilder + DocumentBuilder parser = factory.newDocumentBuilder(); + //Create blank DOM Document + Document doc = parser.newDocument(); + //create the root element + Element root = doc.createElement(DICTIONARY_TAG); + root.setAttribute("name", "root"); + root.setAttribute(VERSION_TAG, "1.0"); + //add it to the xml tree + doc.appendChild(root); + //create a comment + Comment comment = doc.createComment("This is a main root element for dictionary"); + //add in the root element + root.appendChild(comment); + + addBranch(fragTree, doc, root, zos); + + // --- Finally, save dictionary descriptor + + ZipEntry entry = new ZipEntry(cct.GlobalSettings.getDefaultFragmentDictionary()); + zos.putNextEntry(entry); + // Prepare the DOM document for writing + javax.xml.transform.Source source = new DOMSource(doc); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + Result result = new StreamResult(baos); + + // Write the DOM document to the file + Transformer xformer = TransformerFactory.newInstance().newTransformer(); + //xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + xformer.setOutputProperty(OutputKeys.INDENT, "yes"); + + xformer.transform(source, result); + zos.write(baos.toByteArray()); + zos.closeEntry(); + + zos.close(); + } + + private void addBranch(Map fragTree, Document doc, Element root, ZipOutputStream zos) throws Exception { + Iterator iter = fragTree.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String key = me.getKey().toString(); + Object obj = me.getValue(); + if (obj instanceof Map) { + Element child = doc.createElement(DICTIONARY_TAG); + child.setAttribute("name", key); + root.appendChild(child); + Map childTree = (Map) fragTree.get(key); + addBranch(childTree, doc, child, zos); + } + else if (obj instanceof String) { + + Element child = doc.createElement(FRAGMENT_TAG); + child.setAttribute("name", key); + child.setAttribute("url", obj.toString()); + root.appendChild(child); + + InputStream is = getInputStream(obj.toString()); + ZipEntry entry = new ZipEntry(obj.toString()); + zos.putNextEntry(entry); + byte[] c = new byte[1]; + while ( (c[0] = (byte) is.read()) != -1) { + zos.write(c); + } + zos.closeEntry(); + } + else { + System.err.println("addBranch: unknown class" + obj.getClass().getCanonicalName()); + } + + } + + } + +} diff --git a/src/main/java/cct/tools/GeomFormat.java b/src/main/java/cct/tools/GeomFormat.java new file mode 100644 index 0000000..607e6e9 --- /dev/null +++ b/src/main/java/cct/tools/GeomFormat.java @@ -0,0 +1,333 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo (former JMolEditor) - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + + +package cct.tools; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.prefs.Preferences; + +import javax.swing.JFileChooser; + +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.ChemicalElements; + +/** + *

Title: Jamberoo - Computational Chemistry Toolkit

+ * + *

Description: Collection of Computational Chemistry related code

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vasilyev

+ * + *

Company: The Australian National University

+ * + * @author Dr. Vladislav Vasilyev + * @version 1.0 + */ +public class GeomFormat { + + private static String lastPWDKey = "lastPWD"; + + float[] transformMatrix = null; + MoleculeInterface molecule = null; + + float defaultAtomicRadius = 0.05f; + private static float defaulCylinerRadius = 0.01f; + + Preferences prefs = Preferences.userNodeForPackage(getClass()); + File currentWorkingDirectory = null; + JFileChooser chooser = null; + FileFilterImpl filter = null; + + public GeomFormat() { + } + + public void settransformMatrix(float[] matrix) { + transformMatrix = new float[16]; + for (int i = 0; i < 16; i++) { + transformMatrix[i] = matrix[i]; + } + } + + public void setMolecule(MoleculeInterface mol) { + molecule = mol; + } + + public static void main(String[] args) { + GeomFormat geomformat = new GeomFormat(); + } + + public void saveGeomFormatFile() throws Exception { + + if (molecule == null) { + throw new Exception("saveGeomFormatFile: ERROR: molecule is not set"); + } + + if (chooser == null) { + chooser = new JFileChooser(); + filter = new FileFilterImpl(); + + String temp[] = { + "gf", "GF"}; // extensions.split(";"); + for (int i = 0; i < temp.length; i++) { + filter.addExtension(temp[i]); + } + filter.setDescription("Geom Format Files (*.gf)"); + chooser.setFileFilter(filter); + } + + chooser.setDialogTitle("Save as Geom Format File"); + chooser.setDialogType(JFileChooser.SAVE_DIALOG); + + if (currentWorkingDirectory != null) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } + else { + String lastPWD = prefs.get(lastPWDKey, ""); + if (lastPWD.length() > 0) { + currentWorkingDirectory = new File(lastPWD); + if (currentWorkingDirectory.isDirectory() && + currentWorkingDirectory.exists()) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } + } + } + + int returnVal = JFileChooser.CANCEL_OPTION; + + returnVal = chooser.showSaveDialog(null); + + if (returnVal == JFileChooser.CANCEL_OPTION) { + return; + } + + if (returnVal == JFileChooser.APPROVE_OPTION) { + String fileName = chooser.getSelectedFile().getPath(); + if (fileName.endsWith(".")) { + fileName += "gf"; + } + else if (!fileName.endsWith(".gf") && !fileName.endsWith(".GF")) { + fileName += ".gf"; + } + currentWorkingDirectory = chooser.getCurrentDirectory(); + try { + prefs.put(lastPWDKey, currentWorkingDirectory.getAbsolutePath()); + } + catch (Exception ex) { + System.err.println("Cannot save cwd: " + ex.getMessage() + + " Ignored..."); + } + //logger.info("You chose to open this file: " + + // fileName); + + saveGeomFormatFile(fileName); + } + + } + + public void saveGeomFormatFile(String filename) throws Exception { + FileOutputStream out; + try { + out = new FileOutputStream(filename); + + out.write("# --- File is generated by Jamberoo. Contact: vvv900@gmail.com\n".getBytes()); + out.write("#\n".getBytes()); + + // --- Write atom spheres + + out.write("\n# --- Atomic spheres\n#\n".getBytes()); + + for (int i = 0; i < molecule.getNumberOfAtoms(); i++) { + AtomInterface atom = molecule.getAtomInterface(i); + + Object obj = atom.getProperty(AtomInterface.VISIBLE); + if (obj != null && obj instanceof Boolean) { + if (! (Boolean) obj) { + continue; + } + } + + out.write("#\n".getBytes()); + + String monomerName = molecule.getMonomerInterface(atom.getSubstructureNumber()).getName(); + + try { + out.write( ("# Atom " + (i + 1) + " " + atom.getName() + "(" + ChemicalElements.getElementName(atom.getAtomicNumber()) + + ") " + monomerName + "-" + (atom.getSubstructureNumber() + 1) + "\n").getBytes()); + } + catch (Exception ex) {} + + // --- Get sphere radius + + obj = atom.getProperty(AtomInterface.GR_RADIUS); + Float radius = defaultAtomicRadius; + if (obj != null) { + if (obj instanceof Float) { + radius = (Float) obj; + } + else if (obj instanceof Double) { + radius = ( (Double) obj).floatValue(); + } + } + + // --- get sphere color + float red = 0.5f, green = 0.5f, blue = 0.5f; + obj = atom.getProperty(AtomInterface.RGB_COLOR); + if (obj != null) { + if (obj instanceof Integer[]) { + red = (float) ( (Integer[]) obj)[0] / 255.0f; + green = (float) ( (Integer[]) obj)[1] / 255.0f; + blue = (float) ( (Integer[]) obj)[2] / 255.0f; + } + } + + out.write( ("s " + atom.getX() + " " + atom.getY() + " " + atom.getZ() + " " + radius + " " + red + " " + green + " " + + blue + "\n").getBytes()); + } + out.write("#\n".getBytes()); + + // --- Writing bonds + //cylinder { < -5.244, 2.407, -18.493>, < -4.837, 2.627, -18.216>, 0.100 + //pigment { color red 0.000 green 1.000 blue 1.000 } + //finish { ambient 0.3 diffuse 0.7 phong 1 } + //} + + int bondRenderingStyle = BondInterface.CYLINDER_BICOLOR; + + for (int i = 0; i < molecule.getNumberOfBonds(); i++) { + BondInterface bond = molecule.getBondInterface(i); + AtomInterface a1 = bond.getIAtomInterface(); + AtomInterface a2 = bond.getJAtomInterface(); + + // --- Whether atoms are visible + + Object obj = a1.getProperty(AtomInterface.VISIBLE); + if (obj != null && obj instanceof Boolean) { + if (! (Boolean) obj) { + continue; + } + } + + obj = a2.getProperty(AtomInterface.VISIBLE); + if (obj != null && obj instanceof Boolean) { + if (! (Boolean) obj) { + continue; + } + } + + obj = bond.getProperty(BondInterface.RENDERING_STYLE); + int bRendStyle = bondRenderingStyle; + if (obj instanceof Integer) { + bRendStyle = ( (Integer) obj).intValue(); + } + + Float R = (Float) bond.getProperty(BondInterface.CYLINDER_RADIUS); + if (R == null || bRendStyle == BondInterface.LINE_BICOLOR) { + R = defaulCylinerRadius; + } + + out.write("#\n".getBytes()); + + try { + out.write( ("# Bond : #" + (molecule.getAtomIndex(a1) + 1) + ":" + a1.getName() + "(" + + ChemicalElements.getElementName(a1.getAtomicNumber()) + + ") " + molecule.getMonomerInterface(a1.getSubstructureNumber()).getName() + "-" + + (a1.getSubstructureNumber() + 1) + " - #" + (molecule.getAtomIndex(a2) + 1) + ":" + a2.getName() + "(" + + ChemicalElements.getElementName(a2.getAtomicNumber()) + + ") " + molecule.getMonomerInterface(a2.getSubstructureNumber()).getName() + "-" + + (a2.getSubstructureNumber() + 1) + "\n").getBytes()); + } + catch (Exception ex) {} + + if (bRendStyle == BondInterface.CYLINDER_BICOLOR || bRendStyle == BondInterface.LINE_BICOLOR) { + + float red = 0.5f, green = 0.5f, blue = 0.5f; + obj = a1.getProperty(AtomInterface.RGB_COLOR); + if (obj != null) { + if (obj instanceof Integer[]) { + red = (float) ( (Integer[]) obj)[0] / 255.0f; + green = (float) ( (Integer[]) obj)[1] / 255.0f; + blue = (float) ( (Integer[]) obj)[2] / 255.0f; + } + } + + // --- Write the first part of a bond + + out.write( ("c " + a1.getX() + " " + a1.getY() + " " + a1.getZ() + " " + (0.5f * (a1.getX() + a2.getX())) + " " + + (0.5f * (a1.getY() + a2.getY())) + " " + (0.5f * (a1.getZ() + a2.getZ())) + " " + R + " " + R + + " " + red + " " + green + " " + blue + "\n").getBytes()); + + // --- Write the second part of a bond + + red = 0.5f; + green = 0.5f; + blue = 0.5f; + obj = a2.getProperty(AtomInterface.RGB_COLOR); + if (obj != null) { + if (obj instanceof Integer[]) { + red = (float) ( (Integer[]) obj)[0] / 255.0f; + green = (float) ( (Integer[]) obj)[1] / 255.0f; + blue = (float) ( (Integer[]) obj)[2] / 255.0f; + } + } + + out.write( ("c " + (0.5f * (a1.getX() + a2.getX())) + " " + (0.5f * (a1.getY() + a2.getY())) + " " + + (0.5f * (a1.getZ() + a2.getZ())) + " " + a2.getX() + " " + a2.getY() + " " + a2.getZ() + " " + R + + " " + R + " " + red + " " + green + " " + blue + "\n").getBytes()); + } + else if (bRendStyle == BondInterface.CYLINDER_MONOCOLOR) { + + } + else if (bRendStyle == BondInterface.LINE_MONOCOLOR) { + + } + + } + + out.close(); + } + + catch (IOException e) { + throw e; + } + + } +} diff --git a/src/main/java/cct/tools/GraphicsFormat.java b/src/main/java/cct/tools/GraphicsFormat.java new file mode 100644 index 0000000..6887363 --- /dev/null +++ b/src/main/java/cct/tools/GraphicsFormat.java @@ -0,0 +1,17 @@ +package cct.tools; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public enum GraphicsFormat { + OOGL_OFF_FORMAT +} diff --git a/src/main/java/cct/tools/GridProviders.java b/src/main/java/cct/tools/GridProviders.java new file mode 100644 index 0000000..6e4ba05 --- /dev/null +++ b/src/main/java/cct/tools/GridProviders.java @@ -0,0 +1,431 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.tools; + +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.ResourceBundle; +import java.util.Set; +import java.util.logging.Logger; + +import javax.swing.JDialog; +import javax.swing.JOptionPane; +import javax.swing.WindowConstants; + +import cct.grid.CheckPoint; +import cct.grid.FileViewerInterface; +import cct.grid.GridProviderInterface; +import cct.grid.ScriptSubmitterDialogInterface; +import cct.grid.ui.CheckPointStatus; +import cct.grid.ui.JobStatusDialog; +import cct.j3d.Java3dUniverse; +import cct.modelling.MolecularFileFormats; +import cct.tools.ui.JShowText; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class GridProviders + implements ActionListener, FileViewerInterface { + + public static final String SCRIPT_SUBMITTER_ARG = "ScriptSubmitter"; + public static final String PROVIDERS_PROPERTY_FILE = "cct.grid.grid-providers"; + public static final String PROVIDER_KEY = "provider"; + public static final String SUBMITTER_KEY = "submitter"; + static final Logger logger = Logger.getLogger(GridProviders.class.getCanonicalName()); + public static String JOB_STATUS_DIALOG = "cct.grid.ui.JobStatusDialog"; + private static ResourceBundle resources = null; + static JobStatusDialog jobStatus = null; + static Object jobStatusSource = null; + static Java3dUniverse java3dUniverse = null; + static Map scriptSubmitters = new LinkedHashMap(); + private static Map actionTable = new HashMap(); + static Map taskProviders = new LinkedHashMap(); + static private GridProviders phantom = new GridProviders(); + static java.awt.Component parentComponent = null; + + private GridProviders() { + try { + resources = ResourceBundle.getBundle(PROVIDERS_PROPERTY_FILE); + + } catch (Exception ex) { + System.err.println(ex.getMessage()); + if (resources == null) { + System.err.println("Resources " + PROVIDERS_PROPERTY_FILE + " are not found"); + return; + } + } + + getProviders(); + if (taskProviders.size() < 1) { + System.err.println("No available task providers"); + return; + } + getScriptSubmitters(); + } + + public static void setParentComponent(java.awt.Component component) { + parentComponent = component; + } + + public static void setMolecularViewer(Java3dUniverse java3d) { + java3dUniverse = java3d; + } + + public void getProviders() { + + for (Enumeration keys = resources.getKeys(); keys.hasMoreElements();) { + String originalOption = keys.nextElement(); + String option = originalOption.toLowerCase(); + if (option.startsWith(PROVIDER_KEY + ".")) { + String className = ""; + try { + className = resources.getString(originalOption); + Class cl = this.getClass().getClassLoader().loadClass(className); + Object obj = cl.newInstance(); + GridProviderInterface gpi = (GridProviderInterface) obj; + logger.info("Task provider " + className + " is loaded..."); + taskProviders.put(gpi.getName(), gpi); + } catch (Exception ex) { + System.err.println("Error Loading Task provider " + className + ": " + ex.getMessage()); + } + } + } + try { + //cct.grid.TaskProvider.setAvailableTaskProviders(taskProviders); + cct.grid.TaskProvider.addTaskProviders(taskProviders); + logger.info("Available providers: " + cct.grid.TaskProvider.getAvailableTaskProviders().toString()); + } catch (Exception ex) { + } + //Class cl = java.lang.ClassLoader.loadClass(provider); + + } + + static public boolean isJobStatusDialogAvailable() { + try { + Class cl = phantom.getClass().getClassLoader().loadClass( + JOB_STATUS_DIALOG); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + return false; + } + return true; + } + + public void invokeJobStatusDialog() { + invokeJobStatusDialog(null, "Jobs Status", false); + jobStatus.setFileViewer(this); + } + + static public void invokeJobStatusDialog(Frame owner, String title, + boolean modal) { + + if (!isJobStatusDialogAvailable()) { + logger.warning("No Job Status Dialog is available"); + return; + } + + if (jobStatus == null) { + CheckPointStatus chk = new CheckPointStatus(); + jobStatus = new JobStatusDialog(owner, title, modal, chk); + + jobStatus.queryJobStatus(); + jobStatus.validate(); + /* + jobStatus.hideButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + System.exit(0); + } + } + ); + */ + jobStatus.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); + jobStatus.setLocationRelativeTo(owner); + + } + + jobStatus.setVisible(true); + } + + @Override + public void setFileInfo(CheckPoint chk, String fileName) { + String fullPath = null; + String type = null; + try { + fullPath = chk.getFullLocalPath(fileName); + type = chk.getOutputFileType(fileName); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + JOptionPane.showMessageDialog(new Frame(), + "Cannot download file " + + fullPath + ": " + ex.getMessage(), + "Warning", + JOptionPane.WARNING_MESSAGE); + return; + } + logger.info("Full path: " + fullPath + " File type" + type); + + if (java3dUniverse != null) { + if (chk.getProgram().equalsIgnoreCase("G03")) { + if (type.equalsIgnoreCase("gaussianOutput")) { + java3dUniverse.openMolecularModelingFile(MolecularFileFormats.gaussian03Output, fullPath); + } else { + JShowText show = new JShowText(fileName); + show.setLocationByPlatform(true); + + try { + BufferedReader in = new BufferedReader(new FileReader( + fullPath)); + String str; + while ((str = in.readLine()) != null) { + show.appendText(str + "\n"); + } + in.close(); + } catch (IOException e) { + JOptionPane.showMessageDialog(new Frame(), + "Error opening file " + + fullPath + ": " + e.getMessage(), + "Error opening file", + JOptionPane.ERROR_MESSAGE); + show.dispose(); + return; + + } + show.setSize(640, 480); + show.setVisible(true); + } + } + + } + } + + public static ScriptSubmitterDialogInterface getScriptSubmitter(String submitter) { + Object obj = scriptSubmitters.get(SUBMITTER_KEY + "." + submitter.toLowerCase()); + if (obj == null) { + return null; + } + return ((ScriptSubmitterDialogInterface) obj).newInstance(); + } + + private void getScriptSubmitters() { + logger.info("Loading Script Submitters..."); + logger.info("Loading Script Submitters..."); + for (Enumeration keys = resources.getKeys(); keys.hasMoreElements();) { + String originalOption = keys.nextElement(); + String option = originalOption.toLowerCase(); + if (option.startsWith(SUBMITTER_KEY + ".")) { + String className = ""; + try { + className = resources.getString(originalOption); + String customOptions = ""; + int index = className.indexOf(" "); + if (index != -1) { + customOptions = className.substring(index).trim(); + className = className.substring(0, index); + logger.info("Submitter Class: " + className + " Custom options: " + customOptions); + logger.info("Submitter Class: " + className + " Custom options: " + customOptions); + } + Class cl = this.getClass().getClassLoader().loadClass(className); + Object obj = cl.newInstance(); + ScriptSubmitterDialogInterface ssd = (ScriptSubmitterDialogInterface) obj; + if (customOptions.length() > 0) { + ssd.setCustomOptions(customOptions); + } + ssd.setTaskProviders(cct.grid.TaskProvider.getAvailableTaskProviders()); + //ssd.setTaskProviders(taskProviders); cct.grid.TaskProvider.getAvailableTaskProviders() + JDialog dialog = ssd.getDialog(); + dialog.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); + dialog.validate(); + dialog.pack(); + //if (parentComponent != null) { + dialog.setLocationRelativeTo(parentComponent); + //} + logger.info("Script submitter " + className + " is loaded..."); + scriptSubmitters.put(option, ssd); + } catch (Exception ex) { + System.err.println("Script submitter " + className + ": " + ex.getMessage()); + } + } + } + } + + public static List getAvailableScriptSubmitters() { + if (scriptSubmitters.size() < 1) { + return null; + } + List submitters = new ArrayList(); + Set k = scriptSubmitters.keySet(); + for (Iterator keys = k.iterator(); keys.hasNext();) { + String option = (String) keys.next(); + submitters.add(option.substring(option.indexOf(".") + 1)); + } + return submitters; + } + + /* + protected synchronized static void loadProviderProperties() { + try { + providerProperties = new Hashtable(); + aliases = new Hashtable(); + Enumeration e = GridProviders.class.getClassLoader().getResources( + PROVIDERS_PROPERTY_FILE); + while (e.hasMoreElements()) { + try { + loadProviderProperties(((URL) e.nextElement()).openStream()); + } + catch (Exception ee) { + logger.debug("Error reading from provider properties", ee); + } + } + } + catch (Exception e) { + logger.warn("No " + PROVIDER_PROPERTY_FILE + + " resource found. You should have at least one provider."); + } + } + */ + + /* + private static void loadProviderProperties(InputStream is) { + Properties props = new Properties(); + try { + props.load(is); + AbstractionProperties map = null; + AbstractionProperties common = new AbstractionProperties(); + String classLoader = null; + String classLoaderProps = null; + String classLoaderBoot = null; + boolean nameFound = false; + Iterator i = props.iterator(); + while (i.hasNext()) { + Property prop = (Property) i.next(); + + if (prop.name.equalsIgnoreCase("provider")) { + map = new AbstractionProperties(); + map.putAll(common); + providerProperties.put(prop.value.trim().toLowerCase(), map); + nameFound = true; + } + else if (prop.name.equalsIgnoreCase("alias")) { + String[] alias = prop.value.split(":"); + if (alias.length != 2) { + logger.warn("Invalid alias line: " + prop.name + "=" + prop.value); + } + else { + aliases.put(alias[0], alias[1]); + } + } + else { + if (map == null) { + common.put(prop.name.trim().toLowerCase(), prop.value.trim()); + } + else { + map.put(prop.name.trim().toLowerCase(), prop.value.trim()); + } + } + } + if (!nameFound) { + logger.warn("Provider name missing from provider properties file"); + } + } + catch (Exception e) { + logger.warn("Could not load properties", e); + } + } + + */ + public static void addActionListener(Object source, String eventType) { + actionTable.put(source, eventType); + + if (eventType.equalsIgnoreCase("JobStatus")) { + jobStatusSource = source; + } + } + + public static ActionListener getActionListener() { + return phantom; + } + + @Override + public void actionPerformed(ActionEvent e) { + + if (!actionTable.containsKey(e.getSource())) { + System.err.println("Error in actionPerformed. Ignored..."); + return; + } + + String actionType = actionTable.get(e.getSource()); + String arg = e.getActionCommand(); + + if (actionType.equalsIgnoreCase(SCRIPT_SUBMITTER_ARG)) { + ScriptSubmitterDialogInterface ssdi = scriptSubmitters.get(SUBMITTER_KEY + "." + arg); + JDialog dialog = ssdi.getDialog(); + dialog.setLocationRelativeTo(null); + dialog.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); + dialog.setVisible(true); + } else if (actionType.equalsIgnoreCase(JOB_STATUS_DIALOG)) { + invokeJobStatusDialog(); + } + + } + + public static void main(String[] args) { + GridProviders gridproviders = new GridProviders(); + gridproviders.getProviders(); + logger.info("Job status dialog: " + GridProviders.isJobStatusDialogAvailable()); + } +} diff --git a/src/main/java/cct/tools/IOUtils.java b/src/main/java/cct/tools/IOUtils.java new file mode 100644 index 0000000..6cbc8a7 --- /dev/null +++ b/src/main/java/cct/tools/IOUtils.java @@ -0,0 +1,263 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.tools; + +import java.awt.Component; +import java.io.BufferedReader; +import java.io.Closeable; +import java.io.DataInput; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; +import java.io.StringWriter; +import java.net.URL; +import java.nio.CharBuffer; +import java.util.logging.Logger; + +import javax.swing.JFileChooser; + +public class IOUtils { + + static final Logger logger = Logger.getLogger(IOUtils.class.getCanonicalName()); + + public IOUtils() { + } + + public static String useFormatTemplate(String format, int number) { + return String.format(format, number); + } + + public static String loadFileIntoString(String filename) { + String line; + StringWriter sWriter = null; + + try { + BufferedReader in = new BufferedReader(new FileReader(filename)); + sWriter = new StringWriter(); + while ((line = in.readLine()) != null) { + sWriter.write(line + "\n"); + } + in.close(); + } catch (IOException e) { + logger.info("loadFileIntoString: " + e.getMessage()); + return null; + } + return sWriter.toString(); + } + + public static boolean saveStringIntoFile(String Text, String fileName) throws + Exception { + FileOutputStream out; + try { + out = new FileOutputStream(fileName); + } catch (java.io.FileNotFoundException er) { + logger.info(er.getMessage()); + //JOptionPane.showMessageDialog(new Frame(), + // er.getMessage(),"Error", + // JOptionPane.ERROR_MESSAGE); + throw new Exception(er.getMessage()); + //return false; + } catch (SecurityException se) { + logger.info(fileName + ": Security Eception\n"); + //JOptionPane.showMessageDialog(new Frame(), + // se.getMessage(),"Error", + // JOptionPane.ERROR_MESSAGE); + throw new Exception(se.getMessage()); + //return false; + } catch (IOException ioe) { + logger.info(ioe.getMessage()); + //JOptionPane.showMessageDialog(new Frame(), + // ioe.getMessage(),"Error", + // JOptionPane.ERROR_MESSAGE); + throw new Exception(ioe.getMessage()); + //return false; + } + + try { + out.write(Text.getBytes()); + } catch (IOException ioe) { + logger.info("Error writing into " + fileName); + //JOptionPane.showMessageDialog(new Frame(), + // ioe.getMessage(),"Error", + // JOptionPane.ERROR_MESSAGE); + throw new Exception(ioe.getMessage()); + //return false; + } + + // --- Finally, close a stream + try { + out.close(); + } catch (IOException ioe) { + logger.info("Error closing " + fileName); + //JOptionPane.showMessageDialog(new Frame(), + // ioe.getMessage(),"Error", + // JOptionPane.ERROR_MESSAGE); + throw new Exception(ioe.getMessage()); + //return false; + } + + return true; + } + + public static URL findFragmentSet(ClassLoader cl, String fragSetName) throws + Exception { + URL loc = null; + loc = cl.getResource(fragSetName); + /* + try { + loc = new URL(""); + } catch ( Exception ex ) { + throw new Exception("findFragmentSet: ERROR: "+ex.getMessage()); + } + */ + return loc; + } + + public static String getRootDirectory(Object obj) { + //cct.BaseClass.getClass().getName() + + String fullName = obj.getClass().getName(); + logger.info("full Name : " + fullName); + + //BaseClass bc = new BaseClass(); + //String fullName = bc.getClass().getName(); + int packageLen = fullName.lastIndexOf('.'); + // get the directory where the contents of this package are stored + + //String packageDir = bc.getClass().getResource(".").getFile(); + String packageDir = obj.getClass().getResource(".").getFile(); + logger.info("Package directory : " + packageDir); + String classesDir = packageDir.substring(0, + packageDir.length() - packageLen + - 1); + //int index = classesDir.lastIndexOf('/'); + //String rootDir = classesDir.substring(0, index + 1); + String rootDir = classesDir; + return rootDir; + } + + public static URL getURL(String protocol, Object obj, String path, + String file) { + + String rootDir = getRootDirectory(obj); + + String fullURLPath = protocol + rootDir + path + file; + + URL url = null; + try { + url = new URL(fullURLPath); + return url; + } catch (java.net.MalformedURLException ex) { + System.err.println("Creating URL : " + fullURLPath + " : " + + ex.getMessage()); + } + + return url; + } + + /** + * + * @param filters FileFilter[] + * @param title String + * @param workingDirectory String + * @param mode int - JFileChooser.OPEN_DIALOG or JFileChooser.SAVE_DIALOG + * @return String + * @throws Exception + */ + public static String chooseFileDialog(javax.swing.filechooser.FileFilter[] filters, Component parent, String title, + String workingDirectory, int mode) throws + Exception { + + if (mode != JFileChooser.OPEN_DIALOG && mode != JFileChooser.SAVE_DIALOG) { + throw new Exception("Unknown mode"); + } + + JFileChooser chooser = new JFileChooser(); + + chooser.setAcceptAllFileFilterUsed(false); + + chooser.setDialogTitle(title); + chooser.setDialogType(mode); + chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + chooser.setMultiSelectionEnabled(false); + + if (workingDirectory != null & workingDirectory.length() > 0) { + File cwd = new File(workingDirectory); + if (cwd.isDirectory() && cwd.exists()) { + chooser.setCurrentDirectory(cwd); + } + } + + for (int i = 0; i < filters.length; i++) { + chooser.addChoosableFileFilter(filters[i]); + logger.info("Adding filter: " + filters[i].getDescription()); + } + chooser.setFileFilter(filters[0]); + logger.info("# of filters: " + chooser.getChoosableFileFilters().length); + + int answer = JFileChooser.CANCEL_OPTION; + + if (mode == JFileChooser.OPEN_DIALOG) { + answer = chooser.showOpenDialog(parent); + } else if (mode == JFileChooser.SAVE_DIALOG) { + answer = chooser.showSaveDialog(parent); + } + + if (answer == JFileChooser.APPROVE_OPTION) { + return chooser.getSelectedFile().getAbsolutePath(); + } + return null; + } + + static public String readLine(Object reader) throws Exception { + if (reader instanceof DataInput) { + return ((DataInput) reader).readLine(); + } else if (reader instanceof BufferedReader) { + return ((BufferedReader) reader).readLine(); + } + throw new Exception("Object " + reader.getClass().getCanonicalName() + " does not support line reading in"); + } + + static public void close(Object reader) throws Exception { + if (reader instanceof Closeable) { + ((Closeable) reader).close(); + } + System.err.println("Warning: object "+reader.getClass().getCanonicalName()+" does not implement Closable interface"); + } +} diff --git a/src/main/java/cct/tools/ImageTools.java b/src/main/java/cct/tools/ImageTools.java new file mode 100644 index 0000000..b27adc3 --- /dev/null +++ b/src/main/java/cct/tools/ImageTools.java @@ -0,0 +1,362 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.tools; + +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.logging.Logger; + +import javax.imageio.IIOImage; +import javax.imageio.ImageIO; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.plugins.jpeg.JPEGImageWriteParam; +import javax.swing.JFileChooser; +import javax.swing.filechooser.FileFilter; + +import cct.tools.ui.FileChooserDialog; +import cct.tools.ui.JPEGOptionsDialog; + +/** + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2006

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class ImageTools { + + static boolean Debug = true; + public static final String IMAGE_PNG = "png"; + public static final String IMAGE_JPEG = "jpg"; + public static final String IMAGE_BMP = "bmp"; + public static final String IMAGE_TIFF = "tiff"; + + static final String LastSaveImagePWD = "LastSaveImageDirectory"; + + protected static final Set supportedSaveImageFormats = new HashSet(); + protected static Set canSaveForThisPlatform; + + static private boolean jpegProgressiveMode = false; + static private boolean optimizeHuffmanCode = false; + static private float jpegImageQuality = 0.99f; + + static final Logger logger = Logger.getLogger(ImageTools.class.getCanonicalName()); + + static { + supportedSaveImageFormats.add(IMAGE_PNG.toUpperCase()); + supportedSaveImageFormats.add(IMAGE_JPEG.toUpperCase()); + supportedSaveImageFormats.add(IMAGE_BMP.toUpperCase()); + } + + private static ImageTools phantom = new ImageTools(); + + public ImageTools() { + if (canSaveForThisPlatform == null) { + String[] supported = getSaveImageFormatNames(); + canSaveForThisPlatform = new HashSet(supported.length); + for (int i = 0; i < supported.length; i++) { + canSaveForThisPlatform.add(supported[i].toUpperCase()); + } + } + } + + public static String[] getSaveImageFormatNames() { + String formats[] = ImageIO.getWriterFormatNames(); + Set tempStore = new HashSet(formats.length); + if (Debug) { + logger.info("System available formats"); + } + for (int i = 0; i < formats.length; i++) { + tempStore.add(formats[i].toUpperCase()); + if (Debug) { + logger.info(formats[i]); + } + } + + List temp = new ArrayList(supportedSaveImageFormats.size()); + Iterator iter = supportedSaveImageFormats.iterator(); + while (iter.hasNext()) { + String format = iter.next(); + if (tempStore.contains(format)) { + temp.add(format); + } + } + String[] supported = new String[temp.size()]; + temp.toArray(supported); + return supported; + } + + public static void saveImageAsDialog(BufferedImage bImage, String imageType) throws + Exception { + saveImageAsDialog(bImage, imageType, new java.awt.Frame()); + } + + public static void saveImageAsDialog(BufferedImage bImage, String imageType, java.awt.Frame parent) throws Exception { + + FileFilterImpl filters[] = null; + String formats[] = null; + + if (imageType == null || imageType.length() == 0) { + formats = ImageTools.getSaveImageFormatNames(); + } else { + formats = new String[1]; + formats[0] = imageType; + } + + filters = new FileFilterImpl[formats.length]; + for (int i = 0; i < formats.length; i++) { + filters[i] = new FileFilterImpl(); + if (formats[i].equalsIgnoreCase("JPG") || formats[i].equalsIgnoreCase("JPEG")) { + filters[i].addExtension("jpg"); + filters[i].addExtension("JPG"); + filters[i].addExtension("jpeg"); + filters[i].addExtension("JPEG"); + filters[i].setDescription("JPEG files (*.jpg;*.jpeg)"); + } else { + filters[i].addExtension(formats[i].toLowerCase()); + filters[i].addExtension(formats[i].toUpperCase()); + filters[i].setDescription(formats[i].toUpperCase() + " files (*." + formats[i].toLowerCase() + ")"); + } + } + + String workingDirectory = Utils.getPreference(phantom, LastSaveImagePWD); + + FileChooserDialog fileChooser = new FileChooserDialog(filters, null, + "Select file to save", JFileChooser.SAVE_DIALOG); + fileChooser.setWorkingDirectory(workingDirectory); + + String outFileName = fileChooser.getFile(); + + if (outFileName == null) { + return; + } + + if (imageType == null || imageType.length() == 0) { + FileFilter filter = fileChooser.getFileFilter(); + String descr = filter.getDescription(); + if (descr.contains("jpg")) { + imageType = "jpg"; + } else if (descr.contains("bmp")) { + imageType = "bmp"; + } else if (descr.contains("png")) { + imageType = "png"; + } else { + throw new Exception("Internal error: cannot deduct image file type from " + descr); + } + } + + String pwd = fileChooser.getCurrentDirectory().getAbsolutePath(); + Utils.savePreference(phantom, LastSaveImagePWD, pwd); + + JPEGOptionsDialog params = new JPEGOptionsDialog(null, "Choose JPEG Parameters", true); + params.setLocationByPlatform(true); + params.setVisible(true); + if (!params.isOKPressed()) { + return; + } + jpegImageQuality = (params.getJPEGQuality()) / 100.0f; + optimizeHuffmanCode = params.isOptimizeHuffmanCode(); + jpegProgressiveMode = params.isProgressiveEncoding(); + + saveImage(bImage, imageType, outFileName); + } + + /** + * Saves buffered image into file + * + * @param bImage + * @param imageType - "jpg", "png" or "bmp" + * @param outFileName + * @throws Exception + */ + public static void saveImage(BufferedImage bImage, String imageType, String outFileName) throws Exception { + + if (!outFileName.endsWith("." + imageType.toUpperCase()) + && !outFileName.endsWith("." + imageType.toLowerCase())) { + outFileName += "." + imageType.toLowerCase(); + } + + // --- Format support check + if (!canSaveForThisPlatform.contains(imageType.toUpperCase())) { + throw new Exception("Image type " + imageType + " is not supported for this platform"); + } + + BufferedImage imageToSave = bImage; + ImageWriter iWriter = null; + + if (imageType.equalsIgnoreCase("JPG") + || imageType.equalsIgnoreCase("JPEG")) { // + + Iterator iter = ImageIO.getImageWritersByFormatName(IMAGE_JPEG); + + if (iter == null) { + throw new Exception("Error Saving Jpeg Image: no such image writer on the system"); + } + + while (iter.hasNext()) { + if (iWriter == null) { + iWriter = iter.next(); + JPEGImageWriteParam param = (JPEGImageWriteParam) iWriter.getDefaultWriteParam(); + if (param.getCompressionMode() != ImageWriteParam.MODE_EXPLICIT) { + param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + } + String[] descr = param.getCompressionQualityDescriptions(); + + param.setCompressionQuality(jpegImageQuality); + param.setOptimizeHuffmanTables(optimizeHuffmanCode); + int mode = ImageWriteParam.MODE_DISABLED; + if (jpegProgressiveMode) { + mode = ImageWriteParam.MODE_DEFAULT; + } + param.setProgressiveMode(mode); + + System.out.print("Compress qual descr: "); + for (int i = 0; i < descr.length; i++) { + System.out.print(" " + descr[i]); + } + System.out.print("\n"); + logger.info("Compression type: " + param.getCompressionType()); + logger.info("Compression quality: " + param.getCompressionQuality()); + + if (bImage.getType() == BufferedImage.TYPE_INT_ARGB) { + imageToSave = convertImage(bImage, BufferedImage.TYPE_INT_RGB); + } + + FileOutputStream out; + try { + out = new FileOutputStream(outFileName); + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + iWriter.setOutput(ImageIO.createImageOutputStream(bout)); + iWriter.write(null, new IIOImage(imageToSave, null, null), param); + byte[] data = bout.toByteArray(); + out.write(data); + out.close(); + return; + } catch (Exception e) { + System.err.println("Error saving " + outFileName + e.getMessage()); + throw new Exception("Error saving " + outFileName + e.getMessage()); + + } + + } + logger.info("Writer: " + iWriter.toString()); + + } + + } else if (imageType.equalsIgnoreCase(IMAGE_BMP)) { + if (bImage.getType() == BufferedImage.TYPE_INT_ARGB) { + imageToSave = convertImage(bImage, BufferedImage.TYPE_INT_RGB); + } + //filters[0].addExtension("bmp"); + //filters[0].addExtension("BMP"); + //filters[0].setDescription("BMP files (*.bmp)"); + } else if (imageType.equalsIgnoreCase(IMAGE_PNG)) { + //filters[0].addExtension("png"); + //filters[0].addExtension("PNG"); + //filters[0].setDescription("PNG files (*.png)"); + } + + try { + ImageIO.write(imageToSave, imageType, + new File(outFileName)); + //new File(workingDirectory + outFileName)); + } catch (Exception ex) { + throw new Exception("Error Saving Image: " + outFileName + " : " + ex.getMessage()); + } + + } + + public static BufferedImage convertImage(BufferedImage bImage, int imageType) { + + BufferedImage imageToSave = new BufferedImage(bImage.getWidth(), + bImage.getHeight(), + imageType); + Graphics2D graphics2D = imageToSave.createGraphics(); + graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, + RenderingHints.VALUE_INTERPOLATION_BILINEAR); + graphics2D.drawImage(bImage, 0, 0, bImage.getWidth(), + bImage.getHeight(), null); + return imageToSave; + } + + public static void main(String[] args) { + ImageTools imagetools = new ImageTools(); + } + + public boolean isJpegProgressiveMode() { + return jpegProgressiveMode; + } + + public void setJpegProgressiveMode(boolean jpegProgressiveMode) { + ImageTools.jpegProgressiveMode = jpegProgressiveMode; + } + + public boolean isOptimizeHuffmanCode() { + return optimizeHuffmanCode; + } + + public void setOptimizeHuffmanCode(boolean optimizeHuffmanCode) { + ImageTools.optimizeHuffmanCode = optimizeHuffmanCode; + } + + public float getJpegImageQuality() { + return jpegImageQuality; + } + + public void setJpegImageQuality(float jpegImageQuality) { + ImageTools.jpegImageQuality = jpegImageQuality; + } +} diff --git a/src/main/java/cct/tools/MemoryMonitor.java b/src/main/java/cct/tools/MemoryMonitor.java new file mode 100644 index 0000000..97504aa --- /dev/null +++ b/src/main/java/cct/tools/MemoryMonitor.java @@ -0,0 +1,377 @@ +/* + * @(#)MemoryMonitor.java 1.34 04/07/26 + * + * Copyright (c) 2004 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * -Redistribution of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * -Redistribution in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING + * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE + * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") + * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE + * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST + * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, + * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY + * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, + * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed, licensed or intended + * for use in the design, construction, operation or maintenance of any + * nuclear facility. + */ + +/* + * @(#)MemoryMonitor.java 1.34 04/07/26 + */ + +package cct.tools; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.awt.geom.Line2D; +import java.awt.geom.Rectangle2D; +import java.awt.image.BufferedImage; +import java.util.Date; +import java.util.logging.Logger; + +import javax.swing.JCheckBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.border.EtchedBorder; +import javax.swing.border.TitledBorder; + +/** + * Tracks Memory allocated & used, displayed in graph form. + */ +public class MemoryMonitor + extends JPanel { + + static JCheckBox dateStampCB = new JCheckBox("Output Date Stamp"); + public Surface surf; + JPanel controls; + boolean doControls; + JTextField tf; + static final Logger logger = Logger.getLogger(MemoryMonitor.class.getCanonicalName()); + + public MemoryMonitor() { + setLayout(new BorderLayout()); + setBorder(new TitledBorder(new EtchedBorder(), "Memory Monitor")); + add(surf = new Surface()); + controls = new JPanel(); + controls.setPreferredSize(new Dimension(135, 80)); + Font font = new Font("serif", Font.PLAIN, 10); + JLabel label = new JLabel("Sample Rate"); + label.setFont(font); + label.setForeground(Color.black); + controls.add(label); + tf = new JTextField("1000"); + tf.setPreferredSize(new Dimension(45, 20)); + controls.add(tf); + controls.add(label = new JLabel("ms")); + label.setFont(font); + label.setForeground(Color.black); + controls.add(dateStampCB); + dateStampCB.setFont(font); + addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + removeAll(); + if ( (doControls = !doControls)) { + surf.stop(); + add(controls); + } + else { + try { + surf.sleepAmount = Long.parseLong(tf.getText().trim()); + } + catch (Exception ex) {} + surf.start(); + add(surf); + } + validate(); + repaint(); + } + }); + } + + public class Surface + extends JPanel implements Runnable { + + public Thread thread; + public long sleepAmount = 1000; + private int w, h; + private BufferedImage bimg; + private Graphics2D big; + private Font font = new Font("Times New Roman", Font.PLAIN, 11); + private Runtime r = Runtime.getRuntime(); + private int columnInc; + private int pts[]; + private int ptNum; + private int ascent, descent; + private float freeMemory, totalMemory; + private Rectangle graphOutlineRect = new Rectangle(); + private Rectangle2D mfRect = new Rectangle2D.Float(); + private Rectangle2D muRect = new Rectangle2D.Float(); + private Line2D graphLine = new Line2D.Float(); + private Color graphColor = new Color(46, 139, 87); + private Color mfColor = new Color(0, 100, 0); + private String usedStr; + + public Surface() { + setBackground(Color.black); + addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (thread == null) { + start(); + } + else { + stop(); + } + } + }); + } + + @Override + public Dimension getMinimumSize() { + return getPreferredSize(); + } + + @Override + public Dimension getMaximumSize() { + return getPreferredSize(); + } + + @Override + public Dimension getPreferredSize() { + return new Dimension(135, 80); + } + + @Override + public void paint(Graphics g) { + + if (big == null) { + return; + } + + big.setBackground(getBackground()); + big.clearRect(0, 0, w, h); + + float freeMemory = r.freeMemory(); + float totalMemory = r.totalMemory(); + + // .. Draw allocated and used strings .. + big.setColor(Color.green); + big.drawString(String.valueOf( (int) totalMemory / (1024 * 1024)) + "Mb allocated", 4.0f, ascent + 0.5f); + usedStr = String.valueOf( ( (int) (totalMemory - freeMemory)) / (1024 * 1024)) + + "Mb used"; + big.drawString(usedStr, 4, h - descent); + + // Calculate remaining size + float ssH = ascent + descent; + float remainingHeight = (h - (ssH * 2) - 0.5f); + float blockHeight = remainingHeight / 10; + float blockWidth = 20.0f; + float remainingWidth = (w - blockWidth - 10); + + // .. Memory Free .. + big.setColor(mfColor); + int MemUsage = (int) ( (freeMemory / totalMemory) * 10); + int i = 0; + for (; i < MemUsage; i++) { + mfRect.setRect(5, ssH + i * blockHeight, + blockWidth, blockHeight - 1); + big.fill(mfRect); + } + + // .. Memory Used .. + big.setColor(Color.green); + for (; i < 10; i++) { + muRect.setRect(5, ssH + i * blockHeight, + blockWidth, blockHeight - 1); + big.fill(muRect); + } + + // .. Draw History Graph .. + big.setColor(graphColor); + int graphX = 30; + int graphY = (int) ssH; + int graphW = w - graphX - 5; + int graphH = (int) remainingHeight; + graphOutlineRect.setRect(graphX, graphY, graphW, graphH); + big.draw(graphOutlineRect); + + int graphRow = graphH / 10; + + // .. Draw row .. + for (int j = graphY; j <= graphH + graphY; j += graphRow) { + graphLine.setLine(graphX, j, graphX + graphW, j); + big.draw(graphLine); + } + + // .. Draw animated column movement .. + int graphColumn = graphW / 15; + + if (columnInc == 0) { + columnInc = graphColumn; + } + + for (int j = graphX + columnInc; j < graphW + graphX; j += graphColumn) { + graphLine.setLine(j, graphY, j, graphY + graphH); + big.draw(graphLine); + } + + --columnInc; + + if (pts == null) { + pts = new int[graphW]; + ptNum = 0; + } + else if (pts.length != graphW) { + int tmp[] = null; + if (ptNum < graphW) { + tmp = new int[ptNum]; + System.arraycopy(pts, 0, tmp, 0, tmp.length); + } + else { + tmp = new int[graphW]; + System.arraycopy(pts, pts.length - tmp.length, tmp, 0, tmp.length); + ptNum = tmp.length - 2; + } + pts = new int[graphW]; + System.arraycopy(tmp, 0, pts, 0, tmp.length); + } + else { + big.setColor(Color.yellow); + pts[ptNum] = (int) (graphY + graphH * (freeMemory / totalMemory)); + for (int j = graphX + graphW - ptNum, k = 0; k < ptNum; k++, j++) { + if (k != 0) { + if (pts[k] != pts[k - 1]) { + big.drawLine(j - 1, pts[k - 1], j, pts[k]); + } + else { + big.fillRect(j, pts[k], 1, 1); + } + } + } + if (ptNum + 2 == pts.length) { + // throw out oldest point + for (int j = 1; j < ptNum; j++) { + pts[j - 1] = pts[j]; + } + --ptNum; + } + else { + ptNum++; + } + } + g.drawImage(bimg, 0, 0, this); + } + + public void start() { + thread = new Thread(this); + thread.setPriority(Thread.MIN_PRIORITY); + thread.setName("MemoryMonitor"); + thread.start(); + } + + public synchronized void stop() { + thread = null; + notify(); + } + + @Override + public void run() { + + Thread me = Thread.currentThread(); + + while (thread == me && !isShowing() || getSize().width == 0) { + try { + Thread.sleep(500); + } + catch (InterruptedException e) { + return; + } + } + + while (thread == me && isShowing()) { + Dimension d = getSize(); + if (d.width != w || d.height != h) { + w = d.width; + h = d.height; + bimg = (BufferedImage) createImage(w, h); + big = bimg.createGraphics(); + big.setFont(font); + FontMetrics fm = big.getFontMetrics(font); + ascent = fm.getAscent(); + descent = fm.getDescent(); + } + repaint(); + try { + Thread.sleep(sleepAmount); + } + catch (InterruptedException e) { + break; + } + if (MemoryMonitor.dateStampCB.isSelected()) { + logger.info(new Date().toString() + " " + usedStr); + } + } + thread = null; + } + } + + public static void main(String s[]) { + final MemoryMonitor demo = new MemoryMonitor(); + WindowListener l = new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + System.exit(0); + } + + @Override + public void windowDeiconified(WindowEvent e) { + demo.surf.start(); + } + + @Override + public void windowIconified(WindowEvent e) { + demo.surf.stop(); + } + }; + JFrame f = new JFrame("MemoryMonitor"); + f.addWindowListener(l); + f.getContentPane().add("Center", demo); + f.pack(); + f.setSize(new Dimension(200, 200)); + f.setVisible(true); + demo.surf.start(); + } +} diff --git a/src/main/java/cct/tools/MessagePost.java b/src/main/java/cct/tools/MessagePost.java new file mode 100644 index 0000000..b7afde8 --- /dev/null +++ b/src/main/java/cct/tools/MessagePost.java @@ -0,0 +1,126 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLEncoder; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class MessagePost { + String urlString; + String Message = ""; + String serverResponseMessage = ""; + URL url = null; + + public MessagePost(String URL) { + urlString = URL; + } + + public MessagePost() { + } + + public void setURL(String URL) { + urlString = URL; + } + + public void addMessage(String key, String message) throws Exception { + if (Message.length() > 1) { + Message += "&"; + } + try { + Message += URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(message, "UTF-8"); + } + catch (Exception ex) { + throw new Exception("Error forming message: " + ex.getMessage()); + } + } + + public void postMessage() throws Exception { + + try { + url = new URL(urlString); + } + catch (Exception ex) { + throw new Exception("Unknown protocol is specidied: " + urlString + " " + ex.getMessage()); + } + + try { + URLConnection conn = url.openConnection(); + conn.setDoOutput(true); + + OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); + wr.write(Message); + wr.flush(); + + // Get the response + BufferedReader rd = new BufferedReader(new InputStreamReader(conn. + getInputStream())); + String line; + while ( (line = rd.readLine()) != null) { + // Process line... + serverResponseMessage += line + "\n"; + } + wr.close(); + rd.close(); + + } + catch (Exception ex) { + throw new Exception("Error sending message: " + ex.getMessage()); + //ex.printStackTrace(); + } + } + + public String getResponseMessage() { + return this.serverResponseMessage; + } +} diff --git a/src/main/java/cct/tools/MultiplyFrames.java b/src/main/java/cct/tools/MultiplyFrames.java new file mode 100644 index 0000000..562b762 --- /dev/null +++ b/src/main/java/cct/tools/MultiplyFrames.java @@ -0,0 +1,161 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools; + +import java.awt.Frame; +import java.io.File; +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.Arrays; +import java.util.Comparator; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.JFileChooser; +import javax.swing.JOptionPane; + +/** + * + * @author Dr. Vladislav Vasyliev + * Multiplies half-cycle frames into a long predefined sequence + */ +public class MultiplyFrames implements Comparator { + + void doInteractively() { + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setMultiSelectionEnabled(true); + fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); + int result = fileChooser.showOpenDialog(null); + + if (result != JFileChooser.APPROVE_OPTION) { + return; + } + + File[] files = fileChooser.getSelectedFiles(); + if (files.length < 1) { + System.err.println("No files selected"); + return; + } + System.out.println(files.length + " files selected"); + Arrays.sort(files, this); + // + File currentDir = fileChooser.getCurrentDirectory(); + System.out.println("Current working directory: " + currentDir.getAbsolutePath()); + System.setProperty("user.dir", fileChooser.getCurrentDirectory().getAbsolutePath()); + + Object obj = JOptionPane.showInputDialog(new Frame(), "Number of repeats", "", JOptionPane.INFORMATION_MESSAGE, + null, null, "1"); + if (obj == null) { + return; + } + int repeat = 1; + try { + repeat = Integer.parseInt(obj.toString()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, "Wrong number " + + obj.toString() + " : " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return; + } + if (repeat < 1) { + System.err.println("Number of repeats should be positive number"); + return; + } + // ---- + Path[] sources = new Path[files.length]; + for (int i = 0; i < files.length; i++) { + Path source = FileSystems.getDefault().getPath("./", files[i].getName()); + sources[i] = source; + Path target = FileSystems.getDefault().getPath("./", String.format("%06d", i) + ".jpg"); + try { + Files.copy(source, target,StandardCopyOption.REPLACE_EXISTING); + } catch (IOException ex) { + Logger.getLogger(MultiplyFrames.class.getName()).log(Level.SEVERE, null, ex); + } + } + + // --- + int pointer = files.length - 1; + int sign = -1; + for (int frame = files.length; frame < files.length * repeat; frame++) { + if (pointer == files.length - 1) { + sign = -1; + } else if (pointer == 0) { + sign = 1; + } + pointer += sign; + Path target = FileSystems.getDefault().getPath("./", String.format("%06d", frame) + ".jpg"); + + try { + Files.copy(sources[pointer], target,StandardCopyOption.REPLACE_EXISTING); + } catch (IOException ex) { + Logger.getLogger(MultiplyFrames.class.getName()).log(Level.SEVERE, null, ex); + } + + } + + } + + public static void main(String[] args) { + boolean interactively = true; + MultiplyFrames mf = new MultiplyFrames(); + for (String arg : args) { + if (arg.equalsIgnoreCase("-gui")) { + interactively = true; + continue; + } + } + // --- + + if (interactively) { + mf.doInteractively(); + } else { + + } + System.exit(0); + } + + public int compare(File o1, File o2) { + return o1.getName().compareTo(o2.getName()); + } + + public boolean equals(Object obj) { + return this == obj; + } +} diff --git a/src/main/java/cct/tools/OOGL.java b/src/main/java/cct/tools/OOGL.java new file mode 100644 index 0000000..00723d7 --- /dev/null +++ b/src/main/java/cct/tools/OOGL.java @@ -0,0 +1,367 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools; + +import java.awt.Color; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.StringReader; +import java.util.StringTokenizer; + +import cct.vecmath.Point3f; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * Syntax Common to All OOGL File Formats + * Most OOGL object file formats are free-format ASCII -- any amount of white space + * (blanks, tabs, newlines) may appear between tokens (numbers, key words, etc.). + * + * Line breaks are almost always insignificant, with a couple of exceptions as noted. + * + * Comments begin with # and continue to the end of the line; they're allowed anywhere a newline is. + * + * Binary formats are also defined for several objects; See section Binary format, and the individual object descriptions. + * + * Typical OOGL objects begin with a key word designating object type, + * possibly with modifiers indicating presence of color information etc. + * In some formats the key word is optional, for compatibility with file formats defined elsewhere. Object + * type is then determined by guessing from the file suffix (if any) or from the data itself. + * + * Key words are case sensitive. Some have optional prefix letters indicating presence of color or other data; + * in this case the order of prefixes is significant, e.g. CNMESH is meaningful but NCMESH is invalid. + * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class OOGL { + + int NVertices = 0, NFaces = 0, NEdges = 0; + int Ndim; + boolean yesSpaceDimension = false; + boolean yesNormals = false; + boolean yesColors = false; + boolean yesTextures = false; + Point3f Vertices[] = null; + Color colors[] = null; + Point3f normals[] = null; + Face faces[] = null; + + public OOGL() { + } + + public int getNFaces() { + return this.NFaces; + } + + public int getNVertices() { + return this.NVertices; + } + + public Point3f[] getVertices() { + return Vertices; + } + + public Color[] getColors() { + return colors; + } + + public Point3f[] getNormals() { + return normals; + } + + public Face[] getFaces() { + return faces; + } + + public void parseOFF(String filename, int fileType) throws Exception { + String line; + BufferedReader in = null; + + if (fileType == 0) { // Read from file + try { + in = new BufferedReader(new FileReader(filename)); + } + catch (java.io.FileNotFoundException e) { + throw new Exception("Error parsing file " + filename + ": " + + e.getMessage()); + } + } + else if (fileType == 1) { // Read from String + in = new BufferedReader(new StringReader(filename)); + } + else { + throw new Exception("Unknown file type"); + } + + int vertexComponents = 3; + int vertexNumbers = 0; + + try { + //BufferedReader in = new BufferedReader(new FileReader(filename)); + + while ( (line = in.readLine()) != null) { + // [ST][C][N][4][n]OFF # Header keyword + StringTokenizer st = new StringTokenizer(line, " \t"); + String header = st.nextToken(); + if (!header.contains("OFF")) { + throw new Exception("Error parsing file " + filename + + ": header does not have OFF string"); + } + if (header.contains("n")) { + yesSpaceDimension = true; + } + + if (header.contains("N")) { + yesNormals = true; + vertexNumbers += 3; + } + + if (header.contains("C")) { + yesColors = true; + vertexNumbers += 4; + } + + if (header.contains("ST")) { + yesTextures = true; + vertexNumbers += 1; + } + + // --- [Ndim] # Space dimension of vertices, present only if nOFF (if any) + if (yesSpaceDimension) { + line = in.readLine(); + st = new StringTokenizer(line, " \t"); + try { + Ndim = Integer.parseInt(st.nextToken()); + } + catch (Exception ex) { + throw new Exception("Error parsing file " + filename + + ": wrong number for Space dimension: " + line); + } + + if (header.contains("4OFF")) { + vertexComponents = 4; + } + else if (header.contains("nOFF")) { + vertexComponents = Ndim; + } + else if (header.contains("4nOFF")) { + vertexComponents = Ndim + 1; + } + vertexNumbers += vertexComponents; + } + + // --- NVertices NFaces NEdges # NEdges not used or checked + line = in.readLine(); + + st = new StringTokenizer(line, " \t"); + if (st.countTokens() < 3) { + throw new Exception("Error parsing file " + filename + + ": expecting three numbers for NVertices, NFaces, and NEdges. Got: " + + line); + } + + try { + NVertices = Integer.parseInt(st.nextToken()); + } + catch (Exception ex) { + throw new Exception("Error parsing file " + filename + + ": wrong number for NVertices: " + line); + } + + try { + NFaces = Integer.parseInt(st.nextToken()); + } + catch (Exception ex) { + throw new Exception("Error parsing file " + filename + + ": wrong number for NFaces: " + line); + } + + try { + NEdges = Integer.parseInt(st.nextToken()); + } + catch (Exception ex) { + //throw new Exception("Error parsing file " + filename + + // ": wrong number for NFaces: " + line); + System.err.println("Error parsing file " + filename + + ": wrong number for NFaces: " + line + + " Error ignored..."); + } + + // x[0] y[0] z[0] # Vertices, possibly with normals, + // # colors, and/or texture coordinates, in that order, + // # if the prefixes N, C, ST + // # are present. + // # If 4OFF, each vertex has 4 components, + // # including a final homogeneous component. + // # If nOFF, each vertex has Ndim components. + // # If 4nOFF, each vertex has Ndim+1 components. + + Vertices = new Point3f[NVertices]; + + if (yesColors) { + colors = new Color[NVertices]; + } + if (yesNormals) { + normals = new Point3f[NVertices]; + } + + for (int i = 0; i < NVertices; i++) { + line = in.readLine(); + + st = new StringTokenizer(line, " \t"); + // --- Error check here + try { + Vertices[i] = new Point3f(Float.parseFloat(st.nextToken()), + Float.parseFloat(st.nextToken()), + Float.parseFloat(st.nextToken())); + } + catch (Exception ex) { + throw new Exception("Error parsing file " + filename + + ": wrong number(s) for vertex coordinate(s): " + + line); + + } + + // --- Parsing normals (if any ) + // --- Error check here + if (yesNormals) { + try { + normals[i] = new Point3f(Float.parseFloat(st.nextToken()), + Float.parseFloat(st.nextToken()), + Float.parseFloat(st.nextToken())); + } + catch (Exception ex) { + throw new Exception("Error parsing file " + filename + + ": wrong number(s) for vertex coordinate(s): " + + line); + + } + + } + + // --- Parsing colors (if any ) + // --- Error check here + if (yesColors) { + try { + colors[i] = new Color(Float.parseFloat(st.nextToken()), + Float.parseFloat(st.nextToken()), + Float.parseFloat(st.nextToken()), + Float.parseFloat(st.nextToken())); + } + catch (Exception ex) { + throw new Exception("Error parsing file " + filename + + ": wrong number(s) for vertex color: " + + line); + + } + } + + // --- Ignore texture for now !!! + } + + // # Faces + // # Nv = # vertices on this face + // # v[0] ... v[Nv-1]: vertex indices + // # in range 0..NVertices-1 + // Nv v[0] v[1] ... v[Nv-1] colorspec + // ... + // # colorspec continues past v[Nv-1] + // # to end-of-line; may be 0 to 4 numbers + // # nothing: default + // # integer: colormap index + // # 3 or 4 integers: RGB[A] values 0..255 + // # 3 or 4 floats: RGB[A] values 0..1 + + faces = new Face[NFaces]; + + for (int i = 0; i < NFaces; i++) { + line = in.readLine(); + + st = new StringTokenizer(line, " \t"); + int nV = 0; + + try { + nV = Integer.parseInt(st.nextToken()); + } + catch (Exception ex) { + throw new Exception("Error parsing file " + filename + + ": wrong number for # vertices: " + line); + } + int v[] = new int[nV]; + for (int j = 0; j < nV; j++) { + try { + v[j] = Integer.parseInt(st.nextToken()); + } + catch (Exception ex) { + throw new Exception("Error parsing file " + filename + + ": wrong number for vertex indices: " + line); + } + faces[i] = new Face(v); + } + + } + + } + + if (fileType == 0) { + in.close(); + } + } + catch (Exception e) { + throw new Exception("Error parsing file " + filename + + " : " + e.getMessage()); + } + + } + + public static void main(String[] args) { + OOGL oogl = new OOGL(); + try { + oogl.parseOFF("C:/ftp/IvanRostov/pcm/tesserae.ogl", 0); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } +} diff --git a/src/main/java/cct/tools/PostMessageType.java b/src/main/java/cct/tools/PostMessageType.java new file mode 100644 index 0000000..f01b96a --- /dev/null +++ b/src/main/java/cct/tools/PostMessageType.java @@ -0,0 +1,34 @@ +package cct.tools; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public enum PostMessageType { + SUGGESTION, BUG_REPORT; + + static final String suggestionKey = "suggest"; + static final String bugKey = "bug"; + + PostMessageType() { } + + /* + public String getKey() { + switch (this) { + case SUGGESTION: + return suggestionKey; + case BUG_REPORT: + return bugKey; + } + return null; + } + */ +} diff --git a/src/main/java/cct/tools/SimpleParserFactory.java b/src/main/java/cct/tools/SimpleParserFactory.java new file mode 100644 index 0000000..230b9b2 --- /dev/null +++ b/src/main/java/cct/tools/SimpleParserFactory.java @@ -0,0 +1,290 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.tools; + +import java.io.BufferedReader; +import java.io.FileReader; + +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.ChemicalElements; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + * @Deprecated Use cct.mdl.MDLMol class instead + */ +@Deprecated +public class SimpleParserFactory { + + static final double ONE_BOHR = 0.529177249; // In Angstrom + + private SimpleParserFactory() { + } + + /** + * + * @param filename + * @param mol + * @return + * @throws Exception + * @Deprecated Use cct.mdl.MDLMol.parseFile method instead + */ + @Deprecated + public static MoleculeInterface parseMDLMolfile(String filename, + MoleculeInterface mol) throws + Exception { + String line; + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(filename)); + + // --- Line 1 + // Molecule name. This line is unformatted, but like all other lines in a molfile + // may not extend beyond column 80. If no name is available, a blank line must be present. + + if ((line = in.readLine()) == null) { + in.close(); + throw new Exception( + "parseMDLMolfile: ERROR: Unxpected End of file while reading Line 1"); + } + + mol.setName(line.trim()); + + // -- Line 2 - Ignored for now !!! + // This line has the format: + // IIPPPPPPPPMMDDYYHHmmddSSssssssssssEEEEEEEEEEEERRRRRR + //(FORTRAN: A2<--A8--><---A10-->A2I2<--F10.5-><---F12.5--><-I6-> ) + // User's first and last initials (l), program name (P), + // date/time (M/D/Y,H:m), dimensional codes (d), scaling factors (S, s), + // energy (E) if modeling program input, internal registry number (R) if input through MDL form. + // A blank line can be substituted for line 2. + + if ((line = in.readLine()) == null) { + in.close(); + throw new Exception( + "parseMDLMolfile: ERROR: Unxpected End of file while reading Line 2"); + } + + // --- Line 3 - Ignored + // A line for comments. If no comment is entered, a blank line must be present. + + if ((line = in.readLine()) == null) { + in.close(); + throw new Exception( + "parseMDLMolfile: ERROR: Unxpected End of file while reading Line 2"); + } + + // -- Counts line + // aaabbblllfffcccsssxxxrrrpppiiimmmvvvvvv + // Where: + // aaa = number of atoms (current max 255)* [Generic] + // bbb = number of bonds (current max 255)* [Generic] + // lll = number of atom lists (max 30)* [Query] + // fff = (obsolete) + // ccc = chiral flag: 0=not chiral, 1=chiral [Generic] + // sss = number of stext entries [MDL ISIS/Desktop] + // xxx = (obsolete) + // rrr = (obsolete) + // ppp = (obsolete) + // iii = (obsolete) + // mmm = number of lines of additional properties, including the M END line. + // No longer supported, the default is set to 999. [Generic] + // * These limits apply to MACCS-II, REACCS, and the MDL ISIS/Host Reaction Gateway, + // but not to the MDL ISIS/Host Molecule Gateway or MDL ISIS/Desktop. + + if ((line = in.readLine()) == null) { + in.close(); + throw new Exception( + "parseMDLMolfile: ERROR: Unxpected End of file while reading Counts line"); + } + + int natoms = 0; + int nbonds = 0; + try { + natoms = Integer.parseInt(line.substring(0, 3).trim()); + } catch (Exception e) { + in.close(); + throw new Exception( + "parseMDLMolfile: ERROR: Error while parsing number of atoms: " + + e.getMessage()); + } + + try { + nbonds = Integer.parseInt(line.substring(3, 6).trim()); + } catch (Exception e) { + in.close(); + throw new Exception( + "parseMDLMolfile: ERROR: Error while parsing number of bonds: " + + e.getMessage()); + } + + // --- The atom block + // The Atom Block is made up of atom lines, one line per atom with the following format: + // xxxxx.xxxxyyyyy.yyyyzzzzz.zzzz aaaddcccssshhhbbbvvvHHHrrriiimmmnnneee + // where the values are described in the following table: + // x y z - atom coordinates [Generic] + // aaa - atom symbol - entry in periodic table or L for atom list, A, Q, + // * for unspecified atom, and LP for lone pair, or R# for Rgroup label - [Generic, Query, 3D, Rgroup] + // dd - mass difference - -3, -2, -1, 0, 1, 2, 3, 4 - (0 if value beyond these limits) + // [Generic] Difference from mass in periodic table. Wider range of values allowed by M ISO line, below. + // Retained for compatibility with older Ctabs, M ISO takes precedence. + // ccc - charge - 0 = uncharged or value other than these, 1 = +3, 2 = +2, 3 = +1, + // 4 = doublet radical, 5 = -1, 6 = -2, 7 = -3 [Generic] Wider range of values in M CHG and M RAD lines below. + // Retained for compatibility with older Ctabs, M CHG and M RAD lines take precedence. + // sss - atom stereo parity - 0 = not stereo, 1 = odd, 2 = even, 3 = either or unmarked stereo center + // [Generic] Ignored when read. + // hhh - hydrogen count + 1; 1 = H0, 2 = H1, 3 = H2, 4 = H3, 5 = H4 + // [Query] H0 means no H atoms allowed unless explicitly drawn. Hn means atom must have n or more Hs in excess of explicit H�s. + // bbb - stereo care box; 0 = ignore stereo configuration of this double bond atom, 1 = stereo configuration of double bond atom must match + // [Query] Double bond stereochemistry is considered during SSS only if both ends of the bond are marked with stereo care boxes. + // vvv - valence; 0 = no marking (default) (1 to 14) = (1 to 14) 15 = zero valence + // [Generic] Shows number of bonds to this atom, including bonds to implied H�s. + // HHH - H0 designator; 0 = not specified, 1 = no H atoms allowed + // [MDL ISIS/Desktop] Redundant with hydrogen count information. May be unsupported in future releases of Elsevier MDL software. + // rrr - Not used + // iii - Not used + // mmm - atom-atom mapping number; 1 - number of atoms; [Reaction] + // nnn - inversion/retention flag; 0 = property not applied; 1 = configuration is inverted, + // 2 = configuration is retained,; [Reaction] + // eee - exact change flag; 0 = property not applied, 1 = change on atom must be exactly as shown; [Reaction, Query] + + + // --- Reading atoms + + for (int i = 0; i < natoms; i++) { + + if ((line = in.readLine()) == null) { + in.close(); + throw new Exception("parseMDLMolfile: ERROR: Unxpected End of file while reading atom " + (i + 1)); + } + + AtomInterface atom = mol.getNewAtomInstance(); + + // --- Getting x,y,z + + float xyz; + try { + xyz = Float.parseFloat(line.substring(0, 10).trim()); + atom.setX(xyz); + xyz = Float.parseFloat(line.substring(10, 20).trim()); + atom.setY(xyz); + xyz = Float.parseFloat(line.substring(20, 30).trim()); + atom.setZ(xyz); + } catch (Exception ex) { + in.close(); + throw new Exception( + "parseMDLMolfile: ERROR: Error while parsing atom: " + + (i + 1) + + " Cannot parse atom's coordinate(s): " + line); + } + + // --- Getting element + + //String token = line.substring(31, 34).trim(); + String token = line.substring(31, Math.min(line.length(), 34)).trim(); + int element = ChemicalElements.getAtomicNumber(token); + atom.setAtomicNumber(element); + atom.setName(token); + + mol.addAtom(atom); + } + + // --- The Bond block + // The Bond Block is made up of bond lines, one line per bond, with the following format: + // 111222tttsssxxxrrrccc + // where + // 111 - first atom number; 1 - number of atoms; [Generic] + // 222 - second atom number; 1 - number of atoms; [Generic] + // ttt - bond type; 1 = Single, 2 = Double, 3 = Triple, 4 = Aromatic, 5 = Single or Double, + // 6 = Single or Aromatic, 7 = Double or Aromatic, 8 = Any [Query] Values 4 through 8 are for SSS queries only. + // sss - bond stereo; Single bonds: 0 = not stereo, 1 = Up, 4 = Either, 6 = Down, Double bonds: 0 = Use x-, y-, z-coords from atom block to determine cis or trans, + // 3 = Cis or trans (either) double bond; [Generic] The wedge (pointed) end of the stereo bond is at the first atom (Field 111 above) + // xxx - not used + // rrr - bond topology; 0 = Either, 1 = Ring, 2 = Chain; [Query] SSS queries only. + // ccc - reacting center status; 0 = unmarked, 1 = a center, -1 = not a center, + // Additional: 2 = no change, 4 = bond made/broken, 8 = bond order changes + // 12 = 4+8 (both made/broken and changes); 5 = (4 + 1), 9 = (8 + 1), and 13 = (12 + 1) are also possible; [Reaction, Query] + + + + for (int i = 0; i < nbonds; i++) { + + if ((line = in.readLine()) == null) { + in.close(); + throw new Exception( + "parseMDLMolfile: ERROR: Unxpected End of file while reading bond " + + (i + 1)); + } + + int a_i, a_j; + try { + a_i = Integer.parseInt(line.substring(0, 3).trim()) - 1; + a_j = Integer.parseInt(line.substring(3, 6).trim()) - 1; + } catch (Exception e) { + in.close(); + throw new Exception( + "parseMDLMolfile: ERROR: Error while parsing bond: " + + (i + 1) + " : " + + e.getMessage()); + } + + BondInterface bond = mol.getNewBondInstance(mol.getAtomInterface( + a_i), mol.getAtomInterface(a_j)); + mol.addBond(bond); + } + + in.close(); + } catch (Exception ex) { + if (in != null) { + in.close(); + } + throw new Exception("parseMDLMolfile: ERROR: " + ex.getMessage()); + } + + return mol; + } +} diff --git a/src/main/java/cct/tools/SwingLookAndFeel.java b/src/main/java/cct/tools/SwingLookAndFeel.java new file mode 100644 index 0000000..ffaffa8 --- /dev/null +++ b/src/main/java/cct/tools/SwingLookAndFeel.java @@ -0,0 +1,149 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools; + +import java.util.prefs.Preferences; + +import javax.swing.UIManager; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class SwingLookAndFeel { + + private static String lookAndFeelKey = "preferredLookAndFeel"; + private static Preferences prefs; + + private SwingLookAndFeel() { + } + + public static String getLookAndFeel() { + return UIManager.getLookAndFeel().getName(); + } + + public static String[] getAvailableLookAndFeels() { + UIManager.LookAndFeelInfo[] inst = UIManager.getInstalledLookAndFeels(); + if (inst.length < 1) { + return null; + } + + String looks[] = new String[inst.length]; + + for (int i = 0; i < inst.length; i++) { + looks[i] = inst[i].getName(); + } + return looks; + } + + public static String retrieveLookAndFeelPrefs(Class c) { + try { + prefs = Preferences.userNodeForPackage(c); + } + catch (Exception ex) { + System.err.println("Error retrieving L&F Preferences: " + ex.getMessage()); + return UIManager.getLookAndFeel().getName(); + } + + String look = prefs.get(lookAndFeelKey, UIManager.getLookAndFeel().getName()); + + String looks[] = getAvailableLookAndFeels(); + + for (int i = 0; i < looks.length; i++) { + if (look.equalsIgnoreCase(looks[i])) { + return look; + } + } + + //System.err.println("Retrieving Preferences: There is no such L&F in the system: " + look); + return UIManager.getLookAndFeel().getName(); + //return null; + } + + public static void saveLookAndFeelPrefs(Class c) { + try { + prefs = Preferences.userNodeForPackage(c); + } + catch (Exception ex) { + System.err.println("Error saving L&F: " + + ex.getMessage()); + return; + } + + try { + prefs.put(lookAndFeelKey, UIManager.getLookAndFeel().getName()); + } + catch (Exception ex) { + System.err.println("Cannot save L&F Preferences: " + + ex.getMessage()); + } + + } + + public static void setLookAndFeel(String lookAndFeelName) throws Exception { + UIManager.LookAndFeelInfo[] inst = UIManager.getInstalledLookAndFeels(); + if (inst.length < 1) { + return; + } + + for (int i = 0; i < inst.length; i++) { + if (lookAndFeelName.equalsIgnoreCase(inst[i].getName())) { + try { + UIManager.setLookAndFeel(inst[i].getClassName()); + } + catch (Exception ex) { + throw ex; + } + return ; + } + } + + } + + public static void main(String[] args) { + SwingLookAndFeel swinglookandfeel = new SwingLookAndFeel(); + } +} diff --git a/src/main/java/cct/tools/SwingWorker.java b/src/main/java/cct/tools/SwingWorker.java new file mode 100644 index 0000000..16a7604 --- /dev/null +++ b/src/main/java/cct/tools/SwingWorker.java @@ -0,0 +1,145 @@ +package cct.tools; + +//import javax.swing.SwingUtilities; + +import javax.swing.SwingUtilities; + + +/** + * This is the 3rd version of SwingWorker (also known as + * SwingWorker 3), an abstract class that you subclass to + * perform GUI-related work in a dedicated thread. For + * instructions on and examples of using this class, see: + * + * http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html + * + * Note that the API changed slightly in the 3rd version: + * You must now invoke start() on the SwingWorker after + * creating it. + */ +public abstract class SwingWorker { + private Object value; // see getValue(), setValue() + + /** + * Class to maintain reference to current worker thread + * under separate synchronization control. + */ + private static class ThreadVar { + private Thread thread; + ThreadVar(Thread t) { + thread = t; + } + + synchronized Thread get() { + return thread; + } + + synchronized void clear() { + thread = null; + } + } + + private ThreadVar threadVar; + + /** + * Get the value produced by the worker thread, or null if it + * hasn't been constructed yet. + */ + protected synchronized Object getValue() { + return value; + } + + /** + * Set the value produced by worker thread + */ + private synchronized void setValue(Object x) { + value = x; + } + + /** + * Compute the value to be returned by the get method. + */ + public abstract Object construct(); + + /** + * Called on the event dispatching thread (not on the worker thread) + * after the construct method has returned. + */ + public void finished() { + } + + /** + * A new method that interrupts the worker thread. Call this method + * to force the worker to stop what it's doing. + */ + public void interrupt() { + Thread t = threadVar.get(); + if (t != null) { + t.interrupt(); + } + threadVar.clear(); + } + + /** + * Return the value created by the construct method. + * Returns null if either the constructing thread or the current + * thread was interrupted before a value was produced. + * + * @return the value created by the construct method + */ + public Object get() { + while (true) { + Thread t = threadVar.get(); + if (t == null) { + return getValue(); + } + try { + t.join(); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); // propagate + return null; + } + } + } + + /** + * Start a thread that will call the construct method + * and then exit. + */ + public SwingWorker() { + final Runnable doFinished = new Runnable() { + @Override + public void run() { + finished(); + } + }; + + Runnable doConstruct = new Runnable() { + @Override + public void run() { + try { + setValue(construct()); + } + finally { + threadVar.clear(); + } + + SwingUtilities.invokeLater(doFinished); + } + }; + + Thread t = new Thread(doConstruct); + threadVar = new ThreadVar(t); + } + + /** + * Start the worker thread. + */ + public void start() { + Thread t = threadVar.get(); + if (t != null) { + t.start(); + } + } +} diff --git a/src/main/java/cct/tools/TextClipboard.java b/src/main/java/cct/tools/TextClipboard.java new file mode 100644 index 0000000..686c3c0 --- /dev/null +++ b/src/main/java/cct/tools/TextClipboard.java @@ -0,0 +1,107 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Attribution-Noncommercial-Share Alike 3.0 Unported + http://www.javapractices.com/home/HomeAction.do + + You are free: + # to Share to copy, distribute and transmit the work + # to Remix to adapt the work + + Under the following conditions: + + * Attribution. You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). + + Attribute this work: + What does "Attribute this work" mean? + The page you came from contained embedded licensing metadata, including how the creator wishes to be attributed for re-use. You can use the HTML here to cite the work. Doing so will also include metadata on your page so that others can find the original work as well. + + * Noncommercial. You may not use this work for commercial purposes. + * Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one. + + * For any reuse or distribution, you must make clear to others the license terms of this work. The best way to do this is with a link to this web page. + * Any of the above conditions can be waived if you get permission from the copyright holder. + * Nothing in this license impairs or restricts the author's moral rights. + + Modified by Dr. Vladislav Vasilyev + ***** END LICENSE BLOCK *****/ + +package cct.tools; + +import java.awt.Toolkit; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.ClipboardOwner; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.StringSelection; +import java.awt.datatransfer.Transferable; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.io.IOException; +import java.util.logging.Logger; + +public final class TextClipboard + implements ClipboardOwner { + + static final Logger logger = Logger.getLogger(TextClipboard.class.getCanonicalName()); + + public static void main(String ...aArguments) { + TextClipboard textTransfer = new TextClipboard(); + + //display what is currently on the clipboard + try { + logger.info("Clipboard contains:" + textTransfer.getClipboardContents()); + + //change the contents and then re-display + textTransfer.setClipboardContents("blah, blah, blah"); + logger.info("Clipboard contains:" + textTransfer.getClipboardContents()); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + + /** + * Empty implementation of the ClipboardOwner interface. + */ + @Override + public void lostOwnership(Clipboard aClipboard, Transferable aContents) { + //do nothing + } + + /** + * Place a String on the clipboard, and make this class the + * owner of the Clipboard's contents. + */ + public void setClipboardContents(String aString) { + StringSelection stringSelection = new StringSelection(aString); + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + clipboard.setContents(stringSelection, this); + } + + /** + * Get the String residing on the clipboard. + * + * @return any text found on the Clipboard; if none found, return an + * empty String. + */ + public String getClipboardContents() throws Exception { + String result = ""; + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + //odd: the Object param of getContents is not currently used + Transferable contents = clipboard.getContents(null); + boolean hasTransferableText = (contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor); + if (hasTransferableText) { + try { + result = (String) contents.getTransferData(DataFlavor.stringFlavor); + } + catch (UnsupportedFlavorException ex) { + //highly unlikely since we are using a standard DataFlavor + System.err.println(ex.getMessage()); + throw ex; + } + catch (IOException ex) { + System.err.println(ex.getMessage()); + throw ex; + //ex.printStackTrace(); + } + } + return result; + } +} diff --git a/src/main/java/cct/tools/UncompressInputStream.java b/src/main/java/cct/tools/UncompressInputStream.java new file mode 100644 index 0000000..616ef5d --- /dev/null +++ b/src/main/java/cct/tools/UncompressInputStream.java @@ -0,0 +1,455 @@ +/* + * @(#)UncompressInputStream.java 0.3-3 06/05/2001 + * + * This file is part of the HTTPClient package + * Copyright (C) 1996-2001 Ronald Tschalr + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free + * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307, USA + * + * For questions, suggestions, bug-reports, enhancement-requests etc. + * I may be contacted at: + * + * ronald@innovation.ch + * + * The HTTPClient's home page is located at: + * + * http://www.innovation.ch/java/HTTPClient/ + * + */ + +package cct.tools; + +import java.io.EOFException; +import java.io.FileInputStream; +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; + + +/** + * This class decompresses an input stream containing data compressed with + * the unix "compress" utility (LZC, a LZW variant). This code is based + * heavily on the unlzw.c code in gzip-1.2.4 (written + * by Peter Jannesen) and the original compress code. + * + * @version 0.3-3 06/05/2001 + * @author Ronald Tschalr + */ +public class UncompressInputStream extends FilterInputStream +{ + /** + * @param is the input stream to decompress + * @exception IOException if the header is malformed + */ + public UncompressInputStream(InputStream is) throws IOException + { + super(is); + parse_header(); + } + + + byte[] one = new byte[1]; + @Override + public synchronized int read() throws IOException + { + int b = in.read(one, 0, 1); + if (b == 1) + return (one[0] & 0xff); + else + return -1; + } + + + // string table stuff + private static final int TBL_CLEAR = 0x100; + private static final int TBL_FIRST = TBL_CLEAR + 1; + + private int[] tab_prefix; + private byte[] tab_suffix; + private int[] zeros = new int[256]; + private byte[] stack; + + // various state + private boolean block_mode; + private int n_bits; + private int maxbits; + private int maxmaxcode; + private int maxcode; + private int bitmask; + private int oldcode; + private byte finchar; + private int stackp; + private int free_ent; + + // input buffer + private byte[] data = new byte[10000]; + private int bit_pos = 0, end = 0, got = 0; + private boolean eof = false; + private static final int EXTRA = 64; + + + @Override + public synchronized int read(byte[] buf, int off, int len) + throws IOException + { + if (eof) return -1; + int start = off; + + /* Using local copies of various variables speeds things up by as + * much as 30% ! + */ + int[] l_tab_prefix = tab_prefix; + byte[] l_tab_suffix = tab_suffix; + byte[] l_stack = stack; + int l_n_bits = n_bits; + int l_maxcode = maxcode; + int l_maxmaxcode = maxmaxcode; + int l_bitmask = bitmask; + int l_oldcode = oldcode; + byte l_finchar = finchar; + int l_stackp = stackp; + int l_free_ent = free_ent; + byte[] l_data = data; + int l_bit_pos = bit_pos; + + + // empty stack if stuff still left + + int s_size = l_stack.length - l_stackp; + if (s_size > 0) + { + int num = (s_size >= len) ? len : s_size ; + System.arraycopy(l_stack, l_stackp, buf, off, num); + off += num; + len -= num; + l_stackp += num; + } + + if (len == 0) + { + stackp = l_stackp; + return off-start; + } + + + // loop, filling local buffer until enough data has been decompressed + + main_loop: do + { + if (end < EXTRA) fill(); + + int bit_in = (got > 0) ? (end - end%l_n_bits)<<3 : + (end<<3)-(l_n_bits-1); + + while (l_bit_pos < bit_in) + { + // check for code-width expansion + + if (l_free_ent > l_maxcode) + { + int n_bytes = l_n_bits << 3; + l_bit_pos = (l_bit_pos-1) + + n_bytes - (l_bit_pos-1+n_bytes) % n_bytes; + + l_n_bits++; + l_maxcode = (l_n_bits==maxbits) ? l_maxmaxcode : + (1<>3; + int code = (((l_data[pos]&0xFF) | ((l_data[pos+1]&0xFF)<<8) | + ((l_data[pos+2]&0xFF)<<16)) + >> (l_bit_pos & 0x7)) & l_bitmask; + l_bit_pos += l_n_bits; + + + // handle first iteration + + if (l_oldcode == -1) + { + if (code >= 256) + throw new IOException("corrupt input: " + code + + " > 255"); + l_finchar = (byte) (l_oldcode = code); + buf[off++] = l_finchar; + len--; + continue; + } + + + // handle CLEAR code + + if (code == TBL_CLEAR && block_mode) + { + System.arraycopy(zeros, 0, l_tab_prefix, 0, zeros.length); + l_free_ent = TBL_FIRST - 1; + + int n_bytes = l_n_bits << 3; + l_bit_pos = (l_bit_pos-1) + + n_bytes - (l_bit_pos-1+n_bytes) % n_bytes; + l_n_bits = INIT_BITS; + l_maxcode = (1 << l_n_bits) - 1; + l_bitmask = l_maxcode; + + if (debug) System.err.println("Code tables reset"); + + l_bit_pos = resetbuf(l_bit_pos); + continue main_loop; + } + + + // setup + + int incode = code; + l_stackp = l_stack.length; + + + // Handle KwK case + + if (code >= l_free_ent) + { + if (code > l_free_ent) + throw new IOException("corrupt input: code=" + code + + ", free_ent=" + l_free_ent); + + l_stack[--l_stackp] = l_finchar; + code = l_oldcode; + } + + + // Generate output characters in reverse order + + while (code >= 256) + { + l_stack[--l_stackp] = l_tab_suffix[code]; + code = l_tab_prefix[code]; + } + l_finchar = l_tab_suffix[code]; + buf[off++] = l_finchar; + len--; + + + // And put them out in forward order + + s_size = l_stack.length - l_stackp; + int num = (s_size >= len) ? len : s_size ; + System.arraycopy(l_stack, l_stackp, buf, off, num); + off += num; + len -= num; + l_stackp += num; + + + // generate new entry in table + + if (l_free_ent < l_maxmaxcode) + { + l_tab_prefix[l_free_ent] = l_oldcode; + l_tab_suffix[l_free_ent] = l_finchar; + l_free_ent++; + } + + + // Remember previous code + + l_oldcode = incode; + + + // if output buffer full, then return + + if (len == 0) + { + n_bits = l_n_bits; + maxcode = l_maxcode; + bitmask = l_bitmask; + oldcode = l_oldcode; + finchar = l_finchar; + stackp = l_stackp; + free_ent = l_free_ent; + bit_pos = l_bit_pos; + + return off-start; + } + } + + l_bit_pos = resetbuf(l_bit_pos); + } while (got > 0); + + n_bits = l_n_bits; + maxcode = l_maxcode; + bitmask = l_bitmask; + oldcode = l_oldcode; + finchar = l_finchar; + stackp = l_stackp; + free_ent = l_free_ent; + bit_pos = l_bit_pos; + + eof = true; + return off-start; + } + + + /** + * Moves the unread data in the buffer to the beginning and resets + * the pointers. + */ + private final int resetbuf(int bit_pos) + { + int pos = bit_pos >> 3; + System.arraycopy(data, pos, data, 0, end-pos); + end -= pos; + return 0; + } + + + private final void fill() throws IOException + { + got = in.read(data, end, data.length-1-end); + if (got > 0) end += got; + } + + + @Override + public synchronized long skip(long num) throws IOException + { + byte[] tmp = new byte[(int) num]; + int got = read(tmp, 0, (int) num); + + if (got > 0) + return got; + else + return 0L; + } + + + @Override + public synchronized int available() throws IOException + { + if (eof) return 0; + + return in.available(); + } + + + private static final int LZW_MAGIC = 0x1f9d; + private static final int MAX_BITS = 16; + private static final int INIT_BITS = 9; + private static final int HDR_MAXBITS = 0x1f; + private static final int HDR_EXTENDED = 0x20; + private static final int HDR_FREE = 0x40; + private static final int HDR_BLOCK_MODE = 0x80; + + private void parse_header() throws IOException + { + // read in and check magic number + + int t = in.read(); + if (t < 0) throw new EOFException("Failed to read magic number"); + int magic = (t & 0xff) << 8; + t = in.read(); + if (t < 0) throw new EOFException("Failed to read magic number"); + magic += t & 0xff; + if (magic != LZW_MAGIC) + throw new IOException("Input not in compress format (read " + + "magic number 0x" + + Integer.toHexString(magic) + ")"); + + + // read in header byte + + int header = in.read(); + if (header < 0) throw new EOFException("Failed to read header"); + + block_mode = (header & HDR_BLOCK_MODE) > 0; + maxbits = header & HDR_MAXBITS; + + if (maxbits > MAX_BITS) + throw new IOException("Stream compressed with " + maxbits + + " bits, but can only handle " + MAX_BITS + + " bits"); + + if ((header & HDR_EXTENDED) > 0) + throw new IOException("Header extension bit set"); + + if ((header & HDR_FREE) > 0) + throw new IOException("Header bit 6 set"); + + if (debug) + { + System.err.println("block mode: " + block_mode); + System.err.println("max bits: " + maxbits); + } + + + // initialize stuff + + maxmaxcode = 1 << maxbits; + n_bits = INIT_BITS; + maxcode = (1 << n_bits) - 1; + bitmask = maxcode; + oldcode = -1; + finchar = 0; + free_ent = block_mode ? TBL_FIRST : 256; + + tab_prefix = new int[1 << maxbits]; + tab_suffix = new byte[1 << maxbits]; + stack = new byte[1 << maxbits]; + stackp = stack.length; + + for (int idx=255; idx>=0; idx--) + tab_suffix[idx] = (byte) idx; + } + + + private static final boolean debug = false; + + public static void main (String args[]) throws Exception + { + if (args.length != 1) + { + System.err.println("Usage: UncompressInputStream "); + System.exit(1); + } + + InputStream in = + new UncompressInputStream(new FileInputStream(args[0])); + + byte[] buf = new byte[100000]; + int tot = 0; + long beg = System.currentTimeMillis(); + + while (true) + { + int got = in.read(buf); + if (got < 0) break; + System.out.write(buf, 0, got); + tot += got; + } + + long end = System.currentTimeMillis(); + System.err.println("Decompressed " + tot + " bytes"); + System.err.println("Time: " + (end-beg)/1000. + " seconds"); + } +} diff --git a/src/main/java/cct/tools/UserPasswordDialog.java b/src/main/java/cct/tools/UserPasswordDialog.java new file mode 100644 index 0000000..08bd6c3 --- /dev/null +++ b/src/main/java/cct/tools/UserPasswordDialog.java @@ -0,0 +1,347 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.tools; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JPasswordField; +import javax.swing.JTextField; +import javax.swing.SwingConstants; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class UserPasswordDialog + extends JDialog { + + boolean OKpressed = false; + JPanel panel1 = new JPanel(); + JPanel buttonPanel = new JPanel(); + BorderLayout borderLayout2 = new BorderLayout(); + JButton cancelButton = new JButton(); + JButton okButton = new JButton(); + JLabel jLabel1 = new JLabel(); + JTextField userTextField = new JTextField(); + JPasswordField jPasswordField1 = new JPasswordField(); + JLabel jLabel2 = new JLabel(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + JLabel messageLabel = new JLabel(); + + public UserPasswordDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + jbInit(); + pack(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public UserPasswordDialog() { + this(new Frame(), "Enter your username and password", true); + } + + private void jbInit() throws Exception { + panel1.setLayout(gridBagLayout1); + this.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); + this.addKeyListener(new UserPasswordDialog_this_keyAdapter(this)); + this.getContentPane().setLayout(borderLayout2); + cancelButton.setToolTipText("Cancel dialog"); + cancelButton.setText("Cancel"); + cancelButton.addKeyListener(new UserPasswordDialog_cancelButton_keyAdapter(this)); + cancelButton.addActionListener(new UserPasswordDialog_cancelButton_actionAdapter(this)); + okButton.setMaximumSize(new Dimension(65, 23)); + okButton.setMinimumSize(new Dimension(65, 23)); + okButton.setPreferredSize(new Dimension(65, 23)); + okButton.setToolTipText("Confirm Username and Password"); + okButton.setText("OK"); + okButton.addKeyListener(new UserPasswordDialog_okButton_keyAdapter(this)); + okButton.addActionListener(new UserPasswordDialog_okButton_actionAdapter(this)); + jLabel1.setToolTipText(""); + jLabel1.setHorizontalAlignment(SwingConstants.RIGHT); + jLabel1.setHorizontalTextPosition(SwingConstants.RIGHT); + jLabel1.setText("Password:"); + jLabel2.setToolTipText(""); + jLabel2.setHorizontalAlignment(SwingConstants.RIGHT); + jLabel2.setHorizontalTextPosition(SwingConstants.RIGHT); + jLabel2.setText("User Name: "); + userTextField.setColumns(15); + userTextField.addActionListener(new UserPasswordDialog_jTextField1_actionAdapter(this)); + jPasswordField1.setColumns(15); + jPasswordField1.addKeyListener(new UserPasswordDialog_jPasswordField1_keyAdapter(this)); + jPasswordField1.addActionListener(new UserPasswordDialog_jPasswordField1_actionAdapter(this)); + messageLabel.setToolTipText(""); + messageLabel.setText("Enter username & password:"); + messageLabel.setVisible(false); + this.getContentPane().add(panel1, BorderLayout.CENTER); + this.getContentPane().add(buttonPanel, BorderLayout.SOUTH); + buttonPanel.add(okButton); + buttonPanel.add(cancelButton); + this.getContentPane().add(messageLabel, BorderLayout.NORTH); + panel1.add(jLabel2, + new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), + 0, 0)); + panel1.add(userTextField, + new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + panel1.add(jPasswordField1, + new GridBagConstraints(1, 1, 1, 1, 1.0, 1.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + panel1.add(jLabel1, + new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + } + + public void setUsername(String username) { + userTextField.setText(username); + } + + public void setUsernameEnabled(boolean enable) { + userTextField.setEnabled(enable); + } + + public void setMessage(String message) { + messageLabel.setText(message); + } + + public void setMessageVisible(boolean visible) { + messageLabel.setVisible(visible); + } + + public boolean isOKPressed() { + return OKpressed; + } + + public String getUsername() { + return userTextField.getText(); + } + + public char[] getPassword() { + //char[] pass = jPasswordField1.getPassword(); + //String password = String.copyValueOf(pass); + //return password; + return jPasswordField1.getPassword(); + } + + public void okButton_actionPerformed(ActionEvent e) { + OKpressed = true; + setVisible(false); + } + + public void cancelButton_actionPerformed(ActionEvent e) { + OKpressed = false; + setVisible(false); + } + + class UserPasswordDialog_okButton_actionAdapter + implements ActionListener { + + private UserPasswordDialog adaptee; + + UserPasswordDialog_okButton_actionAdapter(UserPasswordDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.okButton_actionPerformed(e); + } + } + + class UserPasswordDialog_cancelButton_actionAdapter + implements ActionListener { + + private UserPasswordDialog adaptee; + + UserPasswordDialog_cancelButton_actionAdapter(UserPasswordDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.cancelButton_actionPerformed(e); + } + } + + public void jTextField1_actionPerformed(ActionEvent e) { + jPasswordField1.grabFocus(); + } + + public void jPasswordField1_actionPerformed(ActionEvent e) { + okButton.grabFocus(); + } + + public void okButton_keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ENTER) { + OKpressed = true; + setVisible(false); + } + } + + public void cancelButton_keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ENTER) { + OKpressed = false; + setVisible(false); + } + } + + public void this_keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { + OKpressed = false; + setVisible(false); + } + } + + class UserPasswordDialog_jTextField1_actionAdapter + implements ActionListener { + + private UserPasswordDialog adaptee; + + UserPasswordDialog_jTextField1_actionAdapter(UserPasswordDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.jTextField1_actionPerformed(e); + } + } + + class UserPasswordDialog_jPasswordField1_actionAdapter + implements ActionListener { + + private UserPasswordDialog adaptee; + + UserPasswordDialog_jPasswordField1_actionAdapter(UserPasswordDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.jPasswordField1_actionPerformed(e); + } + } + + public void jPasswordField1_keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ENTER) { + OKpressed = true; + setVisible(false); + } + } +} + +class UserPasswordDialog_jPasswordField1_keyAdapter + extends KeyAdapter { + + private UserPasswordDialog adaptee; + + UserPasswordDialog_jPasswordField1_keyAdapter(UserPasswordDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void keyPressed(KeyEvent e) { + adaptee.jPasswordField1_keyPressed(e); + } +} + +class UserPasswordDialog_cancelButton_keyAdapter + extends KeyAdapter { + + private UserPasswordDialog adaptee; + + UserPasswordDialog_cancelButton_keyAdapter(UserPasswordDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void keyPressed(KeyEvent e) { + adaptee.cancelButton_keyPressed(e); + } +} + +class UserPasswordDialog_this_keyAdapter + extends KeyAdapter { + + private UserPasswordDialog adaptee; + + UserPasswordDialog_this_keyAdapter(UserPasswordDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void keyPressed(KeyEvent e) { + adaptee.this_keyPressed(e); + } +} + +class UserPasswordDialog_okButton_keyAdapter + extends KeyAdapter { + + private UserPasswordDialog adaptee; + + UserPasswordDialog_okButton_keyAdapter(UserPasswordDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void keyPressed(KeyEvent e) { + adaptee.okButton_keyPressed(e); + } +} diff --git a/src/main/java/cct/tools/Utils.java b/src/main/java/cct/tools/Utils.java new file mode 100644 index 0000000..1eae1fb --- /dev/null +++ b/src/main/java/cct/tools/Utils.java @@ -0,0 +1,532 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.tools; + +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringWriter; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.prefs.Preferences; + +import cct.j3d.QueryProperties; +import java.io.BufferedWriter; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; + +/** + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2006

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Utils { + + static final String DIVIDER = "@"; + static String CCT_DIRECTORY = ".cct"; + static private Utils utils = new Utils(); + + private Utils() { + } + + static public Properties getProperties(String propertiesFile) throws Exception { + + Properties props = null; + URL url = null; + try { + url = Utils.class.getClassLoader().getResource(propertiesFile); + props = new Properties(); + props.load(url.openStream()); + } catch (Exception ex) { + throw new Exception("Cannot open properties file " + propertiesFile + ": " + ex.getMessage()); + } + return props; + } + + public static List toSimpleList(Map complexList, List simpleList) { + + Set set = complexList.entrySet(); + Iterator iter = set.iterator(); + + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String dicName = me.getKey().toString(); + Object obj = me.getValue(); + + if (obj instanceof Map) { + simpleList = toSimpleList((Map) obj, simpleList); + } else { + simpleList.add(dicName); + } + } + return simpleList; + } + + public static Map toSimpleList(Map complexList, Map simpleList) { + + Set set = complexList.entrySet(); + Iterator iter = set.iterator(); + + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + String dicName = me.getKey().toString(); + Object obj = me.getValue(); + + if (obj instanceof Map) { + simpleList = toSimpleList((Map) obj, simpleList); + } else { + simpleList.put(dicName, obj); + } + } + return simpleList; + } + + /** + * Checks if the ~/CCT_DIRECTORY (~/.cct) directory exists. If not, it creates one. Returns absolute path of the + * directory + */ + public static String getCCTDirectory() throws Exception { + + File cctDir = new File(System.getProperty("user.home"), CCT_DIRECTORY); + if (cctDir.exists()) { + if (!cctDir.isDirectory()) { + /* + JOptionPane.showMessageDialog( + null, + ".globus is not a directory.\nA .globus directory is needed in your home directory by the Java CoG Kit.\nHowever this directory could not be created because a file with that name already exists.\nPlease either remove or rename the .globus file, then restart this wizard", + "Error", JOptionPane.ERROR_MESSAGE); + */ + throw new Exception(CCT_DIRECTORY + "is not a directory.\nA " + + CCT_DIRECTORY + + " directory is needed in your home directory by the Java CCT Kit.\n" + + "However this directory could not be created because a file with that name already exists.\n" + + "Please either remove or rename the " + + CCT_DIRECTORY + + " file, then restart this application"); + //return false; + } else { + return cctDir.getAbsolutePath() + "/"; + } + } else { + try { + cctDir.mkdir(); + } catch (Exception ex) { + throw new Exception("Failed to create " + CCT_DIRECTORY + " : " + + ex.getMessage()); + } + return cctDir.getAbsolutePath() + "/"; + } + } + + public static void printVector(T v[]) { + printVector(v, v.length); + } + + public static void printVector(T v[], int n) { + System.out.print("\n"); + + int N = 5; + int IFIRST = 0; + while (IFIRST < n) { + int ILAST = Math.min(IFIRST + N - 1, n - 1); + System.out.print("\n I "); + for (int i = IFIRST; i <= ILAST; i++) { + System.out.print(String.format(" %6d ", i + 1)); + } + System.out.print("\n V(I)"); + for (int i = IFIRST; i <= ILAST; i++) { + System.out.print(String.format(" %12f", v[i])); + } + IFIRST = ILAST + 1; + } + System.out.print("\n"); + } + + public static void printVector(double v[]) { + printVector(v, v.length); + } + + public static void printVector(double v[], int n) { + System.out.print("\n"); + + int N = 5; + int IFIRST = 0; + while (IFIRST < n) { + int ILAST = Math.min(IFIRST + N - 1, n - 1); + System.out.print("\n I "); + for (int i = IFIRST; i <= ILAST; i++) { + System.out.print(String.format(" %6d ", i + 1)); + } + System.out.print("\n V(I)"); + for (int i = IFIRST; i <= ILAST; i++) { + System.out.print(String.format(" %12f", v[i])); + } + IFIRST = ILAST + 1; + } + System.out.print("\n"); + } + + public static void printFloatVector(int n, float v[]) { + System.out.print("\n"); + + int N = 5; + int IFIRST = 0; + while (IFIRST < n) { + int ILAST = Math.min(IFIRST + N - 1, n - 1); + System.out.print("\n I "); + for (int i = IFIRST; i <= ILAST; i++) { + System.out.print(String.format(" %6d ", i + 1)); + } + System.out.print("\n V(I)"); + for (int i = IFIRST; i <= ILAST; i++) { + System.out.print(String.format(" %12f", v[i])); + } + IFIRST = ILAST + 1; + } + System.out.print("\n"); + } + + public static void printFloatVectors(int n, float v1[], float v2[]) { + System.out.print("\n"); + + int N = 5; + int IFIRST = 0; + while (IFIRST < n) { + int ILAST = Math.min(IFIRST + N - 1, n - 1); + System.out.print("\n I "); + for (int i = IFIRST; i <= ILAST; i++) { + System.out.print(String.format(" %6d ", i + 1)); + } + System.out.print("\n V1(I)"); + for (int i = IFIRST; i <= ILAST; i++) { + System.out.print(String.format(" %12f", v1[i])); + } + System.out.print("\n V2(I)"); + for (int i = IFIRST; i <= ILAST; i++) { + System.out.print(String.format(" %12f", v2[i])); + } + + IFIRST = ILAST + 1; + } + System.out.print("\n"); + } + + //static public void printMatrix(double[][] matrix) throws Exception { + // printMatrix(matrix, new BufferedWriter(new OutputStreamWriter(System.out))); + //} + static public void printMatrix(double[][] matrix, Writer out) throws Exception { + if (matrix == null) { + out.write("Matrix to be printed is not defined or of zero size\n"); + return; + } + for (int i = 0; i < matrix.length; i++) { + out.write(String.format("%3d", i + 1)); + for (int j = 0; j < matrix[i].length; j++) { + out.write(String.format(" %12.4f", matrix[i][j])); + } + out.write("\n"); + } + } + + static public void printMatrix(double[][] matrix) throws Exception { + if (matrix == null) { + System.out.println("Matrix to be printed is not defined or of zero size\n"); + return; + } + for (int i = 0; i < matrix.length; i++) { + System.out.print(String.format("%3d", i + 1)); + for (int j = 0; j < matrix[i].length; j++) { + System.out.print(String.format(" %12.4f", matrix[i][j])); + } + System.out.print("\n"); + } + } + + public static String getPreference(Object object, String Key) { + String value = null; + try { + Preferences prefs = Preferences.userNodeForPackage(object.getClass()); + value = prefs.get(Key, ""); + } catch (Exception ex) { + System.err.println("getPreference: cannot get preference " + Key + + " for " + object.getClass().getCanonicalName() + + " : " + ex.getMessage()); + } + if (value == null || value.length() < 1) { + return null; + } + return value; + } + + public static void savePreference(Object object, String Key, String value) { + try { + Preferences prefs = Preferences.userNodeForPackage(object.getClass()); + prefs.put(Key, value); + } catch (Exception ex) { + System.err.println("savePreference: cannot save preference " + Key + + " for " + object.getClass().getCanonicalName() + + " : " + ex.getMessage()); + } + + } + + public static String getResourceAsString(String resource) { + InputStream is = null; + try { + ClassLoader cl = Utils.class.getClassLoader(); + is = cl.getResourceAsStream(resource); + BufferedReader in = new BufferedReader(new InputStreamReader(is)); + StringBuffer sb = new StringBuffer(); + String line = null; + while ((line = in.readLine()) != null) { + sb.append(line + "\n"); + } + return sb.toString(); + } catch (Exception ex) { + System.err.println("Cannot get resource " + resource + " : " + ex.getMessage()); + return "Cannot get resource " + resource + " : " + ex.getMessage(); + } + } + + public static String getSystemInfoAsString() { + //Integer i = new Integer(0); + ClassLoader classLoader = utils.getClass().getClassLoader(); + + try { + Properties sysProp = System.getProperties(); + StringWriter sWriter = new StringWriter(); + for (Enumeration e = sysProp.propertyNames(); e.hasMoreElements();) { + String key = e.nextElement().toString(); + String value = sysProp.getProperty(key); + sWriter.write(key + " : " + value + "\n"); + } + + // --- java3d info + sWriter.write("\n\n ***** Java3d Properties *****\n\n"); + + sWriter.write(QueryProperties.getJava3dPropsAsString()); + + sWriter.write(packageInfoAsString(classLoader, "org.scijava.vecmath", "Point3d")); + sWriter.write(packageInfoAsString(classLoader, "org.scijava.java3d", "SceneGraphObject")); + sWriter.write(packageInfoAsString(classLoader, "org.scijava.java3d.utils.universe", "SimpleUniverse")); + + return sWriter.toString(); + } catch (SecurityException see) { + return "Error getting System Info: " + see.getMessage(); + } + } + + public static String packageInfoAsString(ClassLoader classLoader, String pkgName, + String className) { + StringWriter sWriter = new StringWriter(); + try { + classLoader.loadClass(pkgName + "." + className); + + Package p = Package.getPackage(pkgName); + if (p == null) { + sWriter.write("Package " + pkgName + " : no package information is available from the archive or codebase\n"); + } else { + sWriter.write("\n" + p.toString() + "\n"); + sWriter.write("Specification Title = " + p.getSpecificationTitle() + "\n"); + sWriter.write("Specification Vendor = " + p.getSpecificationVendor() + "\n"); + sWriter.write("Specification Version = " + p.getSpecificationVersion() + "\n"); + + sWriter.write("Implementation Vendor = " + p.getImplementationVendor() + "\n"); + sWriter.write("Implementation Version = " + p.getImplementationVersion() + "\n"); + } + } catch (ClassNotFoundException e) { + sWriter.write("Unable to load package " + pkgName + "\n"); + } + + return sWriter.toString(); + } + + public static Map reverseLinkedHashMap(Map toReverse) { + + if (toReverse == null) { + return null; + } + + Map reversed = new LinkedHashMap(toReverse.size()); + + Set set = toReverse.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + reversed.put(me.getValue(), me.getKey()); + } + return reversed; + } + + /** + * Converts time in seconds into time string in hours + * + * @param time_in_secs - time in seconds + * @return - Time string in hours in the form: HH:MM:SS + */ + public static String timeInHours(float time_in_secs) { + if (time_in_secs < 0) { + return "00:00:00"; + } + int hours = (int) (time_in_secs / 3600.0f); + float therest = time_in_secs - hours * 3600.0f; + int minutes = (int) (therest / 60.0f); + therest = therest - minutes * 60.0f; + int secs = (int) therest; + return String.format("%d:%02d:%02d", hours, minutes, secs); + } + + public static Object loadClass(String className) throws Exception { + Class builderClass = Class.forName(className); + // Get the ClassLoader object associated with this Class. + ClassLoader loader = builderClass.getClassLoader(); + + Class cl = loader.loadClass(className); + Object obj = cl.newInstance(); + return obj; + } + + /** + * Converts double into a byte array + * + * @param value - double number + * @return byte array + */ + public static byte[] toByteArray(double value) { + byte[] bytes = new byte[8]; + ByteBuffer.wrap(bytes).putDouble(value); + return bytes; + } + + /** + * Converts byte array into a double number + * + * @param bytes + * @return + */ + public static double toDouble(byte[] bytes) { + return ByteBuffer.wrap(bytes).getDouble(); + } + + /** + * Converts bytes array into a double array + * + * @param bytes + * @return + */ + public static double[] toDoubleArray(byte[] bytes) { + double[] doubles = new double[bytes.length / 8]; + ByteBuffer.wrap(bytes).asDoubleBuffer().get(doubles); + return doubles; + } + + /** + * Converts a double array into a byte array + * + * @param doubleArray + * @return + */ + public static byte[] toByteArray(double[] doubleArray) { + byte[] bytes = new byte[doubleArray.length * 8]; + ByteBuffer.wrap(bytes).asDoubleBuffer().put(doubleArray); + return bytes; + } + + /** + * Converts an array of string into a byte array while treating strings as a UTF8 ones + * + * @param strings - array of strings + * @return - byte array + */ + public static byte[] toByteArrayUTF8(String[] strings) { + int n = 0; + for (int i = 0; i < strings.length; i++) { + n += strings[i].length(); + } + + byte[] bytes = new byte[n]; + int index = 0; + for (int i = 0; i < strings.length; i++) { + byte[] b = strings[i].getBytes(StandardCharsets.UTF_8); + for (int j = 0; j < b.length; j++) { + bytes[index] = b[j]; + ++index; + } + } + + return bytes; + } + + public static byte[] toByteArrayUTF16(String[] strings) { + int n = 0; + for (int i = 0; i < strings.length; i++) { + n += strings[i].length(); + } + + byte[] bytes = new byte[2 * n]; + int index = 0; + for (int i = 0; i < strings.length; i++) { + byte[] b = strings[i].getBytes(StandardCharsets.UTF_8); + for (int j = 0; j < b.length; j++) { + bytes[index] = b[j]; + ++index; + } + } + + return bytes; + } +} diff --git a/src/main/java/cct/tools/XMolXYZ.java b/src/main/java/cct/tools/XMolXYZ.java new file mode 100644 index 0000000..699db71 --- /dev/null +++ b/src/main/java/cct/tools/XMolXYZ.java @@ -0,0 +1,317 @@ +package cct.tools; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.StringWriter; +import java.io.Writer; +import java.util.StringTokenizer; + +import cct.Constants; +import cct.interfaces.AtomInterface; +import cct.interfaces.CoordinateBuilderInterface; +import cct.interfaces.CoordinateParserInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.ChemicalElements; +import java.io.File; + +/** + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author not attributable + * @version 1.0 + */ +public class XMolXYZ + implements CoordinateBuilderInterface, CoordinateParserInterface { + + private boolean atomicSymbols = true; + private boolean printComment = true; + private boolean printNumberOfAtoms = true; + + public XMolXYZ() { + } + + public void saveXMolXYZ(Writer writer, MoleculeInterface mol, boolean atomicSymbols, boolean inAngstroms) throws + Exception { + if (mol == null || mol.getNumberOfAtoms() < 1) { + throw new Exception("No atoms in molecule"); + } + float factor = 1.0f; + if (!inAngstroms) { + factor = (float) (1.0 / Constants.ONE_BOHR); + } + + BufferedWriter out; + try { + out = new BufferedWriter(writer); + } catch (Exception ex) { + throw new Exception("Cannot write :" + ex.getMessage()); + } + + try { + if (printNumberOfAtoms) { + out.write(mol.getNumberOfAtoms() + "\n"); + } + + if (printComment) { + out.write("Generated by Jamberoo, units: "); + if (inAngstroms) { + out.write("Angstroms\n"); + } else { + out.write("Bohrs\n"); + } + } + + for (int i = 0; i < mol.getNumberOfAtoms(); i++) { + AtomInterface atom = mol.getAtomInterface(i); + if (atomicSymbols) { + out.write(String.format("%3s ", ChemicalElements.getElementSymbol(atom.getAtomicNumber()))); + } else { + out.write(String.format("%3d ", atom.getAtomicNumber())); + } + out.write(String.format("%12.6f %12.6f %12.6f\n", atom.getX() * factor, atom.getY() * factor, atom.getZ() * factor)); + } + + out.close(); + } catch (Exception ex) { + throw new Exception("Cannot write : " + ex.getMessage()); + } + + } + + public void saveXMolXYZ(String filename, MoleculeInterface mol, boolean atomicSymbols, boolean inAngstroms) throws + Exception { + try { + saveXMolXYZ(new FileWriter(filename), mol, atomicSymbols, inAngstroms); + } catch (Exception ex) { + throw new Exception("Error saving into file " + filename + " : " + ex.getMessage()); + } + + } + + public MoleculeInterface parseXMolXYZ(File file, MoleculeInterface mol) throws Exception { + return parseXMolXYZ(file.getAbsolutePath(), mol); + } + + /** + * Parses XMol XYZ files 1) The first line contains the number of atoms in the molecule. 2) The second line contains + * the name or title of the molecule. It can be blank if desired. 3) The rest of the file is composed of one line for + * each atom in the molecule. Each atom is designated by the atomic number and then the x, y, and z coordinate value. + * Separate each value by at least 1 space; there is no strict format for these lines. + * + * @param filename String + * @param mol MoleculeInterface + * @return MoleculeInterface + * @throws Exception + */ + public MoleculeInterface parseXMolXYZ(String filename, MoleculeInterface mol) throws + Exception { + String line; + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(filename)); + + // --- Reading number of atoms + if ((line = in.readLine()) == null) { + in.close(); + throw new Exception( + "parseXMolXYZ: ERROR: Unxpected End of file while reading number of atoms"); + } + + int natoms = 0; + try { + natoms = Integer.parseInt(line.trim()); + } catch (Exception e) { + in.close(); + throw new Exception( + "parseXMolXYZ: ERROR: Error while parsing number of atoms: " + + e.getMessage()); + } + + // --- Reading molecule name + if ((line = in.readLine()) == null) { + in.close(); + throw new Exception( + "parseXMolXYZ: ERROR: Unxpected End of file while reading fragment name"); + } + mol.setName(line); + + // --- Reading atoms + for (int i = 0; i < natoms; i++) { + + AtomInterface atom = mol.getNewAtomInstance(); + + if ((line = in.readLine()) == null) { + in.close(); + throw new Exception("parseXMolXYZ: ERROR: Unxpected End of file while atom " + (i + 1)); + } + StringTokenizer st = new StringTokenizer(line, " \t", false); + if (st.countTokens() < 4) { + in.close(); + throw new Exception( + "parseXMolXYZ: ERROR: Error while parsing atom: " + (i + 1) + " Number of tokens < 4: " + line); + } + + // --- Getting element + String token = st.nextToken(); + int element = ChemicalElements.getAtomicNumber(token); + atom.setAtomicNumber(element); + atom.setName(token); + + // --- Getting x,y,z + float xyz; + try { + xyz = Float.parseFloat(st.nextToken()); + atom.setX(xyz); + xyz = Float.parseFloat(st.nextToken()); + atom.setY(xyz); + xyz = Float.parseFloat(st.nextToken()); + atom.setZ(xyz); + } catch (Exception ex) { + in.close(); + throw new Exception( + "parseXMolXYZ: ERROR: Error while parsing atom: " + (i + 1) + " Cannot parse atom's coordinate(s): " + line); + } + + mol.addAtom(atom); + } + + in.close(); + } catch (Exception ex) { + if (in != null) { + in.close(); + } + throw new Exception("parseXMolXYZ: ERROR: " + ex.getMessage()); + } + + return mol; + } + + @Override + public void getCoordinates(MoleculeInterface mol, boolean inAngstroms, Writer writer) throws Exception { + boolean store_1 = printComment; + boolean store_2 = printNumberOfAtoms; + printComment = false; + printNumberOfAtoms = false; + + saveXMolXYZ(writer, mol, atomicSymbols, inAngstroms); + + printComment = store_1; + printNumberOfAtoms = store_2; + } + + @Override + public String getCoordinatesAsString(MoleculeInterface molec, boolean inAngstroms) throws Exception { + boolean store_1 = printComment; + boolean store_2 = printNumberOfAtoms; + printComment = false; + printNumberOfAtoms = false; + + StringWriter sw = new StringWriter(); + saveXMolXYZ(sw, molec, atomicSymbols, inAngstroms); + + printComment = store_1; + printNumberOfAtoms = store_2; + + return sw.toString(); + } + + @Override + public void parseCoordinates(BufferedReader in, MoleculeInterface molecule) throws Exception { + try { + molecule.addMonomer("XMol"); + // --- Reading atoms + String line; + while ((line = in.readLine()) != null) { + + line = line.trim(); + if (line.length() < 1) { + continue; // Empty line + } + + AtomInterface atom = molecule.getNewAtomInstance(); + + StringTokenizer st = new StringTokenizer(line, " \t", false); + if (st.countTokens() < 4) { + throw new Exception("parseXMolXYZ: Expected at least 4 tokens, got: " + line); + } + + // --- Getting element + String token = st.nextToken(); + int element = ChemicalElements.getAtomicNumber(token); + atom.setAtomicNumber(element); + atom.setName(token); + + // --- Getting x,y,z + float xyz; + try { + xyz = Float.parseFloat(st.nextToken()); + atom.setX(xyz); + xyz = Float.parseFloat(st.nextToken()); + atom.setY(xyz); + xyz = Float.parseFloat(st.nextToken()); + atom.setZ(xyz); + } catch (Exception ex) { + throw new Exception("parseXMolXYZ: Error while parsing atom's coordinate: " + line); + } + + molecule.addAtom(atom); + } + + } catch (Exception ex) { + throw ex; + } + + } + + @Override + public double evaluateCompliance(BufferedReader in) throws Exception { + double score = 0; + try { + String line; + while ((line = in.readLine()) != null) { + + line = line.trim(); + if (line.length() < 1) { + continue; // Empty line + } + + score = 1; + StringTokenizer st = new StringTokenizer(line, " \t", false); + if (st.countTokens() < 4) { + return 0; + } else if (st.countTokens() > 4) { + score -= 0.25; + } + + // --- Getting element + st.nextToken(); + + // --- Getting x,y,z + try { + Float.parseFloat(st.nextToken()); + Float.parseFloat(st.nextToken()); + Float.parseFloat(st.nextToken()); + } catch (Exception ex) { + return 0; + } + return score; + } + + } catch (Exception ex) { + throw ex; + } + return score; + } +} diff --git a/src/main/java/cct/tools/filebrowser/ConfirmFileOverwriteDialog.java b/src/main/java/cct/tools/filebrowser/ConfirmFileOverwriteDialog.java new file mode 100644 index 0000000..8a5b634 --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/ConfirmFileOverwriteDialog.java @@ -0,0 +1,296 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.SwingConstants; + +/** + * + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class ConfirmFileOverwriteDialog + extends JDialog implements ActionListener { + + public final static int YES = 0; + public final static int YES_TO_ALL = 1; + public final static int NO = 2; + public final static int NO_TO_ALL = 3; + public final static int CANCEL = 4; + + int buttonPressed = CANCEL; + + JPanel panel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JLabel topLabel = new JLabel(); + JPanel buttonsPanel = new JPanel(); + JButton cancelButton = new JButton(); + JButton notoallButton = new JButton(); + JButton noButton = new JButton(); + JButton yestoallButton = new JButton(); + JButton yesButton = new JButton(); + JPanel jPanel1 = new JPanel(); + JPanel jPanel2 = new JPanel(); + JLabel jLabel2 = new JLabel(); + JLabel jLabel3 = new JLabel(); + JLabel existingSize = new JLabel(); + JLabel existingModification = new JLabel(); + JLabel jLabel4 = new JLabel(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + JPanel jPanel3 = new JPanel(); + JLabel jLabel1 = new JLabel(); + JLabel jLabel5 = new JLabel(); + JLabel jLabel6 = new JLabel(); + GridBagLayout gridBagLayout2 = new GridBagLayout(); + GridBagLayout gridBagLayout3 = new GridBagLayout(); + JPanel jPanel4 = new JPanel(); + JLabel fileNameLabel = new JLabel(); + JLabel jLabel8 = new JLabel(); + JLabel folderLabel = new JLabel(); + FlowLayout flowLayout1 = new FlowLayout(); + JLabel candidateSize = new JLabel(); + JLabel candidateModification = new JLabel(); + public ConfirmFileOverwriteDialog(Frame owner, String title) { + super(owner, title, true); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public ConfirmFileOverwriteDialog() { + this(new Frame(), "Confirm File Overwrite"); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + this.setDefaultCloseOperation(javax.swing.WindowConstants. + DO_NOTHING_ON_CLOSE); + topLabel.setToolTipText(""); + topLabel.setText("Folder "); + cancelButton.setMinimumSize(new Dimension(73, 23)); + cancelButton.setPreferredSize(new Dimension(73, 23)); + cancelButton.setToolTipText(""); + cancelButton.setText("Cancel"); + notoallButton.setToolTipText(""); + notoallButton.setText("No to All"); + noButton.setMinimumSize(new Dimension(73, 23)); + noButton.setPreferredSize(new Dimension(73, 23)); + noButton.setToolTipText(""); + noButton.setText("No"); + yestoallButton.setMinimumSize(new Dimension(79, 23)); + yestoallButton.setPreferredSize(new Dimension(79, 23)); + yestoallButton.setToolTipText(""); + yestoallButton.setText("Yes to All"); + yesButton.setMinimumSize(new Dimension(73, 23)); + yesButton.setPreferredSize(new Dimension(73, 23)); + yesButton.setToolTipText(""); + yesButton.setText("Yes"); + jLabel2.setToolTipText(""); + jLabel2.setText(" Modified: "); + jPanel1.setLayout(gridBagLayout2); + jPanel2.setLayout(gridBagLayout1); + jLabel3.setToolTipText(""); + jLabel3.setText(" Size: "); + jLabel4.setToolTipText(""); + jLabel4.setHorizontalAlignment(SwingConstants.LEFT); + jLabel4.setHorizontalTextPosition(SwingConstants.LEFT); + jLabel4.setText("Would you like to replace existing file"); + jLabel1.setToolTipText(""); + jLabel1.setHorizontalAlignment(SwingConstants.LEFT); + jLabel1.setHorizontalTextPosition(SwingConstants.LEFT); + jLabel1.setText("with this one?"); + jLabel5.setToolTipText(""); + jLabel5.setText(" Size: "); + jLabel6.setToolTipText(""); + jLabel6.setText(" Modified: "); + jPanel3.setLayout(gridBagLayout3); + fileNameLabel.setToolTipText(""); + fileNameLabel.setText("FILE-NAME"); + jLabel8.setToolTipText(""); + jLabel8.setText("already contains file named "); + folderLabel.setToolTipText(""); + folderLabel.setText("FOLDER-NAME"); + jPanel4.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + candidateSize.setToolTipText(""); + candidateSize.setText("FILE-SIZE"); + candidateModification.setToolTipText(""); + candidateModification.setHorizontalAlignment(SwingConstants.LEFT); + candidateModification.setHorizontalTextPosition(SwingConstants.LEFT); + candidateModification.setText("MODIFICATION-DATE"); + existingSize.setToolTipText(""); + existingSize.setText("FILE-SIZE"); + existingModification.setToolTipText(""); + existingModification.setText("MODIFICATION-DATE"); + getContentPane().add(panel1); + buttonsPanel.add(yesButton); + buttonsPanel.add(yestoallButton); + buttonsPanel.add(noButton); + buttonsPanel.add(notoallButton); + buttonsPanel.add(cancelButton); + panel1.add(jPanel4, BorderLayout.NORTH); + jPanel4.add(topLabel); + jPanel4.add(folderLabel); + jPanel4.add(jLabel8); + jPanel4.add(fileNameLabel); + panel1.add(jPanel1, BorderLayout.CENTER); + panel1.add(buttonsPanel, BorderLayout.SOUTH); + jPanel2.add(jLabel3, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + jPanel2.add(existingSize, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + + jPanel2.add(jLabel2, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + jPanel2.add(existingModification, + new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(jPanel3, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0 + , + GridBagConstraints.NORTHWEST, + GridBagConstraints.HORIZONTAL, + new Insets(0, 0, 0, 0), 0, 0)); + jPanel1.add(jPanel2, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.BOTH, + new Insets(0, 0, 0, 0), 270, + 0)); + jPanel3.add(jLabel5, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + jPanel3.add(jLabel6, new GridBagConstraints(0, 2, 1, 1, 0.0, 1.0 + , + GridBagConstraints.NORTHWEST, + GridBagConstraints.BOTH, + new Insets(5, 5, 5, 5), 0, 0)); + jPanel3.add(jLabel1, new GridBagConstraints(0, 0, 2, 1, 1.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(1, 5, 5, 5), 0, 0)); + jPanel3.add(candidateSize, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(0, 0, 0, 0), 0, 0)); + jPanel3.add(candidateModification, + new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(0, 0, 0, 0), 0, 0)); + jPanel2.add(jLabel4, new GridBagConstraints(0, 0, 2, 1, 1.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + + yesButton.addActionListener(this); + yestoallButton.addActionListener(this); + noButton.addActionListener(this); + notoallButton.addActionListener(this); + cancelButton.addActionListener(this); + + } + + public int showDialog(String folder, String fileName, String targetSize, + String targetMod, String originSize, String originMod) { + folderLabel.setText(folder); + fileNameLabel.setText(fileName); + existingSize.setText(targetSize); + existingModification.setText(targetMod); + candidateSize.setText(originSize); + candidateModification.setText(originMod); + setVisible(true); + return buttonPressed; + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == yesButton) { + buttonPressed = YES; + } + else if (e.getSource() == yestoallButton) { + buttonPressed = YES_TO_ALL; + } + else if (e.getSource() == noButton) { + buttonPressed = NO; + } + else if (e.getSource() == notoallButton) { + buttonPressed = NO_TO_ALL; + } + else { + buttonPressed = CANCEL; + } + setVisible(false); + } + +} diff --git a/src/main/java/cct/tools/filebrowser/ConnectHostDialog.java b/src/main/java/cct/tools/filebrowser/ConnectHostDialog.java new file mode 100644 index 0000000..e23a353 --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/ConnectHostDialog.java @@ -0,0 +1,295 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.awt.BorderLayout; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JPasswordField; +import javax.swing.JTextField; +import javax.swing.SwingConstants; + +/** + * + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * This dialog is used by other classes for the SSH connection + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class ConnectHostDialog + extends JDialog implements ActionListener { + + public static final int CONNECT = 0; + public static final int CANCEL = 1; + int keyPressed = CONNECT; + int portNumber = 22; + + JPanel buttonPanel = new JPanel(); + JButton helpButton = new JButton(); + JButton cancelButton = new JButton(); + JButton connectButton = new JButton(); + JPanel jPanel2 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JLabel jLabel1 = new JLabel(); + JTextField portTextField = new JTextField(); + JLabel jLabel2 = new JLabel(); + JLabel jLabel3 = new JLabel(); + JLabel hostLabel = new JLabel(); + JPasswordField passwordTextField = new JPasswordField(); + JTextField userTextField = new JTextField(); + JTextField hostTextField = new JTextField(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + + public ConnectHostDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public ConnectHostDialog() { + this(new Frame(), "Connect to Host", true); + } + + private void jbInit() throws Exception { + this.setDefaultCloseOperation(javax.swing.WindowConstants. + DO_NOTHING_ON_CLOSE); + this.getContentPane().setLayout(borderLayout1); + helpButton.setEnabled(false); + helpButton.setText("Help"); + cancelButton.setToolTipText(""); + cancelButton.setText("Cancel"); + connectButton.setToolTipText(""); + connectButton.setText("Connect"); + jLabel1.setToolTipText(""); + jLabel1.setHorizontalAlignment(SwingConstants.RIGHT); + jLabel1.setText("Port: "); + jLabel1.setVerticalAlignment(SwingConstants.TOP); + jLabel2.setToolTipText(""); + jLabel2.setHorizontalAlignment(SwingConstants.RIGHT); + jLabel2.setText("Password: "); + jLabel3.setToolTipText(""); + jLabel3.setText("Username: "); + hostLabel.setToolTipText(""); + hostLabel.setText("Host address: "); + jPanel2.setLayout(gridBagLayout1); + hostTextField.setToolTipText(""); + hostTextField.addActionListener(new ConnectHostDialog_hostTextField_actionAdapter(this)); + userTextField.setToolTipText("Enter your username here"); + userTextField.addActionListener(new ConnectHostDialog_userTextField_actionAdapter(this)); + portTextField.setColumns(6); + passwordTextField.setToolTipText("Enter your password here"); + passwordTextField.addActionListener(new ConnectHostDialog_passwordTextField_actionAdapter(this)); + buttonPanel.add(connectButton); + buttonPanel.add(cancelButton); + buttonPanel.add(helpButton); + this.getContentPane().add(jPanel2, BorderLayout.CENTER); + this.getContentPane().add(buttonPanel, BorderLayout.SOUTH); + jPanel2.add(portTextField, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + jPanel2.add(hostTextField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + jPanel2.add(userTextField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + jPanel2.add(passwordTextField, + new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + jPanel2.add(jLabel1, new GridBagConstraints(0, 3, 1, 1, 0.0, 1.0 + , + GridBagConstraints.NORTHEAST, + GridBagConstraints.VERTICAL, + new Insets(5, 5, 5, 5), 0, 0)); + jPanel2.add(jLabel2, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + jPanel2.add(jLabel3, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + jPanel2.add(hostLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + + connectButton.addActionListener(this); + cancelButton.addActionListener(this); + } + + public int showDialog() { + hostTextField.setText(""); + userTextField.setText(""); + portTextField.setText(String.valueOf(portNumber)); + passwordTextField.setText(""); + + hostTextField.grabFocus(); + setVisible(true); + return keyPressed; + } + + public int getKeyPressed() { + return keyPressed; + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == cancelButton) { + keyPressed = CANCEL; + setVisible(false); + return; + } + + try { + portNumber = Integer.parseInt(portTextField.getText().trim()); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Wrong port number: " + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + if (portNumber < 1) { + JOptionPane.showMessageDialog(this, + "Port number should be a positive number!", + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + keyPressed = CONNECT; + setVisible(false); + } + + public String getHost() { + return hostTextField.getText().trim(); + } + + public String getUsername() { + return userTextField.getText(); + } + + public char[] getPassword() { + return passwordTextField.getPassword(); + } + + public int getPort() { + return this.portNumber; + } + + public void hostTextField_actionPerformed(ActionEvent e) { + if (hostTextField.getText().trim().length() > 0) { + this.userTextField.grabFocus(); + } + } + + public void userTextField_actionPerformed(ActionEvent e) { + if (userTextField.getText().trim().length() > 0) { + this.passwordTextField.grabFocus(); + } + } + + public void passwordTextField_actionPerformed(ActionEvent e) { + this.connectButton.doClick(); + } + + private class ConnectHostDialog_passwordTextField_actionAdapter + implements ActionListener { + private ConnectHostDialog adaptee; + ConnectHostDialog_passwordTextField_actionAdapter(ConnectHostDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.passwordTextField_actionPerformed(e); + } + } + + private class ConnectHostDialog_userTextField_actionAdapter + implements ActionListener { + private ConnectHostDialog adaptee; + ConnectHostDialog_userTextField_actionAdapter(ConnectHostDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.userTextField_actionPerformed(e); + } + } + + private class ConnectHostDialog_hostTextField_actionAdapter + implements ActionListener { + private ConnectHostDialog adaptee; + ConnectHostDialog_hostTextField_actionAdapter(ConnectHostDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.hostTextField_actionPerformed(e); + } + } +} diff --git a/src/main/java/cct/tools/filebrowser/EditHostsDialog.java b/src/main/java/cct/tools/filebrowser/EditHostsDialog.java new file mode 100644 index 0000000..7f3c010 --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/EditHostsDialog.java @@ -0,0 +1,165 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.awt.BorderLayout; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class EditHostsDialog + extends JDialog { + + boolean okPressed = false; + + JPanel panel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JScrollPane jScrollPane1 = new JScrollPane(); + JPanel jPanel1 = new JPanel(); + JList hostsList = new JList(); + JButton cancelButton = new JButton(); + JButton removeButton = new JButton(); + + public EditHostsDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public void setListData(String[] hosts) { + hostsList.removeAll(); + hostsList.setListData(hosts); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + cancelButton.setToolTipText(""); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new EditHostsDialog_cancelButton_actionAdapter(this)); + removeButton.setToolTipText(""); + removeButton.setText("Remove Selected"); + removeButton.addActionListener(new EditHostsDialog_removeButton_actionAdapter(this)); + this.setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); + getContentPane().add(panel1); + panel1.add(jScrollPane1, BorderLayout.CENTER); + jScrollPane1.getViewport().add(hostsList); + panel1.add(jPanel1, BorderLayout.SOUTH); + jPanel1.add(removeButton); + jPanel1.add(cancelButton); + + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent we) { + okPressed = false; + we.getWindow().setVisible(false); + } + }); + + } + + public void removeButton_actionPerformed(ActionEvent e) { + okPressed = true; + setVisible(false); + } + + public int[] getSelectedIndices() { + return hostsList.getSelectedIndices(); + } + + public boolean isOKPressed() { + return okPressed; + } + + public void cancelButton_actionPerformed(ActionEvent e) { + okPressed = false; + setVisible(false); + } + + private class EditHostsDialog_cancelButton_actionAdapter + implements ActionListener { + private EditHostsDialog adaptee; + EditHostsDialog_cancelButton_actionAdapter(EditHostsDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.cancelButton_actionPerformed(e); + } + } + + private class EditHostsDialog_removeButton_actionAdapter + implements ActionListener { + private EditHostsDialog adaptee; + EditHostsDialog_removeButton_actionAdapter(EditHostsDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.removeButton_actionPerformed(e); + } + } + +} diff --git a/src/main/java/cct/tools/filebrowser/FTPManager.java b/src/main/java/cct/tools/filebrowser/FTPManager.java new file mode 100644 index 0000000..6f08bad --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/FTPManager.java @@ -0,0 +1,96 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import cct.interfaces.FTPManagerInterface; +import cct.interfaces.FileBrowserInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class FTPManager + implements FTPManagerInterface { + + static final String SFTP_Protocol = "sftp"; + static final String GridFTP_Protocol = "gridftp"; + + static String[] FTP_Protocols = { + SFTP_Protocol}; + final static FileBrowserInterface[] ftpBrowsers = new FileBrowserInterface[1]; + static { + ftpBrowsers[0] = new SFTPBrowser(); + } + + public FTPManager() { + } + + public static void main(String[] args) { + FTPManager ftpmanager = new FTPManager(); + } + + @Override + public String[] getAvailableFTPProtocols() { + String[] protocols = new String[FTP_Protocols.length]; + for (int i = 0; i < FTP_Protocols.length; i++) { + protocols[i] = FTP_Protocols[i]; + } + return protocols; + } + + @Override + public FileBrowserInterface getFTPBrowser(String protocol) { + for (int i = 0; i < FTP_Protocols.length; i++) { + if (FTP_Protocols[i].equalsIgnoreCase(protocol)) { + if (protocol.equalsIgnoreCase(SFTP_Protocol)) { + return new SFTPBrowser(); + } + } + } + return null; + } + +} diff --git a/src/main/java/cct/tools/filebrowser/FileBrowserPanel.java b/src/main/java/cct/tools/filebrowser/FileBrowserPanel.java new file mode 100644 index 0000000..afa3c9c --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/FileBrowserPanel.java @@ -0,0 +1,448 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.SwingConstants; + +import cct.interfaces.FileBrowserGUIInterface; +import cct.interfaces.FileBrowserInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class FileBrowserPanel + extends JPanel implements FileBrowserGUIInterface { + + FileBrowserInterface fileBrowser = null; + boolean browserIsBusy = false; + Object[] titles = { + "Name", "Size", "Modified", "Attributes"}; + Object[][] data = { + { + "", "", "", ""} + }; + JTable table = new JTable(data, titles); + + BorderLayout borderLayout1 = new BorderLayout(); + JScrollPane fileScrollPane = new JScrollPane(); + JPanel controlsPanel = new JPanel(); + JButton upButton = new JButton(); + JComboBox jComboBox1 = new JComboBox(); + JButton refreshButton = new JButton(); + Component currentComponent = null; + + ImageIcon up = new ImageIcon(cct.resources.Resources.class. + getResource("cct/images/icons16x16/up.png")); + ImageIcon refresh = new ImageIcon(cct.resources.Resources.class. + getResource( + "cct/images/icons16x16/refresh-2.png")); + ImageIcon createFolder = new ImageIcon(cct.resources.Resources.class. + getResource( + "cct/images/icons16x16/addEntry.png")); + ImageIcon delete = new ImageIcon(cct.resources.Resources.class. + getResource("cct/images/icons16x16/delete2.png")); + ImageIcon help = new ImageIcon(cct.resources.Resources.class. + getResource("cct/images/icons16x16/help.png")); + ImageIcon arrowUp = new ImageIcon(cct.resources.Resources.class. + getResource( + "cct/images/icons16x16/blue-arrow-up.png")); + ImageIcon arrowDown = new ImageIcon(cct.resources.Resources.class. + getResource( + "cct/images/icons16x16/blue-arrow-down.png")); + + FlowLayout flowLayout1 = new FlowLayout(); + JButton mkdirButton = new JButton(); + JButton deleteButton = new JButton(); + JButton helpButton = new JButton(); + JButton downloadButton = new JButton(); + JButton uploadButton = new JButton(); + public FileBrowserPanel() { + this(null); + } + + public FileBrowserPanel(FileBrowserInterface file_browser) { + fileBrowser = file_browser; + setFileBrowser(file_browser); + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + upButton.setMaximumSize(new Dimension(23, 23)); + upButton.setMinimumSize(new Dimension(23, 23)); + upButton.setPreferredSize(new Dimension(23, 23)); + upButton.setToolTipText("Up a Directory"); + upButton.setHorizontalTextPosition(SwingConstants.CENTER); + upButton.setIcon(up); + upButton.addActionListener(new FileBrowserPanel_upButton_actionAdapter(this)); + refreshButton.setMaximumSize(new Dimension(23, 23)); + refreshButton.setMinimumSize(new Dimension(23, 23)); + refreshButton.setPreferredSize(new Dimension(23, 23)); + refreshButton.setToolTipText("Refresh Folder"); + refreshButton.setHorizontalTextPosition(SwingConstants.CENTER); + refreshButton.setIcon(refresh); + refreshButton.addActionListener(new + FileBrowserPanel_refreshButton_actionAdapter(this)); + controlsPanel.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + mkdirButton.setMaximumSize(new Dimension(23, 23)); + mkdirButton.setMinimumSize(new Dimension(23, 23)); + mkdirButton.setPreferredSize(new Dimension(23, 23)); + mkdirButton.setToolTipText("New Folder"); + mkdirButton.setHorizontalTextPosition(SwingConstants.CENTER); + mkdirButton.setIcon(createFolder); + mkdirButton.addActionListener(new + FileBrowserPanel_mkdirButton_actionAdapter(this)); + deleteButton.setMaximumSize(new Dimension(23, 23)); + deleteButton.setMinimumSize(new Dimension(23, 23)); + deleteButton.setPreferredSize(new Dimension(23, 23)); + deleteButton.setToolTipText("Delete Selected"); + deleteButton.setHorizontalTextPosition(SwingConstants.CENTER); + deleteButton.setIcon(delete); + deleteButton.addActionListener(new + FileBrowserPanel_deleteButton_actionAdapter(this)); + helpButton.setEnabled(false); + helpButton.setMaximumSize(new Dimension(23, 23)); + helpButton.setMinimumSize(new Dimension(23, 23)); + helpButton.setPreferredSize(new Dimension(23, 23)); + helpButton.setToolTipText("Help"); + helpButton.setHorizontalTextPosition(SwingConstants.CENTER); + helpButton.setIcon(help); + jComboBox1.setToolTipText( + "Select visited folders or type and press Enter for a new one"); + jComboBox1.setEditable(true); + jComboBox1.addActionListener(new + FileBrowserPanel_jComboBox1_actionAdapter(this)); + downloadButton.setMaximumSize(new Dimension(23, 23)); + downloadButton.setMinimumSize(new Dimension(23, 23)); + downloadButton.setPreferredSize(new Dimension(23, 23)); + downloadButton.setToolTipText("Download Selected File(s)/Folder(s)"); + downloadButton.setHorizontalTextPosition(SwingConstants.CENTER); + downloadButton.setIcon(arrowDown); + downloadButton.addActionListener(new + FileBrowserPanel_downloadButton_actionAdapter(this)); + uploadButton.setMaximumSize(new Dimension(23, 23)); + uploadButton.setMinimumSize(new Dimension(23, 23)); + uploadButton.setPreferredSize(new Dimension(23, 23)); + uploadButton.setToolTipText("Open Upload Dialog"); + uploadButton.setHorizontalTextPosition(SwingConstants.CENTER); + uploadButton.setIcon(arrowUp); + this.add(fileScrollPane, BorderLayout.CENTER); + controlsPanel.add(jComboBox1); + controlsPanel.add(upButton); + controlsPanel.add(refreshButton); + controlsPanel.add(deleteButton); + controlsPanel.add(mkdirButton); + controlsPanel.add(downloadButton); + controlsPanel.add(uploadButton); + controlsPanel.add(helpButton); + this.add(controlsPanel, BorderLayout.NORTH); + if (fileBrowser != null) { + fileScrollPane.add(fileBrowser.getComponent()); + } + else { + + fileScrollPane.getViewport().add(table); + } + } + + public String[] getSelectedFiles() { + return fileBrowser.getSelectedFiles(); + } + + public String[] getSelectedFolders() { + return fileBrowser.getSelectedFiles(); + } + + public String getPWD() { + return fileBrowser.pwd(); + } + + public void setFileBrowser(FileBrowserInterface file_browser) { + fileBrowser = file_browser; + if (fileBrowser != null) { + if (currentComponent != null) { + fileScrollPane.getViewport().remove(currentComponent); + } + fileBrowser.setTopGUI(this); + Component comp = fileBrowser.getComponent(); + fileScrollPane.getViewport().add(comp); + fileScrollPane.setForeground(comp.getForeground()); + } + } + + public void switchFileBrowser(FileBrowserInterface file_browser) { + fileBrowser = file_browser; + if (fileBrowser != null) { + //fileBrowser.setTopGUI(this); + if (currentComponent != null) { + fileScrollPane.getViewport().remove(currentComponent); + } + fileScrollPane.getViewport().add(fileBrowser.getComponent()); + } + } + + /** + * Client informs whether it busy or not. If it's busy all controls are inactive + * @param busy boolean - "true" if busy, "false" otherwise + */ + @Override + public void setBusy(boolean busy) { + if (busy) { + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + upButton.setEnabled(false); + jComboBox1.setEnabled(false); + refreshButton.setEnabled(false); + mkdirButton.setEnabled(false); + deleteButton.setEnabled(false); + //helpButton = new JButton(); + downloadButton.setEnabled(false); + uploadButton.setEnabled(false); + } + else { + setCursor(Cursor.getDefaultCursor()); + upButton.setEnabled(true); + jComboBox1.setEnabled(true); + refreshButton.setEnabled(true); + mkdirButton.setEnabled(true); + deleteButton.setEnabled(true); + //helpButton = new JButton(); + downloadButton.setEnabled(true); + uploadButton.setEnabled(true); + + } + } + + @Override + public void updateCWD(String cwd) { + jComboBox1.setEnabled(false); + jComboBox1.addItem(cwd); + jComboBox1.setSelectedIndex(jComboBox1.getItemCount() - 1); + jComboBox1.setEnabled(true); + } + + @Override + public void updateFieView(Component fileView) { + fileScrollPane.getViewport().add(fileView); + } + + public void refreshButton_actionPerformed(ActionEvent e) { + if (!refreshButton.isEnabled()) { + return; + } + refreshButton.setEnabled(false); + if ( fileBrowser != null ) fileBrowser.refresh(); + refreshButton.setEnabled(true); + } + + public void upButton_actionPerformed(ActionEvent e) { + if (!upButton.isEnabled()) { + return; + } + upButton.setEnabled(false); + fileBrowser.upDirectory(); + upButton.setEnabled(true); + } + + public void mkdirButton_actionPerformed(ActionEvent e) { + if (!mkdirButton.isEnabled()) { + return; + } + mkdirButton.setEnabled(false); + if ( fileBrowser != null ) fileBrowser.mkdir(); + mkdirButton.setEnabled(true); + } + + public void jComboBox1_itemStateChanged(ItemEvent e) { + if (!jComboBox1.isEnabled()) { + return; + } + jComboBox1.setEnabled(false); + fileBrowser.cd(jComboBox1.getSelectedItem().toString()); + jComboBox1.setEnabled(true); + + } + + public void jComboBox1_actionPerformed(ActionEvent e) { + if (!jComboBox1.isEnabled()) { + return; + } + jComboBox1.setEnabled(false); + if ( fileBrowser != null ) fileBrowser.cd(jComboBox1.getSelectedItem().toString()); + jComboBox1.setEnabled(true); + } + + public void deleteButton_actionPerformed(ActionEvent e) { + if (!deleteButton.isEnabled()) { + return; + } + deleteButton.setEnabled(false); + if ( fileBrowser != null ) fileBrowser.removeSelectedPaths(); + deleteButton.setEnabled(true); + } + + public void downloadButton_actionPerformed(ActionEvent e) { + if (!downloadButton.isEnabled()) { + return; + } + downloadButton.setEnabled(false); + if ( fileBrowser != null ) fileBrowser.downloadSelected(); + downloadButton.setEnabled(true); + } +} + +class FileBrowserPanel_downloadButton_actionAdapter + implements ActionListener { + private FileBrowserPanel adaptee; + FileBrowserPanel_downloadButton_actionAdapter(FileBrowserPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.downloadButton_actionPerformed(e); + } +} + +class FileBrowserPanel_deleteButton_actionAdapter + implements ActionListener { + private FileBrowserPanel adaptee; + FileBrowserPanel_deleteButton_actionAdapter(FileBrowserPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.deleteButton_actionPerformed(e); + } +} + +class FileBrowserPanel_jComboBox1_actionAdapter + implements ActionListener { + private FileBrowserPanel adaptee; + FileBrowserPanel_jComboBox1_actionAdapter(FileBrowserPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.jComboBox1_actionPerformed(e); + } +} + +class FileBrowserPanel_jComboBox1_itemAdapter + implements ItemListener { + private FileBrowserPanel adaptee; + FileBrowserPanel_jComboBox1_itemAdapter(FileBrowserPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void itemStateChanged(ItemEvent e) { + adaptee.jComboBox1_itemStateChanged(e); + } +} + +class FileBrowserPanel_mkdirButton_actionAdapter + implements ActionListener { + private FileBrowserPanel adaptee; + FileBrowserPanel_mkdirButton_actionAdapter(FileBrowserPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.mkdirButton_actionPerformed(e); + } +} + +class FileBrowserPanel_upButton_actionAdapter + implements ActionListener { + private FileBrowserPanel adaptee; + FileBrowserPanel_upButton_actionAdapter(FileBrowserPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.upButton_actionPerformed(e); + } +} + +class FileBrowserPanel_refreshButton_actionAdapter + implements ActionListener { + private FileBrowserPanel adaptee; + FileBrowserPanel_refreshButton_actionAdapter(FileBrowserPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.refreshButton_actionPerformed(e); + } +} diff --git a/src/main/java/cct/tools/filebrowser/FileBrowserTableModel.java b/src/main/java/cct/tools/filebrowser/FileBrowserTableModel.java new file mode 100644 index 0000000..9524bdd --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/FileBrowserTableModel.java @@ -0,0 +1,174 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.util.List; +import java.util.logging.Logger; + +import javax.swing.table.AbstractTableModel; + +/** + *

Title: Molecular Structure Viewer/Editor

+ * + *

Description: Computational Chemistry Toolkit

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class FileBrowserTableModel + extends AbstractTableModel { + String[] columnNames = null; + boolean DEBUG = true; + Object[][] data = null; + static final Logger logger = Logger.getLogger(FileBrowserTableModel.class.getCanonicalName()); + + public FileBrowserTableModel(Object[][] new_data) { + data = new_data; + } + + public FileBrowserTableModel(String[] column_names, Object[][] new_data) { + columnNames = column_names; + data = new_data; + } + + public FileBrowserTableModel(List statuses) { + if (statuses.size() < 1) { + data = null; + return; + } + columnNames = new String[] { + "Handle", "Status", "Selection"}; + data = new Object[statuses.size()][]; + for (int i = 0; i < statuses.size(); i++) { + List job = (List) statuses.get(i); + data[i] = new Object[3]; + data[i][0] = job.get(0); // Job Handle + data[i][1] = job.get(1); // Job Status as a String + data[i][2] = new Boolean(false); + } + } + + @Override + public int getColumnCount() { + return columnNames.length; + } + + @Override + public int getRowCount() { + if (data == null) { + return 0; + } + return data.length; + } + + @Override + public String getColumnName(int col) { + return columnNames[col]; + } + + @Override + public Object getValueAt(int row, int col) { + return data[row][col]; + } + + /* + * JTable uses this method to determine the default renderer/ + * editor for each cell. If we didn't implement this method, + * then the last column would contain text ("true"/"false"), + * rather than a check box. + */ + @Override + public Class getColumnClass(int c) { + return getValueAt(0, c).getClass(); + } + + /* + * Don't need to implement this method unless your table's + * editable. + */ + @Override + public boolean isCellEditable(int row, int col) { + //Note that the data/cell address is constant, + //no matter where the cell appears onscreen. + + //if (col < 2) { + return false; + //} + //else { + // return true; + //} + } + + /* + * Don't need to implement this method unless your table's + * data can change. + */ + @Override + public void setValueAt(Object value, int row, int col) { + if (DEBUG) { + logger.info("Setting value at " + row + "," + col + " to " + value + " (an instance of " + value.getClass() + ")"); + } + + data[row][col] = value; + fireTableCellUpdated(row, col); + + if (DEBUG) { + logger.info("New value of data:"); + printDebugData(); + } + } + + private void printDebugData() { + int numRows = getRowCount(); + int numCols = getColumnCount(); + + for (int i = 0; i < numRows; i++) { + System.out.print(" row " + i + ":"); + for (int j = 0; j < numCols; j++) { + System.out.print(" " + data[i][j]); + } + System.out.print("\n"); + } + logger.info("--------------------------"); + } + +} diff --git a/src/main/java/cct/tools/filebrowser/FileChooserDialog.java b/src/main/java/cct/tools/filebrowser/FileChooserDialog.java new file mode 100644 index 0000000..749b937 --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/FileChooserDialog.java @@ -0,0 +1,191 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +import cct.interfaces.FileBrowserInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class FileChooserDialog + extends JDialog implements ActionListener { + + final public static int CONFIRM = 0; + final public static int CANCEL = 1; + int keyPressed = CANCEL; + + JPanel panel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + FileBrowserPanel jFileBrowserPanel1 = null; + JButton cancelButton = new JButton(); + JPanel jPanel1 = new JPanel(); + JButton confirmButton = new JButton(); + + public FileChooserDialog(Frame owner, String title, boolean modal, + FileBrowserInterface fileBrowser) { + super(owner, title, modal); + try { + jFileBrowserPanel1 = new FileBrowserPanel(fileBrowser); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private FileChooserDialog() { + super(new Frame(), "Choose File", true); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + + //this(new Frame(), "FileChooserDialog", false); + } + + public String pwd() { + return jFileBrowserPanel1.getPWD(); + } + + public String[] getSelectedFiles() { + return jFileBrowserPanel1.getSelectedFiles(); + } + + public String[] getSelectedFolders() { + return jFileBrowserPanel1.getSelectedFolders(); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == confirmButton) { + keyPressed = CONFIRM; + } + else { + keyPressed = CANCEL; + } + setVisible(false); + } + + public int getPressedKey() { + return keyPressed; + } + + private void jbInit() throws Exception { + + panel1.setLayout(borderLayout1); + cancelButton.setToolTipText(""); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(this); + confirmButton.setToolTipText(""); + confirmButton.setText("Confirm Selection"); + confirmButton.addActionListener(this); + jFileBrowserPanel1.setPreferredSize(new Dimension(452, 100)); + jFileBrowserPanel1.setToolTipText(""); + panel1.setPreferredSize(new Dimension(452, 450)); + panel1.setToolTipText(""); + jPanel1.add(confirmButton); + jPanel1.add(cancelButton); + panel1.add(jFileBrowserPanel1, BorderLayout.CENTER); + panel1.add(jPanel1, BorderLayout.SOUTH); + this.getContentPane().add(panel1, BorderLayout.CENTER); + this.getContentPane().add(panel1, BorderLayout.CENTER); + + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent we) { + keyPressed = CANCEL; + setVisible(false); + } + }); + + } + + public void setFileBrowser(FileBrowserInterface fileBrowser) { + jFileBrowserPanel1.setFileBrowser(fileBrowser); + } + + public static void main(String[] args) { + + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } + catch (Exception exception) { + exception.printStackTrace(); + } + + LocalFileBrowser lfb = new LocalFileBrowser(); + FileChooserDialog dialog = new FileChooserDialog(new Frame(), + "Select file", true, lfb); + dialog.setVisible(true); + } + }); + } + +} diff --git a/src/main/java/cct/tools/filebrowser/FileName.java b/src/main/java/cct/tools/filebrowser/FileName.java new file mode 100644 index 0000000..a8361ba --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/FileName.java @@ -0,0 +1,103 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class FileName + implements Comparable { + + public final static int FILE = 1; + public final static int FOLDER = 0; + + String fileName; + int fileType = FILE; + + public FileName(String name) { + fileName = name; + } + + public FileName(String name, int type) throws Exception { + fileName = name; + if (type != FILE && type != FOLDER) { + throw new Exception("Unknown file type"); + } + fileType = type; + } + + public int getFileType() { + return fileType; + } + + public String getFileName() { + return fileName; + } + + public boolean isDirectory() { + return fileType == FOLDER; + } + + public boolean isFile() { + return fileType == FILE; + } + + @Override + public int compareTo(Object val) { + if (val instanceof String) { + return fileName.compareTo( (String) val); + } + + FileName name = (FileName) val; + if (fileType != name.getFileType()) { + return fileType - name.getFileType(); + } + + return fileName.compareTo(name.getFileName()); + } + +} diff --git a/src/main/java/cct/tools/filebrowser/FileNameRenderer.java b/src/main/java/cct/tools/filebrowser/FileNameRenderer.java new file mode 100644 index 0000000..cf98e8f --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/FileNameRenderer.java @@ -0,0 +1,146 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.awt.Color; +import java.awt.Component; + +import javax.swing.ImageIcon; +import javax.swing.JLabel; +import javax.swing.JTable; +import javax.swing.table.TableCellRenderer; + +import cct.tools.FileUtilities; + +import com.sshtools.j2ssh.sftp.SftpFile; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ + +class FileNameRenderer + extends JLabel implements TableCellRenderer { + + final static ImageIcon folder = new ImageIcon(cct.resources.Resources.class. + getResource( + "cct/images/icons16x16/folder.png")); + + final static ImageIcon document = new ImageIcon(cct.resources.Resources.class. + getResource( + "cct/images/icons16x16/document.png")); + + final static ImageIcon gaussianImage = new ImageIcon(cct.resources.Resources.class. + getResource( + "cct/images/icons16x16/gaussian-16x16.png")); + + final static ImageIcon triposImage = new ImageIcon(cct.resources.Resources.class. + getResource("cct/images/icons16x16/tripos-transp-16x16.png")); + + static ImageIcon mdlImage = new ImageIcon(cct.resources.Resources.class. + getResource( + "cct/images/icons16x16/MDL-16x16.png")); + + public FileNameRenderer(boolean isBordered) { + + //this.isBordered = isBordered; + + setOpaque(true); //MUST do this for background to show up. + + } + + @Override + public Component getTableCellRendererComponent( + JTable table, Object filename, + boolean isSelected, boolean hasFocus, + int row, int column) { + + if (isSelected) { + //selectedBorder is a solid border in the color + Color bg = table.getSelectionBackground(); + this.setBackground(bg); + //setBorder(selectedBorder); + } + else { + //unselectedBorder is a solid border in the color + Color bg = table.getBackground(); + this.setBackground(bg); + //setBorder(unselectedBorder); + } + + String fileName; + + if (filename instanceof SftpFile) { + SftpFile file = (SftpFile) filename; + this.setText(file.getFilename()); + if (file.isDirectory()) { + setIcon(folder); + return this; + } + fileName = file.getFilename(); + } + else if (filename instanceof FileName) { + fileName = ( (FileName) filename).getFileName(); + setText(fileName); + if ( ( (FileName) filename).isDirectory()) { + setIcon(folder); + return this; + } + } + else { + fileName = filename.toString(); + this.setText(fileName); + } + + setIcon(FileUtilities.getIcon16x16(fileName)); + + //setToolTipText(...); //Discussed in the following section + + return this; + + } + +} diff --git a/src/main/java/cct/tools/filebrowser/FilePropertiesDialog.java b/src/main/java/cct/tools/filebrowser/FilePropertiesDialog.java new file mode 100644 index 0000000..47a606f --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/FilePropertiesDialog.java @@ -0,0 +1,161 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class FilePropertiesDialog + extends JDialog implements ActionListener { + + final static int SET = 0; + final static int CANCEL = 1; + int keyPressed = CANCEL; + + JPanel panel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + FilePropertiesPanel fileProperties = new FilePropertiesPanel(); + JPanel buttonPanel = new JPanel(); + JButton jButton1 = new JButton(); + JButton jButton2 = new JButton(); + JButton setButton = new JButton(); + public FilePropertiesDialog(Frame owner, String title) { + super(owner, title, true); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public FilePropertiesDialog() { + this(new Frame(), "File Properties Dialog"); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + this.setDefaultCloseOperation(javax.swing.WindowConstants. + DO_NOTHING_ON_CLOSE); + jButton1.setEnabled(false); + jButton1.setToolTipText(""); + jButton1.setText("Help"); + jButton2.setToolTipText(""); + jButton2.setText("Cancel"); + setButton.setToolTipText(""); + setButton.setText("Set"); + getContentPane().add(panel1); + panel1.add(fileProperties, BorderLayout.CENTER); + panel1.add(buttonPanel, BorderLayout.SOUTH); + buttonPanel.add(setButton); + buttonPanel.add(jButton2); + buttonPanel.add(jButton1); + + jButton2.addActionListener(this); + setButton.addActionListener(this); + } + + public int showDialog() { + setVisible(true); + return keyPressed; + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == setButton) { + keyPressed = SET; + } + else { + keyPressed = CANCEL; + } + setVisible(false); + } + + public void setFileName(String name) { + fileProperties.fileNameLabel.setText(name); + } + + public void setFileType(String type) { + fileProperties.fileTypeLabel.setText(type); + } + + public void setFileSize(String size) { + fileProperties.fileSizeLabel.setText(size); + } + + public void setFileModified(String modified) { + fileProperties.fileModifiedLabel.setText(modified); + } + + public void setFileLocation(String location) { + fileProperties.fileLocationLabel.setText(location); + } + + public void setPermissions(int perm) { + fileProperties.permissionsPanel1.setupControls(perm); + } + + public void setPermissions(String permissions) { + fileProperties.permissionsPanel1.setupControls(permissions); + } + + public int getPermissions() { + return fileProperties.permissionsPanel1.getPermissions(); + } + + public void setFileIcon(ImageIcon icon) { + fileProperties.emptyLabel.setIcon(icon); + } + +} diff --git a/src/main/java/cct/tools/filebrowser/FilePropertiesPanel.java b/src/main/java/cct/tools/filebrowser/FilePropertiesPanel.java new file mode 100644 index 0000000..7fe0cea --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/FilePropertiesPanel.java @@ -0,0 +1,155 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import javax.swing.*; +import javax.swing.border.TitledBorder; +import java.awt.*; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class FilePropertiesPanel + extends JPanel { + + static ImageIcon emptyImage = new ImageIcon(cct.resources.Resources.class. + getResource( + "/cct/images/icons32x32/emptyTransparent.png")); + + BorderLayout borderLayout1 = new BorderLayout(); + JPanel topPanel = new JPanel(); + JPanel centralPanel = new JPanel(); + JLabel emptyLabel = new JLabel(); + public JLabel fileNameLabel = new JLabel(); + JPanel permissionPanel = new JPanel(); + JPanel infoPanel = new JPanel(); + BorderLayout borderLayout2 = new BorderLayout(); + public JLabel fileModifiedLabel = new JLabel(); + JLabel modifiedLabel = new JLabel(); + public JLabel fileSizeLabel = new JLabel(); + JLabel sizeLabel = new JLabel(); + public JLabel fileLocationLabel = new JLabel(); + JLabel locationLabel = new JLabel(); + public JLabel fileTypeLabel = new JLabel(); + JLabel typeLabel = new JLabel(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + FlowLayout flowLayout1 = new FlowLayout(); + PermissionsPanel permissionsPanel1 = new PermissionsPanel(); + + public FilePropertiesPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + emptyLabel.setToolTipText(""); + emptyLabel.setIcon(emptyImage); + emptyLabel.setText(" "); + fileNameLabel.setToolTipText(""); + fileNameLabel.setText("File Name"); + centralPanel.setLayout(borderLayout2); + fileModifiedLabel.setToolTipText(""); + fileModifiedLabel.setText("File Modified date is here"); + modifiedLabel.setToolTipText(""); + modifiedLabel.setText("Modified Date: "); + fileSizeLabel.setToolTipText(""); + fileSizeLabel.setText("File size is here"); + sizeLabel.setToolTipText(""); + sizeLabel.setText("Size:"); + fileLocationLabel.setToolTipText(""); + fileLocationLabel.setText("File Location is here"); + locationLabel.setToolTipText(""); + locationLabel.setText("Location:"); + fileTypeLabel.setToolTipText(""); + fileTypeLabel.setText("File type is here"); + typeLabel.setToolTipText(""); + typeLabel.setText("Type:"); + infoPanel.setLayout(gridBagLayout1); + topPanel.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + permissionPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder( + Color.GRAY, 1), "Permissions")); + this.add(centralPanel, BorderLayout.CENTER); + topPanel.add(emptyLabel); + topPanel.add(fileNameLabel); + infoPanel.add(typeLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + infoPanel.add(fileTypeLabel, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + infoPanel.add(locationLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + infoPanel.add(fileLocationLabel, + new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + infoPanel.add(sizeLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + infoPanel.add(fileSizeLabel, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + infoPanel.add(modifiedLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + infoPanel.add(fileModifiedLabel, + new GridBagConstraints(1, 3, 1, 1, 1.0, 1.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(topPanel, BorderLayout.NORTH); + centralPanel.add(permissionPanel, BorderLayout.CENTER); + permissionPanel.add(permissionsPanel1); + centralPanel.add(infoPanel, BorderLayout.NORTH); + } +} diff --git a/src/main/java/cct/tools/filebrowser/FileSize.java b/src/main/java/cct/tools/filebrowser/FileSize.java new file mode 100644 index 0000000..ca7bffb --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/FileSize.java @@ -0,0 +1,241 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.io.Serializable; +import java.math.BigInteger; + +/** + *

Title:

+ * + *

Description:

+ * Handles file size as unsigned integer 64 + * it's a redesign of a UnsignedInteger64 class from the sshtools + * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class FileSize + extends Number implements Serializable, + Comparable { + + public final static BigInteger MAX_VALUE = new BigInteger( + "18446744073709551615"); + + /** */ + public final static BigInteger MIN_VALUE = new BigInteger("0"); + private BigInteger bigInt; + + /** + * Creates a new FileSize object. + * + * @param sval + * + * @throws NumberFormatException + */ + public FileSize(String sval) throws NumberFormatException { + bigInt = new BigInteger(sval); + + if ( (bigInt.compareTo(MIN_VALUE) < 0) || + (bigInt.compareTo(MAX_VALUE) > 0)) { + throw new NumberFormatException(); + } + } + + /** + * Creates a new FileSize object. + * + * @param bval + * + * @throws NumberFormatException + */ + public FileSize(byte[] bval) throws NumberFormatException { + bigInt = new BigInteger(bval); + + if ( (bigInt.compareTo(MIN_VALUE) < 0) || + (bigInt.compareTo(MAX_VALUE) > 0)) { + throw new NumberFormatException(); + } + } + + /** + * Creates a new FileSize object. + * + * @param input + * + * @throws NumberFormatException + */ + public FileSize(BigInteger input) { + bigInt = new BigInteger(input.toString()); + + if ( (bigInt.compareTo(MIN_VALUE) < 0) || + (bigInt.compareTo(MAX_VALUE) > 0)) { + throw new NumberFormatException(); + } + } + + /** + * + * + * @param o + * + * @return + */ + @Override + public boolean equals(Object o) { + try { + FileSize u = (FileSize) o; + + return u.bigInt.equals(this.bigInt); + } + catch (ClassCastException ce) { + // This was not an UnsignedInt64, so equals should fail. + return false; + } + } + + /** + * + * + * @return + */ + public BigInteger bigIntValue() { + return bigInt; + } + + /** + * + * + * @return + */ + @Override + public int intValue() { + return bigInt.intValue(); + } + + /** + * + * + * @return + */ + @Override + public long longValue() { + return bigInt.longValue(); + } + + /** + * + * + * @return + */ + @Override + public double doubleValue() { + return bigInt.doubleValue(); + } + + /** + * + * + * @return + */ + @Override + public float floatValue() { + return bigInt.floatValue(); + } + + /** + * + * + * @param val + * + * @return + */ + @Override + public int compareTo(Object val) { + return bigInt.compareTo( ( (FileSize) val).bigInt); + } + + /** + * + * + * @return + */ + @Override + public String toString() { + return bigInt.toString(); + } + + /** + * + * + * @return + */ + @Override + public int hashCode() { + return bigInt.hashCode(); + } + + /** + * + * + * @param x + * @param y + * + * @return + */ + public static FileSize add(FileSize x, FileSize y) { + return new FileSize(x.bigInt.add(y.bigInt)); + } + + /** + * + * + * @param x + * @param y + * + * @return + */ + public static FileSize add(FileSize x, int y) { + return new FileSize(x.bigInt.add(BigInteger.valueOf(y))); + } + +} diff --git a/src/main/java/cct/tools/filebrowser/FileSizeRenderer.java b/src/main/java/cct/tools/filebrowser/FileSizeRenderer.java new file mode 100644 index 0000000..ee79b36 --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/FileSizeRenderer.java @@ -0,0 +1,103 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.awt.Color; +import java.awt.Component; +import java.text.NumberFormat; + +import javax.swing.JLabel; +import javax.swing.JTable; +import javax.swing.table.TableCellRenderer; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ + +class FileSizeRenderer + extends JLabel implements TableCellRenderer { + + static NumberFormat nf = NumberFormat.getInstance(); + + public FileSizeRenderer() { + + //this.isBordered = isBordered; + + setOpaque(true); //MUST do this for background to show up. + + } + + @Override + public Component getTableCellRendererComponent( + JTable table, Object number, + boolean isSelected, boolean hasFocus, + int row, int column) { + + FileSize size = (FileSize) number; + + this.setText(nf.format(size.doubleValue())); + + if (isSelected) { + //selectedBorder is a solid border in the color + Color bg = table.getSelectionBackground(); + this.setBackground(bg); + //setBorder(selectedBorder); + } + else { + //unselectedBorder is a solid border in the color + Color bg = table.getBackground(); + this.setBackground(bg); + //setBorder(unselectedBorder); + } + + //setToolTipText(...); //Discussed in the following section + + return this; + + } + +} diff --git a/src/main/java/cct/tools/filebrowser/FileTransferFrame.java b/src/main/java/cct/tools/filebrowser/FileTransferFrame.java new file mode 100644 index 0000000..b7adc6a --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/FileTransferFrame.java @@ -0,0 +1,393 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Logger; + +import javax.swing.ComboBoxEditor; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JOptionPane; +import javax.swing.JTextField; +import javax.swing.JToolBar; +import javax.swing.ListCellRenderer; + +import cct.interfaces.FTPManagerInterface; +import cct.interfaces.FileBrowserInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class FileTransferFrame + extends JFrame { + Map browsers = new HashMap(); + FTPManagerInterface ftpManager = null; + ConnectHostDialog connectDialog = new ConnectHostDialog(this, + "Connect to Host", true); + BorderLayout borderLayout1 = new BorderLayout(); + FileTransferPanel fileTransferPanel1 = new FileTransferPanel(); + + ImageIcon connect = new ImageIcon(cct.resources.Resources.class. + getResource( + "cct/images/icons16x16/client_network.png")); + + ImageIcon disconnect = new ImageIcon(cct.resources.Resources.class. + getResource( + "cct/images/icons16x16/delete2.png")); + + ImageIcon serverOK = new ImageIcon(cct.resources.Resources.class. + getResource("cct/images/icons16x16/server.png")); + ImageIcon serverDead = new ImageIcon(cct.resources.Resources.class. + getResource( + "cct/images/icons16x16/server_error.png")); + + JToolBar jToolBar1 = new JToolBar(); + JComboBox hostsComboBox = new JComboBox(); + JButton disconnectButton = new JButton(); + JButton connectButton = new JButton(); + JComboBox protocolComboBox = new JComboBox(); + JLabel jLabel1 = new JLabel(); + JLabel jLabel2 = new JLabel(); + static final Logger logger = Logger.getLogger(FileTransferFrame.class.getCanonicalName()); + + public FileTransferFrame(FTPManagerInterface ftp_manager) { + ftpManager = ftp_manager; + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + getContentPane().setLayout(borderLayout1); + disconnectButton.setMaximumSize(new Dimension(23, 23)); + disconnectButton.setMinimumSize(new Dimension(23, 23)); + disconnectButton.setPreferredSize(new Dimension(23, 23)); + disconnectButton.setToolTipText("Disconnect"); + disconnectButton.setIcon(disconnect); + jLabel1.setToolTipText(""); + jLabel1.setText(" Host:"); + protocolComboBox.setMaximumSize(new Dimension(64, 49)); + jLabel2.setToolTipText(""); + jLabel2.setText("Protocol:"); + hostsComboBox.addActionListener(new + FileTransferFrame_hostsComboBox_actionAdapter(this)); + this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + hostsComboBox.setEditable(false); + connectButton.addActionListener(new + FileTransferFrame_connectButton_actionAdapter(this)); + jToolBar1.add(jLabel2); + jToolBar1.add(protocolComboBox); + jToolBar1.add(jLabel1); + + jToolBar1.add(hostsComboBox); + jToolBar1.add(connectButton); + jToolBar1.add(disconnectButton); + this.getContentPane().add(jToolBar1, BorderLayout.NORTH); + this.getContentPane().add(fileTransferPanel1, BorderLayout.CENTER); + + connectButton.setMinimumSize(new Dimension(23, 23)); + connectButton.setMaximumSize(new Dimension(23, 23)); + connectButton.setPreferredSize(new Dimension(23, 23)); + connectButton.setIcon(connect); + connectButton.setToolTipText("Connect"); + + String[] protocols = ftpManager.getAvailableFTPProtocols(); + for (int i = 0; i < protocols.length; i++) { + protocolComboBox.addItem(protocols[i]); + } + + HostComboBoxRenderer renderer = new HostComboBoxRenderer(); + hostsComboBox.setRenderer(renderer); + } + + public static void main(String[] args) { + //FileBrowserInterface fileBrowser = new LocalFileBrowser(); + Runtime rt = Runtime.getRuntime(); + logger.info("Processors: " + rt.availableProcessors() + + " Memory: " + rt.freeMemory()); + FTPManagerInterface manager = new FTPManager(); + FileTransferFrame filetransferframe = new FileTransferFrame(manager); + filetransferframe.setSize(640, 480); + filetransferframe.setVisible(true); + //System.exit(0); + } + + public void hostsComboBox_actionPerformed(ActionEvent e) { + if (!hostsComboBox.isEnabled()) { + return; + } + + hostsComboBox.setEnabled(false); + Object item = hostsComboBox.getSelectedItem(); + + String host = item.toString(); + + FileBrowserInterface browser = (FileBrowserInterface) browsers.get(host); + + fileTransferPanel1.switchFileBrowser(browser); + fileTransferPanel1.repaint(); + + hostsComboBox.setEnabled(true); + } + + public void connectButton_actionPerformed(ActionEvent e) { + if (!connectButton.isEnabled()) { + return; + } + connectButton.setEnabled(false); + + String protocol = protocolComboBox.getSelectedItem().toString(); + + String host = "Unknown host"; + + String username = ""; + char[] password = "".toCharArray(); + int port = 22; + + if (protocol.equalsIgnoreCase("sftp")) { + connectDialog.setAlwaysOnTop(true); + connectDialog.setLocationRelativeTo(this); + int n = connectDialog.showDialog(); + if (n == ConnectHostDialog.CANCEL) { + return; + } + host = connectDialog.getHost().toLowerCase(); + username = connectDialog.getUsername(); + password = connectDialog.getPassword(); + port = connectDialog.getPort(); + } + + FileBrowserInterface browser = null; + + if (browsers.containsKey(host)) { + + } + + else { + browser = ftpManager.getFTPBrowser(protocol); + + try { + if (protocol.equalsIgnoreCase("sftp")) { + this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + browser.connect(host, username, password, port); + + } + browsers.put(host, browser); + + hostsComboBox.setEnabled(false); + hostsComboBox.addItem(host); + hostsComboBox.setSelectedIndex(hostsComboBox.getItemCount() - 1); + hostsComboBox.setEnabled(true); + + fileTransferPanel1.setFileBrowser(browser); + fileTransferPanel1.repaint(); + pack(); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + } + } + this.setCursor(Cursor.getDefaultCursor()); + connectButton.setEnabled(true); + + } + + class HostComboBoxRenderer + extends JLabel implements ListCellRenderer { + + public HostComboBoxRenderer() { + setOpaque(true); + setHorizontalAlignment(LEFT); + setVerticalAlignment(CENTER); + } + + /* + * This method finds the image and text corresponding + * to the selected value and returns the label, set up + * to display the text and image. + */ + + @Override + public Component getListCellRendererComponent( + JList list, + Object value, + int index, + boolean isSelected, + boolean cellHasFocus) { + + //Get the selected index. (The index param isn't + //always valid, so just use the value.) + + if (value == null) { + return this; + } + + //int selectedIndex = ( (Integer) value).intValue(); + + if (isSelected) { + setBackground(list.getSelectionBackground()); + setForeground(list.getSelectionForeground()); + } + else { + setBackground(list.getBackground()); + setForeground(list.getForeground()); + } + + //Set the icon and text. If icon was null, say so. + + String host = value.toString(); + //logger.info("Value: " + value.toString() + " Class: " + + // value.getClass().getCanonicalName()); + setText(host); + + if (!browsers.containsKey(host)) { + logger.info(host + " is not found in browsers: " + + browsers.toString()); + } + FileBrowserInterface browser = (FileBrowserInterface) browsers.get( + host); + + if (browser == null) { + logger.info("Internal error: Server - null; browser: " + + browsers.toString()); + setIcon(serverDead); + } + else if (browser.isAuthenticated()) { + //logger.info("Server - OK"); + setIcon(serverOK); + } + else { + //logger.info("Server - dead"); + setIcon(serverDead); + } + + return this; + } + } + + class HostEditor + extends JTextField implements ComboBoxEditor, ActionListener { + + @Override + public Component getEditorComponent() { + return null; + } + + @Override + public Object getItem() { + return this.getText(); + } + + @Override + public void removeActionListener(ActionListener l) { + this.removeActionListener(l); + } + + @Override + public void selectAll() { + this.selectAll(); + } + + @Override + public void addActionListener(ActionListener l) { + this.addActionListener(l); + } + + @Override + public void setItem(Object anObject) { + this.setText(anObject.toString()); + } + + @Override + public void actionPerformed(ActionEvent e) { + + } + } +} + +class FileTransferFrame_connectButton_actionAdapter + implements ActionListener { + private FileTransferFrame adaptee; + FileTransferFrame_connectButton_actionAdapter(FileTransferFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.connectButton_actionPerformed(e); + } +} + +class FileTransferFrame_hostsComboBox_actionAdapter + implements ActionListener { + private FileTransferFrame adaptee; + FileTransferFrame_hostsComboBox_actionAdapter(FileTransferFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.hostsComboBox_actionPerformed(e); + } +} diff --git a/src/main/java/cct/tools/filebrowser/FileTransferPanel.java b/src/main/java/cct/tools/filebrowser/FileTransferPanel.java new file mode 100644 index 0000000..64d77f3 --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/FileTransferPanel.java @@ -0,0 +1,108 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.awt.BorderLayout; +import java.awt.Dimension; + +import javax.swing.JFileChooser; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; + +import cct.interfaces.FileBrowserInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class FileTransferPanel + extends JPanel { + BorderLayout borderLayout1 = new BorderLayout(); + JSplitPane jSplitPane1 = new JSplitPane(); + JFileChooser jFileChooser1 = new JFileChooser(); + FileBrowserPanel jFileBrowserPanel1 = new FileBrowserPanel(); + JScrollPane jScrollPane2 = new JScrollPane(); + + public FileTransferPanel() { + this(null); + } + + public FileTransferPanel(FileBrowserInterface fileBrowser) { + try { + jFileBrowserPanel1.setFileBrowser(fileBrowser); + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + jFileChooser1.setMinimumSize(new Dimension(325, 345)); + jFileChooser1.setControlButtonsAreShown(false); + jFileChooser1.setDragEnabled(true); + jFileChooser1.setMultiSelectionEnabled(true); + this.setLayout(borderLayout1); + jSplitPane1.setOrientation(JSplitPane.VERTICAL_SPLIT); + jScrollPane2.setMinimumSize(new Dimension(325, 345)); + jScrollPane2.setPreferredSize(new Dimension(325, 345)); + jSplitPane1.add(jScrollPane2, JSplitPane.BOTTOM); + jSplitPane1.add(jFileBrowserPanel1, JSplitPane.TOP); + jScrollPane2.getViewport().add(jFileChooser1); + + this.add(jSplitPane1, BorderLayout.NORTH); + } + + public void setFileBrowser(FileBrowserInterface fileBrowser) { + jFileBrowserPanel1.setFileBrowser(fileBrowser); + } + + public void switchFileBrowser(FileBrowserInterface file_browser) { + jFileBrowserPanel1.switchFileBrowser(file_browser); + + } +} diff --git a/src/main/java/cct/tools/filebrowser/JFileBrowserPanel.java b/src/main/java/cct/tools/filebrowser/JFileBrowserPanel.java new file mode 100644 index 0000000..9b15228 --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/JFileBrowserPanel.java @@ -0,0 +1,442 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.ListSelectionModel; +import javax.swing.SwingConstants; + +import cct.interfaces.FileBrowserGUIInterface; +import cct.interfaces.FileBrowserInterface; +import cct.tools.FileFilterImpl; + +/** + * + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class JFileBrowserPanel + extends JPanel implements FileBrowserGUIInterface { + + FileBrowserInterface fileBrowser = null; + Object[] titles = { + "Name", "Size", "Modified", "Attributes"}; + Object[][] data = { + { + "", "", "", ""} + }; + JTable table = new JTable(data, titles); + + BorderLayout borderLayout1 = new BorderLayout(); + JScrollPane fileScrollPane = new JScrollPane(); + JPanel controlsPanel = new JPanel(); + JButton upButton = new JButton(); + JComboBox jComboBox1 = new JComboBox(); + JButton refreshButton = new JButton(); + + ImageIcon up = new ImageIcon(cct.resources.Resources.class. + getResource("cct/images/icons16x16/up.png")); + ImageIcon refresh = new ImageIcon(cct.resources.Resources.class. + getResource("cct/images/icons16x16/refresh-2.png")); + ImageIcon createFolder = new ImageIcon(cct.resources.Resources.class. + getResource( + "cct/images/icons16x16/addEntry.png")); + ImageIcon delete = new ImageIcon(cct.resources.Resources.class. + getResource("cct/images/icons16x16/delete2.png")); + ImageIcon help = new ImageIcon(cct.resources.Resources.class. + getResource("cct/images/icons16x16/help.png")); + + FlowLayout flowLayout1 = new FlowLayout(); + JButton mkdirButton = new JButton(); + JButton deleteButton = new JButton(); + JButton helpButton = new JButton(); + + public JFileBrowserPanel() { + this(null); + } + + public JFileBrowserPanel(FileBrowserInterface file_browser) { + fileBrowser = file_browser; + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public FileBrowserInterface getFileBrowserInterface() { + return fileBrowser; + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + upButton.setMaximumSize(new Dimension(23, 23)); + upButton.setMinimumSize(new Dimension(23, 23)); + upButton.setPreferredSize(new Dimension(23, 23)); + upButton.setToolTipText("Up a Directory"); + upButton.setHorizontalTextPosition(SwingConstants.CENTER); + upButton.setIcon(up); + upButton.addActionListener(new JFileBrowserPanel_upButton_actionAdapter(this)); + refreshButton.setMaximumSize(new Dimension(23, 23)); + refreshButton.setMinimumSize(new Dimension(23, 23)); + refreshButton.setPreferredSize(new Dimension(23, 23)); + refreshButton.setToolTipText("Refresh Folder"); + refreshButton.setHorizontalTextPosition(SwingConstants.CENTER); + refreshButton.setIcon(refresh); + refreshButton.addActionListener(new + JFileBrowserPanel_refreshButton_actionAdapter(this)); + controlsPanel.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + mkdirButton.setMaximumSize(new Dimension(23, 23)); + mkdirButton.setMinimumSize(new Dimension(23, 23)); + mkdirButton.setPreferredSize(new Dimension(23, 23)); + mkdirButton.setToolTipText("Create New Folder"); + mkdirButton.setHorizontalTextPosition(SwingConstants.CENTER); + mkdirButton.setIcon(createFolder); + mkdirButton.addActionListener(new + JFileBrowserPanel_mkdirButton_actionAdapter(this)); + deleteButton.setMaximumSize(new Dimension(23, 23)); + deleteButton.setMinimumSize(new Dimension(23, 23)); + deleteButton.setPreferredSize(new Dimension(23, 23)); + deleteButton.setToolTipText("Delete Selected"); + deleteButton.setHorizontalTextPosition(SwingConstants.CENTER); + deleteButton.setIcon(delete); + deleteButton.addActionListener(new + JFileBrowserPanel_deleteButton_actionAdapter(this)); + helpButton.setMaximumSize(new Dimension(23, 23)); + helpButton.setMinimumSize(new Dimension(23, 23)); + helpButton.setPreferredSize(new Dimension(23, 23)); + helpButton.setToolTipText("Help"); + helpButton.setHorizontalTextPosition(SwingConstants.CENTER); + helpButton.setIcon(help); + helpButton.addActionListener(new JFileBrowserPanel_helpButton_actionAdapter(this)); + jComboBox1.setToolTipText( + "Select visited folders or type and press Enter for a new one"); + jComboBox1.setEditable(true); + jComboBox1.addActionListener(new + JFileBrowserPanel_jComboBox1_actionAdapter(this)); + this.add(fileScrollPane, BorderLayout.CENTER); + controlsPanel.add(jComboBox1); + controlsPanel.add(upButton); + controlsPanel.add(refreshButton); + controlsPanel.add(deleteButton); + controlsPanel.add(mkdirButton); + controlsPanel.add(helpButton); + this.add(controlsPanel, BorderLayout.NORTH); + if (fileBrowser != null) { + Component comp = fileBrowser.getComponent(); + fileScrollPane.add(comp); + fileScrollPane.setBackground(comp.getForeground()); + } + else { + fileScrollPane.getViewport().add(table); + fileScrollPane.setBackground(table.getForeground()); + } + + fileScrollPane.setBackground(table.getForeground()); + fileScrollPane.setForeground(table.getForeground()); + + + } + + public void setFileFilter(FileFilterImpl filter) { + fileBrowser.setFileFilter(filter); + } + + public String[] getSelectedFiles() { + return fileBrowser.getSelectedFiles(); + } + + public void setFileBrowser(FileBrowserInterface file_browser) { + fileBrowser = file_browser; + if (fileBrowser != null) { + fileBrowser.setTopGUI(this); + Component comp = fileBrowser.getComponent(); + fileScrollPane.getViewport().add(comp); + fileScrollPane.setBackground(comp.getForeground()); + } + } + + @Override + public void setBusy(boolean busy) { + if (busy) { + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + upButton.setEnabled(false); + jComboBox1.setEnabled(false); + refreshButton.setEnabled(false); + mkdirButton.setEnabled(false); + deleteButton.setEnabled(false); + + } + else { + setCursor(Cursor.getDefaultCursor()); + } + } + + @Override + public void updateCWD(String cwd) { + jComboBox1.setEnabled(false); + jComboBox1.addItem(cwd); + jComboBox1.setSelectedIndex(jComboBox1.getItemCount() - 1); + jComboBox1.setEnabled(true); + } + + @Override + public void updateFieView(Component fileView) { + fileScrollPane.getViewport().add(fileView); + } + + public void refreshButton_actionPerformed(ActionEvent e) { + if (!refreshButton.isEnabled()) { + return; + } + refreshButton.setEnabled(false); + if (fileBrowser != null) { + fileBrowser.refresh(); + } + refreshButton.setEnabled(true); + } + + public void upButton_actionPerformed(ActionEvent e) { + if (!upButton.isEnabled()) { + return; + } + upButton.setEnabled(false); + if (fileBrowser != null) { + fileBrowser.upDirectory(); + } + upButton.setEnabled(true); + } + + public void mkdirButton_actionPerformed(ActionEvent e) { + if (!mkdirButton.isEnabled()) { + return; + } + mkdirButton.setEnabled(false); + if (fileBrowser != null) { + fileBrowser.mkdir(); + } + mkdirButton.setEnabled(true); + } + + public void jComboBox1_itemStateChanged(ItemEvent e) { + if (!jComboBox1.isEnabled()) { + return; + } + jComboBox1.setEnabled(false); + fileBrowser.cd(jComboBox1.getSelectedItem().toString()); + jComboBox1.setEnabled(true); + + } + + public void jComboBox1_actionPerformed(ActionEvent e) { + if (!jComboBox1.isEnabled()) { + return; + } + jComboBox1.setEnabled(false); + if (fileBrowser != null) { + fileBrowser.cd(jComboBox1.getSelectedItem().toString()); + } + jComboBox1.setEnabled(true); + } + + public void deleteButton_actionPerformed(ActionEvent e) { + if (!deleteButton.isEnabled()) { + return; + } + deleteButton.setEnabled(false); + if (fileBrowser != null) { + fileBrowser.removeSelectedPaths(); + } + deleteButton.setEnabled(true); + } + + public void helpButton_actionPerformed(ActionEvent e) { + JOptionPane.showMessageDialog(this, "Toolbar:\n" + + "Use toolbar buttons to go up a directory, refresh current directory\n" + + "to delete selected file(s) and directories (be careful!), to create a new directory\n" + + "Use combobox to switch fast to previously visited directories\n" + + "Files area:\n" + + "Use mouse to select single files and directories\n" + + "Use Shift key + mouse to select blocks of files/directories\n" + + "Using Control key + mouse gives more control for selecting/deselecting\n" + + "To initiate download of selected files and directories do right mouse button click\n" + + " to open the popup menu and select folder on local computer\n" + + "To upload files do right mouse button click to open the popup menu and\n" + + " select \"Upload Dialog\" (no selection should be within the file area)", "Help", + JOptionPane.INFORMATION_MESSAGE); + } + + /** + * Sets table selection mode. Valid values: ListSelectionModel.SINGLE_SELECTION, + * ListSelectionModel.SINGLE_INTERVAL_SELECTION, and ListSelectionModel.MULTIPLE_INTERVAL_SELECTION. + * Otherwise sets ListSelectionModel.SINGLE_SELECTION + * @param mode int + */ + public void setSelectionMode(int mode) { + try { + switch (mode) { + case ListSelectionModel.SINGLE_SELECTION: + case ListSelectionModel.SINGLE_INTERVAL_SELECTION: + case ListSelectionModel.MULTIPLE_INTERVAL_SELECTION: + fileBrowser.setSelectionMode(mode); + return; + } + System.err.println(this.getClass().getCanonicalName() + " : unknown selection mode. Ignored..."); + fileBrowser.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + } + catch (Exception ex) {} + } + + private class JFileBrowserPanel_helpButton_actionAdapter + implements ActionListener { + private JFileBrowserPanel adaptee; + JFileBrowserPanel_helpButton_actionAdapter(JFileBrowserPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.helpButton_actionPerformed(e); + } + } + + private class JFileBrowserPanel_deleteButton_actionAdapter + implements ActionListener { + private JFileBrowserPanel adaptee; + JFileBrowserPanel_deleteButton_actionAdapter(JFileBrowserPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.deleteButton_actionPerformed(e); + } + } + + private class JFileBrowserPanel_jComboBox1_actionAdapter + implements ActionListener { + private JFileBrowserPanel adaptee; + JFileBrowserPanel_jComboBox1_actionAdapter(JFileBrowserPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.jComboBox1_actionPerformed(e); + } + } + + private class JFileBrowserPanel_jComboBox1_itemAdapter + implements ItemListener { + private JFileBrowserPanel adaptee; + JFileBrowserPanel_jComboBox1_itemAdapter(JFileBrowserPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void itemStateChanged(ItemEvent e) { + adaptee.jComboBox1_itemStateChanged(e); + } + } + + private class JFileBrowserPanel_mkdirButton_actionAdapter + implements ActionListener { + private JFileBrowserPanel adaptee; + JFileBrowserPanel_mkdirButton_actionAdapter(JFileBrowserPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.mkdirButton_actionPerformed(e); + } + } + + private class JFileBrowserPanel_upButton_actionAdapter + implements ActionListener { + private JFileBrowserPanel adaptee; + JFileBrowserPanel_upButton_actionAdapter(JFileBrowserPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.upButton_actionPerformed(e); + } + } + + private class JFileBrowserPanel_refreshButton_actionAdapter + implements ActionListener { + private JFileBrowserPanel adaptee; + JFileBrowserPanel_refreshButton_actionAdapter(JFileBrowserPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.refreshButton_actionPerformed(e); + } + } + +} diff --git a/src/main/java/cct/tools/filebrowser/LocalFileBrowser.java b/src/main/java/cct/tools/filebrowser/LocalFileBrowser.java new file mode 100644 index 0000000..fbc1921 --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/LocalFileBrowser.java @@ -0,0 +1,200 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.awt.Component; + +import javax.swing.JTable; + +import cct.interfaces.FileBrowserGUIInterface; +import cct.interfaces.FileBrowserInterface; +import cct.tools.FileFilterImpl; + +import com.sshtools.j2ssh.FileTransferProgress; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class LocalFileBrowser + implements FileBrowserInterface { + + JTable table = new JTable(5, 5); + FileBrowserGUIInterface topGUI = null; + + public LocalFileBrowser() { + } + + @Override + public String[] getFileNames() { + return null; + } + + @Override + public int getFileCount() { + return 0; + } + + @Override + public void listUsingFilePattern(String pattern) throws Exception { + + } + + @Override + public Component getComponent() { + return table; + } + + @Override + public void setSelectionInfoInterface(SelectionInfoInterface selection_info) { + + } + + @Override + public void get(String remote, String local) throws Exception { + + } + + @Override + public void get(String remote, String local, FileTransferProgress progress) throws Exception { + + } + + @Override + public void setFileFilter(FileFilterImpl filter) { + + } + + @Override + public void disconnect() { + + } + + @Override + public String[] getSelectedFiles() { + return null; + } + + @Override + public void downloadSelected() { + + } + + @Override + public String pwd() { + return null; + } + + @Override + public String[] getSelectedFolders() { + return null; + } + + @Override + public void setSelectionMode(int mode) { + + } + + @Override + public void setTopGUI(FileBrowserGUIInterface guiInterface) { + topGUI = guiInterface; + } + + @Override + public void connect(String hostname) throws Exception { + + } + + @Override + public void connect(String hostname, String username, char[] password, + int port) throws Exception { + + } + + @Override + public boolean isAuthenticated() { + return false; + } + + @Override + public void mkdir() { + + } + + @Override + public void mkdir(String dir) { + + } + + @Override + public void cd(String dir) { + + } + + @Override + public void refresh() { + + } + + @Override + public void removeSelectedPaths() { + + } + + @Override + public void rm(String path) { + + } + + @Override + public void upDirectory() { + + } + + public static void main(String[] args) { + LocalFileBrowser localfilebrowser = new LocalFileBrowser(); + } +} diff --git a/src/main/java/cct/tools/filebrowser/PermissionsPanel.java b/src/main/java/cct/tools/filebrowser/PermissionsPanel.java new file mode 100644 index 0000000..eeff348 --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/PermissionsPanel.java @@ -0,0 +1,491 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import javax.swing.JCheckBox; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTextField; + +/** + * + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * Dialog for modifying file attributes + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class PermissionsPanel + extends JPanel implements ItemListener { + + int permission = 0; + + Map setBit = new HashMap(); + Map zeroBit = new HashMap(); + Map checkedToolTips = new HashMap(); + Map uncheckedToolTips = new HashMap(); + + JLabel readLabel = new JLabel(); + JCheckBox otherReadCheckBox = new JCheckBox(); + JTextField modeTextField = new JTextField(); + JCheckBox ownerReadCheckBox = new JCheckBox(); + JCheckBox ownerWriteCheckBox = new JCheckBox(); + JCheckBox ownerExecuteCheckBox = new JCheckBox(); + JCheckBox groupReadCheckBox = new JCheckBox(); + JCheckBox groupWriteCheckBox = new JCheckBox(); + JCheckBox groupExecuteCheckBox = new JCheckBox(); + JCheckBox otherWriteCheckBox = new JCheckBox(); + JCheckBox otherExecuteCheckBox = new JCheckBox(); + JLabel writeLabel = new JLabel(); + JLabel ownerLabel = new JLabel(); + JLabel groupLabel = new JLabel(); + JLabel otherLabel = new JLabel(); + JLabel permissionLabel = new JLabel(); + JLabel executeLabel = new JLabel(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + + public PermissionsPanel(int perm) { + this(); + } + + public PermissionsPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(gridBagLayout1); + readLabel.setToolTipText(""); + readLabel.setText("Read"); + modeTextField.setToolTipText("Enter new value (000-777) and Press Enter"); + modeTextField.setText("000"); + modeTextField.setColumns(4); + modeTextField.addFocusListener(new + PermissionsPanel_modeTextField_focusAdapter(this)); + modeTextField.addActionListener(new + PermissionsPanel_modeTextField_actionAdapter(this)); + writeLabel.setToolTipText(""); + writeLabel.setText("Write"); + ownerLabel.setToolTipText(""); + ownerLabel.setText("Owner:"); + groupLabel.setToolTipText(""); + groupLabel.setText("Group:"); + otherLabel.setToolTipText(""); + otherLabel.setText("Other:"); + permissionLabel.setToolTipText(""); + permissionLabel.setText("Permission mode:"); + executeLabel.setToolTipText(""); + executeLabel.setText("Execute"); + ownerReadCheckBox.setToolTipText("Owner cannot read"); + ownerWriteCheckBox.setToolTipText("Owner cannot write"); + ownerExecuteCheckBox.setToolTipText("Owner cannot execute"); + groupReadCheckBox.setToolTipText("Group cannot read"); + groupWriteCheckBox.setToolTipText("Group cannot write"); + groupExecuteCheckBox.setToolTipText("Group cannot execute"); + otherReadCheckBox.setToolTipText("Others cannot read"); + otherWriteCheckBox.setToolTipText("Others cannot write"); + otherExecuteCheckBox.setToolTipText("Others cannot execute"); + this.add(ownerLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(groupLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(otherLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(permissionLabel, new GridBagConstraints(0, 4, 2, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(modeTextField, new GridBagConstraints(2, 4, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(ownerReadCheckBox, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(ownerWriteCheckBox, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(ownerExecuteCheckBox, + new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(groupReadCheckBox, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(groupWriteCheckBox, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(groupExecuteCheckBox, + new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(otherReadCheckBox, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(otherWriteCheckBox, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(otherExecuteCheckBox, + new GridBagConstraints(3, 3, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(readLabel, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(writeLabel, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + this.add(executeLabel, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + + // --- Masks for setting + setBit.put(otherExecuteCheckBox, new Integer(0001)); + setBit.put(otherWriteCheckBox, new Integer(0002)); + setBit.put(otherReadCheckBox, new Integer(0004)); + + setBit.put(groupExecuteCheckBox, new Integer(0010)); + setBit.put(groupWriteCheckBox, new Integer(0020)); + setBit.put(groupReadCheckBox, new Integer(0040)); + + setBit.put(ownerExecuteCheckBox, new Integer(0100)); + setBit.put(ownerWriteCheckBox, new Integer(0200)); + setBit.put(ownerReadCheckBox, new Integer(0400)); + + // --- Masks for clearing + zeroBit.put(otherExecuteCheckBox, new Integer(0776)); + zeroBit.put(otherWriteCheckBox, new Integer(0775)); + zeroBit.put(otherReadCheckBox, new Integer(0773)); + + zeroBit.put(groupExecuteCheckBox, new Integer(0767)); + zeroBit.put(groupWriteCheckBox, new Integer(0757)); + zeroBit.put(groupReadCheckBox, new Integer(0737)); + + zeroBit.put(ownerExecuteCheckBox, new Integer(0677)); + zeroBit.put(ownerWriteCheckBox, new Integer(0577)); + zeroBit.put(ownerReadCheckBox, new Integer(0377)); + + // --- Adding tooltips for checked boxes + + checkedToolTips.put(otherExecuteCheckBox, "Others can execute"); + checkedToolTips.put(otherWriteCheckBox, "Others can write"); + checkedToolTips.put(otherReadCheckBox, "Others can read"); + + checkedToolTips.put(groupExecuteCheckBox, "Group can execute"); + checkedToolTips.put(groupWriteCheckBox, "Group can write"); + checkedToolTips.put(groupReadCheckBox, "Group can read"); + + checkedToolTips.put(ownerExecuteCheckBox, "Owner can execute"); + checkedToolTips.put(ownerWriteCheckBox, "Owner can write"); + checkedToolTips.put(ownerReadCheckBox, "Owner can read"); + + // --- Adding tooltips for unchecked boxes + + uncheckedToolTips.put(otherExecuteCheckBox, "Others cannot execute"); + uncheckedToolTips.put(otherWriteCheckBox, "Others cannot write"); + uncheckedToolTips.put(otherReadCheckBox, "Others cannot read"); + + uncheckedToolTips.put(groupExecuteCheckBox, "Group cannot execute"); + uncheckedToolTips.put(groupWriteCheckBox, "Group cannot write"); + uncheckedToolTips.put(groupReadCheckBox, "Group cannot read"); + + uncheckedToolTips.put(ownerExecuteCheckBox, "Owner cannot execute"); + uncheckedToolTips.put(ownerWriteCheckBox, "Owner cannot write"); + uncheckedToolTips.put(ownerReadCheckBox, "Owner cannot read"); + + // --- Adding item state changed listener + + otherExecuteCheckBox.addItemListener(this); + otherWriteCheckBox.addItemListener(this); + otherReadCheckBox.addItemListener(this); + + groupExecuteCheckBox.addItemListener(this); + groupWriteCheckBox.addItemListener(this); + groupReadCheckBox.addItemListener(this); + + ownerExecuteCheckBox.addItemListener(this); + ownerWriteCheckBox.addItemListener(this); + ownerReadCheckBox.addItemListener(this); + + } + + void setPermissionMode() { + permission = 0; + Set set = setBit.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + JCheckBox box = (JCheckBox) me.getKey(); + Integer mask = (Integer) me.getValue(); + if (box.isSelected()) { + permission |= mask.intValue(); + } + } + + modeTextField.setEnabled(false); + modeTextField.setText(Integer.toOctalString(permission)); + modeTextField.setEnabled(true); + } + + @Override + public void itemStateChanged(ItemEvent e) { + JCheckBox box = (JCheckBox) e.getItemSelectable(); + if (!box.isEnabled()) { + return; + } + + if (box.isSelected()) { + Integer mask = (Integer) setBit.get(box); + permission |= mask.intValue(); + } + else { + Integer mask = (Integer) zeroBit.get(box); + permission &= mask.intValue(); + } + modeTextField.setEnabled(false); + modeTextField.setText(Integer.toOctalString(permission)); + modeTextField.setEnabled(true); + } + + public void modeTextField_actionPerformed(ActionEvent e) { + parsePermissionMode(); + } + + void parsePermissionMode() { + if (!modeTextField.isEnabled()) { + return; + } + modeTextField.setEnabled(false); + try { + permission = Integer.parseInt(modeTextField.getText().trim(), 8); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, + "Wrong permission mode: " + + modeTextField.getText() + + " Should be in 000-777 range", + "Error", + JOptionPane.ERROR_MESSAGE); + modeTextField.setText(String.valueOf(permission)); + modeTextField.setEnabled(true); + return; + } + + setCheckBoxes(permission); + + modeTextField.setEnabled(true); + + } + + public void modeTextField_focusLost(FocusEvent e) { + parsePermissionMode(); + } + + /** + * Sets/unsets checkboxes ticks + */ + void setCheckBoxes(int permiss) { + enableCheckBoxes(false); + Set set = setBit.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + JCheckBox box = (JCheckBox) me.getKey(); + Integer mask = (Integer) me.getValue(); + if ( (permiss & mask.intValue()) > 0) { + box.setSelected(true); + box.setToolTipText( (String) checkedToolTips.get(box)); + } + else { + box.setSelected(false); + box.setToolTipText( (String) uncheckedToolTips.get(box)); + } + } + enableCheckBoxes(true); + } + + /** + * Enables/disables all checkboxes + * @param enable boolean + */ + void enableCheckBoxes(boolean enable) { + Set set = setBit.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + JCheckBox box = (JCheckBox) me.getKey(); + box.setEnabled(enable); + } + } + + void setupControls(int permiss) { + if (permiss < 0 || permiss > 0777) { + JOptionPane.showMessageDialog(null, + "Wrong permission mode: " + + permiss + + " Should be in 000-777 range", + "Error", + JOptionPane.ERROR_MESSAGE); + permission = 0; + } + else { + permission = permiss; + } + this.setCheckBoxes(permission); + this.setPermissionMode(); + } + + public void setupControls(String permissions) { + permission = 0; + + char[] perm = permissions.toCharArray(); + + if (perm.length != 10) { + JOptionPane.showMessageDialog(null, + "Expecting permissions string of 10 characters. Got: " + + permissions, + "Error", + JOptionPane.ERROR_MESSAGE); + } + else { + + if (perm[9] == 'x') { + permission |= 0001; + } + if (perm[8] == 'w') { + permission |= 0002; + } + if (perm[7] == 'r') { + permission |= 0004; + } + + if (perm[6] == 'x') { + permission |= 0010; + } + if (perm[5] == 'w') { + permission |= 0020; + } + if (perm[4] == 'r') { + permission |= 0040; + } + + if (perm[3] == 'x') { + permission |= 0100; + } + if (perm[2] == 'w') { + permission |= 0200; + } + if (perm[1] == 'r') { + permission |= 0400; + } + + } + + this.setCheckBoxes(permission); + this.setPermissionMode(); + } + + public int getPermissions() { + return permission; + } +} + +class PermissionsPanel_modeTextField_focusAdapter + extends FocusAdapter { + private PermissionsPanel adaptee; + PermissionsPanel_modeTextField_focusAdapter(PermissionsPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void focusLost(FocusEvent e) { + adaptee.modeTextField_focusLost(e); + } +} + +class PermissionsPanel_modeTextField_actionAdapter + implements ActionListener { + private PermissionsPanel adaptee; + PermissionsPanel_modeTextField_actionAdapter(PermissionsPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.modeTextField_actionPerformed(e); + } +} diff --git a/src/main/java/cct/tools/filebrowser/SFTPBrowser.java b/src/main/java/cct/tools/filebrowser/SFTPBrowser.java new file mode 100644 index 0000000..04660ec --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/SFTPBrowser.java @@ -0,0 +1,2312 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.tools.filebrowser; + +import cct.interfaces.FileBrowserGUIInterface; +import cct.interfaces.FileBrowserInterface; +import cct.tools.FileFilterImpl; +import cct.tools.FileUtilities; +import cct.tools.UserPasswordDialog; +import com.sshtools.j2ssh.DirectoryOperation; +import com.sshtools.j2ssh.FileTransferProgress; +import com.sshtools.j2ssh.SftpClient; +import com.sshtools.j2ssh.SshClient; +import com.sshtools.j2ssh.authentication.*; +import com.sshtools.j2ssh.io.UnsignedInteger32; +import com.sshtools.j2ssh.io.UnsignedInteger64; +import com.sshtools.j2ssh.sftp.FileAttributes; +import com.sshtools.j2ssh.sftp.SftpFile; +import com.sshtools.j2ssh.transport.IgnoreHostKeyVerification; + +import javax.swing.*; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.TableCellRenderer; +import javax.swing.table.TableColumn; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.File; +import java.text.DateFormat; +import java.text.NumberFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Logger; + +/** + * + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * It's a workhorse which performs all SFTP Browser functions + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class SFTPBrowser + extends MouseAdapter implements FileBrowserInterface, ActionListener, ListSelectionListener { + + static final String upDirectoryItem = "Up a Directory"; + static final String RefreshItem = "Refresh"; + static final String NewForlderItem = "New Folder"; + static final String GoToForlderItem = "Go to Folder..."; + static final String DeleteItem = "Delete"; + static final String UploadDialogItem = "Upload Dialog"; + static final String SelectAllItem = "Select All"; + static final String DownloadItem = "Download"; + static final String PropertiesItem = "Properties"; + FileFilterImpl Filter = null; + boolean Busy = false; + boolean tableInitiated = false; + int tableSelectionMode = ListSelectionModel.MULTIPLE_INTERVAL_SELECTION; + FileBrowserGUIInterface topGUI = null; + SelectionInfoInterface selectionInfo = null; + Map directories = new HashMap(); + JTable table = new JTable(5, 5); + SshClient ssh = null; + String hostName = null; + String userName = null; + char[] password = null; + String currentPWD = null; + java.util.List currentFileList = null; + java.util.List authenticationMethods = null; + int AuthenticationResult = AuthenticationProtocolState.FAILED; + int portNumber = 22; + SftpClient sftpClient = null; + boolean DEBUG = true; + String[] columnNames = { + "Remote Name", "Size", "Type", "Modified", "Attributes"}; + int[] sortStatus = null; + TableSorter sorter = null; + Object[][] data = null; + NumberFormat numberFormat = NumberFormat.getInstance(); + JPopupMenu generalPopup, filePopup; + FileBrowserTableModel tModel = null; + JFileChooser localFileChooser = null; + FilePropertiesDialog fileProps = null; + static final Logger logger = Logger.getLogger(SFTPBrowser.class.getCanonicalName()); + + public SFTPBrowser() { + try { + tModel = new FileBrowserTableModel(); + localFileChooser = new JFileChooser(); + fileProps = new FilePropertiesDialog(new Frame(), "File Properties"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public int getFileCount() { + if (currentFileList == null) { + return 0; + } + int count = 0; + for (int i = 0; i < currentFileList.size(); i++) { + SftpFile file = (SftpFile) currentFileList.get(i); + if (file.isDirectory()) { + continue; + } + ++count; + } + return count; + } + + public String[] getFileNames() { + if (currentFileList == null) { + return null; + } + java.util.List files = new ArrayList(); + for (int i = 0; i < currentFileList.size(); i++) { + SftpFile file = (SftpFile) currentFileList.get(i); + if (file.isDirectory()) { + continue; + } + files.add(file.getFilename()); + } + if (files.size() < 1) { + return null; + } + String[] fileNames = new String[files.size()]; + files.toArray(fileNames); + return fileNames; + } + + public void setSelectionInfoInterface(SelectionInfoInterface selection_info) { + table.getSelectionModel().removeListSelectionListener(this); + selectionInfo = selection_info; + if (selectionInfo != null) { + table.getSelectionModel().addListSelectionListener(this); + } + } + + public void valueChanged(ListSelectionEvent e) { + if (e.getValueIsAdjusting()) { + return; + } + if (selectionInfo == null) { + return; + } + if (table.getSelectedRowCount() == 0 || table.getSelectedRowCount() > 1) { + return; + } + int n = table.getSelectedRow(); + + //int firstIndex = e.getFirstIndex(); + //int lastIndex = e.getLastIndex(); + //if (firstIndex == lastIndex) { + String type = (String) table.getValueAt(n, 2); // Get type of item + if (type.equalsIgnoreCase("Folder")) { + selectionInfo.setSelectedFileName(""); + return; + } + try { + String item = this.getFileName(table.getValueAt(n, 0)); + selectionInfo.setSelectedFileName(item); + } catch (Exception ex) { + System.err.println(this.getClass().getCanonicalName() + " : cannot get file name"); + } + //} + } + + public void listUsingFilePattern(String filePattern) throws Exception { + java.util.List fileList = null; + String newDir; + + try { + fileList = sftpClient.ls(); + newDir = sftpClient.pwd(); + } catch (Exception ex) { + //ex.printStackTrace(); + throw ex; + } + + for (int i = 0; i < fileList.size(); i++) { + SftpFile file = (SftpFile) fileList.get(i); + if (file.getFilename().equals(".") && file.isDirectory()) { + fileList.remove(i); + break; + } + } + + if (filePattern != null && filePattern.length() > 0) { + + //Pattern pattern = Pattern.compile(filePattern); + + // --- Apply file pattern + + for (int i = fileList.size() - 1; i >= 0; i--) { + SftpFile file = (SftpFile) fileList.get(i); + if (file.isDirectory()) { + continue; + } + + if (file.getFilename().matches(filePattern)) { + continue; + } + + /* + Matcher matcher = pattern.matcher(file.getFilename()); + if (matcher.find()) { + continue; + } + */ + + fileList.remove(i); + } + } + + this.currentFileList = fileList; + currentPWD = newDir; + + setupTable(); + directories.put(currentPWD, currentFileList); + topGUI.updateFieView(table); + topGUI.updateCWD(currentPWD); + + } + + public void setFileFilter(FileFilterImpl filter) { + Filter = filter; + refresh(); + } + + public String getHost() { + return hostName; + } + + public String getUsername() { + return userName; + } + + public char[] getPassword() { + return password; + } + + public int getPort() { + return portNumber; + } + + public void get(String remote, String local) throws Exception { + try { + sftpClient.get(currentPWD + "/" + remote, local); + } catch (Exception ex) { + throw new Exception("Cannot transfer " + currentPWD + "/" + remote + " to " + local + " : " + ex.getMessage()); + } + + } + + public void get(String remote, String local, FileTransferProgress progress) throws Exception { + try { + sftpClient.get(currentPWD + "/" + remote, local, progress); + } catch (Exception ex) { + throw new Exception("Cannot transfer " + currentPWD + "/" + remote + " to " + local + " : " + ex.getMessage()); + } + + } + + public String pwd() { + if (ssh == null) { + return null; + } + if (sftpClient == null) { + return null; + } + return sftpClient.pwd(); + } + + public SftpClient getSftpClient() throws Exception { + if (sftpClient == null) { + try { + sftpClient = ssh.openSftpClient(); + } catch (Exception ex) { + throw ex; + } + } + return sftpClient; + } + + public SshClient getSshClient() { + return ssh; + } + + /** + * Sets selection mode: The following selectionMode values are allowed: + * ListSelectionModel.SINGLE_SELECTION Only one list index can be selected at a time. + * ListSelectionModel.SINGLE_INTERVAL_SELECTION One contiguous index interval can be selected at a time. + * ListSelectionModel.MULTIPLE_INTERVAL_SELECTION In this mode, there's no restriction on what can be selected. This is the default. + * @param mode int - an integer specifying the type of selections that are permissible + */ + public void setSelectionMode(int mode) throws Exception { + switch (mode) { + case ListSelectionModel.SINGLE_SELECTION: + case ListSelectionModel.SINGLE_INTERVAL_SELECTION: + case ListSelectionModel.MULTIPLE_INTERVAL_SELECTION: + tableSelectionMode = mode; + table.setSelectionMode(mode); + return; + } + throw new Exception("Unknown table selection mode: " + mode + + " Available modes: " + + ListSelectionModel.SINGLE_SELECTION + "," + + ListSelectionModel.SINGLE_INTERVAL_SELECTION + "," + + ListSelectionModel.MULTIPLE_INTERVAL_SELECTION + + "(default)"); + } + + /** + * For processing popup menu items + * @param e ActionEvent + */ + public void actionPerformed(ActionEvent e) { + String arg = e.getActionCommand(); + if (arg.equals(upDirectoryItem)) { + this.upDirectory(); + } else if (arg.equals(RefreshItem)) { + this.refresh(); + } else if (arg.equals(NewForlderItem)) { + mkdir(); + } else if (arg.equals(GoToForlderItem)) { + goToFolderDialog(); + } else if (arg.equals(DeleteItem)) { + this.removeSelectedPaths(); + } else if (arg.equals(UploadDialogItem)) { + openUploadDialog(); + } else if (arg.equals(SelectAllItem)) { + table.selectAll(); + } else if (arg.equals(DownloadItem)) { + this.downloadSelected(); + } else if (arg.equals(PropertiesItem)) { + openFilePropertiesDialog(); + } + } + + void openFilePropertiesDialog() { + if (table.getSelectedRowCount() < 1) { + JOptionPane.showMessageDialog(null, + "Select File(s)/Folder(s) first!", + "Warning", + JOptionPane.WARNING_MESSAGE); + return; + } + + if (table.getSelectedRowCount() == 1) { + int n = table.getSelectedRow(); + SftpFile file = null; + Object obj = table.getValueAt(n, 0); + if (obj instanceof FileName) { + FileName fname = (FileName) obj; + String filename = fname.getFileName(); + for (int i = 0; i < this.currentFileList.size(); i++) { // Redo this + SftpFile f = (SftpFile) currentFileList.get(i); + if (filename.equals(f.getFilename())) { + file = f; + break; + } + } + } else { + file = (SftpFile) table.getValueAt(n, 0); + } + + fileProps.setTitle(file.getFilename() + " Properties"); + FileAttributes attr = file.getAttributes(); + + if (file.isDirectory()) { + fileProps.setFileName(file.getFilename()); + fileProps.setFileType("Folder"); + fileProps.setFileSize("0 bytes"); + fileProps.setFileIcon(FileUtilities.getFolderIcon32x32()); + } else { + fileProps.setFileName(file.getFilename()); + fileProps.setFileType("File"); + UnsignedInteger64 size2 = attr.getSize(); + fileProps.setFileSize(numberFormat.format(size2.doubleValue()) + + " bytes"); + fileProps.setFileIcon(FileUtilities.getIcon32x32(file.getFilename())); + } + + String location = file.getAbsolutePath().substring(0, + file.getAbsolutePath().lastIndexOf(file.getFilename())); + fileProps.setFileLocation(location); + + fileProps.setFileModified(attr.getModTimeString()); + + fileProps.setPermissions(attr.getPermissionsString()); + + fileProps.setAlwaysOnTop(true); + fileProps.setLocationRelativeTo(null); + int key = fileProps.showDialog(); + + if (key == FilePropertiesDialog.SET) { + int permissions = fileProps.getPermissions(); + try { + Busy = true; + topGUI.setBusy(true); + //table.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + sftpClient.chmod(permissions, file.getAbsolutePath()); + refresh(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, + "Cannot change permissions for " + + file.getAbsolutePath() + " : " + + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + } + Busy = false; + topGUI.setBusy(false); + } + } + } + + public boolean isAuthenticated() { + if (ssh == null) { + return false; + } + return ssh.isAuthenticated(); + } + + /** + * Downloads selected items + */ + public void downloadSelected() { + if (table.getSelectedRowCount() < 1) { + JOptionPane.showMessageDialog(null, + "Select File(s)/Folder(s) first!", + "Warning", + JOptionPane.WARNING_MESSAGE); + return; + } + + // Setup list of remote files to transfer + int[] rows = table.getSelectedRows(); + java.util.List finalList = new ArrayList(rows.length); + + for (int i = 0; i < rows.length; i++) { + Object obj = table.getValueAt(rows[i], 0); + String path = null; + try { + path = getFileName(obj); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, + "Internal Error: " + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + continue; + } + + SftpFile file = null; + + for (int j = 0; j < currentFileList.size(); j++) { // Stupid thing + file = (SftpFile) currentFileList.get(j); + if (path.equals(file.getFilename())) { + path = file.getAbsolutePath(); + break; + } + } + + if (file == null) { + System.err.println("INTERNAL ERROR: no file " + path + + " in file list\n"); + //errorMess += "INTERNAL ERROR: no file " + path + " in file list\n"; + continue; + } + + finalList.add(file); + } + + localFileChooser.setDialogTitle("Select Folder for Download"); + localFileChooser.setControlButtonsAreShown(true); + localFileChooser.setDragEnabled(true); + localFileChooser.setMultiSelectionEnabled(false); + localFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + Component parent = null; + if (this.topGUI != null && topGUI instanceof Component) { + parent = (Component) topGUI; + } + //int returnVal = localFileChooser.showOpenDialog(parent); + int returnVal = localFileChooser.showDialog(parent, "Start Download"); + if (returnVal == JFileChooser.APPROVE_OPTION) { + File dir = localFileChooser.getSelectedFile(); + + localFileChooser.setCurrentDirectory(dir); + FileTranferWorker downloader = new FileTranferWorker(finalList, + dir.getAbsolutePath()); + downloader.start(); + } else { + } + + } + + public String getFileName(Object fileObject) throws Exception { + String path = null; + if (fileObject instanceof String) { + path = (String) fileObject; + } else if (fileObject instanceof SftpFile) { + SftpFile file = (SftpFile) fileObject; + path = file.getFilename(); // Get selected value + } else if (fileObject instanceof FileName) { + FileName fn = (FileName) fileObject; + path = fn.getFileName(); + } else { + throw new Exception("Unknown class for file name: " + + fileObject.getClass().getCanonicalName()); + } + return path; + } + + /** + * Opens upload dialog + */ + public void openUploadDialog() { + //localFileChooser.setMinimumSize(new Dimension(325, 345)); + localFileChooser.setDialogTitle("Select File(s) for Upload"); + localFileChooser.setControlButtonsAreShown(true); + localFileChooser.setDragEnabled(true); + localFileChooser.setMultiSelectionEnabled(true); + localFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); + Component parent = null; + if (this.topGUI != null && topGUI instanceof Component) { + parent = (Component) topGUI; + } + //int returnVal = localFileChooser.showOpenDialog(parent); + int returnVal = localFileChooser.showDialog(parent, + "Upload Selected File(s)"); + if (returnVal == JFileChooser.APPROVE_OPTION) { + File[] files = localFileChooser.getSelectedFiles(); + //File file = localFileChooser.getSelectedFile(); + //This is where a real application would open the file. + + FileTranferWorker uploader = new FileTranferWorker(files, + currentPWD); + uploader.start(); + } else { + } + + } + + /** + * Upload a file to the remote computer. + * @param file String - the path/name of the local file + * @throws Exception - if an IO error occurs or the file does not exist + */ + public void uploadFile(String file) throws Exception { + try { + sftpClient.put(file); + } catch (java.io.IOException ex) { + throw ex; + } + } + + /** + * Remove a file or directory from the remote computer + * @param path String - the path of the remote file/directory + */ + public void rm(String path) { + + try { + sftpClient.rm(path); + } catch (java.io.IOException ex) { + JOptionPane.showMessageDialog(null, + "Error removing " + path + " : " + + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + refresh(); + } + + /** + * Removes selected file(s)/folder(s) + */ + public void removeSelectedPaths() { + if (table.getSelectedRowCount() == 0) { + JOptionPane.showMessageDialog(null, + "Select file(s)/folder(s) first!", + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + int[] rows = table.getSelectedRows(); + int removed = 0; + String errorMess = ""; + + for (int i = 0; i < rows.length; i++) { + + String path = null; + Object obj = null; + try { + obj = table.getValueAt(rows[i], 0); + path = getFileName(obj); + } catch (Exception ex) { + errorMess += "INTERNAL ERROR: cannot get file name as a String: " + obj.getClass().getCanonicalName() + "\n"; + continue; + } + SftpFile file = null; + + for (int j = 0; j < currentFileList.size(); j++) { // Stupid thing + file = (SftpFile) currentFileList.get(j); + if (path.equals(file.getFilename())) { + break; + } + } + + if (file == null) { + errorMess += "INTERNAL ERROR: no file " + path + " in file list\n"; + continue; + } + + try { + if (DEBUG) { + logger.info("Removing: " + file.getAbsolutePath()); + } + sftpClient.rm(file.getAbsolutePath()); + ++removed; + } catch (java.io.IOException ex) { + errorMess += "Error removing " + file.getAbsolutePath() + " : " + ex.getMessage() + "\n"; + } + } + + if (errorMess.length() > 0) { + JOptionPane.showMessageDialog(null, errorMess, "Error", + JOptionPane.ERROR_MESSAGE); + } + + if (removed == 0) { + return; + } + + refresh(); + + } + + public void goToFolderDialog() { + Component parent = null; + if (topGUI != null && topGUI instanceof Component) { + parent = (Component) topGUI; + } + Object folder = JOptionPane.showInputDialog(parent, "Enter Folder Name:", "Go to Remote Folder", JOptionPane.QUESTION_MESSAGE, null, null, + currentPWD); + + if (folder == null || folder.toString().trim().length() == 0) { + return; + } + + String folderName = folder.toString(); + if (DEBUG) { + logger.info("goToFolderDialog: folder: " + folderName); + } + cd(folderName); + } + + /** + * Changes the working directory on the remote server + * @param dir String - the new working directory + */ + public void cd(String dir) { + try { + changeAbsolutePath(dir); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + topGUI.updateFieView(table); + topGUI.updateCWD(currentPWD); + if (DEBUG) { + logger.info("cd: changed to " + dir + " PWD: " + currentPWD); + } + } + + public void mkdir(String dir) { + // Relative or Absolute path? + + String newDir; + if (!dir.startsWith("/")) { // Relative path + newDir = currentPWD + "/" + dir; + } else { + newDir = dir; + } + + try { + makeDirectory(newDir); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + refresh(); + } + + public void mkdir() { + Component parent = null; + if (topGUI != null && topGUI instanceof Component) { + parent = (Component) topGUI; + } + Object folder = JOptionPane.showInputDialog(parent, + "Enter folder name", + "Create New Forlder", + JOptionPane.QUESTION_MESSAGE, null, null, + ""); + + if (folder == null || folder.toString().trim().length() == 0) { + return; + } + + String folderName = folder.toString(); + + mkdir(folderName); + } + + /** + * Creates a new directory on the remote server + * @param dir String - the name of the new directory + * @throws Exception + */ + private void makeDirectory(String dir) throws Exception { + try { + sftpClient.mkdir(dir); + } catch (java.io.IOException ex) { + throw new Exception("Error creating directory " + dir + " : " + + ex.getMessage()); + } + } + + private void listCurrentDirectory() throws Exception { + java.util.List fileList = null; + String newDir; + + try { + fileList = sftpClient.ls(); + newDir = sftpClient.pwd(); + } catch (Exception ex) { + //ex.printStackTrace(); + throw ex; + } + + for (int i = 0; i < fileList.size(); i++) { + SftpFile file = (SftpFile) fileList.get(i); + if (file.getFilename().equals(".") && file.isDirectory()) { + fileList.remove(i); + break; + } + } + + // --- Apply file filter + for (int i = fileList.size() - 1; i >= 0; i--) { + SftpFile file = (SftpFile) fileList.get(i); + if (file.isDirectory()) { + continue; + } + + if (Filter == null) { + continue; + //System.err.println("File Filter is not set"); + } else if (Filter.accept(file.getFilename(), false)) { + continue; + } + + fileList.remove(i); + } + + this.currentFileList = fileList; + currentPWD = newDir; + } + + private void setupTable() { + + /* + Object[][] data = new Object[currentFileList.size()][columnNames.length]; + + for (int i = 0; i < currentFileList.size(); i++) { + SftpFile file = (SftpFile) currentFileList.get(i); + FileAttributes attr = file.getAttributes(); + + data[i][0] = file.getFilename(); + + UnsignedInteger64 size = attr.getSize(); + //data[i][1] = size.toString(); + data[i][1] = size; + + //data[i][2] = attr.getModTimeString(); + if (attr.isDirectory()) { + data[i][2] = "Folder"; + } + else if (attr.isLink()) { + data[i][2] = "Link"; + } + else { + data[i][2] = "File"; + } + + //data[i][2] = attr.getModTimeString(); + data[i][3] = attr.getModifiedTime(); + + data[i][4] = attr.getPermissionsString(); + //data[i][3] = attr.getPermissions(); + + } + */ + + //FileBrowserTableModel tModel = new FileBrowserTableModel(columnNames, + // data); + //FileBrowserTableModel tModel = new FileBrowserTableModel(); + + // --- Remember previous sorting status + + if (sorter != null) { + for (int i = 0; i < sortStatus.length; i++) { + sortStatus[i] = sorter.getSortingStatus(i); + } + } + + sorter = new TableSorter(tModel); + + if (sortStatus == null) { + sorter.setSortingStatus(0, TableSorter.ASCENDING); + sortStatus = new int[columnNames.length]; + for (int i = 0; i < sortStatus.length; i++) { + sortStatus[i] = sorter.getSortingStatus(i); + } + } else { + for (int i = 0; i < sortStatus.length; i++) { + sorter.setSortingStatus(i, sortStatus[i]); + } + + } + + table.setModel(sorter); + sorter.setTableHeader(table.getTableHeader()); + + } + + public Component getComponent() { + + if (tableInitiated) { + return table; + } + + currentFileList = null; + + try { + if (sftpClient == null) { + sftpClient = ssh.openSftpClient(); + } + currentFileList = sftpClient.ls(); + currentPWD = sftpClient.pwd(); + for (int i = 0; i < currentFileList.size(); i++) { + SftpFile file = (SftpFile) currentFileList.get(i); + if (file.getFilename().equals(".") && file.isDirectory()) { + currentFileList.remove(i); + break; + } + } + + } catch (Exception ex) { + ex.printStackTrace(); + return null; + } + + table.setModel(tModel); + table.setShowGrid(false); + Dimension dim = table.getIntercellSpacing(); + dim.width += 2; + table.setIntercellSpacing(dim); + initColumnSizes(table); + table.setSelectionMode(tableSelectionMode); + + TableSorter sorter = new TableSorter(tModel); + table.setModel(sorter); + sorter.setTableHeader(table.getTableHeader()); + + // --- Create popup menues + createPopups(); + + topGUI.updateCWD(currentPWD); + + // Store all data.... + + //ArrayList bunch = new ArrayList(); + directories.put(currentPWD, currentFileList); + + //table.setDefaultRenderer(SftpFile.class, new FileNameRenderer(true)); + table.setDefaultRenderer(FileName.class, new FileNameRenderer(true)); + + //table.setDefaultRenderer(UnsignedInteger64.class, + // new UnsignedInteger64Renderer()); + table.setDefaultRenderer(FileSize.class, + new FileSizeRenderer()); + + table.getTableHeader().setToolTipText( + "Click to sort; Shift-Click to sort in reverse order"); + tableInitiated = true; + + return table; + } + + /** + * Creates popup menues + */ + private void createPopups() { + + //Create General popup menu. + generalPopup = new JPopupMenu(); + JMenuItem menuItem = new JMenuItem(upDirectoryItem); + menuItem.addActionListener(this); + generalPopup.add(menuItem); + menuItem = new JMenuItem(RefreshItem); + menuItem.addActionListener(this); + generalPopup.add(menuItem); + + menuItem = new JMenuItem(SelectAllItem); + menuItem.setEnabled(true); + menuItem.addActionListener(this); + generalPopup.add(menuItem); + + menuItem = new JMenuItem(UploadDialogItem); + menuItem.setEnabled(true); + menuItem.addActionListener(this); + generalPopup.add(menuItem); + + menuItem = new JMenuItem(GoToForlderItem); + menuItem.setEnabled(true); + menuItem.addActionListener(this); + generalPopup.add(menuItem); + + menuItem = new JMenuItem(NewForlderItem); + menuItem.setEnabled(true); + menuItem.addActionListener(this); + generalPopup.add(menuItem); + + //Create File popup menu. + filePopup = new JPopupMenu(); + menuItem = new JMenuItem("Open"); + menuItem.setEnabled(false); + //menuItem.addActionListener(this); + filePopup.add(menuItem); + menuItem = new JMenuItem(DownloadItem); + menuItem.setEnabled(true); + menuItem.addActionListener(this); + filePopup.add(menuItem); + + menuItem = new JMenuItem(DeleteItem); + menuItem.setEnabled(true); + menuItem.addActionListener(this); + filePopup.add(menuItem); + + menuItem = new JMenuItem("Rename"); + menuItem.setEnabled(false); + //menuItem.addActionListener(this); + filePopup.add(menuItem); + + menuItem = new JMenuItem(PropertiesItem); + menuItem.setEnabled(true); + menuItem.addActionListener(this); + filePopup.add(menuItem); + + //menuItem.addActionListener(this); + filePopup.add(menuItem); + + //Add listener to components that can bring up popup menus. + table.addMouseListener(this); + + } + + public void setTopGUI(FileBrowserGUIInterface guiInterface) { + topGUI = guiInterface; + } + + /* + * This method picks good column sizes. + * If all column heads are wider than the column's cells' + * contents, then you can just use column.sizeWidthToFit(). + */ + private void initColumnSizes(JTable table) { + FileBrowserTableModel model = (FileBrowserTableModel) table.getModel(); + TableColumn column = null; + Component comp = null; + int headerWidth = 0; + int cellWidth = 0; + Object[] longValues = getLongestValues(table); + TableCellRenderer headerRenderer = + table.getTableHeader().getDefaultRenderer(); + + for (int i = 0; i < table.getColumnCount(); i++) { + column = table.getColumnModel().getColumn(i); + + comp = headerRenderer.getTableCellRendererComponent( + null, column.getHeaderValue(), + false, false, 0, 0); + headerWidth = comp.getPreferredSize().width; + + comp = table.getDefaultRenderer(model.getColumnClass(i)). + getTableCellRendererComponent( + table, longValues[i], + false, false, 0, i); + cellWidth = comp.getPreferredSize().width; + + if (DEBUG) { + logger.info("Initializing width of column " + + i + ". " + + "headerWidth = " + headerWidth + + "; cellWidth = " + cellWidth); + } + + //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead. + column.setPreferredWidth(Math.max(headerWidth, cellWidth)); + } + } + + private Object[] getLongestValues(JTable table) { + + Object[] longValues = new Object[table.getColumnCount()]; + int[] widths = new int[table.getColumnCount()]; + for (int j = 0; j < table.getColumnCount(); j++) { + widths[j] = 0; + } + Component comp = null; + int cellWidth = 0; + FileBrowserTableModel model = (FileBrowserTableModel) table.getModel(); + + for (int i = 0; i < table.getRowCount(); i++) { + for (int j = 0; j < table.getColumnCount(); j++) { + Object value = table.getValueAt(i, j); + + comp = table.getDefaultRenderer(model.getColumnClass(j)). + getTableCellRendererComponent( + table, value, + false, false, 0, j); + cellWidth = comp.getPreferredSize().width; + + if (cellWidth > widths[j]) { + widths[j] = cellWidth; + longValues[j] = value; + } + } + } + return longValues; + } + + /** + * Tries to connect to the host + * @param hostname String + * @param port int + * @throws Exception + */ + public void connectToHost(String hostname, int port) throws Exception { + try { + //ConfigurationLoader.initialize(false); + //SshConnectionProperties properties = new SshConnectionProperties(); + //properties.setHost("hostname"); + //properties.setPort(22); + ssh = new SshClient(); + //ssh.connect(properties); + logger.info("Connecting to " + hostname + ":" + port + "..."); + ssh.connect(hostname, port, new IgnoreHostKeyVerification()); + logger.info("System banner:\n" + ssh.getAuthenticationBanner(500)); + } catch (java.io.IOException ex) { + logger.severe("Cannot connect to " + hostname + ":" + port + ": " + ex.getMessage()); + throw ex; + } + + if (!ssh.isConnected()) { + logger.info("Cannot connect to " + hostname); + throw new Exception("Cannot connect to " + hostname); + } else { + logger.info("Connected to " + hostname + ":" + port); + } + } + + public void disconnect() { + ssh.disconnect(); + } + + /** + * Connect the client to the server using default connection properties. + * This call attempts to connect to the hostname specified on the standard SSH port of 22 and uses all the default connection properties. + * @param hostname String - The hostname of the server to connect + * @throws Exception - If an IO error occurs during the connect operation + */ + public void connect(String hostname) throws Exception { + + try { + connectToHost(hostname, portNumber); + } catch (Exception ex) { + throw new Exception("Cannot connect to host " + hostname + " " + ex.getMessage()); + } + + UserPasswordDialog dialog = new UserPasswordDialog(); + dialog.setLocationRelativeTo(null); + dialog.setAlwaysOnTop(true); + dialog.setMessage("Connecting to " + hostname); + dialog.setMessageVisible(true); + dialog.pack(); + dialog.setVisible(true); + + if (!dialog.isOKPressed()) { + throw new Exception("Authentification cancelation"); + } + + userName = dialog.getUsername(); + password = dialog.getPassword(); + + // Retrieving the available authentication Methods + + try { + + authenticationMethods = getAvailableAuthMethods(userName); + + logger.info("Available Authentication Methods:"); + for (int i = 0; i < authenticationMethods.size(); i++) { + logger.info(authenticationMethods.get(i).toString()); + } + + } catch (Exception ex) { + throw new Exception( + "Unable to get available Authentification Methods for user " + + userName + " " + ex.getMessage()); + } + + AuthenticationResult = AuthenticationProtocolState.FAILED; + + try { + AuthenticationResult = authenticate(userName, password); + } catch (Exception ex) { + throw ex; + } + + if (AuthenticationResult == AuthenticationProtocolState.FAILED) { + System.err.println("The authentication failed"); + throw new Exception("The authentication failed"); + } + + if (AuthenticationResult == AuthenticationProtocolState.PARTIAL) { + logger.info("The authentication succeeded but another" + + "authentication is required"); + throw new Exception("The authentication succeeded but another" + + "authentication is required"); + } + + sftpClient = ssh.openSftpClient(); + } + + public void connect(String hostname, String username) throws Exception { + + try { + connectToHost(hostname, portNumber); + } catch (Exception ex) { + throw new Exception("Cannot connect to host " + hostname + " " + + ex.getMessage()); + } + + UserPasswordDialog dialog = new UserPasswordDialog(); + dialog.setUsername(username); + if (username.trim().length() > 0) { + dialog.setUsernameEnabled(false); + } else { + dialog.setUsernameEnabled(true); + } + dialog.setLocationRelativeTo(null); + dialog.setAlwaysOnTop(true); + dialog.setVisible(true); + + if (!dialog.isOKPressed()) { + throw new Exception("Authentification cancelation"); + } + + userName = dialog.getUsername(); + password = dialog.getPassword(); + + // Retrieving the available authentication Methods + + try { + + authenticationMethods = getAvailableAuthMethods(userName); + + logger.info("Available Authentication Methods:"); + for (int i = 0; i < authenticationMethods.size(); i++) { + logger.info(authenticationMethods.get(i).toString()); + } + + } catch (Exception ex) { + throw new Exception( + "Unable to get available Authentification Methods for user " + + userName + " " + ex.getMessage()); + } + + AuthenticationResult = AuthenticationProtocolState.FAILED; + + try { + AuthenticationResult = authenticate(userName, password); + } catch (Exception ex) { + throw ex; + } + + if (AuthenticationResult == AuthenticationProtocolState.FAILED) { + System.err.println("The authentication failed"); + throw new Exception("The authentication failed"); + } + + if (AuthenticationResult == AuthenticationProtocolState.PARTIAL) { + logger.info("The authentication succeeded but another" + + "authentication is required"); + throw new Exception("The authentication succeeded but another" + + "authentication is required"); + } + + } + + private int authenticateUser(String username, char[] pass) throws Exception { + + // --- Get authentication methods + + try { + + this.authenticationMethods = getAvailableAuthMethods(username); + + if (DEBUG) { + logger.info("Available Authentication Methods:"); + for (int i = 0; i < authenticationMethods.size(); i++) { + //logger.info(authenticationMethods.get(i).toString()); + logger.info((i + 1) + " : " + authenticationMethods.get(i).toString()); + } + } + + } catch (Exception ex) { + throw new Exception( + "Unable to get available Authentification Methods for user " + + username + " " + ex.getMessage()); + } + + // --- Athenticate user + + int AuthResult = AuthenticationProtocolState.FAILED; + + try { + AuthResult = authenticate(username, pass); + } catch (Exception ex) { + throw ex; + } + + if (AuthResult == AuthenticationProtocolState.FAILED) { + System.err.println("The authentication failed"); + throw new Exception("The authentication failed"); + } + + if (AuthResult == AuthenticationProtocolState.PARTIAL) { + System.err.println("The authentication succeeded but another" + + "authentication is required"); + throw new Exception("The authentication succeeded but another" + + "authentication is required"); + } + return AuthResult; + } + + /** + * Tries to reconnect + * @throws Exception + */ + public void reconnect() throws Exception { + try { + connect(getHost(), getUsername(), getPassword(), getPort()); + } catch (Exception ex) { + logger.severe("Cannot reconnect to the host " + getHost() + ":" + getPort() + " as " + getUsername() + ": " + ex.getMessage()); + throw ex; + } + } + + /** + * Connect the client to the server using default connection properties. + * This call attempts to connect to the hostname specified on the port of 22 + * and uses all the default connection properties. + * @param hostname String + * @param username String + * @param password char[] + * @param port int + * @throws Exception + */ + public void connect(String hostname, String username, char[] pass, int port) throws Exception { + try { + logger.info("Connecting to " + hostname + ":" + port); + connectToHost(hostname, port); + logger.info("Connection to " + hostname + ":" + port + " established"); + portNumber = port; + } catch (Exception ex) { + logger.severe("Cannot connect to " + hostname + ":" + port + ": " + ex.getMessage()); + throw new Exception("Cannot connect to host " + hostname + " " + ex.getMessage()); + } + + try { + logger.info("Authenticating " + username + " on " + hostname + ":" + port + "..."); + AuthenticationResult = authenticateUser(username, pass); + } catch (Exception ex) { + throw new Exception("Cannot authenticate user " + username + " " + ex.getMessage()); + } + + sftpClient = ssh.openSftpClient(); + } + + /** + * Changes the working directory on the remote server. + * @param directory String - the new working directory + * @throws Exception + */ + public void setRemoteDirectory(String directory) throws Exception { + try { + this.sftpClient.cd(directory); + } catch (Exception ex) { + //ex.printStackTrace(); + throw ex; + } + } + + public static void main(String[] args) { + SFTPBrowser localfilebrowser = new SFTPBrowser(); + } + + /** + * Returns the list of available authentication methods for a given user. + * @param username String The name of the account for which you require the available authentication methods + * @return List - A list of Strings, for example "password", "publickey" & "keyboard-interactive" + * @throws Exception If an IO error occurs during the operation + */ + public java.util.List getAvailableAuthMethods(String username) throws + Exception { + java.util.List available = null; + // Retrieving the available authentication Methods + + // It is possible at any time after the connection has been established + // and before authentication has been completed to request a list of authentication methods that can be used. + // The getAvailableAuthMethods method returns a list of authentication method names. + + try { + available = ssh.getAvailableAuthMethods(username); + } catch (java.io.IOException ex) { + //System.err.println(); + ex.printStackTrace(); + throw ex; + } + return available; + } + + /** + * Authenticate the user on the remote host. + * @return int - The authentication result + */ + public int authenticate(String username, char[] pass) throws Exception { + + int result = AuthenticationProtocolState.FAILED; + + try { + if (authenticationMethods.contains("password")) { + logger.info("Athenticating " + username + " using Password Authentication Client"); + PasswordAuthenticationClient pwd = new PasswordAuthenticationClient(); + + //PasswordAuthenticationDialog dialog = new PasswordAuthenticationDialog(new + // Frame()); + //dialog.setVisible(true); + + //pwd.setAuthenticationPrompt(dialog); // ??? + + pwd.setUsername(username); + + pwd.setPassword(String.valueOf(pass)); + + result = ssh.authenticate(pwd); + + } else if (authenticationMethods.contains("keyboard-interactive")) { + logger.info("Athenticating " + username + " using keyboard interactive Client"); + /* + * Create the keyboard-interactive instance + */ + KBIAuthenticationClient kbi = new KBIAuthenticationClient(); + // Get the users name + //System.out.print("Username? "); + // Read the password + //username = reader.readLine(); + + kbi.setUsername(username); + password = pass; + + // Set the callback interface + kbi.setKBIRequestHandler(new KBIRequestHandler() { + + public void showPrompts(String name, String instructions, + KBIPrompt[] prompts) { + logger.info("Name: " + name); + logger.info("Instructions: " + instructions); + String response; + if (prompts != null) { + for (int i = 0; i < prompts.length; i++) { + //if (DEBUG) { + logger.info("Prompt " + (i + 1) + ": " + prompts[i].getPrompt()); + //} + + if (prompts[i].getPrompt().toLowerCase().indexOf("password") != -1 + || prompts[i].getPrompt().toLowerCase().indexOf("pass") != -1) { + response = String.valueOf(password); + } else { + Object obj = JOptionPane.showInputDialog(null, + prompts[i].getPrompt(), "Response prompt", + JOptionPane.QUESTION_MESSAGE, null, null, ""); + response = obj.toString(); + } + //try { + //response = reader.readLine(); + + prompts[i].setResponse(response); + + //} + //catch (IOException ex) { + // prompts[i].setResponse(""); + // ex.printStackTrace(); + //} + } + } + } + }); + + // Try the authentication + result = ssh.authenticate(kbi); + } + } catch (java.io.IOException ex) { + throw new Exception("Cannot authnenticate user " + username + " : " + ex.getMessage()); + } + + return result; + } + + public void refresh() { + if (DEBUG) { + logger.info("Refreshing directory: " + currentPWD); + } + + try { + listCurrentDirectory(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, + "Unable to list directory " + + currentPWD + " : " + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + setupTable(); + directories.put(currentPWD, currentFileList); + topGUI.updateFieView(table); + topGUI.updateCWD(currentPWD); + } + + public void upDirectory() { + try { + changeRelativePath(".."); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + topGUI.updateFieView(table); + topGUI.updateCWD(currentPWD); + + } + + private void changeAbsolutePath(String newDir) throws Exception { + try { + setRemoteDirectory(newDir); + } catch (Exception ex) { + throw new Exception("Unable to change directory to " + + newDir + " : " + ex.getMessage()); + } + + if (directories.containsKey(newDir)) { + currentFileList = (java.util.List) directories.get(newDir); + currentPWD = newDir; + logger.info("Retrieving old file list for " + currentPWD); + } else { + + try { + listCurrentDirectory(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, + "Unable to list directory " + + newDir + " : " + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + logger.info("Adding directory listing for " + currentPWD); + directories.put(currentPWD, currentFileList); + } + + setupTable(); + + } + + private void changeRelativePath(String Dir) throws Exception { + if (Dir.equalsIgnoreCase(".")) { + return; // The same directory + } + String newDir; + if (Dir.equalsIgnoreCase("..")) { + newDir = "/"; + if (currentPWD.lastIndexOf("/") != -1) { + newDir = currentPWD.substring(0, currentPWD.lastIndexOf("/")); + } + + if (newDir.length() == 0) { + newDir = "/"; + } + + } else { + newDir = currentPWD + "/" + Dir; + } + + try { + changeAbsolutePath(newDir); + } catch (Exception ex) { + throw ex; + } + + } + + public void mousePressed(MouseEvent e) { + maybeShowPopup(e); + } + + public void mouseReleased(MouseEvent e) { + maybeShowPopup(e); + } + + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1) { + logger.info(" double click"); + if (table.getSelectedRowCount() == 0 + || table.getSelectedRowCount() > 1) { + return; + } + int n = table.getSelectedRow(); + String type = (String) table.getValueAt(n, 2); // Get type of item + + if (type.equalsIgnoreCase("Folder")) { + String item = null; + try { + item = this.getFileName(table.getValueAt(n, 0)); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + + try { + changeRelativePath(item); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + topGUI.updateFieView(table); + topGUI.updateCWD(currentPWD); + } + } + } + + /** + * Returns absolute paths of all selected items + * @return String[] + */ + public String[] getSelectedItems() { + if (table.getSelectedRowCount() == 0) { + return null; + } + + int[] rows = table.getSelectedRows(); + String[] items = new String[rows.length]; + for (int i = 0; i < rows.length; i++) { + int n = rows[i]; + try { + items[i] = getFileName(table.getValueAt(n, 0)); + } catch (Exception ex) { + items[i] = null; + System.err.println("INTERNAL ERROR: getSelectedItems: " + ex.getMessage()); + } + } + return items; + } + + /** + * Returns selected files (ignores selected directories, if any) + * @return String[] + */ + public String[] getSelectedFiles() { + if (table.getSelectedRowCount() == 0) { + return null; + } + + int[] rows = table.getSelectedRows(); + String[] items = new String[rows.length]; + for (int i = 0; i < rows.length; i++) { + int n = rows[i]; + String type = (String) table.getValueAt(n, 2); // Get type of item + + if (type.equalsIgnoreCase("Folder")) { // Ignore directories + continue; + } + + try { + items[i] = getFileName(table.getValueAt(n, 0)); + } catch (Exception ex) { + items[i] = null; + System.err.println("INTERNAL ERROR: getSelectedItems: " + ex.getMessage()); + } + } + return items; + } + + /** + * Returns selected directories (ignores selected files, if any) + * @return String[] + */ + public String[] getSelectedFolders() { + if (table.getSelectedRowCount() == 0) { + return null; + } + + int[] rows = table.getSelectedRows(); + String[] items = new String[rows.length]; + for (int i = 0; i < rows.length; i++) { + int n = rows[i]; + String type = (String) table.getValueAt(n, 2); // Get type of item + + if (!type.equalsIgnoreCase("Folder")) { // Ignore directories + continue; + } + + try { + items[i] = getFileName(table.getValueAt(n, 0)); + } catch (Exception ex) { + items[i] = null; + System.err.println("INTERNAL ERROR: getSelectedItems: " + ex.getMessage()); + } + } + return items; + } + + private void maybeShowPopup(MouseEvent e) { + if (e.isPopupTrigger()) { + if (table.getSelectedRowCount() == 0) { + generalPopup.show(e.getComponent(), e.getX(), e.getY()); + } else { + filePopup.show(e.getComponent(), + e.getX(), e.getY()); + } + } + } + + /** + * + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ + private class FileBrowserTableModel + extends AbstractTableModel { + //String[] columnNames = null; + + boolean DEBUG = true; + //Object[][] data = null; + + public FileBrowserTableModel() { + } + + /* + public FileBrowserTableModel(String[] column_names, Object[][] new_data) { + columnNames = column_names; + data = new_data; + } + */ + public int getColumnCount() { + return columnNames.length; + } + + public int getRowCount() { + /* + if (data == null) { + return 0; + } + return data.length; + */ + if (currentFileList == null) { + return 0; + } + return currentFileList.size(); + } + + public String getColumnName(int col) { + return columnNames[col]; + } + + public Object getValueAt(int row, int col) { + //return data[row][col]; + SftpFile file = (SftpFile) currentFileList.get(row); + if (col == 0) { // File name + //return file.getFilename(); + int type = FileName.FILE; + if (file.isDirectory()) { + type = FileName.FOLDER; + } + FileName fname = null; + try { + fname = new FileName(file.getFilename(), type); + } catch (Exception ex) { + } + return fname; + } + + FileAttributes attr = file.getAttributes(); + + if (col == 1) { // Size + if (file.isDirectory()) { + return new FileSize("0"); + } else { + //UnsignedInteger64 size = attr.getSize(); + return new FileSize(attr.getSize().bigIntValue()); + } + } + + if (col == 2) { // Type + if (attr.isDirectory()) { + return "Folder"; + } else { + return "File"; + } + + } + + if (col == 3) { // Modified time + return attr.getModTimeString(); + } + + if (col == 4) { + return attr.getPermissionsString(); + } + + System.err.println("INTERNAL ERROR: Out of columns"); + return ""; + } + + /* + * JTable uses this method to determine the default renderer/ + * editor for each cell. If we didn't implement this method, + * then the last column would contain text ("true"/"false"), + * rather than a check box. + */ + public Class getColumnClass(int c) { + return getValueAt(0, c).getClass(); + } + + /* + * Don't need to implement this method unless your table's + * editable. + */ + public boolean isCellEditable(int row, int col) { + //Note that the data/cell address is constant, + //no matter where the cell appears onscreen. + + //if (col < 2) { + return false; + //} + //else { + // return true; + //} + } + + /* + * Don't need to implement this method unless your table's + * data can change. + */ + public void setValueAt(Object value, int row, int col) { + if (DEBUG) { + logger.info("Setting value at " + row + "," + col + + " to " + value + + " (an instance of " + + value.getClass() + ")"); + } + + data[row][col] = value; + fireTableCellUpdated(row, col); + + if (DEBUG) { + logger.info("New value of data:"); + printDebugData(); + } + } + + private void printDebugData() { + int numRows = getRowCount(); + int numCols = getColumnCount(); + + for (int i = 0; i < numRows; i++) { + System.out.print(" row " + i + ":"); + for (int j = 0; j < numCols; j++) { + System.out.print(" " + data[i][j]); + } + System.out.print("\n"); + } + logger.info("--------------------------"); + } + } + + class FileTranferWorker + extends cct.tools.SwingWorker implements FileTransferProgress { + + File[] filesToUpload = null; + java.util.List filesToDownload = null; + final int MAX = 10; + //JLabel msgLabel = null; + double totalBytes; + TransferProgressDialog dialog = null; + String pwd; + String localDirectory; + String currentLocalFile; + boolean jobCancelled = false; + Object[] options = { + "Continue", "Cancel Transfer", "Ignore Errors"}; + ConfirmFileOverwriteDialog overdial = null; + DateFormat df = DateFormat.getDateInstance(DateFormat.LONG); + NumberFormat nf = NumberFormat.getInstance(); + long start_time; + + FileTranferWorker(File[] files, String PWD) { + super(); + filesToUpload = files; + pwd = PWD; + } + + FileTranferWorker(File file, String PWD) { + super(); + filesToUpload = new File[1]; + filesToUpload[0] = file; + pwd = PWD; + } + + FileTranferWorker(java.util.List file_list, String localDir) { + super(); + filesToDownload = file_list; + localDirectory = localDir; + } + + public Object construct() { + + String result = "done"; + dialog = new TransferProgressDialog(new Frame(), "File transfer progress", false); + dialog.setAlwaysOnTop(true); + dialog.setLocationRelativeTo(null); + dialog.setProgress(0); + dialog.setMaximum(MAX); + dialog.cancelButton.addActionListener(new ActionListener() { + + public void actionPerformed(ActionEvent e) { + cancelTranfer(); + } + }); + + /* + Object[] comp = { + msgLabel, progressBar}; + Object[] options = { + "Cancel"}; + + + JOptionPane pane = new JOptionPane(comp, + JOptionPane.DEFAULT_OPTION, + JOptionPane.INFORMATION_MESSAGE, + null, + options, + options[0]); + + dialog = pane.createDialog(null, "File Transfer Progress"); + */ + + // --- Download + if (filesToDownload != null) { + result = downloadFiles(); + } // Upload + else { + result = this.uploadFiles(); + } + + dialog.setVisible(false); + return "done"; + } + + /** + * Downloads files + * @return String + */ + private String downloadFiles() { + boolean ignoreErrors = false; + boolean yes_to_all = false; + boolean no_to_all = false; + + for (int i = 0; i < filesToDownload.size(); i++) { + if (jobCancelled) { + return "cancelled"; + } + + SftpFile file = (SftpFile) filesToDownload.get(i); + + //currentLocalFile = localDirectory + File.separator + + currentLocalFile = localDirectory + "/" + file.getFilename(); + try { + if (file.isFile()) { + if (DEBUG) { + logger.info("Transfering: " + + file.getAbsolutePath() + " to " + + currentLocalFile); + } + + if (!yes_to_all) { + File newFile = new File(currentLocalFile); + if (newFile.exists()) { + if (no_to_all) { + continue; + } + int n = showConfirmOverwrite(newFile, file); + if (n == ConfirmFileOverwriteDialog.YES) { + } else if (n == ConfirmFileOverwriteDialog.YES_TO_ALL) { + yes_to_all = true; + } else if (n == ConfirmFileOverwriteDialog.NO) { + continue; + } else if (n == ConfirmFileOverwriteDialog.NO_TO_ALL) { + no_to_all = true; + continue; + } else { // Cancel + this.cancelTranfer(); + return "cancelled"; + } + } + } + + FileAttributes attr = sftpClient.get(file.getAbsolutePath(), + localDirectory + + //File.separator + + "/" + + file.getFilename(), this); + } else if (file.isDirectory()) { + if (DEBUG) { + logger.info("Transfering: " + + file.getAbsolutePath() + " to " + + localDirectory); + } + boolean recurse = true; + boolean sync = true; + boolean commit = true; + DirectoryOperation dirop = sftpClient.copyRemoteDirectory( + file.getAbsolutePath(), localDirectory, recurse, sync, commit, + this); + } + + if (jobCancelled) { + return "cancelled"; + } + } catch (Exception ex) { + if (jobCancelled) { + return "cancelled"; + } + if (ignoreErrors) { + continue; + } + int n = JOptionPane.showOptionDialog(null, + "Error: " + ex.getMessage(), + "File Transfer Error", + JOptionPane.YES_NO_CANCEL_OPTION, + JOptionPane.ERROR_MESSAGE, null, + options, options[1]); + if (n == JOptionPane.YES_OPTION) { + continue; + } else if (n == JOptionPane.NO_OPTION) { + cancelTranfer(); + return "cancelled"; + } else if (n == JOptionPane.CANCEL_OPTION) { + ignoreErrors = true; + continue; + } + } + } + return "done"; + } + + /** + * Uploads files + * @return String + */ + private String uploadFiles() { + boolean ignoreErrors = false; + boolean yes_to_all = false; + boolean no_to_all = false; + for (int i = 0; i < filesToUpload.length; i++) { + if (jobCancelled) { + return "cancelled"; + } + + currentLocalFile = filesToUpload[i].getAbsolutePath(); + if (DEBUG) { + logger.info("Transfering: " + currentLocalFile); + } + + try { + // --- Copy file + if (filesToUpload[i].isFile()) { + String remoteFile = pwd + "/" + filesToUpload[i].getName(); + try { + FileAttributes fa = sftpClient.stat(remoteFile); + if (fa.isDirectory()) { + JOptionPane.showMessageDialog(null, + "Folder " + remoteFile + + " already exists on remote host\n" + + "Local file " + + currentLocalFile + + " is not uploaded", + "Warning", + JOptionPane.WARNING_MESSAGE); + continue; + } else if (fa.isFile()) { + int n = showConfirmOverwrite(remoteFile, fa, + filesToUpload[i]); + if (n == ConfirmFileOverwriteDialog.YES) { + } else if (n == ConfirmFileOverwriteDialog.YES_TO_ALL) { + yes_to_all = true; + } else if (n == ConfirmFileOverwriteDialog.NO) { + continue; + } else if (n == ConfirmFileOverwriteDialog.NO_TO_ALL) { + no_to_all = true; + continue; + } else { // Cancel + this.cancelTranfer(); + return "cancelled"; + } + + } + } catch (Exception ex) { // if an IO error occurs or the file does not exist + // Ignore it for now + } + sftpClient.put(currentLocalFile, this); + } // --- Copy directory + else if (filesToUpload[i].isDirectory()) { + boolean recurse = true; + boolean sync = true; + boolean commit = true; + sftpClient.copyLocalDirectory(currentLocalFile, pwd, recurse, + sync, commit, this); + } + + if (jobCancelled) { + return "cancelled"; + } + } catch (Exception ex) { + if (jobCancelled) { + return "cancelled"; + } + if (ignoreErrors) { + continue; + } + int n = JOptionPane.showOptionDialog(null, + "Error: " + ex.getMessage(), + "File Transfer Error", + JOptionPane.YES_NO_CANCEL_OPTION, + JOptionPane.ERROR_MESSAGE, null, + options, options[1]); + if (n == JOptionPane.YES_OPTION) { + continue; + } else if (n == JOptionPane.NO_OPTION) { + cancelTranfer(); + return "cancelled"; + } else if (n == JOptionPane.CANCEL_OPTION) { + ignoreErrors = true; + continue; + } + } + } + return "done"; + } + + /** + * Cancels file transfer + */ + public void cancelTranfer() { + if (DEBUG) { + logger.info("Transfer cancelled..."); + } + jobCancelled = true; + dialog.setVisible(false); + interrupt(); + } + + /** + * Start the worker thread. + */ + public void start() { + + super.start(); + } + + /** + * Called on the event dispatching thread (not on the worker thread) + * after the construct method has returned. + */ + public void finished() { + if (pwd != null && pwd.equals(currentPWD)) { + refresh(); + } + } + + public void completed() { + dialog.setVisible(false); + } + + public boolean isCancelled() { + return jobCancelled; + } + + public void progressed(long bytesSoFar) { + if (jobCancelled) { + return; + } + + // Get elapsed time in milliseconds + long elapsedTimeMillis = System.currentTimeMillis() - start_time; + + // Get elapsed time in seconds + double elapsedTimeSec = (double) elapsedTimeMillis / 1000.0; + + double partSoFar = (double) bytesSoFar / totalBytes; + + if (elapsedTimeSec > 5.0) { // If less than 5 sec - ignore + double timeLeft = elapsedTimeSec * (1.0 / partSoFar - 1.0); + if (timeLeft > 86400.0) { // Number of seconds in a day + int days = (int) (timeLeft / 86400.0); + int hours = (int) (timeLeft - (double) days * 86400.0); + dialog.setTime(days + " days and " + hours + " hours left"); + } else if (timeLeft > 3600.0) { // Number of seconds in hour + int hours = (int) (timeLeft / 3600.0); + int minutes = (int) (timeLeft - (double) hours * 3600.0); + dialog.setTime(hours + " hours and " + minutes + + " minutes left"); + } else if (timeLeft > 60.0) { // Number of seconds in minute + int minutes = (int) (timeLeft / 60.0); + int seconds = (int) (timeLeft - (double) minutes * 60.0); + dialog.setTime(minutes + " minutes and " + seconds + + " seconds left"); + } else { + dialog.setTime(((int) timeLeft) + " seconds left"); + } + + } + + //if (DEBUG) { + // logger.info("SO far: " + bytesSoFar); + //} + + dialog.setProgress((int) (partSoFar * (double) MAX)); + } + + public void started(long bytesTotal, String remoteFile) { + // Get current time + start_time = System.currentTimeMillis(); + totalBytes = (double) bytesTotal; + String size; + long n1024 = 1024; + if (bytesTotal / (1024 * 1024) > 0) { + size = String.valueOf(bytesTotal / (1024 * 1024)) + " Mb"; + } else if (bytesTotal / (1024) > 0) { + size = String.valueOf(bytesTotal / (1024)) + " Kb"; + } else { + size = String.valueOf(bytesTotal) + " b"; + } + + // --- Download + if (filesToDownload != null) { + dialog.setFrom("From: " + remoteFile); + dialog.setTo("To: " + currentLocalFile); + } // Upload + else { + dialog.setFrom("From: " + currentLocalFile); + dialog.setTo("To: " + remoteFile); + } + + dialog.setProgress(0); + dialog.setTime(""); + + dialog.setVisible(true); + } + + /** + * Dialog for download + * @param existingFile File + * @param fileToDownload SftpFile + * @return int + */ + private int showConfirmOverwrite(File existingFile, + SftpFile fileToDownload) { + if (overdial == null) { + overdial = new ConfirmFileOverwriteDialog(); + overdial.setLocationRelativeTo(null); + overdial.setAlwaysOnTop(true); + } + + Date date = new Date(existingFile.lastModified()); + + FileAttributes attr = fileToDownload.getAttributes(); + UnsignedInteger32 modtime = attr.getModifiedTime(); + UnsignedInteger64 size2 = attr.getSize(); + Date date2 = new Date(modtime.longValue()); + + return overdial.showDialog(existingFile.getAbsolutePath(), + existingFile.getName(), + nf.format(existingFile.length()) + + " bytes", + df.format(date), + nf.format(size2.doubleValue()) + + " bytes", + attr.getModTimeString()); + //df.format(date2)); + } + + private int showConfirmOverwrite(String existingFile, FileAttributes attr, File fileToUpload) { + if (overdial == null) { + overdial = new ConfirmFileOverwriteDialog(); + overdial.setLocationRelativeTo(null); + overdial.setAlwaysOnTop(true); + } + + Date date = new Date(fileToUpload.lastModified()); + + UnsignedInteger32 modtime = attr.getModifiedTime(); + UnsignedInteger64 size2 = attr.getSize(); + Date date2 = new Date(modtime.longValue()); + + String fileName = existingFile.lastIndexOf("/") != -1 + ? existingFile.substring(existingFile.lastIndexOf("/") + 1, + existingFile.length()) + : existingFile; + + return overdial.showDialog(existingFile, fileName, attr.getModTimeString(), nf.format(size2.doubleValue()) + " bytes", + df.format(date), nf.format(fileToUpload.length()) + " bytes"); + + //df.format(date2)); + } + } +} diff --git a/src/main/java/cct/tools/filebrowser/SFTPBrowserFrame.java b/src/main/java/cct/tools/filebrowser/SFTPBrowserFrame.java new file mode 100644 index 0000000..3004804 --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/SFTPBrowserFrame.java @@ -0,0 +1,170 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.awt.BorderLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JToolBar; + +import cct.interfaces.FileBrowserInterface; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * It's a marionette class which is used by a class implementing ShadowManagerInterface interface + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class SFTPBrowserFrame + extends JFrame implements ActionListener { + BorderLayout borderLayout1 = new BorderLayout(); + JFileBrowserPanel jFileBrowserPanel1 = new JFileBrowserPanel(); + JMenuBar jMenuBar1 = new JMenuBar(); + JMenu fileMenu = new JMenu(); + JMenu jMenu1 = new JMenu(); + JMenu connectMenu = new JMenu(); + JMenuItem exitMenuItem = new JMenuItem(); + JToolBar jToolBar1 = new JToolBar(); + + ShadowManagerInterface shadowManager = null; + JMenuItem editHostsMenuItem = new JMenuItem(); + public SFTPBrowserFrame(ShadowManagerInterface shadow_manager) { + setShadowManager(shadow_manager); + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public void setShadowManager(ShadowManagerInterface shadow_manager) { + shadowManager = shadow_manager; + } + + private void jbInit() throws Exception { + getContentPane().setLayout(borderLayout1); + jMenu1.setText("File"); + connectMenu.setText("Connect to"); + exitMenuItem.setText("Exit"); + exitMenuItem.addActionListener(this); + this.setJMenuBar(jMenuBar1); + editHostsMenuItem.setText("Edit Host List"); + editHostsMenuItem.addActionListener(this); + jMenuBar1.add(jMenu1); + this.getContentPane().add(jFileBrowserPanel1, BorderLayout.CENTER); + this.getContentPane().add(jToolBar1, BorderLayout.NORTH); + jMenu1.add(connectMenu); + jMenu1.add(editHostsMenuItem); + jMenu1.addSeparator(); + jMenu1.add(exitMenuItem); + jMenuBar1.add(jMenu1); + + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent we) { + shadowManager.processExit(we.getWindow()); + } + }); + + } + + public void setKnownHosts(String[] hosts) { + connectMenu.removeAll(); + for (int i = 0; i < hosts.length; i++) { + JMenuItem item = new JMenuItem(hosts[i]); + item.setActionCommand(hosts[i]); + item.addActionListener(this); + connectMenu.add(item); + } + } + + @Override + public void actionPerformed(ActionEvent e) { + if (shadowManager == null) { + System.err.println("No Shadow Manager is set..."); + return; + } + + if (e.getSource() == exitMenuItem) { + shadowManager.processExit(this); + return; + } + else if (e.getSource() == editHostsMenuItem) { + shadowManager.processEditHosts(this); + return; + } + + String command = e.getActionCommand(); + if (shadowManager == null) { + System.err.println("No Shadow Manager is set..."); + return; + } + try { + shadowManager.processConnection(command, this); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + } + } + + public void setFileBrowser(FileBrowserInterface fileBrowser) { + jFileBrowserPanel1.setFileBrowser(fileBrowser); + jFileBrowserPanel1.repaint(); + pack(); + } + + public static void main(String[] args) { + SFTPBrowserFrame sftpbrowserframe = new SFTPBrowserFrame(null); + } +} diff --git a/src/main/java/cct/tools/filebrowser/SFTPFileChooserDialog.java b/src/main/java/cct/tools/filebrowser/SFTPFileChooserDialog.java new file mode 100644 index 0000000..2e88d85 --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/SFTPFileChooserDialog.java @@ -0,0 +1,730 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.io.File; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.ListSelectionModel; +import javax.swing.SwingConstants; + +import cct.interfaces.FileBrowserInterface; +import cct.tools.FileFilterImpl; + +import com.sshtools.j2ssh.FileTransferProgress; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class SFTPFileChooserDialog + extends JDialog implements ActionListener, ShadowClientInterface, SelectionInfoInterface { + final int MAX = 10; + boolean jobCancelled = false; + long start_time; + double totalBytes; + + JPanel panel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JFileBrowserPanel fileBrowserPanel1 = new JFileBrowserPanel(); + JPanel jPanel1 = new JPanel(); + JButton cancelButton = new JButton(); + JButton loadButton = new JButton(); + JLabel jLabel1 = new JLabel(); + JLabel jLabel2 = new JLabel(); + JTextField fileTextField = new JTextField(); + JComboBox filterComboBox = new JComboBox(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + + ImageIcon help = new ImageIcon(cct.resources.Resources.class. + getResource("cct/images/icons16x16/help.png")); + + FileFilterImpl[] fileFilters = null; + boolean loadPressed = false; + File temporaryLocalFile = null; + FileBrowserInterface browser; + + JButton loadHelpButton = new JButton(); + JButton fileTypesHelpButton = new JButton(); + + public SFTPFileChooserDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + @Override + public void setSelectedFileName(String file_name) { + fileTextField.setText(file_name); + } + + public SFTPFileChooserDialog() { + this(new Frame(), "SFTP File Chooser Dialog", false); + } + + @Override + public Component getComponent() { + return this; + } + + @Override + public void setKnownHosts(String[] hosts) { + + } + + @Override + public void setFileBrowser(String host, String username, FileBrowserInterface file_browser) { + browser = file_browser; + fileBrowserPanel1.setFileBrowser(browser); + if (browser != null) { + browser.setSelectionInfoInterface(this); + Component comp = browser.getComponent(); + fileBrowserPanel1.setBackground(comp.getForeground()); + panel1.setBackground(comp.getForeground()); + } + + fileBrowserPanel1.repaint(); + pack(); + + } + + public void setFileBrowser(FileBrowserInterface fileBrowser) { + browser = fileBrowser; + fileBrowserPanel1.setFileBrowser(fileBrowser); + if (browser != null) { + browser.setSelectionInfoInterface(this); + Component comp = browser.getComponent(); + fileBrowserPanel1.setBackground(comp.getForeground()); + panel1.setBackground(comp.getForeground()); + } + fileBrowserPanel1.repaint(); + pack(); + } + + public void setFileFilters(FileFilterImpl[] filters) { + fileFilters = filters; + filterComboBox.removeAllItems(); + filterComboBox.setEnabled(false); + //try { + for (int i = 0; i < fileFilters.length; i++) { + filterComboBox.addItem(fileFilters[i].getDescription()); + } + //} catch ( Exception ex ) { + // ex.printStackTrace(); + //} + filterComboBox.setEnabled(true); + if (filterComboBox.getItemCount() > 0) { + filterComboBox.setSelectedIndex(0); + if (browser != null) { + browser.setFileFilter(fileFilters[filterComboBox.getSelectedIndex()]); + } + } + } + + public int getSeletedFilterIndex() { + return filterComboBox.getSelectedIndex(); + } + + public String getSeletedFilterDescription() { + return filterComboBox.getSelectedItem().toString(); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + cancelButton.setToolTipText(""); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new SFTPFileChooserDialog_cancelButton_actionAdapter(this)); + loadButton.setToolTipText(""); + loadButton.setText("Load"); + loadButton.addActionListener(new SFTPFileChooserDialog_loadButton_actionAdapter(this)); + jLabel1.setToolTipText(""); + jLabel1.setText("Files of type:"); + jLabel2.setToolTipText(""); + jLabel2.setText("File name:"); + fileTextField.setToolTipText("Type file name or file template and press Enter"); + fileTextField.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + fileTextField_actionPerformed(e); + } + }); + jPanel1.setLayout(gridBagLayout1); + filterComboBox.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + filterComboBox_itemStateChanged(e); + } + }); + loadHelpButton.setMaximumSize(new Dimension(23, 23)); + loadHelpButton.setMinimumSize(new Dimension(23, 23)); + loadHelpButton.setPreferredSize(new Dimension(23, 23)); + loadHelpButton.setToolTipText("Help on loading files"); + loadHelpButton.setHorizontalTextPosition(SwingConstants.CENTER); + loadHelpButton.setIcon(help); + loadHelpButton.setText(""); + loadHelpButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + loadHelpButton_actionPerformed(e); + } + }); + + fileTypesHelpButton.setMaximumSize(new Dimension(23, 23)); + fileTypesHelpButton.setMinimumSize(new Dimension(23, 23)); + fileTypesHelpButton.setPreferredSize(new Dimension(23, 23)); + fileTypesHelpButton.setToolTipText("Help on file types"); + fileTypesHelpButton.setHorizontalTextPosition(SwingConstants.CENTER); + fileTypesHelpButton.setIcon(help); + fileTypesHelpButton.setText(""); + fileTypesHelpButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + fileTypesHelpButton_actionPerformed(e); + } + }); + filterComboBox.setToolTipText("Select File format"); + + getContentPane().add(panel1); + panel1.add(fileBrowserPanel1); + panel1.add(jPanel1, BorderLayout.SOUTH); + jPanel1.add(jLabel2, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(jLabel1, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(filterComboBox, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(fileTextField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(loadHelpButton, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(loadButton, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(cancelButton, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(fileTypesHelpButton, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent we) { + loadPressed = false; + setVisible(false); + } + }); + + } + + @Override + public void actionPerformed(ActionEvent e) { + + } + + public boolean isLoadPressed() { + return loadPressed; + } + + public void cancelButton_actionPerformed(ActionEvent e) { + setVisible(false); + loadPressed = false; + } + + /** + * Sets table selection mode. Valid values: ListSelectionModel.SINGLE_SELECTION, + * ListSelectionModel.SINGLE_INTERVAL_SELECTION, and ListSelectionModel.MULTIPLE_INTERVAL_SELECTION. + * Otherwise sets ListSelectionModel.SINGLE_SELECTION + * @param mode int + */ + public void setSelectionMode(int mode) { + switch (mode) { + case ListSelectionModel.SINGLE_SELECTION: + case ListSelectionModel.SINGLE_INTERVAL_SELECTION: + case ListSelectionModel.MULTIPLE_INTERVAL_SELECTION: + fileBrowserPanel1.setSelectionMode(mode); + return; + } + System.err.println(this.getClass().getCanonicalName() + " : unknown selection mode. Ignored..."); + fileBrowserPanel1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + } + + public void loadButton_actionPerformed(ActionEvent e) { + loadPressed = true; + String fileName = fileTextField.getText().trim(); + if (fileName.length() < 1) { + JOptionPane.showMessageDialog(this, "Select file in the files panel or type its name in the textfield", "Warning", + JOptionPane.WARNING_MESSAGE); + return; + } + + //================================= + /* + String[] file = fileBrowserPanel1.getSelectedFiles(); + if (file == null || file.length < 1) { + JOptionPane.showMessageDialog(this, "Select file first for download", "Warning", + JOptionPane.WARNING_MESSAGE); + return; + } + else if (file == null || file.length > 1) { + JOptionPane.showMessageDialog(this, "INTERNAL ERROR: Only one file can be selected. Got " + file.length, "Error", + JOptionPane.ERROR_MESSAGE); + return; + } + */ + //================================ + /* + browser = fileBrowserPanel1.getFileBrowserInterface(); + + // =============================== + try { + // Create temp file. + temporaryLocalFile = File.createTempFile("cct", null); + + // Delete temp file when program exits. + temporaryLocalFile.deleteOnExit(); + + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Cannot create temporary file: " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + temporaryLocalFile = null; + return; + } + + // --- Transferring file + + try { + jobCancelled = false; + FileTranferWorker downloader = new FileTranferWorker(this, fileName, temporaryLocalFile.getAbsolutePath()); + downloader.start(); + //browser.get(file[0], temporaryLocalFile.getAbsolutePath(), downloader); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Cannot transfer " + fileName + " to " + temporaryLocalFile.getAbsolutePath() + " : " + + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + temporaryLocalFile = null; + return; + } + */ + try { + transferFile(fileName); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + temporaryLocalFile = null; + loadPressed = false; + } + + } + + public File getLocalFile() { + return temporaryLocalFile; + } + + public void transferFile(String remoteFile, String localFile, FileTransferProgress progress) throws Exception { + browser.get(remoteFile, localFile, progress); + } + + public void filterComboBox_itemStateChanged(ItemEvent e) { + if (!filterComboBox.isEnabled()) { + return; + } + if (e.getStateChange() == ItemEvent.DESELECTED) { + return; + } + browser.setFileFilter(fileFilters[filterComboBox.getSelectedIndex()]); + } + + String makeValidPattern(String initialPattern) { + String finalPattern = ""; + boolean charsStarted = false; + for (int i = 0; i < initialPattern.length(); i++) { + if (initialPattern.substring(i, i + 1).equals("*")) { + if (charsStarted) { + charsStarted = false; + finalPattern += "]"; + } + + finalPattern += ".*"; + } + else if (initialPattern.substring(i, i + 1).equals("?")) { + if (charsStarted) { + charsStarted = false; + finalPattern += "]"; + } + + finalPattern += "."; + } + else if (initialPattern.substring(i, i + 1).equals(".")) { + if (charsStarted) { + charsStarted = false; + finalPattern += "]"; + } + + finalPattern += "[.]"; + } + + else { + if (!charsStarted) { + charsStarted = true; + finalPattern += "["; + } + finalPattern += initialPattern.substring(i, i + 1); + } + } + if (charsStarted) { + charsStarted = false; + finalPattern += "]"; + } + + return finalPattern; + } + + public void fileTextField_actionPerformed(ActionEvent e) { + String fileName = fileTextField.getText().trim(); + if (browser == null) { + System.err.println(this.getClass().getCanonicalName() + " : SFTP Browser is not set"); + return; + } + try { + //String pattern = makeValidPattern(fileName); + String pattern = fileName.replaceAll("[.]", "[.]"); + pattern = pattern.replaceAll("[*]", ".*"); + pattern = pattern.replaceAll("[?]", "."); + browser.listUsingFilePattern(pattern); + int nfiles = browser.getFileCount(); + if (nfiles == 1) { + String[] fileNames = browser.getFileNames(); + loadPressed = true; + transferFile(fileNames[0]); + } + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + loadPressed = false; + return; + } + } + + void transferFile(String fileName) throws Exception { + + // --- Creates temporary file + try { + // Create temp file. + temporaryLocalFile = File.createTempFile("cct", null); + + // Delete temp file when program exits. + temporaryLocalFile.deleteOnExit(); + + } + catch (Exception ex) { + temporaryLocalFile = null; + throw new Exception("Cannot create temporary file: " + ex.getMessage()); + } + + // --- Transferring file + + try { + jobCancelled = false; + FileTranferWorker downloader = new FileTranferWorker(this, fileName, temporaryLocalFile.getAbsolutePath()); + downloader.start(); + //browser.get(file[0], temporaryLocalFile.getAbsolutePath(), downloader); + } + catch (Exception ex) { + temporaryLocalFile = null; + throw new Exception("Cannot transfer " + fileName + " to " + temporaryLocalFile.getAbsolutePath() + " : " + + ex.getMessage()); + } + + } + + public void loadHelpButton_actionPerformed(ActionEvent e) { + JOptionPane.showMessageDialog(this, "Left-mouse-click on the file or type file name explicitly in the text field\n" + + " and press \"Load\" button\n" + + "Use file template, for example, *.com for the non-standard file extension", "Help", + JOptionPane.INFORMATION_MESSAGE); + } + + public void fileTypesHelpButton_actionPerformed(ActionEvent e) { + JOptionPane.showMessageDialog(this, "Use combobox to select file format and file template", "Help", + JOptionPane.INFORMATION_MESSAGE); + + } + + private class SFTPFileChooserDialog_cancelButton_actionAdapter + implements ActionListener { + private SFTPFileChooserDialog adaptee; + SFTPFileChooserDialog_cancelButton_actionAdapter(SFTPFileChooserDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.cancelButton_actionPerformed(e); + } + } + + private class SFTPFileChooserDialog_loadButton_actionAdapter + implements ActionListener { + private SFTPFileChooserDialog adaptee; + SFTPFileChooserDialog_loadButton_actionAdapter(SFTPFileChooserDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.loadButton_actionPerformed(e); + } + } + + /** + * + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ + class FileTranferWorker + extends cct.tools.SwingWorker implements FileTransferProgress { + + TransferProgressDialog transferProgressDialog; + private SFTPFileChooserDialog adaptee; + String remoteFile, localFile; + + public FileTranferWorker(SFTPFileChooserDialog adaptee, String remote_file, String local_file) { + this.adaptee = adaptee; + remoteFile = remote_file; + localFile = local_file; + + JFrame frame = null; + if (getOwner() instanceof JFrame) { + frame = (JFrame) getOwner(); + } + + transferProgressDialog = new TransferProgressDialog(frame, "File transfer progress", false); + transferProgressDialog.setLocationRelativeTo(adaptee); + transferProgressDialog.setAlwaysOnTop(true); + transferProgressDialog.setProgress(0); + transferProgressDialog.setMaximum(MAX); + transferProgressDialog.cancelButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + cancelTranfer(); + } + } + ); + + } + + public void cancelTranfer() { + jobCancelled = true; + loadPressed = false; + adaptee.setVisible(false); + interrupt(); + } + + /* + public void actionPerformed(ActionEvent e) { + jobCancelled = true; + //adaptee.loadButton_actionPerformed(e); + } + */ + + @Override + public Object construct() { + + try { + adaptee.transferFile(remoteFile, localFile, this); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + temporaryLocalFile = null; + + } + adaptee.setVisible(false); + + return null; + } + + @Override + public void start() { + + super.start(); + } + + @Override + public void completed() { + transferProgressDialog.setVisible(false); + } + + @Override + public boolean isCancelled() { + return jobCancelled; + } + + @Override + public void progressed(long bytesSoFar) { + if (jobCancelled) { + return; + } + + // Get elapsed time in milliseconds + long elapsedTimeMillis = System.currentTimeMillis() - start_time; + + // Get elapsed time in seconds + double elapsedTimeSec = elapsedTimeMillis / 1000.0; + + double partSoFar = bytesSoFar / totalBytes; + + if (elapsedTimeSec > 5.0) { // If less than 5 sec - ignore + double timeLeft = elapsedTimeSec * (1.0 / partSoFar - 1.0); + if (timeLeft > 86400.0) { // Number of seconds in a day + int days = (int) (timeLeft / 86400.0); + int hours = (int) (timeLeft - days * 86400.0); + transferProgressDialog.setTime(days + " days and " + hours + " hours left"); + } + else if (timeLeft > 3600.0) { // Number of seconds in hour + int hours = (int) (timeLeft / 3600.0); + int minutes = (int) (timeLeft - hours * 3600.0); + transferProgressDialog.setTime(hours + " hours and " + minutes + + " minutes left"); + } + else if (timeLeft > 60.0) { // Number of seconds in minute + int minutes = (int) (timeLeft / 60.0); + int seconds = (int) (timeLeft - minutes * 60.0); + transferProgressDialog.setTime(minutes + " minutes and " + seconds + + " seconds left"); + } + else { + transferProgressDialog.setTime( ( (int) timeLeft) + " seconds left"); + } + + } + + //if (DEBUG) { + // logger.info("SO far: " + bytesSoFar); + //} + + transferProgressDialog.setProgress( (int) (partSoFar * MAX)); + //transferProgressDialog.pack(); + } + + @Override + public void started(long bytesTotal, String remoteFile) { + // Get current time + start_time = System.currentTimeMillis(); + totalBytes = bytesTotal; + String size; + long n1024 = 1024; + if (bytesTotal / (1024 * 1024) > 0) { + size = String.valueOf(bytesTotal / (1024 * 1024)) + " Mb"; + } + else if (bytesTotal / (1024) > 0) { + size = String.valueOf(bytesTotal / (1024)) + " Kb"; + } + else { + size = String.valueOf(bytesTotal) + " b"; + } + + // --- Download + //if (filesToDownload != null) { + transferProgressDialog.setFrom("From: " + remoteFile); + transferProgressDialog.setTo("To: " + temporaryLocalFile.getAbsolutePath()); + /* + } + + // Upload + else { + dialog.setFrom("From: " + currentLocalFile); + dialog.setTo("To: " + remoteFile); + } + */ + + transferProgressDialog.setProgress(0); + transferProgressDialog.setTime(""); + transferProgressDialog.validate(); + transferProgressDialog.pack(); + transferProgressDialog.setVisible(true); + } + + } +} diff --git a/src/main/java/cct/tools/filebrowser/SelectionInfoInterface.java b/src/main/java/cct/tools/filebrowser/SelectionInfoInterface.java new file mode 100644 index 0000000..c3fcc9e --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/SelectionInfoInterface.java @@ -0,0 +1,17 @@ +package cct.tools.filebrowser; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public interface SelectionInfoInterface { + void setSelectedFileName(String file_name); +} diff --git a/src/main/java/cct/tools/filebrowser/ShadowClientInterface.java b/src/main/java/cct/tools/filebrowser/ShadowClientInterface.java new file mode 100644 index 0000000..6bf070a --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/ShadowClientInterface.java @@ -0,0 +1,60 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.awt.Component; + +import cct.interfaces.FileBrowserInterface; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public interface ShadowClientInterface { + Component getComponent(); + void setKnownHosts(String[] hosts); + void setFileBrowser(String host, String username, FileBrowserInterface file_browser); +} diff --git a/src/main/java/cct/tools/filebrowser/ShadowManagerInterface.java b/src/main/java/cct/tools/filebrowser/ShadowManagerInterface.java new file mode 100644 index 0000000..4660859 --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/ShadowManagerInterface.java @@ -0,0 +1,59 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.awt.Component; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public interface ShadowManagerInterface { + String [] getKnownHosts(); + void processConnection(String host_info, Component component) throws Exception; + void processEditHosts(Component component); + void processExit(Component component); +} diff --git a/src/main/java/cct/tools/filebrowser/ShadowSFTPManager.java b/src/main/java/cct/tools/filebrowser/ShadowSFTPManager.java new file mode 100644 index 0000000..49cf36a --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/ShadowSFTPManager.java @@ -0,0 +1,521 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.tools.filebrowser; + +import java.awt.Component; +import java.awt.Window; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.prefs.Preferences; + +import cct.interfaces.FTPManagerInterface; +import cct.interfaces.FileBrowserInterface; + +/** + *

+ * Title: Computational Chemistry Tookit

+ * + *

+ * Description:

+ * Shadow Manager stands behind GUIs and manages SSH connections. Could be run as a SFTP Browser standalone application + *

+ * Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

+ * Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +enum FTP_OBJECT { + + FTP_FRAME, FTP_FILE_CHOOSER, FTP_CLIENT_INTERFACE +} + +public class ShadowSFTPManager + implements ShadowManagerInterface { + + private static final int maxStroredHosts = 10; + static final String NEW_HOST = "New host"; + static final String NUMBER_OF_HOSTS_KEY = "numberOfHosts"; + static final String HOST_KEY = "host"; + String defaultProtocol = "sftp"; + private boolean exitOnAllClose = true; + private Preferences prefs; + private EditHostsDialog editHostsDialog = null; + private java.util.List knownHosts = new ArrayList(); + private Map authenticatedHosts = new HashMap(); + private Map activeBrowsers = new HashMap(); + private FTPManagerInterface manager = null; + + public ShadowSFTPManager() { + + try { + manager = new FTPManager(); + } catch (Exception ex) { + ex.printStackTrace(); + } + + int numHosts = 0; + try { + prefs = Preferences.userNodeForPackage(this.getClass()); + numHosts = prefs.getInt(NUMBER_OF_HOSTS_KEY, 0); + if (numHosts < 0) { + numHosts = 0; + } else if (numHosts > maxStroredHosts) { + numHosts = maxStroredHosts; + } + + for (int i = 0; i < numHosts; i++) { + String host = prefs.get(HOST_KEY + String.valueOf(i), null); + if (host != null) { + knownHosts.add(host); + } + } + } catch (Exception ex) { + System.err.println("Error retrieving known host list: " + ex.getMessage() + " Ignored..."); + } + + } + + public void setExitOnAllClose(boolean enable) { + exitOnAllClose = enable; + } + + public static void main(String[] args) { + ShadowSFTPManager shadowsftpmanager = new ShadowSFTPManager(); + //shadowsftpmanager.start(); + shadowsftpmanager.startFileChooser(); + } + + /** + * Starts file browser + */ + public void startFileBrowser() { + + // --- Check for at least one active file browser + Set set = activeBrowsers.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + SFTPObject sft_object = (SFTPObject) me.getValue(); + if (sft_object.objectSwitch == FTP_OBJECT.FTP_FRAME) { + return; // One borwser is already active... + } + } + + SFTPObject sft_object = new SFTPObject(this, FTP_OBJECT.FTP_FRAME); + activeBrowsers.put(sft_object.getComponent(), sft_object); + sft_object.setKnownHosts(getKnownHosts()); + sft_object.setVisible(true); + } + + public void startFileChooser() { + SFTPObject sft_object = new SFTPObject(this, FTP_OBJECT.FTP_FILE_CHOOSER); + activeBrowsers.put(sft_object.getComponent(), sft_object); + //sft_object.setKnownHosts(getKnownHosts()); + sft_object.setVisible(true); + } + + @Override + public void processEditHosts(Component component) { + if (knownHosts.size() < 1) { + return; + } + + String[] hosts = new String[knownHosts.size()]; + knownHosts.toArray(hosts); + + if (editHostsDialog == null) { + editHostsDialog = new EditHostsDialog(null, "Edit hosts list", true); + editHostsDialog.setAlwaysOnTop(true); + editHostsDialog.setLocationByPlatform(true); + } + + editHostsDialog.setListData(hosts); + + if (component != null) { + editHostsDialog.setLocationRelativeTo(component); + } + + editHostsDialog.setVisible(true); + + if (!editHostsDialog.isOKPressed()) { + return; + } + + int[] indices = editHostsDialog.getSelectedIndices(); + + if (indices == null || indices.length < 1) { + return; + } + + for (int i = indices.length - 1; i >= 0; i--) { + knownHosts.remove(indices[i]); + } + + updateKnownHosts(); + } + + @Override + public String[] getKnownHosts() { + String[] hosts = new String[knownHosts.size() + 1]; + hosts[0] = NEW_HOST; + for (int i = 0; i < knownHosts.size(); i++) { + String hostKey = knownHosts.get(i); + hosts[i + 1] = hostKey.substring(hostKey.indexOf("@") + 1) + " as " + hostKey.substring(0, hostKey.indexOf("@")); + } + return hosts; + } + + public void saveKnownHosts() { + // --- Save known hosts + if (knownHosts.size() > 0) { + try { + //prefs = Preferences.userNodeForPackage(this.getClass()); + prefs.putInt(NUMBER_OF_HOSTS_KEY, knownHosts.size()); + System.out.println("Saving sftp host(s) before exit\n" + NUMBER_OF_HOSTS_KEY + "=" + knownHosts.size()); + + for (int i = 0; i < knownHosts.size(); i++) { + prefs.put(HOST_KEY + String.valueOf(i), knownHosts.get(i)); + System.out.println(HOST_KEY + String.valueOf(i) + "=" + knownHosts.get(i)); + } + for (int i = knownHosts.size(); i < maxStroredHosts; i++) { + prefs.remove(HOST_KEY + String.valueOf(i)); + } + } catch (Exception ex) { + System.err.println("Error retrieving known host list: " + ex.getMessage() + " Ignored..."); + } + } + } + + @Override + public void processExit(Component component) { + SFTPObject sft_object = activeBrowsers.get(component); + activeBrowsers.remove(component); + sft_object.dispose(); + + // --- Save known hosts + saveKnownHosts(); + + // --- Exit + if (activeBrowsers.size() == 0 && exitOnAllClose) { + System.exit(0); + } + } + + @Override + public void processConnection(String host_info, Component component) throws Exception { + String hostKey = null; + String host = null, username = null; + char[] password = null; + int port = 22; // !!! + boolean ask_for_password = false; + + if (host_info.equals(NEW_HOST)) { + ConnectHostDialog connectDialog = new ConnectHostDialog(null, "Connect to Host", true); + connectDialog.setAlwaysOnTop(true); + connectDialog.setLocationRelativeTo(component); + int n = connectDialog.showDialog(); + if (n == ConnectHostDialog.CANCEL) { + return; + } + host = connectDialog.getHost().toLowerCase(); + if (host.length() < 1) { + throw new Exception("Host name is not specified"); + } + username = connectDialog.getUsername(); + if (username.length() < 1) { + throw new Exception("User name is not specified"); + } + password = connectDialog.getPassword(); + port = connectDialog.getPort(); + if (port < 1) { + throw new Exception("Wrong port number: " + port); + } + + hostKey = username + "@" + host; + + } else if (host_info.contains(" as ")) { + host = host_info.substring(0, host_info.indexOf(" ")); + username = host_info.substring(host_info.lastIndexOf(" ") + 1); + hostKey = username + "@" + host; + ask_for_password = true; + } else { + throw new Exception("Shadow Manager Error: Unknown host request: " + host_info); + } + + // --- make connection and authentication... + SFTPObject sftpObject = activeBrowsers.get(component); + FileBrowserInterface browser = null; + //if ((sftpObject == null || !sftpObject.connected) ) { + + browser = manager.getFTPBrowser(defaultProtocol); + if (browser == null) { + throw new Exception("Cannot get File Browser for the protocol: " + defaultProtocol); + } + + if (authenticatedHosts.containsKey(hostKey)) { + UserHostInfo hostInfo = authenticatedHosts.get(hostKey); + try { + browser.connect(hostInfo.Host, hostInfo.User, hostInfo.Password, hostInfo.Port); + } catch (Exception ex) { + throw ex; + } + + } else { + + if (ask_for_password) { + ConnectHostDialog connectDialog = new ConnectHostDialog(null, "Connect to " + host, true); + connectDialog.hostTextField.setText(host); + connectDialog.hostTextField.setEditable(false); + connectDialog.userTextField.setText(username); + connectDialog.userTextField.setEditable(false); + connectDialog.passwordTextField.grabFocus(); + connectDialog.portNumber = port; + connectDialog.portTextField.setText(String.valueOf(port)); + connectDialog.setAlwaysOnTop(true); + connectDialog.setLocationRelativeTo(component); + connectDialog.setVisible(true); + int n = connectDialog.getKeyPressed(); + if (n == ConnectHostDialog.CANCEL) { + return; + } + + password = connectDialog.getPassword(); + port = connectDialog.getPort(); + if (port < 1) { + throw new Exception("Wrong port number: " + port); + } + } + + try { + browser.connect(host, username, password, port); + } catch (Exception ex) { + throw ex; + } + UserHostInfo hostInfo = new UserHostInfo(host, username, password, port); + authenticatedHosts.put(hostKey, hostInfo); + } + //} + + // ---it;s already authenticated component + //else { + //} +// --- So, authentication is successful + addKnownHost(hostKey); + + if (sftpObject == null) { + createNewBrowser(host, username, browser); + } else if (!sftpObject.connected) { + sftpObject.setFileBrowser(host, username, browser); + } else if (sftpObject.connected && sftpObject.browserFrame != null) { + createNewBrowser(host, username, browser); + } else if (sftpObject.connected) { + sftpObject.setFileBrowser(host, username, browser); + //createNewBrowser(host, username, browser); + } + + updateKnownHosts(); + } + + void addKnownHost(String host) { + if (knownHosts.contains(host)) { + return; + } + + if (knownHosts.size() >= maxStroredHosts) { + for (int i = knownHosts.size() - 1; i >= maxStroredHosts - 1; i--) { + knownHosts.remove(i); + } + } + + knownHosts.add(0, host); + } + + void createNewBrowser(String host, String username, FileBrowserInterface browser) { + SFTPObject sft_object = new SFTPObject(this, FTP_OBJECT.FTP_FRAME); + activeBrowsers.put(sft_object.getComponent(), sft_object); + sft_object.setKnownHosts(getKnownHosts()); + sft_object.setFileBrowser(host, username, browser); + sft_object.setVisible(true); + } + + void updateKnownHosts() { + String[] hosts = getKnownHosts(); + Set set = activeBrowsers.entrySet(); + Iterator iter = set.iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + SFTPObject sft_object = (SFTPObject) me.getValue(); + sft_object.setKnownHosts(hosts); + } + + saveKnownHosts(); + } + + public void addClient(ShadowClientInterface client) { + SFTPObject sft_object = new SFTPObject(this, client); + activeBrowsers.put(sft_object.getComponent(), sft_object); + sft_object.setKnownHosts(getKnownHosts()); + sft_object.setVisible(true); + } +} + +class SFTPObject { + + ShadowSFTPManager shadowManager = null; + SFTPBrowserFrame browserFrame = null; + SFTPFileChooserDialog fileChooser = null; + ShadowClientInterface clientInterface = null; + FileBrowserInterface fileBrowser = null; + Window guiObject = null; + FTP_OBJECT objectSwitch = null; + String remoteHost = null; + boolean connected = false; + + public SFTPObject(ShadowSFTPManager manager, FTP_OBJECT object) { + shadowManager = manager; + objectSwitch = object; + switch (object) { + case FTP_FRAME: + browserFrame = new SFTPBrowserFrame(manager); + guiObject = browserFrame; + break; + case FTP_FILE_CHOOSER: + fileChooser = new SFTPFileChooserDialog(null, "Choose file", true); + guiObject = fileChooser; + break; + case FTP_CLIENT_INTERFACE: + break; + } + + //browserFrame.pack(); + guiObject.pack(); + //browserFrame.setLocationByPlatform(true); + guiObject.setLocationByPlatform(true); + } + + public SFTPObject(ShadowSFTPManager manager, ShadowClientInterface client) { + shadowManager = manager; + objectSwitch = FTP_OBJECT.FTP_CLIENT_INTERFACE; + clientInterface = client; + } + + public void setVisible(boolean enable) { + //browserFrame.setVisible(enable); + if (guiObject != null) { + guiObject.setVisible(true); + } + } + + public Component getComponent() { + //return browserFrame; + if (guiObject != null) { + return guiObject; + } + return clientInterface.getComponent(); + } + + public void setKnownHosts(String[] hosts) { + switch (objectSwitch) { + case FTP_FRAME: + browserFrame.setKnownHosts(hosts); + break; + case FTP_CLIENT_INTERFACE: + clientInterface.setKnownHosts(hosts); + break; + } + } + + public void setFileBrowser(String host, String username, FileBrowserInterface file_browser) { + fileBrowser = file_browser; + switch (objectSwitch) { + case FTP_FRAME: + browserFrame.setFileBrowser(fileBrowser); + browserFrame.setTitle("sftp: " + host + " as " + username); + break; + case FTP_FILE_CHOOSER: + fileChooser.setFileBrowser(fileBrowser); + fileChooser.setTitle("sftp: " + host + " as " + username); + break; + case FTP_CLIENT_INTERFACE: + clientInterface.setFileBrowser(host, username, file_browser); + break; + + } + + connected = true; + } + + public void dispose() { + //browserFrame.setVisible(false); + if (guiObject != null) { + guiObject.setVisible(false); + } + if (fileBrowser != null) { + fileBrowser.disconnect(); + } + //browserFrame.dispose(); + if (guiObject != null) { + guiObject.dispose(); + } + } +} + +class UserHostInfo { + + String Host, User; + char[] Password = null; + int Port; + + public UserHostInfo(String host, String user, char[] password, int port) { + Host = host; + User = user; + Port = port; + if (password == null || password.length < 1) { + return; + } + Password = new char[password.length]; + for (int i = 0; i < Password.length; i++) { + Password[i] = password[i]; + } + } +} diff --git a/src/main/java/cct/tools/filebrowser/TableSorter.java b/src/main/java/cct/tools/filebrowser/TableSorter.java new file mode 100644 index 0000000..fd5551e --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/TableSorter.java @@ -0,0 +1,563 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Graphics; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.swing.Icon; +import javax.swing.JLabel; +import javax.swing.JTable; +import javax.swing.SwingConstants; +import javax.swing.event.TableModelEvent; +import javax.swing.event.TableModelListener; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.JTableHeader; +import javax.swing.table.TableCellRenderer; +import javax.swing.table.TableColumnModel; +import javax.swing.table.TableModel; + +/** + * TableSorter is a decorator for TableModels; adding sorting + * functionality to a supplied TableModel. TableSorter does + * not store or copy the data in its TableModel; instead it maintains + * a map from the row indexes of the view to the row indexes of the + * model. As requests are made of the sorter (like getValueAt(row, col)) + * they are passed to the underlying model after the row numbers + * have been translated via the internal mapping array. This way, + * the TableSorter appears to hold another copy of the table + * with the rows in a different order. + *

+ * TableSorter registers itself as a listener to the underlying model, + * just as the JTable itself would. Events recieved from the model + * are examined, sometimes manipulated (typically widened), and then + * passed on to the TableSorter's listeners (typically the JTable). + * If a change to the model has invalidated the order of TableSorter's + * rows, a note of this is made and the sorter will resort the + * rows the next time a value is requested. + *

+ * When the tableHeader property is set, either by using the + * setTableHeader() method or the two argument constructor, the + * table header may be used as a complete UI for TableSorter. + * The default renderer of the tableHeader is decorated with a renderer + * that indicates the sorting status of each column. In addition, + * a mouse listener is installed with the following behavior: + *

    + *
  • + * Mouse-click: Clears the sorting status of all other columns + * and advances the sorting status of that column through three + * values: {NOT_SORTED, ASCENDING, DESCENDING} (then back to + * NOT_SORTED again). + *
  • + * SHIFT-mouse-click: Clears the sorting status of all other columns + * and cycles the sorting status of the column through the same + * three values, in the opposite order: {NOT_SORTED, DESCENDING, ASCENDING}. + *
  • + * CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except + * that the changes to the column do not cancel the statuses of columns + * that are already sorting - giving a way to initiate a compound + * sort. + *
+ *

+ * This is a long overdue rewrite of a class of the same name that + * first appeared in the swing table demos in 1997. + * + * @author Philip Milne + * @author Brendon McLean + * @author Dan van Enckevort + * @author Parwinder Sekhon + * @version 2.0 02/27/04 + */ + +public class TableSorter + extends AbstractTableModel { + protected TableModel tableModel; + + public static final int DESCENDING = -1; + public static final int NOT_SORTED = 0; + public static final int ASCENDING = 1; + + private static Directive EMPTY_DIRECTIVE = new Directive( -1, NOT_SORTED); + + public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() { + @Override + public int compare(Object o1, Object o2) { + return ( (Comparable) o1).compareTo(o2); + } + }; + public static final Comparator LEXICAL_COMPARATOR = new Comparator() { + @Override + public int compare(Object o1, Object o2) { + return o1.toString().compareTo(o2.toString()); + } + }; + + private Row[] viewToModel; + private int[] modelToView; + + private JTableHeader tableHeader; + private MouseListener mouseListener; + private TableModelListener tableModelListener; + private Map columnComparators = new HashMap(); + private List sortingColumns = new ArrayList(); + + public TableSorter() { + this.mouseListener = new MouseHandler(); + this.tableModelListener = new TableModelHandler(); + } + + public TableSorter(TableModel tableModel) { + this(); + setTableModel(tableModel); + } + + public TableSorter(TableModel tableModel, JTableHeader tableHeader) { + this(); + setTableHeader(tableHeader); + setTableModel(tableModel); + } + + private void clearSortingState() { + viewToModel = null; + modelToView = null; + } + + public TableModel getTableModel() { + return tableModel; + } + + public void setTableModel(TableModel tableModel) { + if (this.tableModel != null) { + this.tableModel.removeTableModelListener(tableModelListener); + } + + this.tableModel = tableModel; + if (this.tableModel != null) { + this.tableModel.addTableModelListener(tableModelListener); + } + + clearSortingState(); + fireTableStructureChanged(); + } + + public JTableHeader getTableHeader() { + return tableHeader; + } + + public void setTableHeader(JTableHeader tableHeader) { + if (this.tableHeader != null) { + this.tableHeader.removeMouseListener(mouseListener); + TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer(); + if (defaultRenderer instanceof SortableHeaderRenderer) { + this.tableHeader.setDefaultRenderer( ( (SortableHeaderRenderer) defaultRenderer).tableCellRenderer); + } + } + this.tableHeader = tableHeader; + if (this.tableHeader != null) { + this.tableHeader.addMouseListener(mouseListener); + this.tableHeader.setDefaultRenderer( + new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer())); + } + } + + public boolean isSorting() { + return sortingColumns.size() != 0; + } + + private Directive getDirective(int column) { + for (int i = 0; i < sortingColumns.size(); i++) { + Directive directive = (Directive) sortingColumns.get(i); + if (directive.column == column) { + return directive; + } + } + return EMPTY_DIRECTIVE; + } + + public int getSortingStatus(int column) { + return getDirective(column).direction; + } + + private void sortingStatusChanged() { + clearSortingState(); + fireTableDataChanged(); + if (tableHeader != null) { + tableHeader.repaint(); + } + } + + public void setSortingStatus(int column, int status) { + Directive directive = getDirective(column); + if (directive != EMPTY_DIRECTIVE) { + sortingColumns.remove(directive); + } + if (status != NOT_SORTED) { + sortingColumns.add(new Directive(column, status)); + } + sortingStatusChanged(); + } + + protected Icon getHeaderRendererIcon(int column, int size) { + Directive directive = getDirective(column); + if (directive == EMPTY_DIRECTIVE) { + return null; + } + return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive)); + } + + private void cancelSorting() { + sortingColumns.clear(); + sortingStatusChanged(); + } + + public void setColumnComparator(Class type, Comparator comparator) { + if (comparator == null) { + columnComparators.remove(type); + } + else { + columnComparators.put(type, comparator); + } + } + + protected Comparator getComparator(int column) { + Class columnType = tableModel.getColumnClass(column); + Comparator comparator = (Comparator) columnComparators.get(columnType); + if (comparator != null) { + return comparator; + } + if (Comparable.class.isAssignableFrom(columnType)) { + return COMPARABLE_COMAPRATOR; + } + return LEXICAL_COMPARATOR; + } + + private Row[] getViewToModel() { + if (viewToModel == null) { + int tableModelRowCount = tableModel.getRowCount(); + viewToModel = new Row[tableModelRowCount]; + for (int row = 0; row < tableModelRowCount; row++) { + viewToModel[row] = new Row(row); + } + + if (isSorting()) { + Arrays.sort(viewToModel); + } + } + return viewToModel; + } + + public int modelIndex(int viewIndex) { + return getViewToModel()[viewIndex].modelIndex; + } + + private int[] getModelToView() { + if (modelToView == null) { + int n = getViewToModel().length; + modelToView = new int[n]; + for (int i = 0; i < n; i++) { + modelToView[modelIndex(i)] = i; + } + } + return modelToView; + } + + // TableModel interface methods + + @Override + public int getRowCount() { + return (tableModel == null) ? 0 : tableModel.getRowCount(); + } + + @Override + public int getColumnCount() { + return (tableModel == null) ? 0 : tableModel.getColumnCount(); + } + + @Override + public String getColumnName(int column) { + return tableModel.getColumnName(column); + } + + @Override + public Class getColumnClass(int column) { + return tableModel.getColumnClass(column); + } + + @Override + public boolean isCellEditable(int row, int column) { + return tableModel.isCellEditable(modelIndex(row), column); + } + + @Override + public Object getValueAt(int row, int column) { + return tableModel.getValueAt(modelIndex(row), column); + } + + @Override + public void setValueAt(Object aValue, int row, int column) { + tableModel.setValueAt(aValue, modelIndex(row), column); + } + + // Helper classes + + private class Row + implements Comparable { + private int modelIndex; + + public Row(int index) { + this.modelIndex = index; + } + + @Override + public int compareTo(Object o) { + int row1 = modelIndex; + int row2 = ( (Row) o).modelIndex; + + for (Iterator it = sortingColumns.iterator(); it.hasNext(); ) { + Directive directive = (Directive) it.next(); + int column = directive.column; + Object o1 = tableModel.getValueAt(row1, column); + Object o2 = tableModel.getValueAt(row2, column); + + int comparison = 0; + // Define null less than everything, except null. + if (o1 == null && o2 == null) { + comparison = 0; + } + else if (o1 == null) { + comparison = -1; + } + else if (o2 == null) { + comparison = 1; + } + else { + comparison = getComparator(column).compare(o1, o2); + } + if (comparison != 0) { + return directive.direction == DESCENDING ? -comparison : comparison; + } + } + return 0; + } + } + + private class TableModelHandler + implements TableModelListener { + @Override + public void tableChanged(TableModelEvent e) { + // If we're not sorting by anything, just pass the event along. + if (!isSorting()) { + clearSortingState(); + fireTableChanged(e); + return; + } + + // If the table structure has changed, cancel the sorting; the + // sorting columns may have been either moved or deleted from + // the model. + if (e.getFirstRow() == TableModelEvent.HEADER_ROW) { + cancelSorting(); + fireTableChanged(e); + return; + } + + // We can map a cell event through to the view without widening + // when the following conditions apply: + // + // a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and, + // b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and, + // c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and, + // d) a reverse lookup will not trigger a sort (modelToView != null) + // + // Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS. + // + // The last check, for (modelToView != null) is to see if modelToView + // is already allocated. If we don't do this check; sorting can become + // a performance bottleneck for applications where cells + // change rapidly in different parts of the table. If cells + // change alternately in the sorting column and then outside of + // it this class can end up re-sorting on alternate cell updates - + // which can be a performance problem for large tables. The last + // clause avoids this problem. + int column = e.getColumn(); + if (e.getFirstRow() == e.getLastRow() + && column != TableModelEvent.ALL_COLUMNS + && getSortingStatus(column) == NOT_SORTED + && modelToView != null) { + int viewIndex = getModelToView()[e.getFirstRow()]; + fireTableChanged(new TableModelEvent(TableSorter.this, + viewIndex, viewIndex, + column, e.getType())); + return; + } + + // Something has happened to the data that may have invalidated the row order. + clearSortingState(); + fireTableDataChanged(); + return; + } + } + + private class MouseHandler + extends MouseAdapter { + @Override + public void mouseClicked(MouseEvent e) { + JTableHeader h = (JTableHeader) e.getSource(); + TableColumnModel columnModel = h.getColumnModel(); + int viewColumn = columnModel.getColumnIndexAtX(e.getX()); + int column = columnModel.getColumn(viewColumn).getModelIndex(); + if (column != -1) { + int status = getSortingStatus(column); + if (!e.isControlDown()) { + cancelSorting(); + } + // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or + // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed. + status = status + (e.isShiftDown() ? -1 : 1); + status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1} + setSortingStatus(column, status); + } + } + } + + private static class Arrow + implements Icon { + private boolean descending; + private int size; + private int priority; + + public Arrow(boolean descending, int size, int priority) { + this.descending = descending; + this.size = size; + this.priority = priority; + } + + @Override + public void paintIcon(Component c, Graphics g, int x, int y) { + Color color = c == null ? Color.GRAY : c.getBackground(); + // In a compound sort, make each succesive triangle 20% + // smaller than the previous one. + int dx = (int) (size / 2 * Math.pow(0.8, priority)); + int dy = descending ? dx : -dx; + // Align icon (roughly) with font baseline. + y = y + 5 * size / 6 + (descending ? -dy : 0); + int shift = descending ? 1 : -1; + g.translate(x, y); + + // Right diagonal. + g.setColor(color.darker()); + g.drawLine(dx / 2, dy, 0, 0); + g.drawLine(dx / 2, dy + shift, 0, shift); + + // Left diagonal. + g.setColor(color.brighter()); + g.drawLine(dx / 2, dy, dx, 0); + g.drawLine(dx / 2, dy + shift, dx, shift); + + // Horizontal line. + if (descending) { + g.setColor(color.darker().darker()); + } + else { + g.setColor(color.brighter().brighter()); + } + g.drawLine(dx, 0, 0, 0); + + g.setColor(color); + g.translate( -x, -y); + } + + @Override + public int getIconWidth() { + return size; + } + + @Override + public int getIconHeight() { + return size; + } + } + + private class SortableHeaderRenderer + implements TableCellRenderer { + private TableCellRenderer tableCellRenderer; + + public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) { + this.tableCellRenderer = tableCellRenderer; + } + + @Override + public Component getTableCellRendererComponent(JTable table, + Object value, + boolean isSelected, + boolean hasFocus, + int row, + int column) { + Component c = tableCellRenderer.getTableCellRendererComponent(table, + value, isSelected, hasFocus, row, column); + if (c instanceof JLabel) { + JLabel l = (JLabel) c; + l.setHorizontalTextPosition(SwingConstants.LEFT); + int modelColumn = table.convertColumnIndexToModel(column); + l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize())); + } + return c; + } + } + + private static class Directive { + private int column; + private int direction; + + public Directive(int column, int direction) { + this.column = column; + this.direction = direction; + } + } +} diff --git a/src/main/java/cct/tools/filebrowser/TransferProgressDialog.java b/src/main/java/cct/tools/filebrowser/TransferProgressDialog.java new file mode 100644 index 0000000..59bafc0 --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/TransferProgressDialog.java @@ -0,0 +1,149 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.GridLayout; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JProgressBar; +import javax.swing.border.BevelBorder; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class TransferProgressDialog + extends JDialog { + JPanel panel1 = new JPanel(); + public JLabel fromLabel = new JLabel(); + public JProgressBar ProgressBar = new JProgressBar(); + JPanel jPanel1 = new JPanel(); + public JButton cancelButton = new JButton(); + JPanel jPanel2 = new JPanel(); + GridLayout gridLayout1 = new GridLayout(); + BorderLayout borderLayout1 = new BorderLayout(); + JLabel timeLeftLabel = new JLabel(); + JLabel toLabel = new JLabel(); + public TransferProgressDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public TransferProgressDialog() { + this(new Frame(), "TransferProgressDialog", false); + } + + private void jbInit() throws Exception { + panel1.setLayout(gridLayout1); + this.setDefaultCloseOperation(javax.swing.WindowConstants. + DO_NOTHING_ON_CLOSE); + fromLabel.setToolTipText(""); + fromLabel.setText( + "From " + + " "); + cancelButton.setText("Cancel"); + gridLayout1.setColumns(1); + gridLayout1.setRows(5); + jPanel1.setLayout(borderLayout1); + borderLayout1.setHgap(5); + ProgressBar.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5)); + ProgressBar.setToolTipText("File Transfer Progress"); + ProgressBar.setStringPainted(true); + panel1.setBorder(BorderFactory.createCompoundBorder(BorderFactory. + createBevelBorder(BevelBorder.RAISED, Color.white, Color.white, + new Color(115, 114, 105), new Color(165, 163, 151)), + BorderFactory.createEmptyBorder(0, 10, 0, 10))); + panel1.setPreferredSize(new Dimension(200, 169)); + timeLeftLabel.setToolTipText(""); + timeLeftLabel.setText("XX Seconds Left"); + toLabel.setToolTipText(""); + toLabel.setText("To:"); + getContentPane().add(panel1); + jPanel2.add(cancelButton); + panel1.add(fromLabel, null); + panel1.add(toLabel); + panel1.add(jPanel1, null); + jPanel1.add(ProgressBar, BorderLayout.NORTH); + panel1.add(timeLeftLabel); + panel1.add(jPanel2, null); + } + + public void setProgress(int value) { + ProgressBar.setValue(value); + } + + public void setMaximum(int max) { + ProgressBar.setMaximum(max); + } + + public void setFrom(String from) { + fromLabel.setText(from); + } + + public void setTo(String to) { + toLabel.setText(to); + } + + public void setTime(String time) { + timeLeftLabel.setText(time); + } + +} diff --git a/src/main/java/cct/tools/filebrowser/UnsignedInteger64Renderer.java b/src/main/java/cct/tools/filebrowser/UnsignedInteger64Renderer.java new file mode 100644 index 0000000..7f6fa78 --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/UnsignedInteger64Renderer.java @@ -0,0 +1,105 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.filebrowser; + +import java.awt.Color; +import java.awt.Component; +import java.text.NumberFormat; + +import javax.swing.JLabel; +import javax.swing.JTable; +import javax.swing.table.TableCellRenderer; + +import com.sshtools.j2ssh.io.UnsignedInteger64; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ + +class UnsignedInteger64Renderer + extends JLabel implements TableCellRenderer { + + static NumberFormat nf = NumberFormat.getInstance(); + + public UnsignedInteger64Renderer() { + + //this.isBordered = isBordered; + + setOpaque(true); //MUST do this for background to show up. + + } + + @Override + public Component getTableCellRendererComponent( + JTable table, Object number, + boolean isSelected, boolean hasFocus, + int row, int column) { + + UnsignedInteger64 size = (UnsignedInteger64) number; + + this.setText(nf.format(size.doubleValue())); + + if (isSelected) { + //selectedBorder is a solid border in the color + Color bg = table.getSelectionBackground(); + this.setBackground(bg); + //setBorder(selectedBorder); + } + else { + //unselectedBorder is a solid border in the color + Color bg = table.getBackground(); + this.setBackground(bg); + //setBorder(unselectedBorder); + } + + //setToolTipText(...); //Discussed in the following section + + return this; + + } + +} diff --git a/src/main/java/cct/tools/filebrowser/package.html b/src/main/java/cct/tools/filebrowser/package.html new file mode 100644 index 0000000..003c502 --- /dev/null +++ b/src/main/java/cct/tools/filebrowser/package.html @@ -0,0 +1,24 @@ + + + + +Begin with a one sentence summary about this package. +Follow with the remainder of your description. + +

Package Specification

+This package uses sshtools and implementes interface for using SSH protocol + + +

Related Documentation

+ + + + + diff --git a/src/main/java/cct/tools/ui/.DS_Store b/src/main/java/cct/tools/ui/.DS_Store new file mode 100644 index 0000000..ea38ed5 Binary files /dev/null and b/src/main/java/cct/tools/ui/.DS_Store differ diff --git a/src/main/java/cct/tools/ui/._.DS_Store b/src/main/java/cct/tools/ui/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/cct/tools/ui/._.DS_Store differ diff --git a/src/main/java/cct/tools/ui/DoubleSpinnerDialog.java b/src/main/java/cct/tools/ui/DoubleSpinnerDialog.java new file mode 100644 index 0000000..eb833af --- /dev/null +++ b/src/main/java/cct/tools/ui/DoubleSpinnerDialog.java @@ -0,0 +1,148 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.ui; + +import java.awt.BorderLayout; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JPanel; +import javax.swing.JSpinner; +import javax.swing.SpinnerNumberModel; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class DoubleSpinnerDialog + extends JDialog implements ActionListener { + JPanel panel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JSpinner jSpinner1 = new JSpinner(); + JPanel jPanel1 = new JPanel(); + boolean okPressed = false; + JButton okButton = new JButton(); + JButton cancelButton = new JButton(); + public DoubleSpinnerDialog(Frame owner, String title, boolean modal, + double value, double minimum, double maximum, + double stepSize) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + jSpinner1.setModel(new SpinnerNumberModel(value, minimum, maximum, + stepSize)); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private DoubleSpinnerDialog() { + this(new Frame(), "Select Value", true, 10, 0, 100, 1); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + okButton.setToolTipText("Accept Value"); + okButton.setText("OK"); + cancelButton.setToolTipText("Cancel Input"); + cancelButton.setText("Cancel"); + this.setDefaultCloseOperation(javax.swing.WindowConstants. + DO_NOTHING_ON_CLOSE); + getContentPane().add(panel1); + panel1.add(jSpinner1, BorderLayout.NORTH); + panel1.add(jPanel1, BorderLayout.SOUTH); + jPanel1.add(okButton); + jPanel1.add(cancelButton); + + okButton.addActionListener(this); + cancelButton.addActionListener(this); + } + + public boolean isOKPressed() { + return okPressed; + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == okButton) { + okPressed = true; + setVisible(false); + } + else if (e.getSource() == cancelButton) { + okPressed = false; + setVisible(false); + } + + } + + public double getValue() { + double value = 0; + try { + String size = jSpinner1.getModel().getValue().toString(); + value = Double.parseDouble(size); + } + catch (NumberFormatException nfe) { + } + return value; + } + + public static void main(String [] s) { + DoubleSpinnerDialog dial = new DoubleSpinnerDialog(); + //dial.setSize(640, 480); + dial.pack(); + dial.setVisible(true); + if ( dial.isOKPressed()) { + System.out.println("Selected: "+dial.getValue()); + } + System.exit(0); + } +} diff --git a/src/main/java/cct/tools/ui/FileChooserDialog.java b/src/main/java/cct/tools/ui/FileChooserDialog.java new file mode 100644 index 0000000..5729b35 --- /dev/null +++ b/src/main/java/cct/tools/ui/FileChooserDialog.java @@ -0,0 +1,113 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.ui; + +import java.awt.Component; +import java.io.File; + +import javax.swing.JFileChooser; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class FileChooserDialog + extends JFileChooser { + + int Mode = JFileChooser.OPEN_DIALOG; + Component Parent; + + public FileChooserDialog(javax.swing.filechooser.FileFilter[] filters, + Component parent, + String title, int mode) { + super(); + + Mode = mode; + Parent = parent; + + setAcceptAllFileFilterUsed(false); + + setDialogTitle(title); + setDialogType(mode); + setFileSelectionMode(JFileChooser.FILES_ONLY); + setMultiSelectionEnabled(false); + + for (int i = 0; i < filters.length; i++) { + addChoosableFileFilter(filters[i]); + //logger.info("Adding filter: "+filters[i].getDescription() ); + } + setFileFilter(filters[0]); + + } + + public void setWorkingDirectory(String workingDir) { + if (workingDir != null && workingDir.length() > 0) { + File cwd = new File(workingDir); + if (cwd.isDirectory() && cwd.exists()) { + setCurrentDirectory(cwd); + } + } + + } + + public String getFile() { + int answer = JFileChooser.CANCEL_OPTION; + + if (Mode == JFileChooser.OPEN_DIALOG) { + answer = showOpenDialog(Parent); + } + else if (Mode == JFileChooser.SAVE_DIALOG) { + answer = showSaveDialog(Parent); + } + + if (answer == JFileChooser.APPROVE_OPTION) { + return getSelectedFile().getAbsolutePath(); + } + return null; + + } + +} diff --git a/src/main/java/cct/tools/ui/FontSelectorDialog.java b/src/main/java/cct/tools/ui/FontSelectorDialog.java new file mode 100644 index 0000000..e28dc1a --- /dev/null +++ b/src/main/java/cct/tools/ui/FontSelectorDialog.java @@ -0,0 +1,165 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.ui; + +import java.awt.BorderLayout; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class FontSelectorDialog + extends JDialog implements ActionListener { + JPanel panel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + FontSelectorPanel fontSelectorPanel1 = new FontSelectorPanel(); + JPanel jPanel1 = new JPanel(); + JButton cancelButton = new JButton(); + JButton okButton = new JButton(); + boolean okPressed = false; + + public FontSelectorDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public boolean isOKPressed() { + return okPressed; + } + + public FontSelectorDialog() { + this(new Frame(), "FontSelectorDialog", false); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + cancelButton.setToolTipText(""); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(this); + okButton.setToolTipText(""); + okButton.setText("OK"); + okButton.addActionListener(this); + this.setDefaultCloseOperation(javax.swing.WindowConstants. + DO_NOTHING_ON_CLOSE); + getContentPane().add(panel1); + panel1.add(fontSelectorPanel1, BorderLayout.CENTER); + panel1.add(jPanel1, BorderLayout.SOUTH); + jPanel1.add(okButton); + jPanel1.add(cancelButton); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == okButton) { + okPressed = true; + setVisible(false); + } + else if (e.getSource() == cancelButton) { + okPressed = false; + setVisible(false); + } + + } + + public static void main(String[] args) { + + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } + catch (Exception exception) { + exception.printStackTrace(); + } + + FontSelectorDialog frame = new FontSelectorDialog(new Frame(), + "Select Font", false); + frame.validate(); + /* + frame.hideButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + System.exit(0); + } + } + ); + */ + frame.setDefaultCloseOperation(EXIT_ON_CLOSE); + frame.setVisible(true); + + } + }); + } + + public String getFontName() { + return fontSelectorPanel1.fontComboBox.getSelectedItem().toString(); + } + + public int getFontSize() { + return fontSelectorPanel1.getFontSize(); + } + + public int getFontStyle() { + return fontSelectorPanel1.getFontStyle(); + } + +} diff --git a/src/main/java/cct/tools/ui/FontSelectorPanel.java b/src/main/java/cct/tools/ui/FontSelectorPanel.java new file mode 100644 index 0000000..78eafcb --- /dev/null +++ b/src/main/java/cct/tools/ui/FontSelectorPanel.java @@ -0,0 +1,228 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.ui; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.GraphicsEnvironment; +import java.awt.GridLayout; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; + +import javax.swing.JColorChooser; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JSpinner; +import javax.swing.SpinnerNumberModel; +import javax.swing.SwingConstants; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class FontSelectorPanel + extends JPanel implements ChangeListener, ItemListener { + + String[] styleNames = { + "Plain", "Bold", "Italic", "Bold Italic"}; + + Color currentColor = new Color(Color.BLACK.getRed(), Color.BLACK.getGreen(), + Color.BLACK.getBlue()); + BorderLayout borderLayout1 = new BorderLayout(); + public JColorChooser colorChooser = new JColorChooser(currentColor); + JPanel jPanel1 = new JPanel(); + JPanel jPanel2 = new JPanel(); + JLabel jLabel1 = new JLabel(); + FlowLayout flowLayout2 = new FlowLayout(); + public JComboBox styleComboBox = new JComboBox(styleNames); + JLabel jLabel2 = new JLabel(); + public JComboBox fontComboBox = new JComboBox(); + JLabel jLabel3 = new JLabel(); + public JSpinner sizeSpinner = new JSpinner(new SpinnerNumberModel(12, 6, 24, + 1)); + + String fontChoice = "Dialog"; + JLabel textLabel = new JLabel(); + GridLayout gridLayout1 = new GridLayout(); + + public FontSelectorPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + jLabel1.setToolTipText(""); + jLabel1.setText("Size:"); + jPanel1.setLayout(gridLayout1); + jPanel2.setLayout(flowLayout2); + flowLayout2.setAlignment(FlowLayout.LEFT); + jLabel2.setToolTipText(""); + jLabel2.setText("Style:"); + jLabel3.setToolTipText(""); + jLabel3.setText("Font family:"); + textLabel.setToolTipText(""); + textLabel.setHorizontalAlignment(SwingConstants.CENTER); + textLabel.setHorizontalTextPosition(SwingConstants.CENTER); + textLabel.setText("The quick brown fox jumped over the lazy dog"); + gridLayout1.setColumns(1); + gridLayout1.setHgap(10); + jPanel1.setBackground(Color.white); + jPanel2.add(jLabel3); + jPanel2.add(fontComboBox); + jPanel2.add(jLabel2); + jPanel2.add(styleComboBox); + jPanel2.add(jLabel1); + jPanel2.add(sizeSpinner); + this.add(colorChooser, BorderLayout.SOUTH); + this.add(jPanel1, BorderLayout.CENTER); + this.add(jPanel2, BorderLayout.NORTH); + jPanel1.add(textLabel, null); + GraphicsEnvironment gEnv = + GraphicsEnvironment.getLocalGraphicsEnvironment(); + String[] families = gEnv.getAvailableFontFamilyNames(); + for (int i = 0; i < families.length; i++) { + fontComboBox.addItem(families[i]); + } + fontComboBox.setSelectedItem(fontChoice); + fontComboBox.addItemListener(this); + + styleComboBox.setSelectedIndex(0); + styleComboBox.addItemListener(this); + + sizeSpinner.addChangeListener(this); + + colorChooser.getSelectionModel().addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + updatePreviewColor(); + } + }); + + setFont(); + } + + // Get the appropriate color from our chooser and update previewLabel. + protected void updatePreviewColor() { + currentColor = colorChooser.getColor(); + textLabel.setForeground(currentColor); + // Manually force the label to repaint. + textLabel.repaint(); + } + + public int getFontStyle() { + return styleComboBox.getSelectedIndex(); + } + + public String getFontStyleAsString() { + return styleComboBox.getSelectedItem().toString(); + } + + public int getFontSize() { + int sizeChoice = 12; + try { + String size = sizeSpinner.getModel().getValue().toString(); + sizeChoice = Integer.parseInt(size); + } + catch (NumberFormatException nfe) { + } + return sizeChoice; + } + + public void setFont() { + textLabel.setFont(new Font(fontComboBox.getSelectedItem(). + toString(), + styleComboBox.getSelectedIndex(), + getFontSize())); + } + + /* + * Detect a state change in any of the settings and create a new + * Font with the corresponding settings. Set it on the test component. + */ + @Override + public void itemStateChanged(ItemEvent e) { + + if (e.getStateChange() != ItemEvent.SELECTED) { + return; + } + /* + if (e.getSource() == fonts) { + fontChoice = (String)fonts.getSelectedItem(); + } else { + styleChoice = styles.getSelectedIndex(); + } + */ + //textTestPanel.setFont(new Font(fontChoice, styleChoice, sizeChoice)); + setFont(); + + } + + @Override + public void stateChanged(ChangeEvent e) { + + setFont(); + + /* + try { + String size = sizes.getModel().getValue().toString(); + sizeChoice = Integer.parseInt(size); + textTestPanel.setFont(new Font(fontChoice,styleChoice,sizeChoice)); + } catch (NumberFormatException nfe) { + } + */ + } + +} diff --git a/src/main/java/cct/tools/ui/JPEGOptionsDialog.java b/src/main/java/cct/tools/ui/JPEGOptionsDialog.java new file mode 100644 index 0000000..4c71938 --- /dev/null +++ b/src/main/java/cct/tools/ui/JPEGOptionsDialog.java @@ -0,0 +1,202 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.ui; + +import java.awt.BorderLayout; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JOptionPane; +import javax.swing.JPanel; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class JPEGOptionsDialog + extends JDialog { + JPanel panel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JPanel jPanel2 = new JPanel(); + JButton helpButton = new JButton(); + JButton cancelButton = new JButton(); + JButton okButton = new JButton(); + JPEGOptionsPanel jPEGOptionsPanel1 = new JPEGOptionsPanel(); + + boolean okPressed = false; + + public JPEGOptionsDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JPEGOptionsDialog() { + this(new Frame(), "JPEGOptionsDialog", false); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + helpButton.setToolTipText(""); + helpButton.setText("Help"); + helpButton.addActionListener(new JPEGOptionsDialog_helpButton_actionAdapter(this)); + cancelButton.setToolTipText(""); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new JPEGOptionsDialog_cancelButton_actionAdapter(this)); + okButton.setToolTipText(""); + okButton.setText(" OK "); + okButton.addActionListener(new JPEGOptionsDialog_okButton_actionAdapter(this)); + this.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); + getContentPane().add(panel1); + panel1.add(jPanel2, BorderLayout.SOUTH); + jPanel2.add(okButton); + jPanel2.add(cancelButton); + jPanel2.add(helpButton); + panel1.add(jPEGOptionsPanel1, BorderLayout.NORTH); + + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent we) { + okPressed = false; + we.getWindow().setVisible(false); + } + }); + + } + + public int getJPEGQuality() { + return jPEGOptionsPanel1.getJPEGQuality(); + } + + public boolean isOptimizeHuffmanCode() { + return jPEGOptionsPanel1.isOptimizeHuffmanCode(); + } + + public boolean isProgressiveEncoding() { + return jPEGOptionsPanel1.isProgressiveEncoding(); + } + + public void okButton_actionPerformed(ActionEvent e) { + okPressed = true; + jPEGOptionsPanel1.validate(); + if (jPEGOptionsPanel1.isSaveSettingsAsDefault()) { + jPEGOptionsPanel1.saveSettingsAsDefault(); + } + this.setVisible(false); + } + + public void cancelButton_actionPerformed(ActionEvent e) { + okPressed = false; + this.setVisible(false); + } + + public boolean isOKPressed() { + return okPressed; + } + + public void helpButton_actionPerformed(ActionEvent e) { + JOptionPane.showMessageDialog(this, "JPEG is \"lossy,\" meaning that the decompressed image isn't quite the same \n"+ + "as the one you started with.\n"+ + "JPEG compressor lets you pick a file size vs. image quality tradeoff by\n"+ + "selecting a quality setting.\n"+ + "The quality scale is purely arbitrary; it's not a percentage of anything.\n"+ + "For good-quality, full-color source images, the default JPEG quality setting " + JPEGOptionsPanel.defaultJPEGQuality+"\n"+ + "is very often the best choice. This setting is about the lowest you can go\n"+ + "without expecting to see defects in a typical image. Try the default value first;\n"+ + "if you see defects, then go up.", "JPEG Options Help", + JOptionPane.INFORMATION_MESSAGE); + } + + private class JPEGOptionsDialog_helpButton_actionAdapter + implements ActionListener { + private JPEGOptionsDialog adaptee; + JPEGOptionsDialog_helpButton_actionAdapter(JPEGOptionsDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.helpButton_actionPerformed(e); + } + } + + private class JPEGOptionsDialog_cancelButton_actionAdapter + implements ActionListener { + private JPEGOptionsDialog adaptee; + JPEGOptionsDialog_cancelButton_actionAdapter(JPEGOptionsDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.cancelButton_actionPerformed(e); + } + } + + private class JPEGOptionsDialog_okButton_actionAdapter + implements ActionListener { + private JPEGOptionsDialog adaptee; + JPEGOptionsDialog_okButton_actionAdapter(JPEGOptionsDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.okButton_actionPerformed(e); + } + } +} diff --git a/src/main/java/cct/tools/ui/JPEGOptionsPanel.java b/src/main/java/cct/tools/ui/JPEGOptionsPanel.java new file mode 100644 index 0000000..f533815 --- /dev/null +++ b/src/main/java/cct/tools/ui/JPEGOptionsPanel.java @@ -0,0 +1,291 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.ui; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.SystemColor; +import java.util.prefs.Preferences; + +import javax.swing.BorderFactory; +import javax.swing.JCheckBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JSlider; +import javax.swing.JSpinner; +import javax.swing.SpinnerNumberModel; +import javax.swing.border.TitledBorder; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class JPEGOptionsPanel + extends JPanel { + + static String qualityKey = "JPEG_QUALITY"; + static String optimizeHuffmanKey = "OPTIMIZE_HUFFMAN_CODE"; + static String progressiveKey = "PROGRESSIVE_ENCODING"; + + final static int defaultJPEGQuality = 80; + boolean defaultOptimizeHuffmanCode = false; + boolean progressiveEncoding = false; + + Preferences prefs; + + BorderLayout borderLayout1 = new BorderLayout(); + JPanel imageQualityPanel = new JPanel(); + JSlider qualitySlider = new JSlider(); + JSpinner qualitySpinner = new JSpinner(); + JLabel jLabel1 = new JLabel(); + JLabel jLabel2 = new JLabel(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + JPanel jPanel1 = new JPanel(); + JPanel jPanel2 = new JPanel(); + JPanel jPanel3 = new JPanel(); + JCheckBox progressiveCheckBox = new JCheckBox(); + JCheckBox saveCheckBox = new JCheckBox(); + JCheckBox huffmanCheckBox = new JCheckBox(); + FlowLayout flowLayout1 = new FlowLayout(); + FlowLayout flowLayout2 = new FlowLayout(); + + public JPEGOptionsPanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(borderLayout1); + imageQualityPanel.setBorder(new TitledBorder(BorderFactory.createLineBorder(SystemColor.controlShadow, 1), "Image Quality")); + imageQualityPanel.setLayout(gridBagLayout1); + qualitySlider.setMajorTickSpacing(10); + qualitySlider.setMinorTickSpacing(5); + qualitySlider.setPaintTicks(true); + qualitySlider.addChangeListener(new JPEGOptionsPanel_qualitySlider_changeAdapter(this)); + jLabel1.setToolTipText(""); + jLabel1.setText("Best Quality"); + jLabel2.setText("Best Compression"); + progressiveCheckBox.setMargin(new Insets(2, 2, 2, 20)); + progressiveCheckBox.setMnemonic('0'); + progressiveCheckBox.setText("Progressive"); + saveCheckBox.setToolTipText(""); + saveCheckBox.setText("Save these settings as the default"); + huffmanCheckBox.setToolTipText(""); + huffmanCheckBox.setText("Optimize Huffman codes"); + jPanel3.setLayout(flowLayout1); + flowLayout1.setAlignment(FlowLayout.LEFT); + jPanel2.setLayout(flowLayout2); + flowLayout2.setAlignment(FlowLayout.LEFT); + jPanel3.setBorder(new TitledBorder(BorderFactory.createLineBorder(SystemColor.controlShadow, 1), "Encoding")); + qualitySpinner.addChangeListener(new JPEGOptionsPanel_qualitySpinner_changeAdapter(this)); + imageQualityPanel.add(jLabel2, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0 + , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + imageQualityPanel.add(qualitySlider, new GridBagConstraints(1, 1, 2, 1, 1.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); + imageQualityPanel.add(jLabel1, new GridBagConstraints(2, 2, 1, 1, 1.0, 1.0 + , GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + jPanel1.add(qualitySpinner); + imageQualityPanel.add(jPanel1, new GridBagConstraints(0, 0, 3, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); + jPanel2.add(saveCheckBox); + jPanel3.add(progressiveCheckBox); + jPanel3.add(huffmanCheckBox); + this.add(imageQualityPanel, BorderLayout.NORTH); + this.add(jPanel3, BorderLayout.CENTER); + this.add(jPanel2, BorderLayout.SOUTH); + + //qualitySlider.setValue(defaultJPEGQuality); + SpinnerNumberModel snm = new SpinnerNumberModel(85, 0, 100, 1); + qualitySpinner.setModel(snm); + //JSpinner.NumberEditor ne = new JSpinner.NumberEditor(qualitySpinner); + + int quality = defaultJPEGQuality; + boolean optHuffman = defaultOptimizeHuffmanCode; + boolean progressive_encode = progressiveEncoding; + + try { + prefs = Preferences.userNodeForPackage(this.getClass()); + quality = prefs.getInt(qualityKey, defaultJPEGQuality); + if (quality < 0 || quality > 100) { + quality = defaultJPEGQuality; + } + optHuffman = prefs.getBoolean(optimizeHuffmanKey, defaultOptimizeHuffmanCode); + progressive_encode = prefs.getBoolean(progressiveKey, progressiveEncoding); + } + catch (Exception ex) { + System.err.println("Error retrieving JPEG Preferences: " + + ex.getMessage() + " Ignored..."); + } + + qualitySpinner.setValue(new Integer(quality)); + qualitySlider.setValue(quality); + progressiveCheckBox.setSelected(progressive_encode); + huffmanCheckBox.setSelected(optHuffman); + + Font font = qualitySpinner.getFont(); + if (font.getSize() < 12) { + Font new_font = new Font(font.getName(), font.getStyle(), 12); + qualitySpinner.setFont(new_font); + } + } + + + public int getJPEGQuality() { + return qualitySlider.getValue(); + } + + public boolean isOptimizeHuffmanCode() { + return huffmanCheckBox.isSelected(); + } + + public boolean isProgressiveEncoding() { + return progressiveCheckBox.isSelected(); + } + + public boolean isSaveSettingsAsDefault() { + return saveCheckBox.isSelected(); + } + + public void saveSettingsAsDefault() { + try { + prefs = Preferences.userNodeForPackage(this.getClass()); + prefs.putInt(qualityKey, qualitySlider.getValue()); + prefs.putBoolean(optimizeHuffmanKey, huffmanCheckBox.isSelected()); + prefs.putBoolean(progressiveKey, progressiveCheckBox.isSelected()); + } + catch (Exception ex) { + System.err.println("Error saving JPEG Preferences: " + + ex.getMessage() + " Ignored..."); + } + } + + public void setJPEGQuality(int quality) { + if (quality < 0) { + quality = 0; + } + else if (quality > 100) { + quality = 100; + } + } + + public void qualitySpinner_stateChanged(ChangeEvent e) { + if (!qualitySpinner.isEnabled()) { + return; + } + qualitySpinner.setEnabled(false); + //SpinnerNumberModel snm = (SpinnerNumberModel)qualitySpinner.getModel(); + Object obj = qualitySpinner.getValue(); + int number = 0; + if (obj instanceof Integer) { + number = ( (Integer) obj).intValue(); + } + else { + number = Integer.parseInt(obj.toString()); + } + setSlider(number); + + qualitySpinner.setEnabled(true); + } + + private void setSlider(int number) { + qualitySlider.setEnabled(false); + qualitySlider.setValue(number); + qualitySlider.setEnabled(true); + } + + public void qualitySlider_stateChanged(ChangeEvent e) { + if (!qualitySlider.isEnabled()) { + return; + } + qualitySlider.setEnabled(false); + int value = qualitySlider.getValue(); + setSpinner(value); + qualitySlider.setEnabled(true); + } + + private void setSpinner(int value) { + qualitySpinner.setEnabled(false); + qualitySpinner.setValue(new Integer(value)); + qualitySpinner.setEnabled(true); + } + + private class JPEGOptionsPanel_qualitySpinner_changeAdapter + implements ChangeListener { + private JPEGOptionsPanel adaptee; + JPEGOptionsPanel_qualitySpinner_changeAdapter(JPEGOptionsPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.qualitySpinner_stateChanged(e); + } + } + + private class JPEGOptionsPanel_qualitySlider_changeAdapter + implements ChangeListener { + private JPEGOptionsPanel adaptee; + JPEGOptionsPanel_qualitySlider_changeAdapter(JPEGOptionsPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void stateChanged(ChangeEvent e) { + adaptee.qualitySlider_stateChanged(e); + } + } + +} diff --git a/src/main/java/cct/tools/ui/JShowText.java b/src/main/java/cct/tools/ui/JShowText.java new file mode 100644 index 0000000..a5501a9 --- /dev/null +++ b/src/main/java/cct/tools/ui/JShowText.java @@ -0,0 +1,336 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.ui; + +import java.awt.BorderLayout; +import java.awt.FileDialog; +import java.awt.Font; +import java.awt.GraphicsEnvironment; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.ByteArrayOutputStream; +import java.util.prefs.Preferences; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.WindowConstants; + +import cct.tools.IOUtils; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class JShowText + extends JFrame implements ActionListener { + + public static final int QUIT_WITHOUT_SAVING = 0; + public static final int QUIT_WITH_SAVING = 1; + + private Preferences prefs; + private FontSelectorDialog fontSelector = null; + private static String FontNameKey = "FontName"; + private static String FontSizeKey = "FontSize"; + private static String FontStyleKey = "FontStyle"; + private static String defaultFontName = "default"; + + private JPanel panel1 = new JPanel(); + private BorderLayout borderLayout1 = new BorderLayout(); + private JScrollPane jScrollPane1 = new JScrollPane(); + private JTextArea jTextArea1 = new JTextArea(); + private JPanel jPanel1 = new JPanel(); + private JButton actionButton = new JButton(); + private JMenuBar jMenuBar1 = new JMenuBar(); + private JMenu viewMenu = new JMenu(); + private JMenuItem increaseFontMenuItem = new JMenuItem(); + private JMenuItem decreaseFontMenuItem = new JMenuItem(); + private JMenuItem selectFontMenuItem = new JMenuItem(); + private JMenu fileMenu = new JMenu(); + private JMenuItem saveAsMenuItem = new JMenuItem(); + + private String defaultFileName = "jmoleditor-sysinfo.txt"; + private int buttonAction = QUIT_WITHOUT_SAVING; + + public JShowText(String title) { + //super(owner, title, modal); + super(title); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public JShowText() { + this("JShowText"); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + jTextArea1.setText("jTextArea1"); + actionButton.setToolTipText(""); + actionButton.setText("Quit"); + actionButton.addActionListener(new JShowText_jButton1_actionAdapter(this)); + viewMenu.setToolTipText(""); + viewMenu.setText("View"); + increaseFontMenuItem.setToolTipText(""); + increaseFontMenuItem.setText("Increase Font Size"); + increaseFontMenuItem.addActionListener(this); + decreaseFontMenuItem.addActionListener(this); + selectFontMenuItem.addActionListener(this); + decreaseFontMenuItem.setText("Decrease Font Size"); + selectFontMenuItem.setText("Select Font"); + fileMenu.setText("File"); + saveAsMenuItem.setText("Save As ..."); + saveAsMenuItem.addActionListener(new JShowText_saveAsMenuItem_actionAdapter(this)); + this.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); + getContentPane().add(panel1); + panel1.add(jScrollPane1, BorderLayout.CENTER); + this.getContentPane().add(jPanel1, BorderLayout.SOUTH); + jPanel1.add(actionButton); + jScrollPane1.getViewport().add(jTextArea1); + jMenuBar1.add(fileMenu); + jMenuBar1.add(viewMenu); + fileMenu.add(saveAsMenuItem); + viewMenu.add(increaseFontMenuItem); + viewMenu.add(decreaseFontMenuItem); + viewMenu.addSeparator(); + viewMenu.add(selectFontMenuItem); + jMenuBar1.add(viewMenu); + + this.setJMenuBar(jMenuBar1); + + // --- Retrieving font properties + + Font currentFont = jTextArea1.getFont(); + int size = currentFont.getSize(); + int style = currentFont.getStyle(); + String fontName = currentFont.getFontName(); + + try { + prefs = Preferences.userNodeForPackage(this.getClass()); + fontName = prefs.get(FontNameKey, currentFont.getFontName()); + size = prefs.getInt(FontSizeKey, 12); + style = prefs.getInt(FontStyleKey, 0); + } + catch (Exception ex) { + System.err.println("Error retrieving Font Preferences: " + ex.getMessage()); + return; + } + + GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment(); + + Font newFont = new Font(fontName, style, size); + jTextArea1.setFont(newFont); + + setupActionButton(); + } + + private void setupActionButton() { + switch (buttonAction) { + case QUIT_WITH_SAVING: + actionButton.setText("Save & Quit"); + actionButton.setToolTipText("Quit with saving text"); + break; + case QUIT_WITHOUT_SAVING: + default: + actionButton.setText("Quit"); + actionButton.setToolTipText("Quit without saving text"); + } + } + + public void setActionButton(int action) { + buttonAction = action; + setupActionButton(); + } + + public void setButtonText(String text) { + actionButton.setText(text); + } + + public void setDefaultFileName(String name) { + defaultFileName = name; + } + + public void setText(String text) { + jTextArea1.setText(text); + jTextArea1.setCaretPosition(0); + } + + public void appendText(String text) { + jTextArea1.append(text); + } + + public void setText(ByteArrayOutputStream stream) { + jTextArea1.setText(stream.toString()); + } + + public void jButton1_actionPerformed(ActionEvent e) { + switch (buttonAction) { + case QUIT_WITH_SAVING: + saveTextIntoFile(); + break; + case QUIT_WITHOUT_SAVING: + default: + } + setVisible(false); + } + + public void enableTextEditing(boolean enable) { + jTextArea1.setEditable(enable); + } + + @Override + public void actionPerformed(ActionEvent actionEvent) { + if (actionEvent.getSource() == increaseFontMenuItem) { + Font currentFont = jTextArea1.getFont(); + int size = currentFont.getSize() + 1; + Font newFont = new Font(currentFont.getName(), currentFont.getStyle(), + size); + jTextArea1.setFont(newFont); + saveFontPreferences(); + } + else if (actionEvent.getSource() == decreaseFontMenuItem) { + Font currentFont = jTextArea1.getFont(); + int size = currentFont.getSize(); + size = size > 8 ? size - 1 : size; + Font newFont = new Font(currentFont.getName(), currentFont.getStyle(), + size); + jTextArea1.setFont(newFont); + saveFontPreferences(); + } + else if (actionEvent.getSource() == selectFontMenuItem) { + if (fontSelector == null) { + fontSelector = new FontSelectorDialog(this, "Select Font", true); + } + fontSelector.setVisible(true); + if (!fontSelector.okPressed) { + return; + } + Font newFont = new Font(fontSelector.getFontName(), + fontSelector.getFontStyle(), + fontSelector.getFontSize()); + jTextArea1.setFont(newFont); + saveFontPreferences(); + } + } + + private void saveFontPreferences() { + Font currentFont = jTextArea1.getFont(); + try { + prefs.put(FontNameKey, currentFont.getFontName()); + prefs.putInt(FontSizeKey, currentFont.getSize()); + prefs.putInt(FontStyleKey, currentFont.getStyle()); + prefs.flush(); + } + catch (Exception ex) { + System.err.println("Error saving Font Preferences: " + + ex.getMessage()); + } + } + + public void saveAsMenuItem_actionPerformed(ActionEvent e) { + saveTextIntoFile(); + } + + private void saveTextIntoFile() { + String text = jTextArea1.getText(); + if (text == null || text.length() < 1) { + JOptionPane.showMessageDialog(this, "Nothing to save", "Warning", JOptionPane.WARNING_MESSAGE); + return; + } + + FileDialog fd = new FileDialog(this, "Save File", FileDialog.SAVE); + fd.setFile(defaultFileName); + fd.setVisible(true); + if (fd.getFile() != null) { + String fileName = fd.getFile(); + String workingDirectory = fd.getDirectory(); + try { + IOUtils.saveStringIntoFile(text, workingDirectory + fileName); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error Saving file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + } + } + + class JShowText_saveAsMenuItem_actionAdapter + implements ActionListener { + private JShowText adaptee; + JShowText_saveAsMenuItem_actionAdapter(JShowText adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.saveAsMenuItem_actionPerformed(e); + } + } + + class JShowText_jButton1_actionAdapter + implements ActionListener { + private JShowText adaptee; + JShowText_jButton1_actionAdapter(JShowText adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.jButton1_actionPerformed(e); + } + } +} diff --git a/src/main/java/cct/tools/ui/JTextAreaOutputStream.java b/src/main/java/cct/tools/ui/JTextAreaOutputStream.java new file mode 100644 index 0000000..dd9d67c --- /dev/null +++ b/src/main/java/cct/tools/ui/JTextAreaOutputStream.java @@ -0,0 +1,115 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.ui; + +import java.io.OutputStream; + +import javax.swing.JTextArea; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class JTextAreaOutputStream + extends OutputStream { + + JTextArea textArea = null; + + public JTextAreaOutputStream(JTextArea jTextArea) { + super(); + textArea = jTextArea; + } + + /** + * Has no effect + */ + @Override + public void close() { + } + + /** + * Flushes this output stream and forces any buffered output bytes to be written out. + */ + @Override + public void flush() { + try { + super.flush(); + } + catch (Exception ex) { + + } + textArea.validate(); + } + + /** + * Writes b.length bytes from the specified byte array to this output stream. + * @param b byte[] + */ + @Override + public void write(byte[] b) { + textArea.append(new String(b)); + } + + /** + * Writes len bytes from the specified byte array starting at offset off to this output stream. + * @param b byte[] + * @param off int + * @param len int + */ + @Override + public void write(byte[] b, int off, int len) { + textArea.append(new String(b, off, len)); + } + + /** + * Writes the specified byte to this output stream + * @param b int + */ + @Override + public void write(int b) { + textArea.append(String.valueOf(b)); + } +} diff --git a/src/main/java/cct/tools/ui/JobProgressInterface.java b/src/main/java/cct/tools/ui/JobProgressInterface.java new file mode 100644 index 0000000..275a182 --- /dev/null +++ b/src/main/java/cct/tools/ui/JobProgressInterface.java @@ -0,0 +1,24 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.tools.ui; + +/** + * + * @author vvv900 + */ +public interface JobProgressInterface { + + void setProgress(int p); + + void setProgress(double p); + + void setProgress(float p); + + void setProgressText(String text); + + void setTaskDescription(String text); + + boolean isCanceled(); +} diff --git a/src/main/java/cct/tools/ui/LogPanel.java b/src/main/java/cct/tools/ui/LogPanel.java new file mode 100644 index 0000000..4dfcd2c --- /dev/null +++ b/src/main/java/cct/tools/ui/LogPanel.java @@ -0,0 +1,383 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.tools.ui; + +import java.awt.BorderLayout; +import java.awt.FileDialog; +import java.awt.Font; +import java.awt.GraphicsEnvironment; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.ByteArrayOutputStream; +import java.util.prefs.Preferences; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.WindowConstants; +import javax.swing.event.CaretEvent; +import javax.swing.event.CaretListener; + +import cct.tools.IOUtils; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class LogPanel + extends JFrame implements ActionListener { + + Preferences prefs; + FontSelectorDialog fontSelector = null; + static String FontNameKey = "FontName"; + static String FontSizeKey = "FontSize"; + static String FontStyleKey = "FontStyle"; + static String defaultFontName = "default"; + JPanel panel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JScrollPane jScrollPane1 = new JScrollPane(); + JTextArea jTextArea1 = new JTextArea(); + JPanel jPanel1 = new JPanel(); + JButton clearButton = new JButton(); + JMenuBar jMenuBar1 = new JMenuBar(); + JMenu viewMenu = new JMenu(); + JMenuItem increaseFontMenuItem = new JMenuItem(); + JMenuItem decreaseFontMenuItem = new JMenuItem(); + JMenuItem selectFontMenuItem = new JMenuItem(); + JButton hideButton = new JButton(); + JMenu fileMenu = new JMenu(); + JMenuItem saveAsMenuItem = new JMenuItem(); + JMenuItem hideMenuItem = new JMenuItem(); + LogPanel_jTextArea1_caretAdapter caretUpdateAdaptor = null; + + public LogPanel(String title) { + super(title); + //super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public LogPanel() { + this("LogPanel"); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + jTextArea1.setEditable(false); + jTextArea1.setText("jTextArea1"); + clearButton.setToolTipText("Clear Log"); + clearButton.setText("Clear Log"); + clearButton.addActionListener(new LogPanel_jButton1_actionAdapter(this)); + viewMenu.setToolTipText(""); + viewMenu.setText("View"); + increaseFontMenuItem.setToolTipText(""); + increaseFontMenuItem.setText("Increase Font Size"); + increaseFontMenuItem.addActionListener(this); + decreaseFontMenuItem.addActionListener(this); + selectFontMenuItem.addActionListener(this); + decreaseFontMenuItem.setText("Decrease Font Size"); + selectFontMenuItem.setText("Select Font"); + this.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); + hideButton.setToolTipText("Hide a Panel"); + hideButton.setText("Hide"); + hideButton.addActionListener(new LogPanel_hideButton_actionAdapter(this)); + fileMenu.setText("File"); + saveAsMenuItem.setText("Save As"); + saveAsMenuItem.addActionListener(new LogPanel_saveAsMenuItem_actionAdapter(this)); + hideMenuItem.setText("Hide"); + hideMenuItem.addActionListener(new LogPanel_hideMenuItem_actionAdapter(this)); + getContentPane().add(panel1); + panel1.add(jScrollPane1, BorderLayout.CENTER); + this.getContentPane().add(jPanel1, BorderLayout.SOUTH); + jPanel1.add(hideButton); + jPanel1.add(clearButton); + jScrollPane1.getViewport().add(jTextArea1); + jMenuBar1.add(fileMenu); + jMenuBar1.add(viewMenu); + fileMenu.add(saveAsMenuItem); + fileMenu.add(hideMenuItem); + viewMenu.add(increaseFontMenuItem); + viewMenu.add(decreaseFontMenuItem); + viewMenu.addSeparator(); + viewMenu.add(selectFontMenuItem); + jMenuBar1.add(viewMenu); + + this.setJMenuBar(jMenuBar1); + + // --- Retrieving font properties + + Font currentFont = jTextArea1.getFont(); + int size = currentFont.getSize(); + int style = currentFont.getStyle(); + String fontName = currentFont.getFontName(); + + try { + prefs = Preferences.userNodeForPackage(this.getClass()); + fontName = prefs.get(FontNameKey, currentFont.getFontName()); + size = prefs.getInt(FontSizeKey, 12); + style = prefs.getInt(FontStyleKey, 0); + } catch (Exception ex) { + System.err.println("Error retrieving Font Preferences: " + ex.getMessage()); + return; + } + + GraphicsEnvironment gEnv = + GraphicsEnvironment.getLocalGraphicsEnvironment(); + + Font newFont = new Font(fontName, style, size); + jTextArea1.setFont(newFont); + } + + public JTextArea getTextArea() { + return jTextArea1; + } + + public void popupOnUpdate(boolean popup) { + if (popup) { + if (caretUpdateAdaptor == null) { + caretUpdateAdaptor = new LogPanel_jTextArea1_caretAdapter(this); + } + jTextArea1.addCaretListener(caretUpdateAdaptor); + } else { + if (caretUpdateAdaptor != null) { + jTextArea1.removeCaretListener(caretUpdateAdaptor); + } + } + } + + public void addButton(JButton button) { + jPanel1.add(button); + } + + public void setText(String text) { + jTextArea1.setText(text); + } + + public String getText() { + return jTextArea1.getText(); + } + + public void appendText(String text) { + jTextArea1.append(text); + } + + public void setText(ByteArrayOutputStream stream) { + jTextArea1.setText(stream.toString()); + } + + public void jButton1_actionPerformed(ActionEvent e) { + this.jTextArea1.setText(""); + } + + @Override + public void actionPerformed(ActionEvent actionEvent) { + if (actionEvent.getSource() == increaseFontMenuItem) { + Font currentFont = jTextArea1.getFont(); + int size = currentFont.getSize() + 1; + Font newFont = new Font(currentFont.getName(), currentFont.getStyle(), + size); + jTextArea1.setFont(newFont); + saveFontPreferences(); + } else if (actionEvent.getSource() == decreaseFontMenuItem) { + Font currentFont = jTextArea1.getFont(); + int size = currentFont.getSize(); + size = size > 8 ? size - 1 : size; + Font newFont = new Font(currentFont.getName(), currentFont.getStyle(), + size); + jTextArea1.setFont(newFont); + saveFontPreferences(); + } else if (actionEvent.getSource() == selectFontMenuItem) { + if (fontSelector == null) { + fontSelector = new FontSelectorDialog(this, "Select Font", true); + } + fontSelector.setVisible(true); + if (!fontSelector.okPressed) { + return; + } + Font newFont = new Font(fontSelector.getFontName(), + fontSelector.getFontStyle(), + fontSelector.getFontSize()); + jTextArea1.setFont(newFont); + saveFontPreferences(); + } + } + + private void saveFontPreferences() { + Font currentFont = jTextArea1.getFont(); + try { + prefs.put(FontNameKey, currentFont.getFontName()); + prefs.putInt(FontSizeKey, currentFont.getSize()); + prefs.putInt(FontStyleKey, currentFont.getStyle()); + prefs.flush(); + } catch (Exception ex) { + System.err.println("Error saving Font Preferences: " + + ex.getMessage()); + } + } + + public void hideButton_actionPerformed(ActionEvent e) { + this.setVisible(false); + } + + public void hideMenuItem_actionPerformed(ActionEvent e) { + this.setVisible(false); + } + + public void saveAsMenuItem_actionPerformed(ActionEvent e) { + String text = jTextArea1.getText(); + if (text == null || text.length() < 1) { + JOptionPane.showMessageDialog(this, + "Nothing to save", "Warning", + JOptionPane.WARNING_MESSAGE); + return; + } + + FileDialog fd = new FileDialog(this, "Save Errors Log into Text File", + FileDialog.SAVE); + fd.setFile("jmoleditor-stderr.txt"); + fd.setVisible(true); + if (fd.getFile() != null) { + String fileName = new String(fd.getFile()); + String workingDirectory = new String(fd.getDirectory()); + try { + IOUtils.saveStringIntoFile(text, workingDirectory + fileName); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Error Saving Errors Log: " + ex.getMessage(), "Error", + JOptionPane.ERROR_MESSAGE); + } + } + } + + public void jTextArea1_caretUpdate(CaretEvent e) { + this.setVisible(true); + } + + private class LogPanel_hideButton_actionAdapter + implements ActionListener { + + private LogPanel adaptee; + + LogPanel_hideButton_actionAdapter(LogPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.hideButton_actionPerformed(e); + } + } + + private class LogPanel_jButton1_actionAdapter + implements ActionListener { + + private LogPanel adaptee; + + LogPanel_jButton1_actionAdapter(LogPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.jButton1_actionPerformed(e); + } + } + + class LogPanel_jTextArea1_caretAdapter + implements CaretListener { + + private LogPanel adaptee; + + LogPanel_jTextArea1_caretAdapter(LogPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void caretUpdate(CaretEvent e) { + adaptee.jTextArea1_caretUpdate(e); + } + } + + class LogPanel_saveAsMenuItem_actionAdapter + implements ActionListener { + + private LogPanel adaptee; + + LogPanel_saveAsMenuItem_actionAdapter(LogPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.saveAsMenuItem_actionPerformed(e); + } + } + + class LogPanel_hideMenuItem_actionAdapter + implements ActionListener { + + private LogPanel adaptee; + + LogPanel_hideMenuItem_actionAdapter(LogPanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.hideMenuItem_actionPerformed(e); + } + } +} diff --git a/src/main/java/cct/tools/ui/MemoryMonitorFrame.java b/src/main/java/cct/tools/ui/MemoryMonitorFrame.java new file mode 100644 index 0000000..5c76e1d --- /dev/null +++ b/src/main/java/cct/tools/ui/MemoryMonitorFrame.java @@ -0,0 +1,133 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.ui; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; + +import javax.swing.JFrame; + +import cct.tools.MemoryMonitor; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class MemoryMonitorFrame extends JFrame { + + final MemoryMonitor monitor = new MemoryMonitor(); + BorderLayout borderLayout1 = new BorderLayout(); + + public MemoryMonitorFrame() { + super("Memory Monitor"); + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + getContentPane().setLayout(borderLayout1); + + monitor.surf.start(); + this.addWindowListener(new MemoryMonitorFrame_this_windowAdapter(this)); + this.getContentPane().add(monitor, BorderLayout.CENTER); + + //WindowListener l = new WindowAdapter() { + //public void windowClosing(WindowEvent e) { } + //public void windowDeiconified(WindowEvent e) { monitor.surf.start(); } + //public void windowIconified(WindowEvent e) { monitor.surf.stop(); } + //}; + + } + + public static void main(String s[]) { + MemoryMonitorFrame demo = new MemoryMonitorFrame(); + WindowListener l = new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + System.exit(0); + } + //public void windowDeiconified(WindowEvent e) { monitor.surf.start(); } + //public void windowIconified(WindowEvent e) { monitor.surf.stop(); } + }; + demo.addWindowListener(l); + demo.pack(); + demo.setSize(new Dimension(200, 200)); + demo.setVisible(true); + } + + public void this_windowClosing(WindowEvent e) { + this.setVisible(false); + } + + public void this_windowIconified(WindowEvent e) { + monitor.surf.stop(); + } + + public void this_windowDeiconified(WindowEvent e) { + monitor.surf.start(); + } + +} + +class MemoryMonitorFrame_this_windowAdapter + extends WindowAdapter { + private MemoryMonitorFrame adaptee; + MemoryMonitorFrame_this_windowAdapter(MemoryMonitorFrame adaptee) { + this.adaptee = adaptee; + } + + @Override + public void windowClosing(WindowEvent e) { + adaptee.this_windowClosing(e); + } +} diff --git a/src/main/java/cct/tools/ui/PostMessageDialog.java b/src/main/java/cct/tools/ui/PostMessageDialog.java new file mode 100644 index 0000000..5fd09f5 --- /dev/null +++ b/src/main/java/cct/tools/ui/PostMessageDialog.java @@ -0,0 +1,215 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.ui; + +import java.awt.BorderLayout; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JOptionPane; +import javax.swing.JPanel; + +import cct.tools.MessagePost; +import cct.tools.PostMessageType; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ + + +public class PostMessageDialog + extends JDialog implements ActionListener { + + public static final int EMAIL_IS_OPTIONAL = 0; + public static final int EMAIL_IS_OPTIONAL_BUT_WARN = 2; + public static final int EMAIL_IS_MANDATORY = 1; + + private JPanel panel1 = new JPanel(); + private BorderLayout borderLayout1 = new BorderLayout(); + private JPanel buttonsPanel = new JPanel(); + private PostMessagePanel postMessagePanel1 = new PostMessagePanel(); + private JButton cancelButton = new JButton(); + private JButton postButton = new JButton(); + + private PostMessageType messageType = PostMessageType.SUGGESTION; + + private int emailOption = EMAIL_IS_OPTIONAL; + static String URL_Address = "http://dc2.apac.edu.au/~vvv900/cct/appl/jmoleditor/leave-message.php"; + + public PostMessageDialog(Frame owner, String title, boolean modal) { + super(owner, title, modal); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public void setEmailImportance(int type) { + switch (type) { + case EMAIL_IS_OPTIONAL: + case EMAIL_IS_OPTIONAL_BUT_WARN: + case EMAIL_IS_MANDATORY: + emailOption = type; + break; + default: + emailOption = EMAIL_IS_OPTIONAL; + } + } + + public void setDialogType(PostMessageType type) { + messageType = type; + switch (messageType) { + case SUGGESTION: + postMessagePanel1.setInitialText("Please, type your suggestion(s) here..."); + break; + case BUG_REPORT: + postMessagePanel1.setInitialText("Please, report a bug here.\nTell exactly what you did\n" + + "Which GUI controls you selected and what order you selected them in.\n" + + "If the program reads from a file, you will probably need to send a copy of the file.\n" + + "Above all, be precise. Programmers like precision... :-)"); + break; + } + + } + + public void setMessage(String message) { + postMessagePanel1.setMessage(message); + } + + public PostMessageDialog() { + this(new Frame(), "PostMessageDialog", false); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + cancelButton.setToolTipText(""); + cancelButton.setText("Cancel"); + postButton.setToolTipText("Post Message"); + postButton.setText("Post"); + getContentPane().add(panel1); + panel1.add(buttonsPanel, BorderLayout.SOUTH); + buttonsPanel.add(postButton); + buttonsPanel.add(cancelButton); + panel1.add(postMessagePanel1, BorderLayout.CENTER); + + cancelButton.addActionListener(this); + postButton.addActionListener(this); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == cancelButton) { + + } + else if (e.getSource() == postButton) { + + boolean emailEntered = postMessagePanel1.getEmailAddress().length() > 0 && postMessagePanel1.getEmailAddress().contains("@"); + switch (emailOption) { + case EMAIL_IS_OPTIONAL: + break; + case EMAIL_IS_OPTIONAL_BUT_WARN: + int n = JOptionPane.showConfirmDialog(this, "Warning: You didn't specify your e-mail address.\n" + + "Without your e-mail address it will be impossible to contact you to get more info about the bug\n" + + "Continue to send bug report - Press Yes", "Warning", JOptionPane.YES_NO_OPTION); + if (n == JOptionPane.NO_OPTION || n == JOptionPane.CLOSED_OPTION) { + return; + } + break; + case EMAIL_IS_MANDATORY: + JOptionPane.showMessageDialog(this, "E-mail address is mandatory", "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + MessagePost post = new MessagePost(URL_Address); + String string = postMessagePanel1.getMessage().trim(); + if (string.length() < 1) { + JOptionPane.showMessageDialog(this, "Nothing to send...", "Warning", JOptionPane.WARNING_MESSAGE); + return; + } + + String key = ""; + switch (messageType) { + case SUGGESTION: + key = "suggest"; + break; + case BUG_REPORT: + key = "bug"; + break; + } + + try { + post.addMessage(key, string); + + string = postMessagePanel1.getUserName(); + if (string.length() > 0) { + post.addMessage("name", string); + } + string = postMessagePanel1.getEmailAddress(); + if (string.length() > 0) { + post.addMessage("email", string); + } + + post.postMessage(); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error Posting Message: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return; + } + postMessagePanel1.savePreferences(); + JOptionPane.showMessageDialog(this, post.getResponseMessage(), "Server Response", JOptionPane.INFORMATION_MESSAGE); + } + setVisible(false); + } + +} diff --git a/src/main/java/cct/tools/ui/PostMessagePanel.java b/src/main/java/cct/tools/ui/PostMessagePanel.java new file mode 100644 index 0000000..cd1467d --- /dev/null +++ b/src/main/java/cct/tools/ui/PostMessagePanel.java @@ -0,0 +1,209 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.ui; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +import javax.swing.BorderFactory; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.border.TitledBorder; + +import cct.tools.Utils; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class PostMessagePanel + extends JPanel { + + static final String nameKey = "name"; + static final String emailKey = "email"; + + private JLabel jLabel1 = new JLabel(); + private JTextField nameTextField = new JTextField(); + private JTextArea messageTextArea = new JTextArea(); + private JLabel jLabel2 = new JLabel(); + private JTextField emailTextField = new JTextField(); + private GridBagLayout gridBagLayout1 = new GridBagLayout(); + + boolean initialized = false; + private MyMouseAdapter mouseAdapter = null; + private JScrollPane jScrollPane1 = new JScrollPane(); + private JPanel jPanel1 = new JPanel(); + private BorderLayout borderLayout1 = new BorderLayout(); + + private boolean nameIsOptional = true; + + public PostMessagePanel() { + try { + jbInit(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setLayout(gridBagLayout1); + jLabel1.setToolTipText(""); + jLabel1.setText("Your Name " + (nameIsOptional ? "(Optional)" : "")); + jLabel2.setToolTipText(""); + jLabel2.setText("Your e-mail (Optional)"); + nameTextField.setToolTipText("Your Name"); + emailTextField.setToolTipText("Your e-mail address"); + messageTextArea.setMinimumSize(new Dimension(20, 20)); + messageTextArea.setColumns(50); + messageTextArea.setLineWrap(true); + messageTextArea.setRows(10); + jPanel1.setLayout(borderLayout1); + jPanel1.setBorder(BorderFactory.createEmptyBorder()); + jScrollPane1.setBorder(new TitledBorder(BorderFactory.createLineBorder(new Color(127, 157, 185), 1), "Your Message")); + this.add(nameTextField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); + this.add(jLabel1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + this.add(jLabel2, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + this.add(emailTextField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); + jScrollPane1.getViewport().add(jPanel1); + this.add(jScrollPane1, new GridBagConstraints(0, 2, 2, 1, 1.0, 1.0 + , GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, + 0)); + jPanel1.add(messageTextArea, BorderLayout.CENTER); + Font currentFont = messageTextArea.getFont(); + int size = currentFont.getSize(); + int style = currentFont.getStyle(); + String fontName = currentFont.getFontName(); + if (size < 12) { + size = 12; + Font newFont = new Font(fontName, style, size); + messageTextArea.setFont(newFont); + } + + String name = Utils.getPreference(this, nameKey); + name = Utils.getPreference(this, emailKey); + } + + public void savePreferences() { + Utils.savePreference(this, emailKey, emailTextField.getText()); + Utils.savePreference(this, nameKey, nameTextField.getText()); + } + + public void setMessage(String text) { + initialized = true; + if (mouseAdapter != null) { + messageTextArea.removeMouseListener(mouseAdapter); + } + messageTextArea.setText(text); + } + + public void appendMessage(String text) { + initialized = true; + if (mouseAdapter != null) { + messageTextArea.removeMouseListener(mouseAdapter); + } + messageTextArea.append(text); + } + + public void setInitialText(String text) { + if (initialized) { + return; + } + messageTextArea.setText(text); + mouseAdapter = new MyMouseAdapter(this); + messageTextArea.addMouseListener(mouseAdapter); + } + + public String getMessage() { + + if (!initialized) { + return ""; + } + return messageTextArea.getText(); + } + + public void messageTextArea_mouseClicked(MouseEvent e) { + initialized = true; + messageTextArea.setText(""); + messageTextArea.removeMouseListener(mouseAdapter); + } + + public String getEmailAddress() { + return emailTextField.getText().trim(); + } + + public String getUserName() { + return nameTextField.getText().trim(); + } + + class MyMouseAdapter + extends MouseAdapter { + private PostMessagePanel adaptee; + MyMouseAdapter(PostMessagePanel adaptee) { + this.adaptee = adaptee; + } + + @Override + public void mouseClicked(MouseEvent e) { + adaptee.messageTextArea_mouseClicked(e); + } + } + +} diff --git a/src/main/java/cct/tools/ui/SelectFromListDialog.java b/src/main/java/cct/tools/ui/SelectFromListDialog.java new file mode 100644 index 0000000..adf3790 --- /dev/null +++ b/src/main/java/cct/tools/ui/SelectFromListDialog.java @@ -0,0 +1,173 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tools.ui; + +import java.awt.BorderLayout; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JList; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.ListSelectionModel; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class SelectFromListDialog + extends JDialog implements ActionListener { + private JPanel panel1 = new JPanel(); + private BorderLayout borderLayout1 = new BorderLayout(); + private BorderLayout borderLayout2 = new BorderLayout(); + private JPanel jPanel1 = new JPanel(); + private JButton cancelButton = new JButton(); + private JButton okButton = new JButton(); + private JScrollPane jScrollPane1 = new JScrollPane(); + private JList jList1 = new JList(); + private JButton helpButton = new JButton(); + + public SelectFromListDialog(Frame owner, String title) { + super(owner, title, true); + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public SelectFromListDialog() { + this(new Frame(), "SelectFromListDialog"); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + this.getContentPane().setLayout(borderLayout2); + cancelButton.setToolTipText(""); + cancelButton.setText("Cancel"); + okButton.setToolTipText(""); + okButton.setText(" OK "); + this.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); + helpButton.setToolTipText(""); + helpButton.setText("Help"); + helpButton.addActionListener(new SelectFromListDialog_helpButton_actionAdapter(this)); + this.getContentPane().add(panel1, BorderLayout.CENTER); + this.getContentPane().add(jPanel1, BorderLayout.SOUTH); + jPanel1.add(okButton); + jPanel1.add(cancelButton); + jPanel1.add(helpButton); + panel1.add(jScrollPane1, BorderLayout.CENTER); + jScrollPane1.getViewport().add(jList1); + cancelButton.addActionListener(this); + okButton.addActionListener(this); + } + + public void setListData(Object[] list) { + jList1.setListData(list); + } + + public void selectItem(Object item, boolean enable) { + jList1.setSelectedValue(item, enable); + } + + public void enableMultipleSelection(boolean enable) { + if (enable) { + jList1.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + } + else { + jList1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + } + } + + public Object getSelectedItem() { + return jList1.getSelectedValue(); + } + + public Object[] getSelectedItems() { + return jList1.getSelectedValuesList().toArray(); + } + + @Override + public void actionPerformed(ActionEvent actionEvent) { + this.setVisible(false); + if (actionEvent.getSource() == cancelButton) { + jList1.clearSelection(); + } + } + + public void helpButton_actionPerformed(ActionEvent e) { + JOptionPane.showMessageDialog(this, "To select/deselect particular items hold down the \"Ctrl\" key\n" + + "To select a block of items hold down the \"Shift\" key\n", "Select Items Help", + JOptionPane.INFORMATION_MESSAGE); + } + + public static void main(String s[]) { + Object[] list = {"HF","B3LYP","WB97XD","MP2","MP4", "CCSD","CCSD(T)","CBS-QB3"}; + SelectFromListDialog dial = new SelectFromListDialog(); + dial.setListData(list); + dial.setVisible(true); + } +} + +class SelectFromListDialog_helpButton_actionAdapter + implements ActionListener { + private SelectFromListDialog adaptee; + SelectFromListDialog_helpButton_actionAdapter(SelectFromListDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.helpButton_actionPerformed(e); + } +} diff --git a/src/main/java/cct/tools/ui/TaskProgessDialog.form b/src/main/java/cct/tools/ui/TaskProgessDialog.form new file mode 100644 index 0000000..8c26348 --- /dev/null +++ b/src/main/java/cct/tools/ui/TaskProgessDialog.form @@ -0,0 +1,80 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/cct/tools/ui/TaskProgessDialog.java b/src/main/java/cct/tools/ui/TaskProgessDialog.java new file mode 100644 index 0000000..2b947f4 --- /dev/null +++ b/src/main/java/cct/tools/ui/TaskProgessDialog.java @@ -0,0 +1,191 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.tools.ui; + +import javax.swing.JLabel; + +/** + * + * @author Vlad + */ +public class TaskProgessDialog extends javax.swing.JDialog implements JobProgressInterface { + + private boolean canceled = false; + + /** + * Creates new form TaskProgessDialog + */ + public TaskProgessDialog(java.awt.Frame parent, boolean modal) { + super(parent, modal); + initComponents(); + } + + public void setProgress(double p) { + setProgress((int) p); + } + + public void setProgress(float p) { + setProgress((int) p); + } + + public void setProgress(int p) { + taskProgressBar.setIndeterminate(false); + taskProgressBar.setValue(p); + taskProgressBar.setStringPainted(true); + } + + public void setProgressText(String text) { + taskProgressBar.setIndeterminate(false); + taskProgressBar.setString(text); + this.validate(); + this.pack(); + } + + public String getTaskDescription() { + return taskDescriptionLabel.getText(); + } + + public void setTaskDescription(String taskDescription) { + this.taskDescriptionLabel.setText(taskDescription); + this.validate(); + this.pack(); + } + + public int getMinimumValue() { + return taskProgressBar.getMinimum(); + } + + public int getMaximumValue(int n) { + return taskProgressBar.getMaximum(); + } + + public void setMinimumValue(int n) { + taskProgressBar.setMinimum(n); + } + + public void setMaximumValue(int n) { + taskProgressBar.setMaximum(n); + } + + public boolean isCanceled() { + return canceled; + } + + public void setCanceled(boolean value) { + canceled = value; + } + + public void showCancelButton(boolean show) { + cancelButton.setVisible(show); + } + + public void showHelpButton(boolean show) { + helpButton.setVisible(show); + } + + /** + * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The + * content of this method is always regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + taskProgressBar = new javax.swing.JProgressBar(); + jPanel1 = new javax.swing.JPanel(); + cancelButton = new javax.swing.JButton(); + helpButton = new javax.swing.JButton(); + jPanel2 = new javax.swing.JPanel(); + taskDescriptionLabel = new JLabel(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + + taskProgressBar.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5)); + taskProgressBar.setIndeterminate(true); + getContentPane().add(taskProgressBar, java.awt.BorderLayout.CENTER); + + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + cancelButtonActionPerformed(evt); + } + }); + jPanel1.add(cancelButton); + + helpButton.setText("Help"); + jPanel1.add(helpButton); + + getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH); + + taskDescriptionLabel.setText("Task Progress..."); + jPanel2.add(taskDescriptionLabel); + + getContentPane().add(jPanel2, java.awt.BorderLayout.NORTH); + + pack(); + }// //GEN-END:initComponents + + private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed + canceled = true; + taskProgressBar.setString("Cancel signal was sent... "); + }//GEN-LAST:event_cancelButtonActionPerformed + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + /* + * Set the Nimbus look and feel + */ + // + /* + * If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. For details see + * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html + */ + try { + for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + javax.swing.UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (ClassNotFoundException ex) { + java.util.logging.Logger.getLogger(TaskProgessDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (InstantiationException ex) { + java.util.logging.Logger.getLogger(TaskProgessDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + java.util.logging.Logger.getLogger(TaskProgessDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (javax.swing.UnsupportedLookAndFeelException ex) { + java.util.logging.Logger.getLogger(TaskProgessDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + // + + /* + * Create and display the dialog + */ + java.awt.EventQueue.invokeLater(new Runnable() { + + public void run() { + TaskProgessDialog dialog = new TaskProgessDialog(new javax.swing.JFrame(), true); + dialog.addWindowListener(new java.awt.event.WindowAdapter() { + + @Override + public void windowClosing(java.awt.event.WindowEvent e) { + System.exit(0); + } + }); + dialog.setVisible(true); + } + }); + } + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton cancelButton; + private javax.swing.JButton helpButton; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + private JLabel taskDescriptionLabel; + private javax.swing.JProgressBar taskProgressBar; + // End of variables declaration//GEN-END:variables +} diff --git a/src/main/java/cct/tools/ui/TextToPost.java b/src/main/java/cct/tools/ui/TextToPost.java new file mode 100644 index 0000000..b9c61f7 --- /dev/null +++ b/src/main/java/cct/tools/ui/TextToPost.java @@ -0,0 +1,107 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.tools.ui; + +import cct.GlobalSettings; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JOptionPane; + +import cct.tools.PostMessageType; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class TextToPost + implements ActionListener { + + LogPanel Origin = null; + //PostMessageDialog Target = null; + + public TextToPost(LogPanel origin, String title, boolean modal) { + Origin = origin; + /* + Target = target; + if (Target == null) { + Target = new PostMessageDialog(null, title, modal); + Target.setDialogType(PostMessageType.BUG_REPORT); + Target.setEmailImportance(PostMessageDialog.EMAIL_IS_OPTIONAL_BUT_WARN); + Target.validate(); + Target.pack(); + } + */ + } + + @Override + public void actionPerformed(ActionEvent e) { + if (Origin == null) { + JOptionPane.showMessageDialog(null, "Internal Error: Origin == null", "Error", JOptionPane.ERROR_MESSAGE); + System.err.println(this.getClass().getCanonicalName() + ": Origin == null"); + return; + } + String message = Origin.getText().trim(); + if (message.length() < 1) { + JOptionPane.showMessageDialog(null, "Nothing to send", "Warning", JOptionPane.WARNING_MESSAGE); + return; + } + + //Target.setMessage(message + "\n\nPlease, tell exactly what you did to get a message above\n" + // + "Which GUI controls you selected and what order you selected them in.\n"); + //Target.setVisible(true); + + try { + GlobalSettings.mailUsingDefaultClient(GlobalSettings.getProperty(GlobalSettings.HELP_EMAIL), "Jamberoo bug", message + + "\n\nPlease, tell exactly what you did to get a message above\n" + + "Which GUI controls you selected and what order you selected them in.\n"); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + System.err.println(ex.getMessage()); + } + + + } +} diff --git a/src/main/java/cct/tools/ui/TruhlarExtrapolationFrame.form b/src/main/java/cct/tools/ui/TruhlarExtrapolationFrame.form new file mode 100644 index 0000000..29459a2 --- /dev/null +++ b/src/main/java/cct/tools/ui/TruhlarExtrapolationFrame.form @@ -0,0 +1,117 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/cct/tools/ui/TruhlarExtrapolationFrame.java b/src/main/java/cct/tools/ui/TruhlarExtrapolationFrame.java new file mode 100644 index 0000000..cc8988c --- /dev/null +++ b/src/main/java/cct/tools/ui/TruhlarExtrapolationFrame.java @@ -0,0 +1,204 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.tools.ui; + +import javax.swing.JOptionPane; + +/** + * + * @author vvv900 + */ +public class TruhlarExtrapolationFrame extends javax.swing.JFrame { + + /** + * Creates new form TruhlarExtrapolationFrame + */ + public TruhlarExtrapolationFrame() { + initComponents(); + } + + /** + * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The + * content of this method is always regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jPanel1 = new javax.swing.JPanel(); + jLabel1 = new javax.swing.JLabel(); + Ehf2_TextField = new javax.swing.JTextField(); + jLabel2 = new javax.swing.JLabel(); + Ehf3_TextField = new javax.swing.JTextField(); + jLabel3 = new javax.swing.JLabel(); + alphaTextField = new javax.swing.JTextField(); + jLabel4 = new javax.swing.JLabel(); + betaMP2TextField = new javax.swing.JTextField(); + jLabel5 = new javax.swing.JLabel(); + betaCCSDTextField = new javax.swing.JTextField(); + jPanel2 = new javax.swing.JPanel(); + jButton1 = new javax.swing.JButton(); + jButton2 = new javax.swing.JButton(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + + jPanel1.setLayout(new java.awt.GridLayout(5, 2)); + + jLabel1.setText("E(hf)2:"); + jPanel1.add(jLabel1); + + Ehf2_TextField.setText("0.0"); + jPanel1.add(Ehf2_TextField); + + jLabel2.setText("E(hf)3:"); + jPanel1.add(jLabel2); + + Ehf3_TextField.setText("0.0"); + Ehf3_TextField.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + Ehf3_TextFieldActionPerformed(evt); + } + }); + jPanel1.add(Ehf3_TextField); + + jLabel3.setText("alpha:"); + jPanel1.add(jLabel3); + + alphaTextField.setText("3.4"); + jPanel1.add(alphaTextField); + + jLabel4.setText("beta(MP2):"); + jPanel1.add(jLabel4); + + betaMP2TextField.setText("2.2"); + jPanel1.add(betaMP2TextField); + + jLabel5.setText("beta(CCSD(T)):"); + jPanel1.add(jLabel5); + + betaCCSDTextField.setText("2.4"); + jPanel1.add(betaCCSDTextField); + + getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); + + jButton1.setText("Calculate"); + jButton1.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jButton1ActionPerformed(evt); + } + }); + jPanel2.add(jButton1); + + jButton2.setText("Cancel"); + jPanel2.add(jButton2); + + getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH); + + pack(); + }// //GEN-END:initComponents + + private void Ehf3_TextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Ehf3_TextFieldActionPerformed + // TODO add your handling code here: + }//GEN-LAST:event_Ehf3_TextFieldActionPerformed + + private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed + // TODO add your handling code here: + double e2 = 0.0, e3 = 0, alpha, betaMP2, betaCCSD; + try { + e2 = Double.parseDouble(Ehf2_TextField.getText()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Wrong number for E(HF2): " + Ehf2_TextField.getText(), "Wrong number", + JOptionPane.ERROR_MESSAGE); + return; + } + try { + e3 = Double.parseDouble(Ehf3_TextField.getText()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Wrong number for E(HF3): " + Ehf3_TextField.getText(), "Wrong number", + JOptionPane.ERROR_MESSAGE); + return; + } + try { + alpha = Double.parseDouble(alphaTextField.getText()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Wrong number for alpha: " + alphaTextField.getText(), "Wrong number", + JOptionPane.ERROR_MESSAGE); + return; + } + try { + betaMP2 = Double.parseDouble(betaMP2TextField.getText()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Wrong number for beta(MP2): " + betaMP2TextField.getText(), "Wrong number", + JOptionPane.ERROR_MESSAGE); + return; + } + try { + betaCCSD = Double.parseDouble(betaCCSDTextField.getText()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Wrong number for beta(CCSD): " + betaCCSDTextField.getText(), "Wrong number", + JOptionPane.ERROR_MESSAGE); + return; + } + }//GEN-LAST:event_jButton1ActionPerformed + + + //public double calculateTruhlarExtrapolation(double Ehf2, double Ehf3, double alpha, double beta) { + //return Math.pow(3.0, alpha)/(Math.pow(3.0, alpha)-Math.pow(2.0, alpha)) * Ehf3 - + // Math.pow(2.0, alpha)/(Math.pow(3.0, alpha) - Math.pow(2.0, alpha)) * Ehf2 + + // Math.pow(3.0, beta)/(Math.pow(3.0, beta) - Math.pow(2.0, beta)) + //} + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + /* Set the Nimbus look and feel */ + // + /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. + * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html + */ + try { + for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + javax.swing.UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (ClassNotFoundException ex) { + java.util.logging.Logger.getLogger(TruhlarExtrapolationFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (InstantiationException ex) { + java.util.logging.Logger.getLogger(TruhlarExtrapolationFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + java.util.logging.Logger.getLogger(TruhlarExtrapolationFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (javax.swing.UnsupportedLookAndFeelException ex) { + java.util.logging.Logger.getLogger(TruhlarExtrapolationFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + // + + /* Create and display the form */ + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + new TruhlarExtrapolationFrame().setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JTextField Ehf2_TextField; + private javax.swing.JTextField Ehf3_TextField; + private javax.swing.JTextField alphaTextField; + private javax.swing.JTextField betaCCSDTextField; + private javax.swing.JTextField betaMP2TextField; + private javax.swing.JButton jButton1; + private javax.swing.JButton jButton2; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel3; + private javax.swing.JLabel jLabel4; + private javax.swing.JLabel jLabel5; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + // End of variables declaration//GEN-END:variables +} diff --git a/src/main/java/cct/tools/ui/images/memory-monitor-16x16.png b/src/main/java/cct/tools/ui/images/memory-monitor-16x16.png new file mode 100644 index 0000000..776ea35 Binary files /dev/null and b/src/main/java/cct/tools/ui/images/memory-monitor-16x16.png differ diff --git a/src/main/java/cct/tools/ui/images/memory-monitor-24x24.png b/src/main/java/cct/tools/ui/images/memory-monitor-24x24.png new file mode 100644 index 0000000..ac20d51 Binary files /dev/null and b/src/main/java/cct/tools/ui/images/memory-monitor-24x24.png differ diff --git a/src/main/java/cct/tools/ui/images/memory-monitor-32x32.png b/src/main/java/cct/tools/ui/images/memory-monitor-32x32.png new file mode 100644 index 0000000..9d2d268 Binary files /dev/null and b/src/main/java/cct/tools/ui/images/memory-monitor-32x32.png differ diff --git a/src/main/java/cct/tools/ui/images/memory-monitor-48x48.png b/src/main/java/cct/tools/ui/images/memory-monitor-48x48.png new file mode 100644 index 0000000..9fb78e9 Binary files /dev/null and b/src/main/java/cct/tools/ui/images/memory-monitor-48x48.png differ diff --git a/src/main/java/cct/tripos/Tripos.java b/src/main/java/cct/tripos/Tripos.java new file mode 100644 index 0000000..64dcb36 --- /dev/null +++ b/src/main/java/cct/tripos/Tripos.java @@ -0,0 +1,119 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.tripos; + +import java.util.List; + +import cct.interfaces.AtomInterface; +import cct.modelling.ChemicalElements; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Tripos { + private Tripos() { + } + + /** + * Guesses SYBYL atom types + * @param atom AtomInterface + * @return String + */ + public static String guessTriposAtomType(AtomInterface atom) { + int element = atom.getAtomicNumber(); + if (element == 0) { + return "Du"; + } + + switch (element) { + case 6: // Carbon + List nb = atom.getBondedToAtoms(); + if (nb.size() == 4) { + return "C.3"; + } + else if (nb.size() == 3) { + return "C.2"; + } + else if (nb.size() == 2) { + return "C.1"; + } + break; + + case 7: // Nitrogen + nb = atom.getBondedToAtoms(); + if (nb.size() == 4) { + return "N.4"; + } + else if (nb.size() == 3) { + return "N.2"; + } + else if (nb.size() == 2) { + return "N.1"; + } + break; + + case 8: // Oxygen + nb = atom.getBondedToAtoms(); + if (nb.size() == 2) { + return "O.3"; + } + else if (nb.size() == 1) { + return "O.2"; + } + break; + + case 16: // Sulphur + nb = atom.getBondedToAtoms(); + if (nb.size() == 2) { + return "S.3"; + } + break; + + } + return ChemicalElements.getElementSymbol(element); + } +} diff --git a/src/main/java/cct/tripos/TriposParser.java b/src/main/java/cct/tripos/TriposParser.java new file mode 100644 index 0000000..462b770 --- /dev/null +++ b/src/main/java/cct/tripos/TriposParser.java @@ -0,0 +1,1021 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.tripos; + +import java.awt.Color; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.BondInterface; +import cct.interfaces.MoleculeInterface; +import cct.interfaces.MonomerInterface; +import cct.modelling.GeneralMolecularDataParser; +import cct.modelling.AtomProperties; +import cct.modelling.AtomicSet; +import cct.modelling.AtomicSets; +import cct.modelling.ChemicalElements; +import cct.modelling.Molecule; +import java.io.File; +import java.io.RandomAccessFile; +import java.util.Arrays; +import java.util.Comparator; +import java.util.logging.Level; +import javax.swing.JFileChooser; + +/** + * + *

+ * Title: ParseTriposMol2

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2006

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class TriposParser extends GeneralMolecularDataParser + implements AtomProperties { + + public static final Map colorMap = new HashMap(); + private boolean Debug = false; + private List residues = new ArrayList(); + private List molecules = new ArrayList(); + + static { + colorMap.put("WHITE", Color.WHITE); + colorMap.put("BLUE", Color.BLUE); + colorMap.put("RED", Color.RED); + colorMap.put("YELLOW", Color.YELLOW); + colorMap.put("ORANGE", Color.ORANGE); + colorMap.put("CYAN", Color.CYAN); + colorMap.put("GREEN", Color.GREEN); + colorMap.put("PURPLE", new Color(160, 32, 240)); + colorMap.put("MAGENTA", Color.MAGENTA); + colorMap.put("GREENBLUE", Color.CYAN); + } + static final Logger logger = Logger.getLogger(TriposParser.class.getCanonicalName()); + + public TriposParser() { + } + + public void setLoggerLevel(Level level) { + logger.setLevel(level); + } + + public int getNumberOfMolecules() { + return molecules.size(); + } + + public int validFormatScore(BufferedReader in) throws Exception { + TriposParser t = new TriposParser(); + try { + t.parseData(in); + } catch (Exception ex) { + return 0; + } + + if (t.getMolecule() == null || t.getMolecule().getNumberOfAtoms() < 1) { + return 0; + } + return 10; + } + + public void parseData(BufferedReader in) throws Exception { + MoleculeInterface mol = getMoleculeInterface(); + this.addMolecule(mol); + AtomInterface atom; + BondInterface bond; + String line = "", token = ""; + StringTokenizer st; + AtomicSets sets = new AtomicSets(); + Integer natoms = 0, nbonds = 0, nresidues = 0; + Float cartes = new Float(0.0f); + double totalCharge = 0; + + try { + //BufferedReader in = new BufferedReader(new FileReader(filename)); + boolean read_line_first = true; + while (true) { + + if (read_line_first) { + if ((line = in.readLine()) == null) { + break; + } + } else { + read_line_first = true; + } + + line = line.trim(); + + if (line.compareToIgnoreCase("@MOLECULE") == 0) { + // Read Molecule name + line = in.readLine(); + //line.trim(); + mol.setName(line); + + // read number of atoms & bonds + line = in.readLine(); + st = new StringTokenizer(line, " "); + + try { + natoms = new Integer(st.nextToken()); + nbonds = new Integer(st.nextToken()); + nresidues = new Integer(st.nextToken()); + } catch (NumberFormatException e) { + break; + } + + } else if (line.compareToIgnoreCase("@ATOM") == 0) { + //@ATOM + // 1 P 5.9733 -6.8476 27.4300 P.3 1 A1 0.0000 BACKBONE|DICT|DIRECT + // 2 O1P 6.2573 -8.2786 27.2100 O.co2 1 A1 0.0000 BACKBONE|DICT + int current_subst_id = 0; + + for (int i = 0; i < natoms.intValue(); i++) { + if ((line = in.readLine()) == null) { + break; + } + st = new StringTokenizer(line, " "); + + boolean new_residue = false; + String substr = null; + + st.nextToken(); // skip first token + + atom = mol.getNewAtomInstance(); // gAtom(); + atom.setName(st.nextToken()); + + // --- Read in coordinates + if (st.countTokens() < 3) { + break; // Actually it's an error + } + + try { + atom.setX(Float.parseFloat(st.nextToken())); + atom.setY(Float.parseFloat(st.nextToken())); + atom.setZ(Float.parseFloat(st.nextToken())); + + } catch (NumberFormatException e) { + System.err.println("Error converting cartesin coordinates: " + e.getMessage()); + break; + } + + if (st.countTokens() > 0) { // Parse Tripos Atom Type + String triposName = st.nextToken(); + atom.setProperty(AtomInterface.SYBYL_TYPE, triposName); + atom.setAtomicNumber(triposAtomTypeToElement(triposName)); + } + // --- + int subst_id = current_subst_id; + if (st.countTokens() > 0) { // Parse the ID number of the substructure containing the atom + try { + subst_id = Integer.parseInt(st.nextToken()); + --subst_id; + } catch (NumberFormatException e) { + System.err.println("Error converting ID number of the substructure containing the atom"); + break; + } + + if (subst_id < 0) { + System.err.println("Error in MOL2 file: substructure ID is negative: " + subst_id); + break; + } + + if (subst_id > current_subst_id) { + new_residue = true; + current_subst_id = subst_id; + } + } + + if (st.hasMoreTokens()) { // Parse the name of the substructure containing the atom + token = st.nextToken(); + substr = ""; + if (token.startsWith("<")) { + StringTokenizer res = new StringTokenizer(token, "<>"); + if (res.hasMoreTokens()) { + substr = res.nextToken(); + } + } else { + StringTokenizer res = new StringTokenizer(token, "0123456789"); + if (res.hasMoreTokens()) { + substr = res.nextToken(); + } + } + if (substr.length() < 1) { + substr = "RES"; + } + } + + if (st.hasMoreTokens()) { + Double charge = 0.0; + try { + token = st.nextToken(); + charge = Double.parseDouble(token); + } catch (Exception ex) { + System.err.println("Error in MOL2 file: cannot parse atom charge: " + token + " Set it to zero..."); + } + totalCharge += charge; + atom.setProperty(AtomInterface.ATOMIC_CHARGE, charge); + } + + if (Debug) { + logger.info(atom.getAtomicNumber() + " XYZ: " + atom.getX() + " " + atom.getY() + " " + atom.getZ()); + } + if (substr == null) { + substr = "UNK"; + } + mol.addAtom(atom, subst_id, substr); + } + + mol.addProperty(MoleculeInterface.ChargeProperty, totalCharge); + logger.info("Number of atoms: " + mol.getNumberOfAtoms()); + for (int i = 0; i < mol.getNumberOfAtoms(); i++) { + atom = mol.getAtomInterface(i); + logger.info(i + " " + atom.getName() + " " + atom.getSubstructureNumber()); + } + for (int i = 0; i < mol.getNumberOfMonomers(); i++) { + MonomerInterface m = mol.getMonomerInterface(i); + logger.info("Res: " + i + " " + m.getName() + " atoms:" + m.getNumberOfAtoms()); + } + + } else if (line.compareToIgnoreCase("@BOND") == 0) { + + for (int i = 0; i < nbonds.intValue(); i++) { + if ((line = in.readLine()) == null) { + break; + } + st = new StringTokenizer(line, " "); + + // Inform about error and continue.... + if (st.countTokens() < 3) { + logger.info( + "Uncomplete BOND record... Continuing...\n"); + continue; + } + + st.nextToken(); // skip first token + + int a1, a2; + try { + a1 = Integer.parseInt(st.nextToken()) - 1; + a2 = Integer.parseInt(st.nextToken()) - 1; + } catch (NumberFormatException e) { + logger.info( + "Error converting bonded atoms\n"); + break; + } + + AtomInterface a_i = mol.getAtomInterface(a1); + AtomInterface a_j = mol.getAtomInterface(a2); + bond = mol.getNewBondInstance(a_i, a_j); + mol.addBond(bond); + //mol.createNewBond(a_i, a_j); + + } + + logger.info("Number of bonds: " + mol.getNumberOfBonds()); + + } else if (false && line.compareToIgnoreCase("@SUBSTRUCTURE") == 0) { // Skip for now + while (true) { + if ((line = in.readLine()) == null) { + break; + } + line = line.trim(); + if (line.startsWith("@") || line.length() < 1) { + read_line_first = false; + break; + } + + st = new StringTokenizer(line, " "); + if (st.countTokens() < 3) { + System.err.println("Error reading set in mol2 file: expecting at least 3 token to SUBSTRUCTURE info, got " + line + + " Ignored..."); + break; + } + + st.nextToken(); // Skip first token + String subst_name = st.nextToken(); + String root_atom = st.nextToken(); + String subst_type = null; + if (st.hasMoreTokens()) { + subst_type = st.nextToken(); + } + String dict_type = null; + if (st.hasMoreTokens()) { + dict_type = st.nextToken(); + } + String chain = null; + if (st.hasMoreTokens()) { + chain = st.nextToken(); + } + String sub_type = null; + if (st.hasMoreTokens()) { + sub_type = st.nextToken(); + } + String inter_bonds = null; + if (st.hasMoreTokens()) { + inter_bonds = st.nextToken(); + } + String status = null; + if (st.hasMoreTokens()) { + status = st.nextToken(); + } + String comment = null; + if (st.hasMoreTokens()) { + comment = st.nextToken(); + } + + int root_at = 0; + try { + root_at = Integer.parseInt(root_atom) - 1; + } catch (Exception ex) { + System.err.println("Error reading set in mol2 file: cannot parse root atom number, got " + line + " Ignored..."); + break; + } + RES_INFO res_info; + if (sub_type == null) { + st = new StringTokenizer(subst_name, "0123456789"); + if (st.hasMoreTokens()) { + sub_type = st.nextToken(); + } else { + System.err.println("Warning: set residue name (possibly non-standard) to" + subst_name); + sub_type = subst_name; + } + } + res_info = new RES_INFO(root_at, sub_type); + residues.add(res_info); + } + } else if (line.compareToIgnoreCase("@SET") == 0) { + + while (true) { + if ((line = in.readLine()) == null) { + break; + } + line = line.trim(); + + if (line.startsWith("@") || line.length() < 1) { + read_line_first = false; + break; + } + + st = new StringTokenizer(line, " "); + if (st.countTokens() < 3) { + System.err.println("Error reading set in mol2 file: expecting at least 3 token, got " + line + " Ignored..."); + break; + } + + String set_name = st.nextToken(); + String set_type = st.nextToken(); + String obj_type = st.nextToken(); + + if (!set_type.equalsIgnoreCase("STATIC")) { + logger.info("Problem reading set in mol2 file: currently can handle only STATIC sets. Ignored..."); + break; + } + + if (!obj_type.equalsIgnoreCase("ATOMS")) { + logger.info("Problem reading set in mol2 file: currently can handle only ATOMS sets. Ignored..."); + break; + } + + boolean colorgroup = false; + Color color = null; + if (st.hasMoreTokens() && st.nextToken().equalsIgnoreCase("COLORGROUP")) { + colorgroup = true; + color = getColor(set_name); + } + + AtomicSet aset = new AtomicSet(set_name); + + if ((line = in.readLine()) == null) { + break; + } + st = new StringTokenizer(line, " "); + if (st.countTokens() < 1) { + System.err.println( + "Error reading set in mol2 file: expecting at least 1 token for reading num_members member..., got " + + line + " Ignored..."); + break; + } + int num_members = 0; + token = st.nextToken(); + try { + num_members = Integer.parseInt(token); + } catch (Exception ex) { + System.err.println("Error reading set in mol2 file: expecting int value for num_members, got " + + token + " Ignored..."); + break; + } + + if (num_members < 1) { + logger.info("Reading mol2 file: set " + set_name + " is empty. Ignored..."); + continue; + } + int n_read = 0; + do { + if (!st.hasMoreTokens()) { + System.err.println( + "Error reading set in mol2 file: unexpected end of set: expecting int value for set member. Ignored..."); + break; + } + + token = st.nextToken(); + if (token.equals("\\")) { + if ((line = in.readLine()) == null) { + System.err.println( + "Error reading set in mol2 file: unexpected end of file while reading set members. Ignored..."); + break; + } + st = new StringTokenizer(line, " "); + continue; + } + + int member = 0; + try { + member = Integer.parseInt(token); + } catch (Exception ex) { + System.err.println( + "Error reading set in mol2 file: cannot parse set member number: Expecting int number, got " + token + + " Ignored..."); + break; + } + + --member; + if (member >= 0 && member < mol.getNumberOfAtoms()) { + atom = mol.getAtomInterface(member); + if (colorgroup && color != null) { + atom.setProperty(AtomInterface.RGB_COLOR, new Integer[]{color.getRed(), color.getGreen(), color.getBlue()}); + } + aset.add(atom); + } + + ++n_read; + if (n_read == num_members && aset.size() > 0) { + sets.put(aset.getName(), aset); + } + } while (n_read < num_members); + if (n_read != num_members) { + break; + } + } + } + + } // --- End of while + + } catch (IOException e) { + logger.info("parseMol2File: " + e.getMessage() + "\n"); + return; + } + + if (sets.size() > 0) { + Map props = mol.getProperties(); + props.put(MoleculeInterface.AtomicSets, sets); + } + } + + /** + * + * @param filename + * @param mol + * @throws Exception + * @deprecated Use parseData methods instead + */ + @Deprecated + public void parseMol2File(String filename, MoleculeInterface mol) throws Exception { + BufferedReader in = new BufferedReader(new FileReader(filename)); + parseMol2File(in, mol); + try { + in.close(); + } catch (Exception ex) { + logger.warning("Warning: Error closing file " + filename + " : " + ex.getMessage()); + } + } + + /** + * + * @param in + * @param mol + * @throws Exception + * @deprecated Use parseData methods instead + */ + @Deprecated + public void parseMol2File(BufferedReader in, MoleculeInterface mol) throws Exception { + parseData(in); + } + + /** + * Saves molecule in the Tripos mol2 format + * + * @param m MoleculeInterface + * @param filename String + * @throws Exception + */ + public static void saveTriposMol2File(MoleculeInterface m, String filename) throws + Exception { + + BufferedWriter out; + try { + out = new BufferedWriter(new FileWriter(filename)); + } catch (java.io.FileNotFoundException e) { + System.err.println(filename + " not found"); + throw new Exception("saveTriposMol2File: ERROR: " + e.getMessage()); + //return; + } catch (SecurityException e) { + System.err.println(filename + ": " + e.getMessage()); + throw new Exception("saveTriposMol2File: ERROR: " + e.getMessage()); + //return; + } catch (IOException e) { + System.err.println(filename + ": " + e.getMessage()); + throw new Exception("saveTriposMol2File: ERROR: " + e.getMessage()); + //return; + } + + try { + out.write("@MOLECULE"); + out.write("\n"); + + // mol_name (all strings on the line) = the name of the molecule. + out.write(m.getName()); + out.write("\n"); + + // num_atoms [num_bonds [num_subst [num_feat[num_sets]]]] + // num_atoms (integer) = the number of atoms in the molecule. + // num_bonds (integer) = the number of bonds in the molecule. + // num_subst (integer) = the number of substructures in the molecule. + // num_feat (integer) = the number of features in the molecule. + // num_sets (integer) = the number of sets in the molecule. + out.write(String.format("%5d %5d %5d %5d %5d\n", m.getNumberOfAtoms(), m.getNumberOfBonds(), m.getNumberOfMonomers(), 0, 0)); + out.write("\n"); + + // mol_type (string) = the molecule type: SMALL, BIOPOLYMER, + // PROTEIN, NUCLEIC_ACID, SACCHARIDE + out.write("SMALL"); + out.write("\n"); + + // charge_type (string) = the type of charges associated with the molecule: + // NO_CHARGES, DEL_RE, GASTEIGER, GAST_HUCK, HUCKEL, + // PULLMAN, GAUSS80_CHARGES, AMPAC_CHARGES, + // MULLIKEN_CHARGES, DICT_ CHARGES, MMFF94_CHARGES, + // USER_CHARGES + boolean no_charges = true; + for (int i = 0; i < m.getNumberOfAtoms(); i++) { + AtomInterface atom = m.getAtomInterface(i); + Object charge = atom.getProperty(AtomInterface.ATOMIC_CHARGE); + if (charge != null) { + no_charges = false; + break; + } + } + + if (no_charges) { + out.write("NO_CHARGES"); + } else { + out.write("USER_CHARGES"); + } + out.write("\n"); + + // status_bits (string) = the internal SYBYL status bits associated with the + // molecule. These should never be set by the user. Valid status bits are + // system, invalid_charges, analyzed, substituted, altered or ref_angle. + out.write("\n"); + + // mol_comment (all strings on data line) = the comment associated with the molecule. + out.write("\n"); + + // Writing atoms + // atom_id atom_name x y z atom_type [subst_id [subst_name [charge [status_bit]]]] + // � atom_id (integer) = the ID number of the atom at the time the file was + // created. This is provided for reference only and is not used when the + // .mol2 file is read into SYBYL. + // � atom_name (string) = the name of the atom. + // � x (real) = the x coordinate of the atom. + // � y (real) = the y coordinate of the atom. + // � z (real) = the z coordinate of the atom. + // � atom_type (string) = the SYBYL atom type for the atom. + // � subst_id (integer) = the ID number of the substructure containing the atom. + // � subst_name (string) = the name of the substructure containing the atom. + // � charge (real) = the charge associated with the atom. + // � status_bit (string) = the internal SYBYL status bits associated with the + // atom. These should never be set by the user. Valid status bits are + // DSPMOD, TYPECOL, CAP, BACKBONE, DICT, ESSENTIAL, WATER and + // DIRECT. + // Example: + // 1 CA -0.149 0.299 0.000 C.3 1 ALA1 0.000 BACKBONE|DICT|DIRECT + // 1 CA -0.149 0.299 0.000 C.3 + // In the first example the atom has ID number 1. It is named CA and is + // located at (-0.149, 0.299, 0.000). Its atom type is C.3. It belongs to the + // substructure with ID 1 which is named ALA1. The charge associated with + // the atom is 0.000 and the SYBYL status bits associated with the atom are + // BACKBONE, DICT, and DIRECT. Example two is the minimal information + // necessary for the MOL2 command to create an atom. + out.write("@ATOM"); + out.write("\n"); + + Object obj; + String str; + for (int i = 0; i < m.getNumberOfAtoms(); i++) { + AtomInterface a = m.getAtomInterface(i); + + str = a.getName(); + if (str == null || str.length() == 0) { + str = "UNK"; + } + + out.write(String.format("%5d %-5s", (i + 1), str)); + + // --- Writing X,Y & Z + out.write(String.format(" %9.4f %9.4f %9.4f", a.getX(), a.getY(), a.getZ())); + + // --- Writing Tripos atom type + str = (String) a.getProperty(AtomInterface.SYBYL_TYPE); + if (str == null || str.length() == 0) { + str = Tripos.guessTriposAtomType(a); + } + out.write(String.format(" %-5s", str)); + + // --- Writing substructure number + int substr = a.getSubstructureNumber(); + out.write(String.format(" %5d", (substr + 1))); + + MonomerInterface mono = m.getMonomerInterface(substr); + str = mono.getName(); + if (str == null || str.length() == 0 || str.equalsIgnoreCase("null")) { + str = "XXX"; + } + + out.write(String.format(" %-5s", str)); + + // --- Writing atomic charge (if any) + if (!no_charges) { + float charge = 0; + obj = a.getProperty(AtomInterface.ATOMIC_CHARGE); + if (obj != null) { + if (obj instanceof Float) { + Float f = (Float) obj; + charge = f.floatValue(); + } else if (obj instanceof Double) { + Double d = (Double) obj; + charge = d.floatValue(); + } else { + System.err.println( + "saveTriposMol2File: Warning: atomic charge is not Float or Double: " + + obj.getClass().getCanonicalName()); + System.err.println(" Action: Ignored: set to zero"); + } + } + out.write(String.format(" %9.4f", charge)); + } + + out.write("\n"); + } + + // --- Writing bonds + // bond_id origin_atom_id target_atom_id bond_type [status_bits] + // � bond_id (integer) = the ID number of the bond at the time the file was + // created. This is provided for reference only and is not used when the + // .mol2 file is read into SYBYL. + // � origin_atom_id (integer) = the ID number of the atom at one end of the bond. + // � target_atom_id (integer) = the ID number of the atom at the other end of the bond. + // � bond_type (string) = the SYBYL bond type (see below). + // � status_bits (string) = the internal SYBYL status bits associated with the + // bond. These should never be set by the user. Valid status bit values are + // TYPECOL, GROUP, CAP, BACKBONE, DICT and INTERRES. + // Bond Types: + // � 1 = single + // � 2 = double + // � 3 = triple + // � am = amide + // � ar = aromatic + // � du = dummy + // � un = unknown (cannot be determined from the parameter tables) + // � nc = not connected + // Example: + // 5 4 9 am BACKBONE|DICT|INTERRES + // 5 4 9 am + // The bond in the first example has ID number 5 and connects atoms 4 and 9. + // It is an amide bond. The status bits indicate the bond is part of the backbone + // chain, joins two residues, and that a dictionary was used when creating the + // molecule. The second example is a minimal representation of the same bond. + if (m.getNumberOfBonds() > 0) { + out.write("@BOND"); + out.write("\n"); + } + + for (int i = 0; i < m.getNumberOfBonds(); i++) { + BondInterface bond = m.getBondInterface(i); + AtomInterface a_i = bond.getIAtomInterface(); + AtomInterface a_j = bond.getJAtomInterface(); + + out.write(String.format("%6d %5d %5d un", (i + 1), (m.getAtomIndex(a_i) + 1), (m.getAtomIndex(a_j) + 1))); + out.write("\n"); + } + + // --- Writing substructure + // subst_id subst_name root_atom [subst_type [dict_type[chain [sub_type [inter_bonds [status[comment]]]]]]] + // subst_id (integer) = the ID number of the substructure. This is provided + // for reference only and is not used by the MOL2 command when reading the file. + // subst_name (string) = the name of the substructure. + // root_atom (integer) = the ID number of the substructure�s root atom. + // subst_type - string) = the substructure type: temp, perm, residue, group or domain. + // dict_type (integer) = the type of dictionary associated with the substructure. + // chain (string) = the chain to which the substructure belongs (� 4 chars). + // sub_type (string) = the subtype of the chain. + // inter_bonds (integer) = the number of inter substructure bonds. + // status (string) = the internal SYBYL status bits. These should never be + // set by the user. Valid status bit values are LEAF, ROOT, TYPECOL, DICT, + // BACKWARD and BLOCK. + // comment (remaining strings on data line) = the comment for the substructure. + // Example: + // 1 ALA1 1 RESIDUE 1 A ALA 1 ROOT|DICT Comment here + // The substructure has 1 as ID, ALA1 as name and atom 1 as root atom. It is + // of type RESIDUE and the associated dictionary type is 1 (protein). It is part + // of the A chain in the molecule and it is an ALAnine. There is only one inter + // substructure bonds. The SYBYL status bits indicate it is the ROOT + // substructure of the chain and it came from a dictionary. The comment reads + // �Comment here�. + // 1 ALA1 1 + // Minimal representation of a substructure. + out.write("@SUBSTRUCTURE"); + out.write("\n"); + + for (int i = 0; i < m.getNumberOfMonomers(); i++) { + MonomerInterface mono = m.getMonomerInterface(i); + str = mono.getName(); + if (str == null || str.length() == 0 || str.equalsIgnoreCase("null")) { + str = "XXX"; + } + + out.write((i + 1) + " " + str); + + if (mono.getNumberOfAtoms() < 1) { + out.write(" 1\n"); + System.err.println("saveTriposMol2File: Warning: residue # " + (i + 1) + " " + str + " has no atoms"); + } else { + AtomInterface a = mono.getAtom(0); + out.write(" " + (m.getAtomIndex(a) + 1) + "\n"); + } + } + + Molecule.validateSets(m); + obj = m.getProperty(MoleculeInterface.AtomicSets); + if (obj != null && obj instanceof AtomicSets) { + out.write("@SET\n"); + AtomicSets sets = (AtomicSets) obj; + Iterator iter = sets.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry me = (Map.Entry) iter.next(); + obj = me.getValue(); + if (!(obj instanceof AtomicSet)) { + continue; + } + AtomicSet aset = (AtomicSet) obj; + if (aset.size() < 1) { + continue; + } + out.write(aset.getName() + " STATIC ATOMS ****\n" + aset.size()); + int index, count = 0; + for (int i = 0; i < aset.size(); i++) { + AtomInterface atom = aset.get(i); + index = m.getAtomIndex(atom) + 1; + out.write(" " + index); + ++count; + if ((count % 20) == 0 && i < aset.size() - 1) { + out.write(" \\\n"); + } + } + out.write("\n"); + } + } + + out.close(); + } catch (IOException e) { + System.err.println("Error writing into " + filename); + throw new Exception("saveTriposMol2File: ERROR: " + e.getMessage()); + //return; + } + + } + + public static Color getColor(String name) { + StringTokenizer st = new StringTokenizer(name, "$"); + if (st.countTokens() != 2) { + return null; + } + st.nextElement(); + String color = st.nextToken(); + return colorMap.get(color); + } + + private void processResidueInfo(MoleculeInterface mol, List res) { + if (mol.getNumberOfAtoms() < 1 || res.size() < 1) { + return; + } + } + + public int parseMultipleMolecules(String fileName) throws Exception { + File file = new File(fileName); + return parseMultipleMolecules(file); + } + + public int parseMultipleMolecules(File file) throws Exception { + RandomAccessFile raf = new RandomAccessFile(file, "r"); + String line; + long pointer = 0L; + boolean found = false; + while (true) { + pointer = raf.getFilePointer(); + line = raf.readLine(); + if (line == null) { + break; + } + line = line.trim(); + + if (line.compareToIgnoreCase("@MOLECULE") == 0) { + // Read Molecule name + line = raf.readLine(); + if (line == null) { + System.err.println("Warning: unexpected eof while reading a molecule name"); + break; + } + line = line.trim(); + MoleculeInfo mol = new MoleculeInfo(line, pointer); + molecules.add(mol); + } + + } + + raf.close(); + return molecules.size(); + } + + public void splitIntoMultipleFiles(String fileName, boolean overwrite) throws Exception { + File file = new File(fileName); + splitIntoMultipleFiles(file, overwrite); + } + + public void splitIntoMultipleFiles(File file, boolean overwrite) throws Exception { + if (molecules.size() < 2) { + System.err.println("Nothing to split: Number of molecules in file - " + molecules.size()); + return; + } + + String line; + boolean found = false; + int count = 0; + BufferedWriter out = null; + BufferedReader in = new BufferedReader(new FileReader(file)); + try { + while ((line = in.readLine()) != null) { + line = line.trim(); + if (line.compareToIgnoreCase("@MOLECULE") == 0) { + if (found) { + out.close(); + } + found = true; + ++count; + out = new BufferedWriter(new FileWriter(String.format("%06d.mol2", count))); + out.write(line + "\n"); + } else if (found) { + out.write(line + "\n"); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + if (out != null) { + out.close(); + } + in.close(); + } + + public static void main(String[] args) { + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setMultiSelectionEnabled(true); + fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); + int result = fileChooser.showOpenDialog(null); + + if (result != JFileChooser.APPROVE_OPTION) { + return; + } + + File[] files = fileChooser.getSelectedFiles(); + if (files.length < 1) { + System.err.println("No files selected"); + return; + } + System.out.println(files.length + " files selected"); + FilesComparator fc = new FilesComparator(); + Arrays.sort(files, fc); + // + File currentDir = fileChooser.getCurrentDirectory(); + System.out.println("Current working directory: " + currentDir.getAbsolutePath()); + System.setProperty("user.dir", fileChooser.getCurrentDirectory().getAbsolutePath()); + + for (int i = 0; i < files.length; i++) { + TriposParser tp = new TriposParser(); + int n = 0; + try { + n = tp.parseMultipleMolecules(files[i]); + tp.splitIntoMultipleFiles(files[i], true); + } catch (Exception ex) { + Logger.getLogger(TriposParser.class.getName()).log(Level.SEVERE, null, ex); + } + System.out.println("Number of molecules in file: " + n); + } + + System.exit(0); + } + +//************************************************************************** + public static int triposAtomTypeToElement(String atomType) { + StringTokenizer tok = new StringTokenizer(atomType, " ."); + return ChemicalElements.getAtomicNumber(tok.nextToken()); + + } + + class RES_INFO { + + int root_atom; + String sub_type; + + public RES_INFO(int root_atom, String sub_type) { + this.root_atom = root_atom; + this.sub_type = sub_type; + } + } + + class MoleculeInfo { + + String name; + long pointer; + + public MoleculeInfo(String name, long pointer) { + this.name = name; + this.pointer = pointer; + } + } + +} + +class FilesComparator implements Comparator { + + public int compare(File o1, File o2) { + return o1.getName().compareTo(o2.getName()); + } + + public boolean equals(Object obj) { + return this == obj; + } + +} diff --git a/src/main/java/cct/vasp/.DS_Store b/src/main/java/cct/vasp/.DS_Store new file mode 100644 index 0000000..bbe4204 Binary files /dev/null and b/src/main/java/cct/vasp/.DS_Store differ diff --git a/src/main/java/cct/vasp/._.DS_Store b/src/main/java/cct/vasp/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/cct/vasp/._.DS_Store differ diff --git a/src/main/java/cct/vasp/Vasp.java b/src/main/java/cct/vasp/Vasp.java new file mode 100644 index 0000000..a23c529 --- /dev/null +++ b/src/main/java/cct/vasp/Vasp.java @@ -0,0 +1,527 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.vasp; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.ChemicalElements; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2007

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Vasp { + + static final int CARTESIAN_COORDINATES = 0; + static final int DIRECT_COORDINATES = 1; + + static int colorMap[][] = { + { + 227, 38, 54}, { // 0.8900 0.1500 0.2100 alizarin_crimson + 240, 248, 255}, { // 0.9412 0.9725 1.0000 alice_blue + 127, 255, 0}, { // 0.4980 1.0000 0.0000 chartreuse + 127, 255, 212}, { // 0.4980 1.0000 0.8314 aquamarine + 255, 97, 3}, // 1.0000 0.3800 0.0100 cadmium_orange + + { + 156, 102, 31}, { // 0.6100 0.4000 0.1200 brick + 0, 0, 255}, { // 0.0000 0.0000 1.0000 blue + 102, 128, 20}, { // 0.4000 0.5000 0.0800 chromeoxidegreen + 102, 205, 170}, { // 0.4000 0.8039 0.6667 aquamarinemedium + 255, 3, 13}, // 1.0000 0.0100 0.0500 cadmium_red_light + + { + 227, 23, 13}, { // 0.8900 0.0900 0.0500 cadmium_red_deep + 173, 216, 230}, { // 0.6784 0.8471 0.9020 blue_light + 97, 179, 41}, { // 0.3800 0.7000 0.1600 cinnabar_green + 0, 255, 255}, { // 0.0000 1.0000 1.0000 cyan + 237, 145, 33} // 0.9300 0.5700 0.1300 carrot + }; + + String Comment = ""; + float latticeConstant = 1.0f; + float latticeVectors[][] = new float[3][3]; + int[] atomicSpecies = null; + int numberOfAtoms = 0; + + boolean selectiveDynamicsSwitch = false; + String selectiveDynamicsKey = ""; + String coordinatesKey = ""; + VaspAtom[] Atoms = null; + + int atomicPositionsType = CARTESIAN_COORDINATES; + + List potcarAtomSymbols = null; + List potcarAtomNumbers = null; + static final Logger logger = Logger.getLogger(Vasp.class.getCanonicalName()); + + public Vasp() { + } + + public int getNumberOfAtoms() { + return this.numberOfAtoms; + } + + public float[][] getLatticeVectors() { + return latticeVectors; + } + + public void parsePoscar(String filename, int fileType) throws Exception { + + String line; + StringTokenizer st; + + BufferedReader in = null; + + if (fileType == 0) { // Read from file + try { + in = new BufferedReader(new FileReader(filename)); + } + catch (java.io.FileNotFoundException e) { + throw new Exception("Error opening file " + filename + ": " + e.getMessage()); + } + } + else if (fileType == 1) { // Read from String + in = new BufferedReader(new StringReader(filename)); + } + else { + throw new Exception("Implementation error: unknown file type"); + } + + try { + + // --- 1st line + + if ( (line = in.readLine()) == null) { + throw new Exception("Error reading file " + filename + ": unexpected end of file while reading comment"); + } + Comment = line.trim(); + + // --- 2nd line - lattice constant + // If this value is negative it is interpreted as the total volume of the cell + + if ( (line = in.readLine()) == null) { + throw new Exception("Error reading file " + filename + ": unexpected end of file while reading lattice constant"); + } + + st = new StringTokenizer(line, " \t"); + + if (st.countTokens() < 1) { + throw new Exception("Error reading file " + filename + ": expecting lattice constant, got blank line"); + } + + try { + latticeConstant = Float.parseFloat(st.nextToken()); + } + catch (Exception ex) { + throw new Exception("Error reading file " + filename + ": error parsing lattice constant: " + ex.getMessage()); + } + + // --- 3-5 lines - lattice vectors + // On the following three lines the three lattice vectors defining + // the unit cell of the system are given (first line corresponding to + // the first lattice vector, second to the second, and third to the third). + + for (int i = 0; i < 3; i++) { + if ( (line = in.readLine()) == null) { + throw new Exception("Error reading file " + filename + ": unexpected end of file while reading lattice vectors"); + } + + st = new StringTokenizer(line, " \t"); + + if (st.countTokens() < 3) { + throw new Exception("Error reading file " + filename + ": expecting at least three numbers for lattice vector, got " + + st.countTokens() + " numbers"); + } + + for (int j = 0; j < 3; j++) { + try { + latticeVectors[i][j] = Float.parseFloat(st.nextToken()) * latticeConstant; + } + catch (Exception ex) { + throw new Exception("Error reading file " + filename + ": error parsing lattice vector value: " + ex.getMessage()); + } + } + } + + // --- 6th line + // The sixth line supplies the number of atoms per atomic species + // (one number for each atomic species). The ordering must be consistent with the POTCAR and the INCAR file. + + if ( (line = in.readLine()) == null) { + throw new Exception("Error reading file " + filename + + ": unexpected end of file while reading the number of atoms per atomic species"); + } + + st = new StringTokenizer(line, " \t"); + + if (st.countTokens() < 1) { + throw new Exception("Error reading file " + filename + + ": expecting the number of atoms per atomic species, got blank line"); + } + + atomicSpecies = new int[st.countTokens()]; + numberOfAtoms = 0; + + for (int i = 0; i < atomicSpecies.length; i++) { + try { + atomicSpecies[i] = Integer.parseInt(st.nextToken()); + numberOfAtoms += atomicSpecies[i]; + } + catch (Exception ex) { + throw new Exception("Error reading file " + filename + ": error parsing the number of atoms per atomic species: " + + ex.getMessage()); + } + } + + // --- 7st line + + if ( (line = in.readLine()) == null) { + throw new Exception("Error reading file " + filename + ": unexpected end of file while reading 7th line"); + } + selectiveDynamicsKey = line.trim(); + + if (selectiveDynamicsKey.startsWith("S") || selectiveDynamicsKey.startsWith("s")) { + selectiveDynamicsSwitch = true; + if ( (line = in.readLine()) == null) { + throw new Exception("Error reading file " + filename + ": unexpected end of file while reading 8th line"); + } + coordinatesKey = line.trim(); + } + else { + selectiveDynamicsSwitch = false; + coordinatesKey = selectiveDynamicsKey; + selectiveDynamicsKey = ""; + } + + if (coordinatesKey.startsWith("C") || coordinatesKey.startsWith("c") || coordinatesKey.startsWith("K") || + coordinatesKey.startsWith("k")) { + atomicPositionsType = CARTESIAN_COORDINATES; + } + else if (coordinatesKey.startsWith("D") || coordinatesKey.startsWith("d")) { + atomicPositionsType = DIRECT_COORDINATES; + } + else { + throw new Exception("Error reading file " + filename + ": unknown type of atom input coordinates" + coordinatesKey); + } + + if (atomicPositionsType == CARTESIAN_COORDINATES) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + latticeVectors[i][j] *= latticeConstant; + } + } + } + + // --- Start to read atomic coordinates + + float x, y, z; + boolean[] lf = new boolean[3]; + Atoms = new VaspAtom[numberOfAtoms]; + + int nat = 0; + for (int k = 0; k < atomicSpecies.length; k++) { + for (int i = 0; i < atomicSpecies[k]; i++, nat++) { + if ( (line = in.readLine()) == null) { + throw new Exception("Error reading file " + filename + ": unexpected end of file while reading " + (i + 1) + + " atom"); + } + st = new StringTokenizer(line, " \t"); + + if (st.countTokens() < 3) { + throw new Exception("Error reading file " + filename + + ": should be at least 3 numbers for atomic coordinates for " + + (i + 1) + " atom"); + } + + try { + x = Float.parseFloat(st.nextToken()); + y = Float.parseFloat(st.nextToken()); + z = Float.parseFloat(st.nextToken()); + } + catch (Exception ex) { + throw new Exception("Error reading file " + filename + ": wrong number for atomic coordinate for " + + (i + 1) + " atom"); + } + + if (atomicPositionsType == CARTESIAN_COORDINATES) { + x *= latticeConstant; + y *= latticeConstant; + z *= latticeConstant; + } + else if (atomicPositionsType == DIRECT_COORDINATES) { + float x2 = 0, y2 = 0, z2 = 0; + x2 = x * latticeVectors[0][0] + y * latticeVectors[1][0] + z * latticeVectors[2][0]; + y2 = x * latticeVectors[0][1] + y * latticeVectors[1][1] + z * latticeVectors[2][1]; + z2 = x * latticeVectors[0][2] + y * latticeVectors[1][2] + z * latticeVectors[2][2]; + x = x2; + y = y2; + z = z2; + } + + if (st.countTokens() > 0 && st.countTokens() < 3) { + throw new Exception("Error reading file " + filename + ": should be at least 3 letters for logical flags for " + + (i + 1) + " atom"); + } + + lf[0] = lf[1] = lf[2] = false; + if (st.countTokens() > 0) { + for (int j = 0; j < 3; j++) { + String flag = st.nextToken(); + if (flag.equalsIgnoreCase("T")) { + lf[j] = true; + } + else if (flag.equalsIgnoreCase("F")) { + lf[j] = false; + } + else { + throw new Exception("Error reading file " + filename + ": unknown logical flag for " + + (i + 1) + " atom"); + } + } + } + + Atoms[nat] = new VaspAtom(x, y, z, lf[0], lf[1], lf[2]); + Atoms[nat].species = k; + } + } + } + + catch (IOException e) { + throw new Exception("Error reading file " + filename + ": " + e.getMessage()); + } + } + + public void parsePotcar(String filename, int fileType) throws Exception { + + String line; + StringTokenizer st; + + BufferedReader in = null; + + if (fileType == 0) { // Read from file + try { + in = new BufferedReader(new FileReader(filename)); + } + catch (java.io.FileNotFoundException e) { + throw new Exception("Error opening file " + filename + ": " + e.getMessage()); + } + } + else if (fileType == 1) { // Read from String + in = new BufferedReader(new StringReader(filename)); + } + else { + throw new Exception("Implementation error: unknown file type"); + } + + try { + + while ( (line = in.readLine()) != null) { + // --- 1st line; header + boolean elementResoved = false; + st = new StringTokenizer(line, " \t"); + // assume, that the first token is a type of a potential, and the second is element symbol + String element = null, potential = null; + if (st.countTokens() < 2 && st.countTokens() > 0) { + element = st.nextToken(); + } + else { + potential = st.nextToken(); + element = st.nextToken(); + } + + if (element != null && element.contains("_")) { + element = element.substring(0, element.indexOf("_")); + } + + if (element != null) { + elementResoved = true; + } + + // --- Read potential information + + while ( (line = in.readLine()) != null) { + line = line.trim().toUpperCase(); + if (line.equalsIgnoreCase("End of Dataset")) { + break; + } + if (line.startsWith("VRHFIN")) { + st = new StringTokenizer(line, " =:\t"); + if (st.countTokens() > 1) { + st.nextToken(); + String el = st.nextToken(); + if (el.contains("_")) { + el = el.substring(0, el.indexOf("_")); + } + if (elementResoved) { // Check + if (!el.equalsIgnoreCase(element)) { + element = el; + logger.info("parsePotcar: Warning: element in VRHFIN " + el + " does not match element " + + element + " in header"); + } + } + else { + element = el; + } + } + } + } + + if (element != null) { + Integer atomNumber = ChemicalElements.getAtomicNumber(element); + if (potcarAtomSymbols == null) { + potcarAtomSymbols = new ArrayList (); + potcarAtomNumbers = new ArrayList (); + } + + potcarAtomSymbols.add(element); + potcarAtomNumbers.add(atomNumber); + } + else { + System.err.println("parsePotcar: Warning: cannot resolve element after reading potential information..."); + } + + } + + } + + catch (IOException e) { + throw new Exception("Error reading file " + filename + ": " + e.getMessage()); + } + } + + public static void main(String[] args) { + Vasp vasp = new Vasp(); + } + + public void resolveAtomTypes() throws Exception { + if (atomicSpecies == null) { + throw new Exception("resolveAtomTypes: atomicSpecies == null"); + } + else if (potcarAtomSymbols == null) { + throw new Exception("resolveAtomTypes: potcarAtomSymbols == null"); + } + else if (atomicSpecies.length != potcarAtomSymbols.size()) { + throw new Exception("resolveAtomTypes: amount of atomic species is different in POSCAR and POTCAR files"); + } + + int nat = 0; + for (int i = 0; i < atomicSpecies.length; i++) { + String symbol = potcarAtomSymbols.get(i); + int element = potcarAtomNumbers.get(i); + for (int j = 0; j < atomicSpecies[i]; j++, nat++) { + Atoms[nat].element = element; + } + } + } + + public void getMolecularInterface(MoleculeInterface molec) throws + Exception { + if (molec == null) { + throw new Exception(this.getClass().getCanonicalName() + " : molec == null"); + } + if (Atoms == null || Atoms.length < 1) { + throw new Exception(this.getClass().getCanonicalName() + " : no VASP atoms"); + } + + molec.addMonomer("VASP"); + + boolean typesNotSet = false; + + for (int i = 0; i < Atoms.length; i++) { + AtomInterface atom = molec.getNewAtomInstance(); + atom.setName(Atoms[i].getName()); + atom.setAtomicNumber(Atoms[i].element); + atom.setXYZ(Atoms[i].xyz[0], Atoms[i].xyz[1], Atoms[i].xyz[2]); + + molec.addAtom(atom); + + if (Atoms[i].element > 0) { + continue; + } + typesNotSet = true; + + int index = Atoms[i].species; + if (index >= colorMap.length) { + index = index % colorMap.length; + } + + Integer[] rgbColor = new Integer[3]; + rgbColor[0] = colorMap[index][0]; + rgbColor[1] = colorMap[index][1]; + rgbColor[2] = colorMap[index][2]; + + atom.setProperty(AtomInterface.RGB_COLOR, rgbColor); + + float radius = ChemicalElements.getCovalentRadius(14); + radius *= AtomInterface.COVALENT_TO_GRADIUS_FACTOR; + atom.setProperty(AtomInterface.GR_RADIUS, new Float(radius)); // GR_RADIUS "gradius" is a "graphics radius" + } + + if (typesNotSet) { + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface atom = molec.getAtomInterface(i); + atom.setAtomicNumber(4); + } + for (int i = 0; i < molec.getNumberOfAtoms(); i++) { + AtomInterface atom = molec.getAtomInterface(i); + atom.setAtomicNumber(0); + } + } + + molec.addProperty(MoleculeInterface.LATTICE_VECTORS, latticeVectors); + } + +} diff --git a/src/main/java/cct/vasp/VaspAtom.java b/src/main/java/cct/vasp/VaspAtom.java new file mode 100644 index 0000000..eb27a5b --- /dev/null +++ b/src/main/java/cct/vasp/VaspAtom.java @@ -0,0 +1,127 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.vasp; + +import cct.modelling.ChemicalElements; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class VaspAtom { + public int element = 0; + public int species = 0; + public float xyz[] = new float[3]; + public boolean opt[] = new boolean[3]; + + VaspAtom() {} + + VaspAtom(VaspAtom atom) { + element = atom.element; + species = atom.species; + xyz[0] = atom.getX(); + xyz[1] = atom.getY(); + xyz[2] = atom.getZ(); + opt[0] = atom.opt[0]; + opt[1] = atom.opt[1]; + opt[2] = atom.opt[2]; + } + + VaspAtom(float x, float y, float z) { + xyz[0] = x; + xyz[1] = y; + xyz[2] = z; + } + + VaspAtom(float x, float y, float z, boolean a1, boolean a2, boolean a3) { + xyz[0] = x; + xyz[1] = y; + xyz[2] = z; + opt[0] = a1; + opt[1] = a2; + opt[2] = a3; + } + + public int getAtomicNumber() { + return element; + } + + public String getName() { + if (element == 0) { + return String.valueOf( (species + 1)); + } + return ChemicalElements.getElementSymbol(element); + } + + public void setElement(String el) { + element = ChemicalElements.getAtomicNumber(el); + } + + public void setCoordinates(float x, float y, float z) { + xyz[0] = x; + xyz[1] = y; + xyz[2] = z; + } + + public void setCoordinates(double x, double y, double z) { + xyz[0] = (float) x; + xyz[1] = (float) y; + xyz[2] = (float) z; + } + + public float getX() { + return xyz[0]; + } + + public float getY() { + return xyz[1]; + } + + public float getZ() { + return xyz[2]; + } + +} diff --git a/src/main/java/cct/vasp/VaspSnapshot.java b/src/main/java/cct/vasp/VaspSnapshot.java new file mode 100644 index 0000000..8fa065c --- /dev/null +++ b/src/main/java/cct/vasp/VaspSnapshot.java @@ -0,0 +1,130 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.vasp; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public class VaspSnapshot { + + private double latticeVectors[][] = null; + private List atoms = null; + private Map energyDecomp = new HashMap (10); + + public VaspSnapshot() { + } + + public void addEnergyTerm(String type, double value) { + energyDecomp.put(type, new Double(value)); + } + + public double getEnergyTerm(String type) throws Exception { + if (!energyDecomp.containsKey(type)) { + throw new Exception("Snapshot does not have energy term " + type); + } + return energyDecomp.get(type); + } + + public boolean hasEnergyTerm(String type) { + return energyDecomp.containsKey(type); + } + + public double[][] getLatticeVectors() { + return latticeVectors; + } + + public void setLatticeVectors(double vectors[][]) { + if (latticeVectors == null) { + latticeVectors = new double[3][3]; + } + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + latticeVectors[i][j] = vectors[i][j]; + } + } + if (atoms != null) { + transformFracToCart(atoms, latticeVectors); + } + } + + public List getAtoms() { + return atoms; + } + + public void setAtoms(List at) { + + atoms = new ArrayList (at.size()); + for (int i = 0; i < at.size(); i++) { + VaspAtom atom = new VaspAtom(at.get(i)); + atoms.add(atom); + } + if (latticeVectors != null) { + transformFracToCart(atoms, latticeVectors); + } + + } + + public void transformFracToCart(List at, double vectors[][]) { + double x, y, z, x2 = 0, y2 = 0, z2 = 0; + for (int i = 0; i < at.size(); i++) { + VaspAtom atom = at.get(i); + x = atom.getX(); + y = atom.getY(); + z = atom.getZ(); + x2 = x * vectors[0][0] + y * vectors[1][0] + z * vectors[2][0]; + y2 = x * vectors[0][1] + y * vectors[1][1] + z * vectors[2][1]; + z2 = x * vectors[0][2] + y * vectors[1][2] + z * vectors[2][2]; + atom.setCoordinates(x2, y2, z2); + } + + } +} diff --git a/src/main/java/cct/vasp/VasprunTags.java b/src/main/java/cct/vasp/VasprunTags.java new file mode 100644 index 0000000..62091a5 --- /dev/null +++ b/src/main/java/cct/vasp/VasprunTags.java @@ -0,0 +1,66 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.vasp; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ +public enum VasprunTags { + MODELING, GENERATOR, I, INCAR, KPOINTS, GENERATION, V, VARRAY, PARAMETERS, SEPARATOR, ATOMINFO, ATOMS, TYPES, ARRAY, DIMENSION, + FIELD, SET, RC, C, CRYSTAL, NOSE, STRUCTURE, CALCULATION, SCSTEP, TIME, ENERGY, DIPOLE, R, EIGENVALUES; + + public VasprunTags getCommandObject(String command) { + command = command.toUpperCase(); + for (VasprunTags c : VasprunTags.values()) { + if (command.equalsIgnoreCase(c.name())) { + return c; + } + } + return null; + } + +} diff --git a/src/main/java/cct/vasp/VasprunXML.java b/src/main/java/cct/vasp/VasprunXML.java new file mode 100644 index 0000000..720c5f7 --- /dev/null +++ b/src/main/java/cct/vasp/VasprunXML.java @@ -0,0 +1,937 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.vasp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.InputStream; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +import cct.interfaces.AtomInterface; +import cct.interfaces.MoleculeInterface; +import cct.modelling.StructureManagerInterface; + +/** + *

Title: Computational Chemistry Tookit

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

+ * + *

Company: ANU

+ * + * @author Dr. Vladislav Vassiliev + * @version 1.0 + */ + +enum WhatToParse { + INITIAL_STRUCTURE_ONLY, FINAL_STRUCTURE_ONLY, PARSE_ALL +} + +public class VasprunXML + extends DefaultHandler implements StructureManagerInterface { + + public boolean debug = true; + public static final String TOTAL_ENERGY_KEY = "total"; + + private WhatToParse whatToParse = WhatToParse.FINAL_STRUCTURE_ONLY; + + private int numberAtoms = 0; + private int nTypes = 0; + private VasprunTags currentTag = null; + private VasprunTags validTags = VasprunTags.MODELING; + private String currentEnergyLabel = null; + private boolean yes_modeling = false; + private boolean parse_atominfo = false; + private boolean parse_atoms = false; + private boolean parse_types = false; + private boolean parse_atominfo_array_atoms = false; + private boolean parse_crystal = false; + private boolean parse_structure = false; + private boolean parse_varray = false; + private boolean parse_varray_basis = false; + private boolean parse_varray_positions = false; + private boolean parse_calculation = false; + private boolean parse_scstep = false; + private boolean parse_energy = false; + private boolean parse_v = false; + private boolean parse_c = false; + + private VaspSnapshot vaspSnapshot = null; + private List snapshots = new ArrayList (); + + private Set energyDecomp = new HashSet (); + + private Map termVsStrReference = new HashMap (); + + private VaspAtom vaspAtom = null; + private int vaspAtomIndex = 0; + + private double latticeVectors[][] = null; + private int latticeVectorsIndex = 0; + + private List initialStructure = new ArrayList (); + private boolean initialStrIsSet = false; + private List finalStructure = new ArrayList (); + private int atomIndex = 0; + + private StringWriter sWriter = null; + static final Logger logger = Logger.getLogger(VasprunXML.class.getCanonicalName()); + + public VasprunXML() { + + } + + public String[] getEnergyTerms() { + if (energyDecomp.size() < 1) { + return null; + } + String[] sa = new String[energyDecomp.size()]; + energyDecomp.toArray(sa); + return sa; + } + + /** + * Returns all values for (energy) term "term" + * @param term String - Energy term ("total", etc.) + * @return double[] - (energy) term values + */ + public double[] getAllTerms(String term) { + if (!energyDecomp.contains(term) || snapshots.size() < 1) { + return null; + } + + List references = new ArrayList (snapshots.size()); + List values = new ArrayList (snapshots.size()); + for (int i = 0; i < snapshots.size(); i++) { + VaspSnapshot snapshot = snapshots.get(i); + try { + Double value = snapshot.getEnergyTerm(term); + values.add(value); + references.add(new Integer(i)); + } + catch (Exception ex) {} + } + if (values.size() < 1) { + return null; + } + termVsStrReference.put(term, references); + double[] energies = new double[values.size()]; + for (int i = 0; i < values.size(); i++) { + energies[i] = values.get(i); + } + return energies; + } + + /** + * Returns all total energies ("total" key) + * It's the same as getAllTerms(TOTAL_ENERGY_KEY) + * @return double[] - values + */ + public double[] getTotalEnergies() { + return getAllTerms(TOTAL_ENERGY_KEY); + } + + /** + * Takes the last snapshot from the bunch + * @param molec MoleculeInterface + * @throws Exception - if no snapshots/atoms + */ + public void getMolecularInterface(MoleculeInterface molec) throws + Exception { + if (molec == null) { + throw new Exception(this.getClass().getCanonicalName() + + " : molec == null"); + } + + if (snapshots == null || snapshots.size() < 1) { + throw new Exception(this.getClass().getCanonicalName() + " : no structures..."); + } + + VaspSnapshot snapshot = snapshots.get(snapshots.size() - 1); + + List atoms = snapshot.getAtoms(); + + if (atoms == null || atoms.size() < 1) { + throw new Exception(this.getClass().getCanonicalName() + " : no atoms in selected snapshot"); + } + + //molec.addProperty(MoleculeInterface.ChargeProperty, new Integer(netCharge)); + //molec.addProperty(MoleculeInterface.MultiplicityProperty, new Integer(spinMultiplicity)); + + molec.addMonomer("VASP"); + + for (int i = 0; i < atoms.size(); i++) { + VaspAtom va = atoms.get(i); + AtomInterface atom = molec.getNewAtomInstance(); + atom.setName(va.getName()); + atom.setAtomicNumber(va.getAtomicNumber()); + atom.setXYZ(va.getX(), va.getY(), va.getZ()); + molec.addAtom(atom); + } + } + + public double[][] getLatticeVectors() throws Exception { + + if (snapshots == null || snapshots.size() < 1) { + throw new Exception(this.getClass().getCanonicalName() + + " : no structures..."); + } + + VaspSnapshot snapshot = snapshots.get(snapshots.size() - 1); + + return snapshot.getLatticeVectors(); + } + + public void parseVasprunXML(String fileName) throws Exception { + File file = null; + try { + file = new File(fileName); + } + catch (Exception ex) { + throw new Exception("Cannot open file " + fileName + " : " + ex.getMessage()); + } + parseVasprunXML(file); + } + + public void parseVasprun(String fileName) throws Exception { + String line, token; + BufferedReader in = null; + + try { + in = new BufferedReader(new FileReader(fileName)); + } + catch (Exception ex) { + throw new Exception("Cannot open file " + fileName + " : " + ex.getMessage()); + } + + boolean start_parse = false; + try { + + while ( (line = in.readLine()) != null) { + line = line.trim(); + + if (line.length() < 1) { // Blank line + continue; + } + + if (line.equalsIgnoreCase("")) { + start_parse = true; + continue; + } + else if (line.equalsIgnoreCase("")) { + start_parse = false; + continue; + } + + if (!start_parse) { + continue; + } + + // --- atominfo + + if (line.equalsIgnoreCase("")) { + line = line.trim().toUpperCase(); + // 23 + + } + + StringTokenizer st = new StringTokenizer(line.toUpperCase(), " =,"); + token = st.nextToken(); + } + } + catch (Exception ex) { + throw ex; + } + } + + public void parseVasprunXML(Object inputSource) throws Exception { + + // Use the default (non-validating) parser + SAXParserFactory factory = SAXParserFactory.newInstance(); + + try { + // Parse the input + SAXParser saxParser = factory.newSAXParser(); + + if (inputSource instanceof File) { + saxParser.parse( (File) inputSource, this); + } + else if (inputSource instanceof InputStream) { + saxParser.parse( (InputStream) inputSource, this); + } + else { + throw new Exception("parseVasprunXML: Internal error: Unknown input source: " + + inputSource.getClass().getCanonicalName()); + } + } + catch (Exception ex) { + if (snapshots == null || snapshots.size() < 1) { + ex.printStackTrace(); + throw new Exception("Cannot parse file : " + ex.getMessage()); + } + System.err.println("It was an error while reading XML file, however several snashots have been salvaged..."); + } + } + + @Override + public void startDocument() throws SAXException { + if (debug) { + logger.info("Start Document"); + } + } + + @Override + public void endDocument() throws SAXException { + if (debug) { + logger.info("End Document"); + } + + } + + @Override + public void startElement(String namespaceURI, + String lName, // local name + String qName, // qualified name + Attributes attrs) throws SAXException { + + String eName = lName; // element name + if ("".equals(eName)) { + eName = qName; // namespaceAware = false + } + if (debug) { + System.out.print("<" + eName); + } + if (attrs != null) { + for (int i = 0; i < attrs.getLength(); i++) { + String aName = attrs.getLocalName(i); // Attr name + if ("".equals(aName)) { + aName = attrs.getQName(i); + } + if (debug) { + System.out.print(" " + aName + "=\"" + attrs.getValue(i) + "\""); + } + } + } + if (debug) { + logger.info(">"); + } + // Parse elements... + + currentTag = validTags.getCommandObject(eName); + + if (currentTag == null) { + logger.info("Unknown tag " + eName + " Ignored..."); + return; + } + + if (currentTag == VasprunTags.MODELING) { + yes_modeling = true; + return; + } + + if (!yes_modeling) { + return; + } + + // --- Tags + // + // + // + // + // + // 23 + // + // + // ion + // element + // atomtype + // + // Fe 1 + // + // type + // atomspertype + // element + // mass + // valence + // pseudopotential + // + // 20Fe 55.84700000 8.00000000 US Fe + // + // + // + // 4.94500000 0.00000000 0.00000000 + // -1.64833333 4.66218754 0.00000000 + // 0.00000000 0.00000000 23.77520000 + // 548.12576206 + // + // + // + // + // + // + + + + switch (currentTag) { + case ATOMINFO: + parse_atominfo = true; + break; + case ATOMS: + if (parse_atominfo) { + parse_atoms = true; + sWriter = new StringWriter(); + } + break; + case TYPES: + parse_types = true; + if (parse_types) { + sWriter = new StringWriter(); + } + break; + + case ARRAY: + if (attrs.getValue("name") != null && attrs.getValue("name").equalsIgnoreCase("atoms")) { + parse_atominfo_array_atoms = true; + } + break; + + case SET: + if (parse_atominfo_array_atoms) { + } + break; + + case CALCULATION: + parse_calculation = true; + vaspSnapshot = new VaspSnapshot(); + break; + + case STRUCTURE: + parse_structure = true; + atomIndex = 0; + if (attrs != null) { + if (attrs.getValue("name") != null && attrs.getValue("name").equalsIgnoreCase("initialpos")) { + vaspSnapshot = new VaspSnapshot(); + } + else if (attrs.getValue("name") != null && attrs.getValue("name").equalsIgnoreCase("finalpos")) { + vaspSnapshot = new VaspSnapshot(); + } + } + break; + + case CRYSTAL: + parse_crystal = true; + break; + + case VARRAY: + parse_varray = true; + if (attrs != null) { + if (attrs.getValue("name") != null && attrs.getValue("name").equalsIgnoreCase("basis") && parse_crystal) { + parse_varray_basis = true; + } + else if (attrs.getValue("name") != null && attrs.getValue("name").equalsIgnoreCase("positions")) { + parse_varray_positions = true; + } + } + break; + + case SCSTEP: + parse_scstep = true; + break; + + case ENERGY: + parse_energy = true; + break; + + case V: + parse_v = true; + if (parse_varray_basis || parse_varray_positions) { + sWriter = new StringWriter(); + } + break; + + case C: + parse_c = true; + if (parse_atominfo_array_atoms) { + sWriter = new StringWriter(); + } + break; + + case I: + if (parse_calculation && parse_energy && ! (parse_scstep)) { + sWriter = new StringWriter(); + if (attrs != null && attrs.getValue("name") != null) { + currentEnergyLabel = attrs.getValue("name"); + } + } + + break; + default: + break; + } + + } + + @Override + public void endElement(String namespaceURI, + String sName, // simple name + String qName // qualified name + ) throws SAXException { + + String eName = sName; // element name + if ("".equals(eName)) { + eName = qName; // namespaceAware = false + } + if (debug) { + logger.info(""); + } + // Parse elements... + + currentTag = validTags.getCommandObject(eName); + + if (currentTag == null) { + return; + } + + if (currentTag == VasprunTags.MODELING) { + yes_modeling = false; + return; + } + + String s = null; + if (sWriter != null) { + s = sWriter.toString().trim(); + sWriter = null; + } + + switch (currentTag) { + case ATOMINFO: + parse_atominfo = false; + break; + case ATOMS: + if (parse_atominfo) { + if (parse_atoms) { + try { + numberAtoms = Integer.parseInt(s); + } + catch (Exception ex) { + throw new SAXException("Cannot parse number of atoms: \"" + s + "\" : " + ex.getMessage()); + } + + if (initialStructure.size() > 0 && initialStructure.size() != numberAtoms) { + throw new SAXException("initialStructure.size() > 0 && initialStructure.size() != numberAtoms"); + } + } + } + parse_atoms = false; + break; + case TYPES: + if (parse_types) { + try { + nTypes = Integer.parseInt(s); + } + catch (Exception ex) { + throw new SAXException("Cannot parse number of atom types: " + s + " : " + ex.getMessage()); + } + } + parse_types = false; + break; + + case ARRAY: + if (parse_atominfo_array_atoms) { + parse_atominfo_array_atoms = false; + } + break; + + case SET: + if (parse_atominfo_array_atoms) { + initialStrIsSet = true; + } + break; + + case CALCULATION: + parse_calculation = false; + snapshots.add(vaspSnapshot); + atomIndex = 0; + break; + + case STRUCTURE: + if (!parse_calculation) { + snapshots.add(vaspSnapshot); + } + parse_structure = false; + atomIndex = 0; + break; + + case CRYSTAL: + parse_crystal = false; + break; + + case VARRAY: + + if (parse_varray_positions) { + vaspSnapshot.setAtoms(this.initialStructure); + } + + parse_varray = false; + parse_varray_basis = false; + parse_varray_positions = false; + break; + + case SCSTEP: + parse_scstep = false; + break; + + case ENERGY: + parse_energy = false; + break; + + case V: + if (! (parse_varray_basis || parse_varray_positions)) { + break; + } + + double[] vec = new double[3]; + StringTokenizer tokens = new StringTokenizer(s, " "); + for (int i = 0; i < 3; i++) { + if (!tokens.hasMoreTokens()) { + throw new SAXException("Cannot parse vector data: " + s + " : Unexpected end of data"); + } + try { + vec[i] = Double.parseDouble(tokens.nextToken()); + } + catch (Exception ex) { + throw new SAXException("Cannot parse vector data: " + s + " : " + ex.getMessage()); + } + } + + if (parse_varray_basis) { + if (latticeVectorsIndex >= 3) { + latticeVectorsIndex = 0; + } + if (latticeVectorsIndex == 0) { + latticeVectors = new double[3][3]; + } + latticeVectors[latticeVectorsIndex][0] = vec[0]; + latticeVectors[latticeVectorsIndex][1] = vec[1]; + latticeVectors[latticeVectorsIndex][2] = vec[2]; + ++latticeVectorsIndex; + + if (latticeVectorsIndex >= 3) { + vaspSnapshot.setLatticeVectors(latticeVectors); + latticeVectorsIndex = 0; + break; + } + } + + else if (parse_varray_positions) { + if (atomIndex >= initialStructure.size()) { + throw new SAXException("atomIndex >= initialStructure.size()"); + } + + vaspAtom = initialStructure.get(atomIndex); + vaspAtom.setCoordinates(vec[0], vec[1], vec[2]); + ++atomIndex; + } + parse_v = false; + break; + + case C: + if (parse_atominfo_array_atoms) { + if (vaspAtomIndex == 0) { + vaspAtom = new VaspAtom(); + vaspAtom.setElement(s); + ++vaspAtomIndex; + } + else if (vaspAtomIndex == 1) { + vaspAtomIndex = 0; + initialStructure.add(vaspAtom); + } + } + + parse_c = false; + break; + + case I: + if (parse_calculation && parse_energy && ! (parse_scstep)) { + double value = 0; + try { + value = Double.parseDouble(s); + vaspSnapshot.addEnergyTerm(currentEnergyLabel, value); + } + catch (Exception ex) { + throw new SAXException("Cannot parse value for energy: " + s + " : " + ex.getMessage()); + } + + if (currentEnergyLabel != null && (!energyDecomp.contains(currentEnergyLabel))) { + energyDecomp.add(currentEnergyLabel); + } + } + + break; + + default: + break; + } + + } + + @Override + public void characters(char buf[], int offset, int len) throws + SAXException { + + if (len < 1) { + return; + } + + if (currentTag == null) { + return; + } + + String s = null; + + if (sWriter != null) { + sWriter.write(buf, offset, len); + } + + switch (currentTag) { + case ATOMS: + + /* + if (parse_atoms) { + try { + s = new String(buf, offset, len).trim(); + numberAtoms = Integer.parseInt(s); + } + catch (Exception ex) { + throw new SAXException("Cannot parse number of atoms: \"" + s + "\" : " + ex.getMessage()); + } + + if (initialStructure.size() > 0 && initialStructure.size() != numberAtoms) { + throw new SAXException("initialStructure.size() > 0 && initialStructure.size() != numberAtoms"); + } + } + */ + break; + + case TYPES: + + /* + if (parse_types) { + try { + s = new String(buf, offset, len).trim(); + nTypes = Integer.parseInt(s); + } + catch (Exception ex) { + throw new SAXException("Cannot parse number of atom types: " + s + " : " + ex.getMessage()); + } + } + */ + break; + + case C: + + /* + if (!parse_c) { + break; + } + if (parse_atominfo_array_atoms) { + if (vaspAtomIndex == 0) { + vaspAtom = new VaspAtom(); + vaspAtom.setElement(new String(buf, offset, len).trim()); + ++vaspAtomIndex; + } + else if (vaspAtomIndex == 1) { + vaspAtomIndex = 0; + initialStructure.add(vaspAtom); + } + + } + */ + break; + + case V: + + /* + if (!parse_v) { + break; + } + if (! (parse_varray_basis || parse_varray_positions)) { + break; + } + + double[] vec = new double[3]; + s = new String(buf, offset, len).trim(); + StringTokenizer tokens = new StringTokenizer(s, " "); + for (int i = 0; i < 3; i++) { + if (!tokens.hasMoreTokens()) { + throw new SAXException("Cannot parse vector data: " + s + " : Unexpected end of data"); + } + try { + vec[i] = Double.parseDouble(tokens.nextToken()); + } + catch (Exception ex) { + throw new SAXException("Cannot parse vector data: " + s + " : " + ex.getMessage()); + } + } + + if (parse_varray_basis) { + if (latticeVectorsIndex == 0) { + latticeVectors = new double[3][3]; + } + else if (latticeVectorsIndex >= 3) { + vaspSnapshot.setLatticeVectors(latticeVectors); + latticeVectorsIndex = 0; + break; + } + latticeVectors[latticeVectorsIndex][0] = vec[0]; + latticeVectors[latticeVectorsIndex][1] = vec[1]; + latticeVectors[latticeVectorsIndex][2] = vec[2]; + ++latticeVectorsIndex; + } + + else if (parse_varray_positions) { + if (atomIndex >= initialStructure.size()) { + throw new SAXException("atomIndex >= initialStructure.size()"); + } + + vaspAtom = initialStructure.get(atomIndex); + vaspAtom.setCoordinates(vec[0], vec[1], vec[2]); + } + */ + break; + + } + + } + + /** + * Not implemented yet + * @param number int + * @throws Exception + */ + @Override + public void selectStructure(int number) throws Exception { + throw new Exception(this.getClass().getCanonicalName() + ": selectStructure(int number) is not implemented yet"); + } + + /** + * Not implemented yet... + * @param number int + * @param term String + * @throws Exception + */ + @Override + public void selectStructure(int number, String term) throws Exception { + throw new Exception(this.getClass().getCanonicalName() + ": selectStructure(int number, String term) is not implemented yet"); + } + + @Override + public float[][] getStructure(int n) { + return getStructure(n, TOTAL_ENERGY_KEY); + } + + @Override + public float[][] getStructure(int n, String term) { + if (!energyDecomp.contains(term) || snapshots.size() < 1) { + return null; + } + + if (snapshots == null || snapshots.size() < 1) { + return null; + } + + List references = termVsStrReference.get(term); + if (references == null) { + System.err.println("references == null"); + return null; + } + else if (n >= references.size()) { + System.err.println("n >= references.size()"); + return null; + } + + if (debug) { + logger.info("getStructure: # " + n); + } + + VaspSnapshot snapshot = snapshots.get(references.get(n)); + + List atoms = snapshot.getAtoms(); + + if (atoms == null || atoms.size() < 1) { + System.err.println(this.getClass().getCanonicalName() + " : no atoms in selected snapshot"); + return null; + } + + float[][] coord = new float[atoms.size()][3]; + for (int i = 0; i < atoms.size(); i++) { + VaspAtom va = atoms.get(i); + coord[i][0] = va.getX(); + coord[i][1] = va.getY(); + coord[i][2] = va.getZ(); + if (debug && i == atoms.size() - 1) { + logger.info(i + " : x=" + coord[i][0] + " y=" + coord[i][1] + " z=" + coord[i][2]); + } + + } + return coord; + } + + //=========================================================== + // Utility Methods ... + //=========================================================== + + +} diff --git a/src/main/java/cct/vasp/ui/ReadPoscarDialog.java b/src/main/java/cct/vasp/ui/ReadPoscarDialog.java new file mode 100644 index 0000000..c486507 --- /dev/null +++ b/src/main/java/cct/vasp/ui/ReadPoscarDialog.java @@ -0,0 +1,454 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.vasp.ui; + +import java.awt.BorderLayout; +import java.awt.FileDialog; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.util.logging.Logger; +import java.util.prefs.Preferences; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTextField; + +import cct.interfaces.MoleculeInterface; +import cct.vasp.Vasp; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class ReadPoscarDialog + extends JDialog { + JPanel panel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + JButton helpButton = new JButton(); + JLabel jLabel1 = new JLabel(); + JPanel filesPanel = new JPanel(); + JPanel buttonsPanel = new JPanel(); + JLabel jLabel2 = new JLabel(); + JButton cancelButton = new JButton(); + JButton loadButton = new JButton(); + JButton potcarButton = new JButton(); + JButton browsePoscarButton = new JButton(); + JTextField potcarTextField = new JTextField(); + JTextField poscarTextField = new JTextField(); + GridBagLayout gridBagLayout1 = new GridBagLayout(); + + JFileChooser chooser = null; + Vasp vaspFile = null; + //Java3dUniverse java3dUniverse = null; + MoleculeInterface molecule = null; + private static String lastPWDKey = "lastPWD"; + Preferences prefs = Preferences.userNodeForPackage(getClass()); + File currentWorkingDirectory = null; + boolean OKPressed = false; + boolean atomTypesResolved = false; + static final Logger logger = Logger.getLogger(ReadPoscarDialog.class.getCanonicalName()); + + public ReadPoscarDialog(Frame owner, String title, boolean modal, MoleculeInterface mol) { + super(owner, title, modal); + molecule = mol; + try { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + jbInit(); + pack(); + } + catch (Exception exception) { + exception.printStackTrace(); + } + } + + public void setMolecule(MoleculeInterface mol) { + molecule = mol; + } + + public MoleculeInterface getMolecule() { + return molecule; + } + + private ReadPoscarDialog() { + this(new Frame(), "ReadPoscarDialog", false, null); + } + + private void jbInit() throws Exception { + panel1.setLayout(borderLayout1); + helpButton.setToolTipText(""); + helpButton.setText("Help"); + helpButton.addActionListener(new ReadPoscarDialog_helpButton_actionAdapter(this)); + jLabel1.setToolTipText(""); + jLabel1.setText("POTCAR File:"); + jLabel2.setToolTipText(""); + jLabel2.setText("POSCAR file:"); + cancelButton.setToolTipText(""); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new ReadPoscarDialog_cancelButton_actionAdapter(this)); + loadButton.setEnabled(false); + loadButton.setToolTipText(""); + loadButton.setText("Load"); + loadButton.addActionListener(new ReadPoscarDialog_loadButton_actionAdapter(this)); + potcarButton.setEnabled(false); + potcarButton.setToolTipText(""); + potcarButton.setText("Browse"); + potcarButton.addActionListener(new ReadPoscarDialog_coordButton_actionAdapter(this)); + browsePoscarButton.setToolTipText(""); + browsePoscarButton.setText("Browse"); + browsePoscarButton.addActionListener(new ReadPoscarDialog_browsePrmtopButton_actionAdapter(this)); + potcarTextField.setEnabled(false); + potcarTextField.setEditable(false); + potcarTextField.setText(""); + potcarTextField.setColumns(30); + poscarTextField.setToolTipText(""); + poscarTextField.setEditable(false); + poscarTextField.setText(""); + poscarTextField.setColumns(30); + filesPanel.setLayout(gridBagLayout1); + this.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); + getContentPane().add(panel1); + buttonsPanel.add(loadButton); + buttonsPanel.add(cancelButton); + buttonsPanel.add(helpButton); + panel1.add(buttonsPanel, BorderLayout.SOUTH); + panel1.add(filesPanel, BorderLayout.CENTER); + filesPanel.add(jLabel2, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + filesPanel.add(poscarTextField, + new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + filesPanel.add(browsePoscarButton, + new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + , GridBagConstraints.CENTER, + GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + filesPanel.add(jLabel1, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + filesPanel.add(potcarTextField, + new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0 + , GridBagConstraints.NORTH, + GridBagConstraints.HORIZONTAL, + new Insets(2, 2, 2, 2), 0, 0)); + filesPanel.add(potcarButton, new GridBagConstraints(2, 1, 1, 1, 0.0, 1.0 + , GridBagConstraints.NORTH, GridBagConstraints.NONE, + new Insets(2, 2, 2, 2), 0, 0)); + } + + public boolean isOKPressed() { + return OKPressed; + } + + public float[][] getLatticeVectors() { + return vaspFile.getLatticeVectors(); + } + + public void coordButton_actionPerformed(ActionEvent e) { + + /* + if (chooser == null) { + javax.swing.filechooser.FileFilter[] filters = FileFilterImpl.getFileFilters( "potcar" ); + chooser = new JFileChooser(); + for (int i = 0; i < filters.length; i++) { + chooser.addChoosableFileFilter(filters[i]); + } + + chooser.setAcceptAllFileFilterUsed(false); + chooser.setDialogTitle("Open POTCAR File"); + chooser.setDialogType(JFileChooser.OPEN_DIALOG); + } + */ + + FileDialog fd = new FileDialog(this, "Open VASP POTCAR File (potcar)", FileDialog.LOAD); + fd.setFile("*.dat;*.inp;potcar"); + + if (currentWorkingDirectory == null) { + String lastPWD = prefs.get(lastPWDKey, ""); + if (lastPWD.length() > 0) { + currentWorkingDirectory = new File(lastPWD); + if (currentWorkingDirectory.isDirectory() && + currentWorkingDirectory.exists()) { + //chooser.setCurrentDirectory(currentWorkingDirectory); + } + } + } + + if (currentWorkingDirectory != null) { + fd.setDirectory(currentWorkingDirectory.getAbsolutePath()); + } + fd.setVisible(true); + if (fd.getFile() == null) { + return; + } + + String fileName = fd.getFile(); + String workingDirectory = fd.getDirectory(); + + currentWorkingDirectory = new File(workingDirectory); + + /* + if (currentWorkingDirectory != null) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } + else { + String lastPWD = prefs.get(lastPWDKey, ""); + if (lastPWD.length() > 0) { + currentWorkingDirectory = new File(lastPWD); + if (currentWorkingDirectory.isDirectory() && + currentWorkingDirectory.exists()) { + chooser.setCurrentDirectory(currentWorkingDirectory); + } + } + } + */ + + //int returnVal = chooser.showOpenDialog(this); + + //if (returnVal == JFileChooser.APPROVE_OPTION) { + // String fileName = chooser.getSelectedFile().getPath(); + // currentWorkingDirectory = chooser.getCurrentDirectory(); + + try { + prefs.put(lastPWDKey, currentWorkingDirectory.getAbsolutePath()); + } + catch (Exception ex) { + System.err.println("Cannot save cwd: " + ex.getMessage() + " Ignored..."); + } + logger.info("You chose to open this file: " + fileName); + + try { + vaspFile.parsePotcar(workingDirectory + fileName, 0); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + // Try to resolve atom types + + try { + vaspFile.resolveAtomTypes(); + atomTypesResolved = true; + } + catch (Exception ex) { + atomTypesResolved = false; + JOptionPane.showMessageDialog(this, "Cannot resolve atom types: " + + ex.getMessage(), + "Error", + JOptionPane.ERROR_MESSAGE); + return; + + } + + //loadButton.setEnabled(true); + potcarTextField.setText(workingDirectory + fileName); + //return fileName; + //} + + } + + public void browsePrmtopButton_actionPerformed(ActionEvent e) { + FileDialog fd = new FileDialog(this, "Open VASP POSCAR File (poscar)", FileDialog.LOAD); + fd.setFile("*.dat;*.inp;poscar"); + fd.setVisible(true); + if (fd.getFile() == null) { + return; + } + + String fileName = fd.getFile(); + String workingDirectory = fd.getDirectory(); + + vaspFile = new Vasp(); + try { + vaspFile.parsePoscar(workingDirectory + fileName, 0); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + if (vaspFile.getNumberOfAtoms() < 1) { + JOptionPane.showMessageDialog(this, "Didn't find atoms in file", "Didn't find atoms in file", JOptionPane.ERROR_MESSAGE); + return; + } + + JOptionPane.showMessageDialog(this, "Found " + vaspFile.getNumberOfAtoms() + " atoms in file", "Info", + JOptionPane.INFORMATION_MESSAGE); + + potcarTextField.setEnabled(true); + potcarButton.setEnabled(true); + + loadButton.setEnabled(true); + + poscarTextField.setEnabled(false); + poscarTextField.setText(workingDirectory + fileName); + poscarTextField.setEnabled(true); + } + + public void loadButton_actionPerformed(ActionEvent e) { + this.OKPressed = true; + poscarTextField.setText(""); + potcarTextField.setText(""); + this.loadButton.setEnabled(false); + potcarButton.setEnabled(false); + this.setVisible(false); + + // Try to resolve atom types + + try { + vaspFile.resolveAtomTypes(); + atomTypesResolved = true; + } + catch (Exception ex) { + atomTypesResolved = false; + JOptionPane.showMessageDialog(this, "Cannot resolve atom types: " + ex.getMessage(), "Error", JOptionPane.WARNING_MESSAGE); + return; + + } + + try { + vaspFile.getMolecularInterface(molecule); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Error getting molecule: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + atomTypesResolved = false; + } + + public void cancelButton_actionPerformed(ActionEvent e) { + this.OKPressed = false; + poscarTextField.setText(""); + potcarTextField.setText(""); + this.loadButton.setEnabled(false); + potcarButton.setEnabled(false); + this.setVisible(false); + } + + public void helpButton_actionPerformed(ActionEvent e) { + JOptionPane.showMessageDialog(this, + "Download POSCAR file first. Then download POTCAR file and press Load button", + "Help", + JOptionPane.INFORMATION_MESSAGE); + } + + private class ReadPoscarDialog_helpButton_actionAdapter + implements ActionListener { + private ReadPoscarDialog adaptee; + ReadPoscarDialog_helpButton_actionAdapter(ReadPoscarDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.helpButton_actionPerformed(e); + } + } + + private class ReadPoscarDialog_cancelButton_actionAdapter + implements ActionListener { + private ReadPoscarDialog adaptee; + ReadPoscarDialog_cancelButton_actionAdapter(ReadPoscarDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.cancelButton_actionPerformed(e); + } + } + + private class ReadPoscarDialog_loadButton_actionAdapter + implements ActionListener { + private ReadPoscarDialog adaptee; + ReadPoscarDialog_loadButton_actionAdapter(ReadPoscarDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.loadButton_actionPerformed(e); + } + } + + private class ReadPoscarDialog_browsePrmtopButton_actionAdapter + implements ActionListener { + private ReadPoscarDialog adaptee; + ReadPoscarDialog_browsePrmtopButton_actionAdapter(ReadPoscarDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.browsePrmtopButton_actionPerformed(e); + } + } + + private class ReadPoscarDialog_coordButton_actionAdapter + implements ActionListener { + private ReadPoscarDialog adaptee; + ReadPoscarDialog_coordButton_actionAdapter(ReadPoscarDialog adaptee) { + this.adaptee = adaptee; + } + + @Override + public void actionPerformed(ActionEvent e) { + adaptee.coordButton_actionPerformed(e); + } + } + +} diff --git a/src/main/java/cct/vecmath/FaceIndices.java b/src/main/java/cct/vecmath/FaceIndices.java new file mode 100644 index 0000000..961caf2 --- /dev/null +++ b/src/main/java/cct/vecmath/FaceIndices.java @@ -0,0 +1,25 @@ +package cct.vecmath; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class FaceIndices { + public int i, j, k; + public FaceIndices() { + } + + public FaceIndices(int _i, int _j, int _k) { + i = _i; + j = _j; + k = _k; + } +} diff --git a/src/main/java/cct/vecmath/Geometry3d.java b/src/main/java/cct/vecmath/Geometry3d.java new file mode 100644 index 0000000..aa98e62 --- /dev/null +++ b/src/main/java/cct/vecmath/Geometry3d.java @@ -0,0 +1,464 @@ +/* ***** BEGIN LICENSE BLOCK ***** +Version: Apache 2.0/GPL 3.0/LGPL 3.0 + +CCT - Computational Chemistry Tools +Jamberoo - Java Molecules Editor + +Copyright 2008-2015 Dr. Vladislav Vasilyev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contributor(s): +Dr. Vladislav Vasilyev (original author) + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the Apache 2.0, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.vecmath; + +import cct.interfaces.Point3fInterface; +import java.lang.reflect.Array; + +/** + *

Title: Picking

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2005

+ * + *

Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class Geometry3d { + + static float SMALL_NUM = 0.00000001f; // anything that avoids division overflow + + private Geometry3d() { + } + + /** + * Rotates "point" around axis p2-p1 by angle theta + * @param point Point3fInterface + * @param theta float + * @param p1 Point3fInterface + * @param p2 Point3fInterface + */ + static public void rotatePointAroundArbitraryAxis(Point3fInterface point, float theta, Point3fInterface p1, Point3fInterface p2) { + + Point3f q2 = null; + + // Step 1 + + Point3f q1 = new Point3f(point.getX() - p1.getX(), + point.getY() - p1.getY(), + point.getZ() - p1.getZ()); + Point3f u = new Point3f(p2.getX() - p1.getX(), p2.getY() - p1.getY(), + p2.getZ() - p1.getZ()); + u.normalize(); + float d = (float) Math.sqrt(u.y * u.y + u.z * u.z); + + // Step 2 + if (Math.abs(d) > 0.000001f) { + q2 = new Point3f(q1.x, + q1.y * u.z / d - q1.z * u.y / d, + q1.y * u.y / d + q1.z * u.z / d); + } else { + q2 = new Point3f(q1); + } + + // Step 3 + q1.x = q2.x * d - q2.z * u.x; + q1.y = q2.y; + q1.z = q2.x * u.x + q2.z * d; + + // Step 4 + float cos_theta = (float) Math.cos(theta); + float sin_theta = (float) Math.sin(theta); + q2.x = q1.x * cos_theta - q1.y * sin_theta; + q2.y = q1.x * sin_theta + q1.y * cos_theta; + q2.z = q1.z; + + // Inverse of step 3 + q1.x = q2.x * d + q2.z * u.x; + q1.y = q2.y; + q1.z = -q2.x * u.x + q2.z * d; + + // Inverse of step 2 + if (Math.abs(d) > 0.000001f) { + q2.x = q1.x; + q2.y = q1.y * u.z / d + q1.z * u.y / d; + q2.z = -q1.y * u.y / d + q1.z * u.z / d; + } else { + q2 = q1; + } + + // Inverse of step 1 + point.setX(q2.getX() + p1.getX()); + point.setY(q2.getY() + p1.getY()); + point.setZ(q2.getZ() + p1.getZ()); + } + + /** + * Calculates distance between two segments + * @param s1 Segment3f + * @param s2 Segment3f + * @return double + */ + public static double segmentToSegmentDistance(Segment3f s1, Segment3f s2) { + + Point3f u = new Point3f(s1.p2, s1.p1); + Point3f v = new Point3f(s2.p2, s2.p1); + Point3f w = new Point3f(s1.p1, s2.p1); + + float a = Point3f.product(u, u); //dot(u,u); // always >= 0 + float b = Point3f.product(u, v); //dot(u,v); + float c = Point3f.product(v, v); //dot(v,v); // always >= 0 + float d = Point3f.product(u, w); //dot(u,w); + float e = Point3f.product(v, w); //dot(v,w); + float D = a * c - b * b; // always >= 0 + float sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0 + float tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0 + + // compute the line parameters of the two closest points + if (D < SMALL_NUM) { // the lines are almost parallel + sN = 0; // force using point P0 on segment S1 + sD = 1; // to prevent possible division by 0.0 later + tN = e; + tD = c; + } else { // get the closest points on the infinite lines + sN = (b * e - c * d); + tN = (a * e - b * d); + if (sN < 0) { // sc < 0 => the s=0 edge is visible + sN = 0; + tN = e; + tD = c; + } else if (sN > sD) { // sc > 1 => the s=1 edge is visible + sN = sD; + tN = e + b; + tD = c; + } + } + + if (tN < 0.0) { // tc < 0 => the t=0 edge is visible + tN = 0; + // recompute sc for this edge + if (-d < 0.0) { + sN = 0; + } else if (-d > a) { + sN = sD; + } else { + sN = -d; + sD = a; + } + } else if (tN > tD) { // tc > 1 => the t=1 edge is visible + tN = tD; + // recompute sc for this edge + if ((-d + b) < 0.0) { + sN = 0; + } else if ((-d + b) > a) { + sN = sD; + } else { + sN = (-d + b); + sD = a; + } + } + // finally do the division to get sc and tc + sc = Math.abs(sN) < SMALL_NUM ? 0 : sN / sD; + tc = Math.abs(tN) < SMALL_NUM ? 0 : tN / tD; + + // get the difference of the two closest points + //Vector dP = w + (sc * u) - (tc * v); // = S1(sc) - S2(tc) + float x = w.x + (sc * u.x) - (tc * v.x); + float y = w.y + (sc * u.y) - (tc * v.y); + float z = w.z + (sc * u.z) - (tc * v.z); + + //return norm(dP); // return the closest distance + return Math.sqrt(x * x + y * y + z * z); + } + + /** + * Calculates distance between two segments and returns coordinates of + * the closest points on each segment + * @param s1 Segment3f + * @param s2 Segment3f + * @param p1 Point3fInterface + * @param p2 Point3fInterface + * @return double + */ + public static double segmentToSegmentDistance(Segment3f s1, Segment3f s2, Point3f p1, Point3f p2) { + //Vector u = S1.P1 - S1.P0; + //Vector v = S2.P1 - S2.P0; + //Vector w = S1.P0 - S2.P0; + + Point3f u = new Point3f(s1.p2, s1.p1); + Point3f v = new Point3f(s2.p2, s2.p1); + Point3f w = new Point3f(s1.p1, s2.p1); + + float a = Point3f.product(u, u); //dot(u,u); // always >= 0 + float b = Point3f.product(u, v); //dot(u,v); + float c = Point3f.product(v, v); //dot(v,v); // always >= 0 + float d = Point3f.product(u, w); //dot(u,w); + float e = Point3f.product(v, w); //dot(v,w); + float D = a * c - b * b; // always >= 0 + float sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0 + float tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0 + + // compute the line parameters of the two closest points + if (D < SMALL_NUM) { // the lines are almost parallel + sN = 0; // force using point P0 on segment S1 + sD = 1; // to prevent possible division by 0.0 later + tN = e; + tD = c; + } else { // get the closest points on the infinite lines + sN = (b * e - c * d); + tN = (a * e - b * d); + if (sN < 0) { // sc < 0 => the s=0 edge is visible + sN = 0; + tN = e; + tD = c; + } else if (sN > sD) { // sc > 1 => the s=1 edge is visible + sN = sD; + tN = e + b; + tD = c; + } + } + + if (tN < 0.0) { // tc < 0 => the t=0 edge is visible + tN = 0; + // recompute sc for this edge + if (-d < 0.0) { + sN = 0; + } else if (-d > a) { + sN = sD; + } else { + sN = -d; + sD = a; + } + } else if (tN > tD) { // tc > 1 => the t=1 edge is visible + tN = tD; + // recompute sc for this edge + if ((-d + b) < 0.0) { + sN = 0; + } else if ((-d + b) > a) { + sN = sD; + } else { + sN = (-d + b); + sD = a; + } + } + // finally do the division to get sc and tc + sc = Math.abs(sN) < SMALL_NUM ? 0 : sN / sD; + tc = Math.abs(tN) < SMALL_NUM ? 0 : tN / tD; + + // get the difference of the two closest points + //Vector dP = w + (sc * u) - (tc * v); // = S1(sc) - S2(tc) + + p1.setXYZ(sc * u.x, sc * u.y, sc * u.z); + p2.setXYZ(tc * v.x, tc * v.y, tc * v.z); + + float x = w.x + p1.getX() - p2.getX(); + float y = w.y + p1.getY() - p2.getY(); + float z = w.z + p1.getZ() - p2.getZ(); + + //return norm(dP); // return the closest distance + return Math.sqrt(x * x + y * y + z * z); + } + + /** + * Used for the so-called Alternate Z-matrix Format i.e. allows nuclear positions + * to be specified using two bond angles rather than a bond angle and a dihedral angle. + * Not elegant solution but a quick fix... + * @param a - + * @param b + * @param angle_1 + * @param angle_2 + * @param direction - there are two possible positions + * @return - generated unit vector + * @throws Exception + */ + public static double[] getForTwoBondAngles(double[] a, double[] b, double angle_1, double angle_2, int direction) throws Exception { + double[] target = new double[3]; + // Since we solve the quadratic equation we have two solutions + + // --- Preliminaries... + + double aLength = Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]); + if (aLength == 0) { + throw new Exception("The first vector has zero length"); + } + double A = aLength * Math.cos(angle_1); + double bLength = Math.sqrt(b[0] * b[0] + b[1] * b[1] + b[2] * b[2]); + if (bLength == 0) { + throw new Exception("The second vector has zero length"); + } + double B = bLength * Math.cos(angle_2); + + // Power(az,2)*(Power(bx,2) + Power(by,2)) - 2*ax*az*bx*bz - 2*ay*by*(ax*bx + az*bz) + + // Power(ay,2)*(Power(bx,2) + Power(bz,2)) + Power(ax,2)*(Power(by,2) + Power(bz,2)) + // denominator is an eqivivalent of 2a + double denominator = a[2] * a[2] * (b[0] * b[0] + b[1] * b[1]) + - 2.0 * a[0] * a[2] * b[0] * b[2] - 2.0 * a[1] * b[1] + * (a[0] * b[0] + a[2] * b[2]) + a[1] * a[1] + * (b[0] * b[0] + b[2] * b[2]) + a[0] * a[0] * (b[1] * b[1] + b[2] * b[2]); + + double minusB = 0; + + if (a[0] != 0 || a[1] != 0) { + // A*az*(Power(bx,2) + Power(by,2)) + Power(ax,2)*B*bz - A*ay*by*bz - ax*bx*(az*B + A*bz) + ay*B*(-(az*by) + ay*bz) + // minusB is an equivalent of -b + minusB = A * a[2] * (b[0] * b[0] + b[1] * b[1]) + a[0] * a[0] * B * b[2] - A * a[1] * b[1] * b[2] - a[0] * b[0] * (a[2] * B + A * b[2]) + + a[1] * B * (-(a[2] * b[1]) + a[1] * b[2]); + } else { + // Power(ax,2)*B*by - ax*bx*(ay*B + A*by) + az*B*(az*by - ay*bz) + A*(-(az*by*bz) + ay*(Power(bx,2) + Power(bz,2))) + minusB = Power2(a[0]) * B * b[1] - a[0] * b[0] * (a[1] * B + A * b[1]) + a[2] * B * (a[2] * b[1] - a[1] * b[2]) + + A * (-(a[2] * b[1] * b[2]) + a[1] * (Power2(b[0]) + Power2(b[2]))); + } + + double discriminant = 0; + + if (a[0] != 0 || a[1] != 0) { + // Power(ay*bx - ax*by,2)*(-(Power(az,2)*(Power(B,2) - Power(bx,2) - Power(by,2))) - + // Power(A,2)*(Power(bx,2) + Power(by,2)) + 2*A*az*B*bz - Power(A,2)*Power(bz,2) + + // 2*ay*by*(A*B - az*bz) + 2*ax*bx*(A*B - ay*by - az*bz) + + // Power(ay,2)*(-Power(B,2) + Power(bx,2) + Power(bz,2)) + + // Power(ax,2)*(-Power(B,2) + Power(by,2) + Power(bz,2))) + discriminant = Power2(a[1] * b[0] - a[0] * b[1]) * (-(Power2(a[2]) * (Power2(B) - Power2(b[0]) - Power2(b[1]))) + - Power2(A) * (Power2(b[0]) + Power2(b[1])) + 2.0 * A * a[2] * B * b[2] - Power2(A) * Power2(b[2]) + + 2.0 * a[1] * b[1] * (A * B - a[2] * b[2]) + 2.0 * a[0] * b[0] * (A * B - a[1] * b[1] - a[2] * b[2]) + + Power2(a[1]) * (-Power2(B) + Power2(b[0]) + Power2(b[2])) + + Power2(a[0]) * (-Power2(B) + Power2(b[1]) + Power2(b[2]))); + } else { + // Power(az*bx - ax*bz,2)*(-(Power(az,2)*(Power(B,2) - Power(bx,2) - Power(by,2))) - + // Power(A,2)*(Power(bx,2) + Power(by,2)) + 2*A*az*B*bz - Power(A,2)*Power(bz,2) + + // 2*ay*by*(A*B - az*bz) + 2*ax*bx*(A*B - ay*by - az*bz) + + // Power(ay,2)*(-Power(B,2) + Power(bx,2) + Power(bz,2)) + + // Power(ax,2)*(-Power(B,2) + Power(by,2) + Power(bz,2))) + discriminant = Power2(a[2] * b[0] - a[0] * b[2]) * (-(Power2(a[2]) * (Power2(B) - Power2(b[0]) - Power2(b[1]))) + - Power2(A) * (Power2(b[0]) + Power2(b[1])) + 2.0 * A * a[2] * B * b[2] - Power2(A) * Power2(b[2]) + + 2.0 * a[1] * b[1] * (A * B - a[2] * b[2]) + 2.0 * a[0] * b[0] * (A * B - a[1] * b[1] - a[2] * b[2]) + + Power2(a[1]) * (-Power2(B) + Power2(b[0]) + Power2(b[2])) + + Power2(a[0]) * (-Power2(B) + Power2(b[1]) + Power2(b[2]))); + } + + if (discriminant < 0.0) { + throw new Exception("No solution: discriminant < 0.0"); + } + + int index = 2; + if (a[0] == 0 && a[1] == 0) { + index = 1; + } + + boolean one_root = false; + if (discriminant == 0) { + target[index] = minusB / denominator; + one_root = true; + } else { // Check for the first solution + target[index] = (minusB + Math.sqrt(discriminant)) / denominator; + } + + if (index == 2) { + target = doTheRest(a, b, A, B, target); + } else { + target = doTheRest2(a, b, A, B, target); + } + + if (one_root) { + return target; + } + + double[] cross = crossProduct(a, b); + if (product(target, cross) > 0 && direction > 0) { + return target; + } + + // Check the second root + + target[index] = (minusB - Math.sqrt(discriminant)) / denominator; + if (index == 2) { + target = doTheRest(a, b, A, B, target); + } else { + target = doTheRest2(a, b, A, B, target); + } + if (product(target, cross) < 0 && direction < 0) { + return target; + } + + return target; + } + + public static float[] getForTwoBondAngles(float[] a, float[] b, float angle_1, float angle_2, int direction) throws Exception { + double[] p = getForTwoBondAngles(new double[]{a[0], a[1], a[2]}, new double[]{b[0], b[1], b[2]}, (double) angle_1, (double) angle_2, direction); + return new float[]{(float) p[0], (float) p[1], (float) p[2]}; + } + + private static double[] doTheRest(double[] a, double[] b, double A, double B, double[] target) { + if (a[0] != 0.0) { + //(ax*B - A*bx + az*bx*cz - ax*bz*cz)/(-(ay*bx) + ax*by) + target[1] = (a[0] * B - A * b[0] + a[2] * b[0] * target[2] - a[0] * b[2] * target[2]) / (-(a[1] * b[0]) + a[0] * b[1]); + + // (A - ay cy - az cz)/ax + target[0] = (A - a[1] * target[1] - a[2] * target[2]) / a[0]; + } else if (a[1] != 0.0) { + // (ay*B - A*by + az*by*cz - ay*bz*cz)/(ay*bx - ax*by) + target[0] = (a[1] * B - A * b[1] + a[2] * b[1] * target[2] - a[1] * b[2] * target[2]) / (a[1] * b[0] - a[0] * b[1]); + // (A - ax*cx - az*cz)/ay + target[1] = (A - a[0] * target[0] - a[2] * target[2]) / a[1]; + } + return target; + } + + private static double[] doTheRest2(double[] a, double[] b, double A, double B, double[] target) { + // (az*B - A*bz - az*by*cy + ay*bz*cy)/(az*bx - ax*bz) + target[0] = (a[2] * B - A * b[2] - a[2] * b[1] * target[1] + a[1] * b[2] * target[1]) / (a[2] * b[0] - a[0] * b[2]); + + // ((A - ax*cx - ay*cy)/az) + target[2] = (A - a[0] * target[0] - a[1] * target[1]) / a[2]; + + return target; + } + + /** + * Calculates a cross product of two 3d vectors + * @param a - 1st vector + * @param v - 2nd vector + * @return - cross product vector + */ + public static double[] crossProduct(double a[], double[] v) { + return new double[]{a[1] * v[2] - a[2] * v[1], a[2] * v[0] - a[0] * v[2], a[0] * v[1] - a[1] * v[0]}; + } + + public static double product(double[] a, double[] b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + } + + public static double norm(double[] a) { + return Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]); + } + + private static double Power2(double a) { + return a * a; + } +} diff --git a/src/main/java/cct/vecmath/MeshObject.java b/src/main/java/cct/vecmath/MeshObject.java new file mode 100644 index 0000000..4de89c0 --- /dev/null +++ b/src/main/java/cct/vecmath/MeshObject.java @@ -0,0 +1,168 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.vecmath; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.List; + +import cct.interfaces.Point3fInterface; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class MeshObject { + + public static int GENERAL_MESH_OBJECT = 0; + public static int TRIANGLES_MESH_OBJECT = 1; + + List Vertices = null; + List faceIndices = null; + List normalVectors = null; + List Colors = null; + + int nVertices = 0; + float Opacity = 1; // Opaque... + + int objectType = GENERAL_MESH_OBJECT; + + public MeshObject() { + } + + public int getObjectType() { + return objectType; + } + + public void setOpacity(float opacity) { + if (opacity < 0) { + Opacity = 0; + } + else if (opacity > 1) { + Opacity = 1; + } + else { + Opacity = opacity; + } + } + + public float getOpacity() { + return Opacity; + } + + public float getTransparency() { + return 1.0f - Opacity; + } + + public void setTransparency(float transparency) { + if (transparency < 0) { + Opacity = 1; + } + else if (transparency > 1) { + Opacity = 0; + } + else { + Opacity = 1.0f - transparency; + } + } + + /** + * Sets MeshObject made of triangles (nVertices/3) + * @param nVertices int + * @param coordinates float[] - array with vertex coordinates of a size nVertices*3 + * @param face_indices int[] + * @param normals float[] + * @param colors float[] + * @throws Exception + */ + public void setMeshObjectOfTriangles(int n_vertices, float[] coordinates, int[] face_indices, float[] normals, float[] colors) throws + Exception { + + nVertices = n_vertices; + int nTriangles = nVertices / 3; + + Vertices = new ArrayList (nVertices); + faceIndices = new ArrayList (nTriangles); + normalVectors = new ArrayList (nVertices); + Colors = new ArrayList (nVertices); + + objectType = TRIANGLES_MESH_OBJECT; + + for (int i = 0; i < nVertices; i++) { + Point3fInterface vertex = new Point3f(coordinates[i * 3], coordinates[i * 3 + 1], coordinates[i * 3 + 2]); + Vertices.add(vertex); + + Point3fInterface normal = new Point3f(normals[3 * i], normals[3 * i + 1], normals[3 * i + 2]); + normalVectors.add(normal); + + Color color = new Color(colors[3 * i], colors[3 * i + 1], colors[3 * i + 2]); + Colors.add(color); + } + + for (int i = 0; i < nTriangles; i++) { + FaceIndices face = new FaceIndices(face_indices[i * 3], face_indices[i * 3 + 1], face_indices[i * 3 + 2]); + faceIndices.add(face); + } + } + + public Point3fInterface[] getVerticesAsArray() { + Point3fInterface[] vertices = new Point3fInterface[nVertices]; + return Vertices.toArray(vertices); + } + + public Color[] getColorsAsArray() { + Color[] colors = new Color[nVertices]; + return Colors.toArray(colors); + } + + public List getFaceIndices() { + return faceIndices; + } + + public List getNormals() { + return normalVectors; + } +} diff --git a/src/main/java/cct/vecmath/Plane.java b/src/main/java/cct/vecmath/Plane.java new file mode 100644 index 0000000..a7634ab --- /dev/null +++ b/src/main/java/cct/vecmath/Plane.java @@ -0,0 +1,197 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package cct.vecmath; + +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + * @author Vlad + */ +public class Plane { + + public static final double HALF_PI = Math.PI / 2.0; + private double A = 0, B = 0, C = 1, D = 0; + private double[] unitNormal = new double[]{0, 0, 1.0}; + + /** + * General definition of a plane: Ax + By + Cz + D = 0 + * + * @param A + * @param B + * @param C + * @param D + * @throws Exception + */ + public Plane(double A, double B, double C, double D) throws Exception { + setPlane(A, B, C, D); + } + + public Plane(double[] x1, double[] x2, double[] x3) throws Exception { + Vector3d v1 = new Vector3d(x1, x2); + Vector3d v2 = new Vector3d(x1, x3); + Vector3d cross = v1.crossProduct(v2); + setPlane(x1, cross.getDirection()); + } + + public Plane(Point3f x1, Point3f x2, Point3f x3) throws Exception { + Vector3d v1 = new Vector3d(x1, x2); + Vector3d v2 = new Vector3d(x1, x3); + Vector3d cross = v1.crossProduct(v2); + setPlane(x1, cross.getDirection()); + } + + public Plane(double[] point, double[] vector) throws Exception { + setPlane(point, vector); + } + + public void setPlane(double A, double B, double C, double D) throws Exception { + + if (A == 0 && B == 0 && C == 0) { + throw new Exception("A==0 && B==0 && C== 0"); + } + + double S = Math.sqrt(A * A + B * B + C * C); + + this.A = A / S; + this.B = B / S; + this.C = C / S; + this.D = D / S; + + unitNormal[0] = this.A; + unitNormal[1] = this.B; + unitNormal[2] = this.C; + } + + public void setPlane(double[] point, double[] vector) throws Exception { + this.A = vector[0]; + this.B = vector[1]; + this.C = vector[2]; + this.D = -vector[0] * point[0] - vector[1] * point[1] - vector[2] * point[2]; + + double S = Math.sqrt(A * A + B * B + C * C); + + this.A = A / S; + this.B = B / S; + this.C = C / S; + this.D = D / S; + + unitNormal[0] = this.A; + unitNormal[1] = this.B; + unitNormal[2] = this.C; + } + + public void setPlane(Point3d point, double[] vector) throws Exception { + this.A = vector[0]; + this.B = vector[1]; + this.C = vector[2]; + this.D = -vector[0] * point.getX() - vector[1] * point.getY() - vector[2] * point.getZ(); + + double S = Math.sqrt(A * A + B * B + C * C); + + this.A = A / S; + this.B = B / S; + this.C = C / S; + this.D = D / S; + + unitNormal[0] = this.A; + unitNormal[1] = this.B; + unitNormal[2] = this.C; + } + + public void setPlane(Point3f point, double[] vector) throws Exception { + this.A = vector[0]; + this.B = vector[1]; + this.C = vector[2]; + this.D = -vector[0] * point.getX() - vector[1] * point.getY() - vector[2] * point.getZ(); + + double S = Math.sqrt(A * A + B * B + C * C); + + this.A = A / S; + this.B = B / S; + this.C = C / S; + this.D = D / S; + + unitNormal[0] = this.A; + unitNormal[1] = this.B; + unitNormal[2] = this.C; + } + + public double distanceToPoint(double x, double y, double z) { + return Math.abs(x * A + y * B + z * C + D); + } + + public double distanceToPoint(double[] point) { + return Math.abs(point[0] * A + point[1] * B + point[2] * C + D); + } + + public double distanceToPoint(float x, float y, float z) { + return Math.abs(x * A + y * B + z * C + D); + } + + public double distanceToPointSigned(double x, double y, double z) { + return x * A + y * B + z * C + D; + } + + public double distanceToPointSigned(float x, float y, float z) { + return x * A + y * B + z * C + D; + } + + public boolean isNormal(Plane plane) { + return A * plane.getA() + B * plane.getB() + C * plane.getC() == 0; + } + + public boolean isNormal(Plane plane, double inaccuracy) { + return Math.abs(A * plane.getA() + B * plane.getB() + C * plane.getC()) <= inaccuracy; + } + + public double angle(Plane plane) throws Exception { + + double phi = (A * plane.getA() + B * plane.getB() + C * plane.getC()); + phi = Math.acos(phi); + if (phi > HALF_PI) { + phi = Math.PI - phi; + } + return phi; + } + + public double getA() { + return A; + } + + public double getB() { + return B; + } + + public double getC() { + return C; + } + + public double getD() { + return D; + } + + public static void main(String[] args) { + try { + Plane plane_1 = new Plane(new double[]{0, 0, 0}, new double[]{1, 0, 0}, new double[]{0, 1, 0}); + Plane plane_2 = new Plane(new double[]{0, 0, 0}, new double[]{1, 0, 0}, new double[]{0, 0, 1}); + System.out.println("Angle: " + Math.toDegrees(plane_1.angle(plane_2))); + // + plane_1 = new Plane(5, 7, 6, 8); + plane_2 = new Plane(9, 4, 3, 2); + double[] point = new double[3]; + + System.out.println("Angle: " + Math.toDegrees(plane_1.angle(plane_2)) + + " Ref: " + Math.toDegrees(Math.acos(0.8427371072309235))); + System.out.println("Distance from point (0,0,0): Plane_1: " + plane_1.distanceToPoint(point) + + " Ref: 0.7627700713964738 " + "Plane_2: " + plane_2.distanceToPoint(point) + " Ref: 0.19425717247145283"); + } catch (Exception ex) { + Logger.getLogger(Plane.class.getName()).log(Level.SEVERE, null, ex); + } + System.exit(0); + } + +} diff --git a/src/main/java/cct/vecmath/Point3d.java b/src/main/java/cct/vecmath/Point3d.java new file mode 100644 index 0000000..e999a9f --- /dev/null +++ b/src/main/java/cct/vecmath/Point3d.java @@ -0,0 +1,710 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2012 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.vecmath; + +import cct.interfaces.Point3fInterface; + +/** + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2004

+ * + *

+ * Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class Point3d { + + public static final double RADIANS_TO_DEGREES = 180.0 / Math.PI; + public static final double DEGREES_TO_RADIANS = Math.PI / 180.0; + public static final float PI_FLOAT = (float) Math.PI; + private double x, y, z; + private double xSq, ySq, zSq; + private double norm, normSq; + + // Constructors + public Point3d() { + x = y = z = 0.0; + xSq = ySq = zSq = 0.0; + norm = normSq = 0; + } + + public Point3d(double xx, double yy, double zz) { + x = xx; + y = yy; + z = zz; + precalc(); + } + + public Point3d getInstance(double xx, double yy, double zz) { + return new Point3d(xx, yy, zz); + } + + public Point3d(Point3d p) { + x = p.x; + y = p.y; + z = p.z; + + precalc(); + } + + public Point3d(Point3f p) { + x = p.getX(); + y = p.getY(); + z = p.getZ(); + + precalc(); + } + + /** + * Vector b - a + * + * @param a Point3f + * @param b Point3f + */ + public Point3d(Point3d a, Point3d b) { + x = b.x - a.x; + y = b.y - a.y; + z = b.z - a.z; + + precalc(); + } + + private void precalc() { + xSq = x * x; + ySq = y * y; + zSq = z * z; + normSq = xSq + ySq + zSq; + norm = Math.sqrt(normSq); + } + + private void precalcX() { + xSq = x * x; + normSq = xSq + ySq + zSq; + norm = Math.sqrt(normSq); + } + + private void precalcY() { + ySq = y * y; + normSq = xSq + ySq + zSq; + norm = Math.sqrt(normSq); + } + + private void precalcZ() { + zSq = z * z; + normSq = xSq + ySq + zSq; + norm = Math.sqrt(normSq); + } + + /** + * Substracts vector a2 from vector a1 + * + * @param a1 Point3d + * @param a2 Point3d + */ + public void subtract(Point3d a1, Point3d a2) { + x = a1.getX() - a2.getX(); + y = a1.getY() - a2.getY(); + z = a1.getZ() - a2.getZ(); + + precalc(); + } + + public Point3d getInstance() { + return new Point3d(); + } + + public Point3d getInstance(Point3d a) { + return new Point3d(a); + } + + /** + * Distance between two points + * + * @param p1 + * @param p2 + * @return + */ + public static double distance(Point3d p1, Point3d p2) { + return Math.sqrt(((p1.getX() - p2.getX()) + * (p1.getX() - p2.getX()) + + (p1.getY() - p2.getY()) + * (p1.getY() - p2.getY()) + + (p1.getZ() - p2.getZ()) + * (p1.getZ() - p2.getZ()))); + } + + /** + * Squared distance between two points + * + * @param p1 + * @param p2 + * @return + */ + public static double distanceSquared(Point3d p1, Point3d p2) { + return ((p1.getX() - p2.getX()) + * (p1.getX() - p2.getX()) + + (p1.getY() - p2.getY()) + * (p1.getY() - p2.getY()) + + (p1.getZ() - p2.getZ()) + * (p1.getZ() - p2.getZ())); + } + + public double distanceSquared(Point3d p2) { + return distanceSquared(this, p2); + } + + /** + * Distance from this point to point "point" + * + * @param point + * @return + */ + public double distanceTo(Point3d point) { + return Math.sqrt(((x - point.getX()) * (x - point.getX()) + + (y - point.getY()) * (y - point.getY()) + + (z - point.getZ()) * (z - point.getZ()))); + } + + public double distanceTo(Point3fInterface point) { + return Math.sqrt(((x - point.getX()) * (x - point.getX()) + + (y - point.getY()) * (y - point.getY()) + + (z - point.getZ()) * (z - point.getZ()))); + } + + public double distanceTo(double _x, double _y, double _z) { + return Math.sqrt(((x - _x) * (x - _x) + + (y - _y) * (y - _y) + + (z - _z) * (z - _z))); + } + + public void add(Point3d p) { + x += p.x; + y += p.y; + z += p.z; + + precalc(); + } + + public void add(Point3fInterface p) { + x += p.getX(); + y += p.getY(); + z += p.getZ(); + + precalc(); + } + + public void add(double px, double py, double pz) { + x += px; + y += py; + z += pz; + + precalc(); + } + + public double getX() { + return x; + } + + public double getY() { + return y; + } + + public double getZ() { + return z; + } + + public double getXSq() { + return xSq; + } + + public double getYSq() { + return ySq; + } + + public double getZSq() { + return zSq; + } + + public Point3d getXYZ() { + Point3d temp = new Point3d(this); + return temp; + } + + public void multiply(double number) { + x *= number; + y *= number; + z *= number; + + precalc(); + } + + /** + * Normalizes vector + */ + public void normalize() { + double s = this.vectorNorm(); + if (s != 0.0) { + x /= s; + y /= s; + z /= s; + + precalc(); + } + } + + /** + * Normalize vector v + * + * @param v + */ + public static void normalize(Point3d v) { + double s = Point3d.norm(v); + if (s != 0.0) { + v.setXYZ(v.getX() / s, v.getY() / s, v.getZ() / s); + } + } + + public Point3d crossProduct(Point3d v) { + return new Point3d(y * v.z - z * v.y, z * v.x - x * v.z, + x * v.y - y * v.x); + } + + /** + * Calculate cross vector for vectors v1 and v2 and put result into the crossVector No any memory allocation in the + * subroutine + * + * @param v1 Point3fInterface + * @param v2 Point3fInterface + * @param crossVector Point3fInterface + * @return Point3fInterface - cross product vector + */ + public static Point3d crossProduct(Point3d v1, Point3d v2, Point3d crossVector) { + crossVector.setX(v1.getY() * v2.getZ() - v1.getZ() * v2.getY()); + crossVector.setY(v1.getZ() * v2.getX() - v1.getX() * v2.getZ()); + crossVector.setZ(v1.getX() * v2.getY() - v1.getY() * v2.getX()); + return crossVector; + } + + /* + * inline void VectorProduct(real *x, real *y, real *p) { p[0] = x[1]*y[2] - x[2]*y[1]; p[1] = x[2]*y[0] - x[0]*y[2]; p[2] = + * x[0]*y[1] - x[1]*y[0]; + * + */ + public void crossProduct(Point3fInterface v1, Point3fInterface v2) { + x = v1.getY() * v2.getZ() - v1.getZ() * v2.getY(); + y = v1.getZ() * v2.getX() - v1.getX() * v2.getZ(); + z = v1.getX() * v2.getY() - v1.getY() * v2.getX(); + + precalc(); + } + + public double product(Point3d v) { + return x * v.x + y * v.y + z * v.z; + } + + public double product(Point3fInterface v) { + return x * v.getX() + y * v.getY() + z * v.getZ(); + } + + static public double product(Point3d a, Point3d b) { + return a.getX() * b.getX() + a.getY() * b.getY() + a.getZ() * b.getZ(); + } + + public double vectorNorm() { + return norm; + //return Math.sqrt((x * x + y * y + z * z)); + } + + public double norm() { + return norm; + //return Math.sqrt((x * x + y * y + z * z)); + } + + public static double vectorNorm(double vec[]) { + return Math.sqrt((vec[0] * vec[0] + vec[1] * vec[1] + + vec[2] * vec[2])); + } + + public static double vectorNorm(float vec[]) { + return Math.sqrt((vec[0] * vec[0] + vec[1] * vec[1] + + vec[2] * vec[2])); + } + + public static double norm(float vec[]) { + return Math.sqrt((vec[0] * vec[0] + vec[1] * vec[1] + + vec[2] * vec[2])); + } + + public static double norm(double vec[]) { + return Math.sqrt((vec[0] * vec[0] + vec[1] * vec[1] + + vec[2] * vec[2])); + } + + public static double norm(Point3d vec) { + return Math.sqrt((vec.getX() * vec.getX() + + vec.getY() * vec.getY() + + vec.getZ() * vec.getZ())); + } + + public static double squaredNorm(Point3d vec) { + return vec.getX() * vec.getX() + + vec.getY() * vec.getY() + + vec.getZ() * vec.getZ(); + } + + public double vectorSquaredNorm() { + return normSq; + //return x * x + y * y + z * z; + } + + public double squaredNorm() { + return normSq; + //return x * x + y * y + z * z; + } + + public void setX(double x) { + this.x = x; + this.precalcX(); + } + + public void setY(double y) { + this.y = y; + precalcY(); + } + + public void setZ(double z) { + this.z = z; + precalcZ(); + } + + public void setXYZ(double xx, double yy, double zz) { + x = xx; + y = yy; + z = zz; + + precalc(); + } + + public void setXYZ(Point3d p) { + x = p.x; + y = p.y; + z = p.z; + + precalc(); + } + + public void setXYZ(Point3fInterface xyz) { + x = xyz.getX(); + y = xyz.getY(); + z = xyz.getZ(); + + precalc(); + } + + public void substract(Point3d p) { + x -= p.x; + y -= p.y; + z -= p.z; + + precalc(); + } + + public void substract(Point3f p) { + x -= p.x; + y -= p.y; + z -= p.z; + + precalc(); + } + + /** + * Angle between atoms "a"-"current"-"b" + * + * @param a gAtom + * @param b gAtom + * @return float + */ + public double angleBetween(Point3d a, Point3d b) { + Point3d v1 = new Point3d(a.x - x, a.y - y, a.z - z); + Point3d v2 = new Point3d(b.x - x, b.y - y, b.z - z); + double cosa = ((v1.x * v2.x + v1.y * v2.y + v1.z * v2.z) + / (v1.vectorNorm() * v2.vectorNorm())); + if (cosa > 1.0) { + return 0; + } else if (cosa < -1.0) { + return Math.PI; + } + return Math.acos(cosa); + } + + /** + * Calculate angle a-x-b + * + * @param a Point3fInterface + * @param x Point3fInterface + * @param b Point3fInterface + * @return float + */ + public static double angleBetween(Point3d a, Point3d x, Point3d b) { + double v1_x = a.getX() - x.getX(); + double v1_y = a.getY() - x.getY(); + double v1_z = a.getZ() - x.getZ(); + + double v2_x = b.getX() - x.getX(); + double v2_y = b.getY() - x.getY(); + double v2_z = b.getZ() - x.getZ(); + + double v1_norm = Math.sqrt(v1_x * v1_x + v1_y * v1_y + v1_z * v1_z); + double v2_norm = Math.sqrt(v2_x * v2_x + v2_y * v2_y + v2_z * v2_z); + + double cosa = ((v1_x * v2_x + v1_y * v2_y + v1_z * v2_z) + / (v1_norm * v2_norm)); + + if (cosa > 1.0) { + return 0; + } else if (cosa < -1.0) { + return Math.PI; + } + return Math.acos(cosa); + } + + public static void translatePoint(Point3d p, double dir[], double increment) { + p.setX(p.getX() + dir[0] * increment); + p.setY(p.getY() + dir[1] * increment); + p.setZ(p.getZ() + dir[2] * increment); + } + + /** + * !!! Check out that it works properly!!! + * + * @param p1 Point3f + * @param p2 Point3f + * @return float + */ + public double distanceToLine(Point3d p1, Point3d p2) { + Point3d p21 = new Point3d(p1, p2); + double d = p21.vectorNorm(); + if (d < 0.00001f) { + return 0; // Line is not determined + } + Point3d p10 = new Point3d(this, p1); + Point3d cross = p21.crossProduct(p10); + return cross.vectorNorm() / d; + } + + public static double dihedralAngleInDegrees(Point3d v1, Point3d v2, Point3d v3, Point3d v4) { + return RADIANS_TO_DEGREES * dihedralAngle(v1, v2, v3, v4); + } + + public static double dihedralAngle(Point3d v1, Point3d v2, Point3d v3, Point3d v4) { + //vPoint3f r1, r2, n1, n2, n3; + double cosang, sinang; + //r1 = v1 - v2; + Point3d r1 = new Point3d(v2, v1); + //r2 = v3 - v2; + Point3d r2 = new Point3d(v2, v3); + //n1 = (r2 ^ r1).normalize(); + Point3d n1 = r2.crossProduct(r1); + n1.normalize(); + //n3 = (n1 ^ r2).normalize(); + Point3d n3 = n1.crossProduct(r2); + n3.normalize(); + //r1 = v2 - v3; + r1.x = v2.getX() - v3.getX(); + r1.y = v2.getY() - v3.getY(); + r1.z = v2.getZ() - v3.getZ(); + + //r2 = v4 - v3; + r2.x = v4.getX() - v3.getX(); + r2.y = v4.getY() - v3.getY(); + r2.z = v4.getZ() - v3.getZ(); + + //n2 = (r2 ^ r1).normalize(); + Point3d n2 = r2.crossProduct(r1); + n2.normalize(); + + //cosang = n1 * n2; + cosang = n1.product(n2); + + //sinang = n2 * n3; + sinang = n2.product(n3); + + if (cosang < -1.0f) { + cosang = -1.0f; + } else if (cosang > 1.0f) { + cosang = 1.0f; + } + + if (sinang >= 0) { + return -Math.acos(cosang); + } else { + return Math.acos(cosang); + } + } + + /** + * + * @param point + * @param angle + */ + static public void rotateAroundX(Point3d point, double angle) { + double newY = point.getY() * Math.cos(angle) + point.getZ() * Math.sin(angle); + double newZ = -point.getY() * Math.sin(angle) + point.getZ() * Math.cos(angle); + point.setY(newY); + point.setZ(newZ); + } + + /** + * + * @param point + * @param angle + */ + static public void rotateAroundXinDegrees(Point3d point, double angle) { + angle = angle * DEGREES_TO_RADIANS; + double newY = point.getY() * Math.cos(angle) + point.getZ() * Math.sin(angle); + double newZ = -point.getY() * Math.sin(angle) + point.getZ() * Math.cos(angle); + point.setY(newY); + point.setZ(newZ); + } + + /** + * + * @param point + * @param angle + */ + static public void rotateAroundX(Point3fInterface point, double angle) { + double newY = point.getY() * Math.cos(angle) + point.getZ() * Math.sin(angle); + double newZ = -point.getY() * Math.sin(angle) + point.getZ() * Math.cos(angle); + point.setY(newY); + point.setZ(newZ); + } + + /** + * + * @param point + * @param angle + */ + static public void rotateAroundY(Point3d point, double angle) { + double newX = point.getX() * Math.cos(angle) + point.getZ() * Math.sin(angle); + double newZ = -point.getX() * Math.sin(angle) + point.getZ() * Math.cos(angle); + point.setX(newX); + point.setZ(newZ); + } + + /** + * + * @param point + * @param angle + */ + static public void rotateAroundYinDegrees(Point3d point, double angle) { + angle = angle * DEGREES_TO_RADIANS; + double newX = point.getX() * Math.cos(angle) + point.getZ() * Math.sin(angle); + double newZ = -point.getX() * Math.sin(angle) + point.getZ() * Math.cos(angle); + point.setX(newX); + point.setZ(newZ); + } + + /** + * + * @param point + * @param angle + */ + static public void rotateAroundY(Point3fInterface point, double angle) { + double newX = point.getX() * Math.cos(angle) + point.getZ() * Math.sin(angle); + double newZ = -point.getX() * Math.sin(angle) + point.getZ() * Math.cos(angle); + point.setX(newX); + point.setZ(newZ); + } + + /** + * + * @param point + * @param angle + */ + static public void rotateAroundZ(Point3d point, double angle) { + double newX = point.getX() * Math.cos(angle) - point.getY() * Math.sin(angle); + double newY = point.getX() * Math.sin(angle) + point.getY() * Math.cos(angle); + point.setX(newX); + point.setY(newY); + } + + /** + * + * @param point + * @param angle + */ + static public void rotateAroundZ(Point3fInterface point, double angle) { + double newX = point.getX() * Math.cos(angle) - point.getY() * Math.sin(angle); + double newY = point.getX() * Math.sin(angle) + point.getY() * Math.cos(angle); + point.setX(newX); + point.setY(newY); + } + + /** + * + * @param point + * @param angle + */ + static public void rotateAroundZinDegrees(Point3d point, double angle) { + angle = angle * DEGREES_TO_RADIANS; + double newX = point.getX() * Math.cos(angle) - point.getY() * Math.sin(angle); + double newY = point.getX() * Math.sin(angle) + point.getY() * Math.cos(angle); + point.setX(newX); + point.setY(newY); + } + + public String toString() { + return "(" + x + ", " + y + ", " + z + ") d=" + norm; + } + + public static void main(String[] args) { + Point3d p1 = new Point3d(1f, 2f, 3f); + Point3d p2 = new Point3d(0, 0, 0); + Point3d p3 = new Point3d(2, 2, 2); + p2 = p1; + p1 = p3; + System.out.println("p1: " + p1.toString() + " p2: " + p2.toString() + " p3: " + p3.toString()); + } +} diff --git a/src/main/java/cct/vecmath/Point3f.java b/src/main/java/cct/vecmath/Point3f.java new file mode 100644 index 0000000..5b5cf93 --- /dev/null +++ b/src/main/java/cct/vecmath/Point3f.java @@ -0,0 +1,660 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.vecmath; + +import cct.interfaces.Point3fInterface; + +/** + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2004

+ * + *

+ * Company:

+ * + * @author not attributable + * @version 1.0 + */ +public class Point3f + implements Point3fInterface { + + public static final double RADIANS_TO_DEGREES = 180.0 / Math.PI; + public static final double DEGREES_TO_RADIANS = Math.PI / 180.0; + public static final float PI_FLOAT = (float) Math.PI; + public float x, y, z; + + // Constructors + public Point3f() { + x = y = z = 0.0f; + } + + public Point3f(float xx, float yy, float zz) { + x = xx; + y = yy; + z = zz; + } + + @Override + public Point3fInterface getInstance(float xx, float yy, float zz) { + return new Point3f(xx, yy, zz); + } + + public Point3f(Point3f p) { + x = p.x; + y = p.y; + z = p.z; + } + + public Point3f(Point3fInterface p) { + x = p.getX(); + y = p.getY(); + z = p.getZ(); + } + + /** + * Substracts vector a2 from vector a1 + * + * @param a1 Point3fInterface + * @param a2 Point3fInterface + */ + @Override + public void subtract(Point3fInterface a1, Point3fInterface a2) { + x = a1.getX() - a2.getX(); + y = a1.getY() - a2.getY(); + z = a1.getZ() - a2.getZ(); + } + + /** + * Vector b - a + * + * @param a Point3f + * @param b Point3f + */ + public Point3f(Point3f a, Point3f b) { + x = b.x - a.x; + y = b.y - a.y; + z = b.z - a.z; + } + + /** + * Vector b - a + * + * @param a Point3f + * @param b Point3f + */ + public Point3f(Point3fInterface a, Point3fInterface b) { + x = b.getX() - a.getX(); + y = b.getY() - a.getY(); + z = b.getZ() - a.getZ(); + } + + @Override + public Point3fInterface getInstance() { + return new Point3f(); + } + + @Override + public Point3fInterface getInstance(Point3fInterface a) { + return new Point3f(a); + } + +// Methods + /** + * Distance between two points + * + * @param p1 + * @param p2 + * @return + */ + public static double distance(Point3fInterface p1, Point3fInterface p2) { + return Math.sqrt(((p1.getX() - p2.getX()) + * (p1.getX() - p2.getX()) + + (p1.getY() - p2.getY()) + * (p1.getY() - p2.getY()) + + (p1.getZ() - p2.getZ()) + * (p1.getZ() - p2.getZ()))); + } + + public static double distance(float[] p1, float[] p2) { + return Math.sqrt( + (p1[0] - p2[0]) * (p1[0] - p2[0]) + + (p1[1] - p2[1]) * (p1[1] - p2[1]) + + (p1[2] - p2[2]) * (p1[2] - p2[2])); + } + + public static double distance(Float[] p1, Float[] p2) { + return Math.sqrt( + (p1[0] - p2[0]) * (p1[0] - p2[0]) + + (p1[1] - p2[1]) * (p1[1] - p2[1]) + + (p1[2] - p2[2]) * (p1[2] - p2[2])); + } + + public static double distance(double[] p1, double[] p2) { + return Math.sqrt( + (p1[0] - p2[0]) * (p1[0] - p2[0]) + + (p1[1] - p2[1]) * (p1[1] - p2[1]) + + (p1[2] - p2[2]) * (p1[2] - p2[2])); + } + + public static double distance(Double[] p1, Double[] p2) { + return Math.sqrt( + (p1[0] - p2[0]) * (p1[0] - p2[0]) + + (p1[1] - p2[1]) * (p1[1] - p2[1]) + + (p1[2] - p2[2]) * (p1[2] - p2[2])); + } + + public static double distance(Number[] p1, Number[] p2) { + return Math.sqrt( + (p1[0].doubleValue() - p2[0].doubleValue()) * (p1[0].doubleValue() - p2[0].doubleValue()) + + (p1[1].doubleValue() - p2[1].doubleValue()) * (p1[1].doubleValue() - p2[1].doubleValue()) + + (p1[2].doubleValue() - p2[2].doubleValue()) * (p1[2].doubleValue() - p2[2].doubleValue())); + } + + public static double distanceSquared(Point3fInterface p1, Point3fInterface p2) { + return ((p1.getX() - p2.getX()) + * (p1.getX() - p2.getX()) + + (p1.getY() - p2.getY()) + * (p1.getY() - p2.getY()) + + (p1.getZ() - p2.getZ()) + * (p1.getZ() - p2.getZ())); + } + + @Override + public double distanceTo(Point3fInterface point) { + return Math.sqrt(((x - point.getX()) * (x - point.getX()) + + (y - point.getY()) * (y - point.getY()) + + (z - point.getZ()) * (z - point.getZ()))); + } + + public double distanceTo(float _x, float _y, float _z) { + return Math.sqrt(((x - _x) * (x - _x) + + (y - _y) * (y - _y) + + (z - _z) * (z - _z))); + } + + public double distanceTo(double _x, double _y, double _z) { + return Math.sqrt(((x - _x) * (x - _x) + + (y - _y) * (y - _y) + + (z - _z) * (z - _z))); + } + + public void add(Point3f p) { + x += p.x; + y += p.y; + z += p.z; + } + + public void add(Point3fInterface p) { + x += p.getX(); + y += p.getY(); + z += p.getZ(); + } + + public void add(float px, float py, float pz) { + x += px; + y += py; + z += pz; + } + + @Override + public float getX() { + return x; + } + + @Override + public float getY() { + return y; + } + + @Override + public float getZ() { + return z; + } + + public Point3f getXYZ() { + Point3f temp = new Point3f(this); + return temp; + } + + public void multiply(double number) { + x *= number; + y *= number; + z *= number; + } + + public void multiply(float number) { + x *= number; + y *= number; + z *= number; + } + + /** + * Normalizes vector + */ + public void normalize() { + float s = this.vectorNorm(); + if (s != 0.0) { + x /= s; + y /= s; + z /= s; + } + } + + public static void normalize(Point3fInterface v) { + float s = (float) Point3f.norm(v); + if (s != 0.0) { + v.setXYZ(v.getX() / s, v.getY() / s, v.getZ() / s); + } + } + + public Point3f crossProduct(Point3f v) { + return new Point3f(y * v.z - z * v.y, z * v.x - x * v.z, + x * v.y - y * v.x); + } + + public Point3fInterface crossProduct(Point3fInterface v) { + return v.getInstance(y * v.getZ() - z * v.getY(), + z * v.getX() - x * v.getZ(), + x * v.getY() - y * v.getX()); + } + + /** + * Calculate cross vector for vectors v1 and v2 and put result into the crossVector No any memory allocation in the + * subroutine + * + * @param v1 Point3fInterface + * @param v2 Point3fInterface + * @param crossVector Point3fInterface + * @return Point3fInterface - cross product vector + */ + public static Point3fInterface crossProduct(Point3fInterface v1, + Point3fInterface v2, + Point3fInterface crossVector) { + crossVector.setX(v1.getY() * v2.getZ() - v1.getZ() * v2.getY()); + crossVector.setY(v1.getZ() * v2.getX() - v1.getX() * v2.getZ()); + crossVector.setZ(v1.getX() * v2.getY() - v1.getY() * v2.getX()); + return crossVector; + } + + /* + * inline void VectorProduct(real *x, real *y, real *p) { p[0] = x[1]*y[2] - x[2]*y[1]; p[1] = x[2]*y[0] - x[0]*y[2]; p[2] = + * x[0]*y[1] - x[1]*y[0]; + * + */ + public void crossProduct(Point3fInterface v1, Point3fInterface v2) { + x = v1.getY() * v2.getZ() - v1.getZ() * v2.getY(); + y = v1.getZ() * v2.getX() - v1.getX() * v2.getZ(); + z = v1.getX() * v2.getY() - v1.getY() * v2.getX(); + } + + public float product(Point3f v) { + return x * v.x + y * v.y + z * v.z; + } + + public float product(Point3fInterface v) { + return x * v.getX() + y * v.getY() + z * v.getZ(); + } + + static public float product(Point3fInterface a, Point3fInterface b) { + return a.getX() * b.getX() + a.getY() * b.getY() + a.getZ() * b.getZ(); + } + + public float vectorNorm() { + return (float) Math.sqrt((x * x + y * y + z * z)); + } + + public float norm() { + return (float) Math.sqrt((x * x + y * y + z * z)); + } + + public static double vectorNorm(float vec[]) { + return Math.sqrt((vec[0] * vec[0] + vec[1] * vec[1] + + vec[2] * vec[2])); + } + + public static double norm(float vec[]) { + return Math.sqrt((vec[0] * vec[0] + vec[1] * vec[1] + + vec[2] * vec[2])); + } + + public static double norm(Point3fInterface vec) { + return Math.sqrt((vec.getX() * vec.getX() + + vec.getY() * vec.getY() + + vec.getZ() * vec.getZ())); + } + + public static float squaredNorm(Point3fInterface vec) { + return vec.getX() * vec.getX() + + vec.getY() * vec.getY() + + vec.getZ() * vec.getZ(); + } + + public float vectorSquaredNorm() { + return x * x + y * y + z * z; + } + + public float squaredNorm() { + return x * x + y * y + z * z; + } + + @Override + public void setX(double x) { + this.x = (float) x; + } + + @Override + public void setY(double y) { + this.y = (float) y; + } + + @Override + public void setZ(double z) { + this.z = (float) z; + } + + public void setXYZ(float xx, float yy, float zz) { + x = xx; + y = yy; + z = zz; + } + + @Override + public void setXYZ(double xx, double yy, double zz) { + x = (float) xx; + y = (float) yy; + z = (float) zz; + } + + public void setXYZ(Point3f p) { + x = p.x; + y = p.y; + z = p.z; + } + + @Override + public void setXYZ(Point3fInterface xyz) { + x = xyz.getX(); + y = xyz.getY(); + z = xyz.getZ(); + } + + public void substract(Point3f p) { + x -= p.x; + y -= p.y; + z -= p.z; + } + + /** + * Angle between atoms "a"-"current"-"b" + * + * @param a gAtom + * @param b gAtom + * @return float + */ + public float angleBetween(Point3f a, Point3f b) { + Point3f v1 = new Point3f(a.x - x, a.y - y, a.z - z); + Point3f v2 = new Point3f(b.x - x, b.y - y, b.z - z); + double cosa = ((v1.x * v2.x + v1.y * v2.y + v1.z * v2.z) + / (v1.vectorNorm() * v2.vectorNorm())); + if (cosa > 1.0) { + return 0; + } else if (cosa < -1.0) { + return PI_FLOAT; + } + return (float) Math.acos(cosa); + } + + static public double angle(Point3f a, Point3f b, Point3f c) { + Point3f v1 = new Point3f(a.x - b.x, a.y - b.y, a.z - b.z); + Point3f v2 = new Point3f(c.x - b.x, c.y - b.y, c.z - b.z); + double cosa = ((v1.x * v2.x + v1.y * v2.y + v1.z * v2.z) + / (v1.vectorNorm() * v2.vectorNorm())); + if (cosa > 1.0) { + return 0; + } else if (cosa < -1.0) { + return PI_FLOAT; + } + return (float) Math.acos(cosa); + } + + /** + * Calculate angle a-x-b + * + * @param a Point3fInterface + * @param x Point3fInterface + * @param b Point3fInterface + * @return float + */ + public static float angleBetween(Point3fInterface a, Point3fInterface x, + Point3fInterface b) { + float v1_x = a.getX() - x.getX(); + float v1_y = a.getY() - x.getY(); + float v1_z = a.getZ() - x.getZ(); + + float v2_x = b.getX() - x.getX(); + float v2_y = b.getY() - x.getY(); + float v2_z = b.getZ() - x.getZ(); + + double v1_norm = Math.sqrt(v1_x * v1_x + v1_y * v1_y + v1_z * v1_z); + double v2_norm = Math.sqrt(v2_x * v2_x + v2_y * v2_y + v2_z * v2_z); + + double cosa = ((v1_x * v2_x + v1_y * v2_y + v1_z * v2_z) + / (v1_norm * v2_norm)); + + if (cosa > 1.0) { + return 0; + } else if (cosa < -1.0) { + return PI_FLOAT; + } + return (float) Math.acos(cosa); + } + + /** + * Calculates angle between vectors a & b It's the same as angleBetween(Point3fInterface a, Point3fInterface x, + * Point3fInterface b) where x=(0,0,0) + * + * @param a Point3fInterface + * @param b Point3fInterface + * @return float + */ + public static float angleBetween(Point3fInterface a, Point3fInterface b) { + double cosa = ((a.getX() * b.getX() + a.getY() * b.getY() + + a.getZ() * b.getZ()) + / (norm(a) * norm(b))); + if (cosa > 1.0) { + return 0; + } else if (cosa < -1.0) { + return PI_FLOAT; + } + return (float) Math.acos(cosa); + } + + public static void translatePoint(Point3fInterface p, float dir[], + float increment) { + p.setX(p.getX() + dir[0] * increment); + p.setY(p.getY() + dir[1] * increment); + p.setZ(p.getZ() + dir[2] * increment); + } + + /** + * !!! Check out that it works properly!!! + * + * @param p1 Point3f + * @param p2 Point3f + * @return float + */ + public float distanceToLine(Point3f p1, Point3f p2) { + Point3f p21 = new Point3f(p1, p2); + float d = p21.vectorNorm(); + if (d < 0.00001f) { + return 0; // Line is not determined + } + Point3f p10 = new Point3f(this, p1); + Point3f cross = p21.crossProduct(p10); + return cross.vectorNorm() / d; + } + + public static double dihedralAngle(Point3fInterface v1, Point3fInterface v2, + Point3fInterface v3, + Point3fInterface v4) { + //vPoint3f r1, r2, n1, n2, n3; + float cosang, sinang; + //r1 = v1 - v2; + Point3f r1 = new Point3f(v2, v1); + //r2 = v3 - v2; + Point3f r2 = new Point3f(v2, v3); + //n1 = (r2 ^ r1).normalize(); + Point3f n1 = r2.crossProduct(r1); + n1.normalize(); + //n3 = (n1 ^ r2).normalize(); + Point3f n3 = n1.crossProduct(r2); + n3.normalize(); + //r1 = v2 - v3; + r1.x = v2.getX() - v3.getX(); + r1.y = v2.getY() - v3.getY(); + r1.z = v2.getZ() - v3.getZ(); + + //r2 = v4 - v3; + r2.x = v4.getX() - v3.getX(); + r2.y = v4.getY() - v3.getY(); + r2.z = v4.getZ() - v3.getZ(); + + //n2 = (r2 ^ r1).normalize(); + Point3f n2 = r2.crossProduct(r1); + n2.normalize(); + + //cosang = n1 * n2; + cosang = n1.product(n2); + + //sinang = n2 * n3; + sinang = n2.product(n3); + + if (cosang < -1.0f) { + cosang = -1.0f; + } else if (cosang > 1.0f) { + cosang = 1.0f; + } + + if (sinang >= 0) { + return -Math.acos(cosang); + } else { + return Math.acos(cosang); + } + } + + @Override + public String toString() { + return "X= " + x + " Y= " + y + " Z= " + z; + } + + /** + * + * @param point + * @param angle + */ + static public void rotateAroundX(Point3f point, double angle) { + double newY = point.getY() * Math.cos(angle) + point.getZ() * Math.sin(angle); + double newZ = -point.getY() * Math.sin(angle) + point.getZ() * Math.cos(angle); + point.setY(newY); + point.setZ(newZ); + } + + /** + * + * @param point + * @param angle + */ + static public void rotateAroundX(Point3fInterface point, double angle) { + double newY = point.getY() * Math.cos(angle) + point.getZ() * Math.sin(angle); + double newZ = -point.getY() * Math.sin(angle) + point.getZ() * Math.cos(angle); + point.setY(newY); + point.setZ(newZ); + } + + /** + * + * @param point + * @param angle + */ + static public void rotateAroundY(Point3f point, double angle) { + double newX = point.getX() * Math.cos(angle) + point.getZ() * Math.sin(angle); + double newZ = -point.getX() * Math.sin(angle) + point.getZ() * Math.cos(angle); + point.setX(newX); + point.setZ(newZ); + } + + /** + * + * @param point + * @param angle + */ + static public void rotateAroundY(Point3fInterface point, double angle) { + double newX = point.getX() * Math.cos(angle) + point.getZ() * Math.sin(angle); + double newZ = -point.getX() * Math.sin(angle) + point.getZ() * Math.cos(angle); + point.setX(newX); + point.setZ(newZ); + } + + /** + * + * @param point + * @param angle + */ + static public void rotateAroundZ(Point3f point, double angle) { + double newX = point.getX() * Math.cos(angle) - point.getY() * Math.sin(angle); + double newY = point.getX() * Math.sin(angle) + point.getY() * Math.cos(angle); + point.setX(newX); + point.setY(newY); + } + + /** + * + * @param point + * @param angle + */ + static public void rotateAroundZ(Point3fInterface point, double angle) { + double newX = point.getX() * Math.cos(angle) - point.getY() * Math.sin(angle); + double newY = point.getX() * Math.sin(angle) + point.getY() * Math.cos(angle); + point.setX(newX); + point.setY(newY); + } +} diff --git a/src/main/java/cct/vecmath/Segment3f.java b/src/main/java/cct/vecmath/Segment3f.java new file mode 100644 index 0000000..288c105 --- /dev/null +++ b/src/main/java/cct/vecmath/Segment3f.java @@ -0,0 +1,65 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ + +package cct.vecmath; + +/** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class Segment3f { + public Point3f p1; + public Point3f p2; + + public Segment3f() { + p1 = new Point3f(); + p2 = new Point3f(1, 0, 0); + } + + public Segment3f(Point3f _p1, Point3f _p2) { + p1 = new Point3f(_p1); + p2 = new Point3f(_p2); + } +} diff --git a/src/main/java/cct/vecmath/VecmathTools.java b/src/main/java/cct/vecmath/VecmathTools.java new file mode 100644 index 0000000..d8f73fe --- /dev/null +++ b/src/main/java/cct/vecmath/VecmathTools.java @@ -0,0 +1,226 @@ +/* ***** BEGIN LICENSE BLOCK ***** + Version: Apache 2.0/GPL 3.0/LGPL 3.0 + + CCT - Computational Chemistry Tools + Jamberoo - Java Molecules Editor + + Copyright 2008-2015 Dr. Vladislav Vasilyev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Contributor(s): + Dr. Vladislav Vasilyev (original author) + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the "GPL"), or + the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + in which case the provisions of the GPL or the LGPL are applicable instead + of those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the Apache 2.0, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the Apache 2.0, the GPL or the LGPL. + + ***** END LICENSE BLOCK *****/ +package cct.vecmath; + +import static cct.Constants.DEGREES_TO_RADIANS; +import cct.interfaces.Point3fInterface; +import static cct.vecmath.Point3f.RADIANS_TO_DEGREES; +import java.util.logging.Logger; + +/** + *

+ * Title:

+ * + *

+ * Description:

+ * + *

+ * Copyright: Copyright (c) 2006

+ * + *

+ * Company: ANU

+ * + * @author Dr. V. Vasilyev + * @version 1.0 + */ +public class VecmathTools { + + static final String ZERO_DISTANCE = "Zero distance between atoms"; + static final String UNDERFINED_ANGLE = "Angle is 0 or 180"; + private static final Logger LOG = Logger.getLogger(VecmathTools.class.getName()); + + private VecmathTools() { + } + + /** + * Returns element of the vector (signed) with the largest absolute value + * + * @param x float[] + * @return float + */ + public static float getMaxAbsValue(float x[]) { + float s = 0; + if (x == null || x.length < 1) { + return s; + } + s = x[0]; + for (int i = 1; i < x.length; i++) { + if (Math.abs(s) < Math.abs(x[i])) { + s = x[i]; + } + } + return s; + } + + /** + * Calculates root-mean-square of the vector + * + * @param x float[] + * @return double + */ + public static double getRMS(float x[]) { + double s = 0; + if (x == null || x.length < 1) { + return s; + } + for (int i = 0; i < x.length; i++) { + s += x[i] * x[i]; + } + return Math.sqrt(s / x.length); + } + + public static void fromInternalToCartesiansInDegrees(Point3f atom, double bond, double angle, double torsion, Point3f na, Point3f nb, + Point3f nc) { + fromInternalToCartesians(atom, bond, DEGREES_TO_RADIANS * angle, DEGREES_TO_RADIANS * torsion, na, nb, nc); + } + + public static void fromInternalToCartesians(Point3f atom, double bond, double angle, double torsion, Point3f na, Point3f nb, + Point3f nc) { + if (na == null) { + // --- The first atom. Put it into the origin + atom.setXYZ(0, 0, 0); + return; + } else if (nb == null) { + // --- the second atom: put it along the X-axis + atom.setXYZ(bond, 0, 0); // So, we put it along X-axis + return; + } else if (nc == null) { + // --- Third atom (put it into the XOY plane + atom.setXYZ(bond * Math.cos(angle), bond * Math.sin(angle), 0); // + return; + } + + double SIN2, COS2, SIN3, COS3, + VT[] = new double[3], V1[] = new double[3], + V2[] = new double[3]; + double R2, + V3[] = new double[3], VA1, VB1, VC1, R3, V[] = new double[3]; + + SIN2 = Math.sin(angle); + COS2 = Math.cos(angle); + SIN3 = Math.sin(torsion); + COS3 = Math.cos(torsion); + + VT[0] = bond * COS2; + VT[1] = bond * SIN2 * SIN3; + VT[2] = bond * SIN2 * COS3; + + V1[0] = nc.getX() - nb.getX(); + V1[1] = nc.getY() - nb.getY(); + V1[2] = nc.getZ() - nb.getZ(); + + V2[0] = nb.getX() - na.getX(); + V2[1] = nb.getY() - na.getY(); + V2[2] = nb.getZ() - na.getZ(); + + R2 = Math.sqrt(V2[0] * V2[0] + V2[1] * V2[1] + V2[2] * V2[2]); + + V3[0] = V1[1] * V2[2] - V1[2] * V2[1]; + V3[1] = V1[2] * V2[0] - V1[0] * V2[2]; + V3[2] = V1[0] * V2[1] - V1[1] * V2[0]; + + R3 = Math.sqrt(V3[0] * V3[0] + V3[1] * V3[1] + V3[2] * V3[2]); + + V2[0] = V2[0] / R2; + V2[1] = V2[1] / R2; + V2[2] = V2[2] / R2; + + V3[0] = V3[0] / R3; + V3[1] = V3[1] / R3; + V3[2] = V3[2] / R3; + + V[0] = V2[1] * V3[2] - V2[2] * V3[1]; + V[1] = V2[2] * V3[0] - V2[0] * V3[2]; + V[2] = V2[0] * V3[1] - V2[1] * V3[0]; + + VA1 = V2[0] * VT[0] + V3[0] * VT[1] + V[0] * VT[2]; + VB1 = V2[1] * VT[0] + V3[1] * VT[1] + V[1] * VT[2]; + VC1 = V2[2] * VT[0] + V3[2] * VT[1] + V[2] * VT[2]; + + atom.setXYZ(na.getX() + (float) VA1, na.getY() + (float) VB1, na.getZ() + (float) VC1); + } + + public static double[] makeInternalCoordInDegrees(Point3d atom, Point3d na, Point3d nb, Point3d nc) throws Exception { + double[] internal = makeInternalCoord(atom, na, nb, nc); + internal[1] *= RADIANS_TO_DEGREES; + internal[2] *= RADIANS_TO_DEGREES; + return internal; + } + + public static double[] makeInternalCoord(Point3d atom, Point3d na, Point3d nb, Point3d nc) throws Exception { + double[] internal = new double[3]; + makeInternalCoord(atom, na, nb, nc, internal); + return internal; + } + + public static void makeInternalCoordInDegrees(Point3d atom, Point3d na, Point3d nb, Point3d nc, double[] internal) throws Exception { + makeInternalCoord(atom, na, nb, nc, internal); + internal[1] *= RADIANS_TO_DEGREES; + internal[2] *= RADIANS_TO_DEGREES; + } + + public static void makeInternalCoord(Point3d atom, Point3d na, Point3d nb, Point3d nc, double[] internal) throws Exception { + + internal[0] = atom.distanceTo(na); + if (internal[0] == 0) { + LOG.severe(ZERO_DISTANCE); + throw new Exception(ZERO_DISTANCE); + } + internal[1] = Point3d.angleBetween(atom, na, nb); + if (internal[1] == 0 || internal[1] == Math.PI) { + LOG.severe(UNDERFINED_ANGLE + ": " + internal[1]); + throw new Exception(UNDERFINED_ANGLE + ": " + internal[1]); + } + internal[2] = Point3d.dihedralAngle(atom, na, nb, nc); + } + + public static void makeInternalCoord(Point3fInterface atom, Point3fInterface na, Point3fInterface nb, Point3fInterface nc, double[] internal) throws Exception { + + internal[0] = atom.distanceTo(na); + if (internal[0] == 0) { + LOG.severe(ZERO_DISTANCE); + throw new Exception(ZERO_DISTANCE); + } + internal[1] = Point3f.angleBetween(atom, na, nb); + if (internal[1] == 0 || internal[1] == Math.PI) { + LOG.severe(UNDERFINED_ANGLE + ": " + internal[1]); + throw new Exception(UNDERFINED_ANGLE + ": " + internal[1]); + } + internal[2] = Point3f.dihedralAngle(atom, na, nb, nc); + } + +} diff --git a/src/main/java/cct/vecmath/Vector3d.java b/src/main/java/cct/vecmath/Vector3d.java new file mode 100644 index 0000000..068a5b9 --- /dev/null +++ b/src/main/java/cct/vecmath/Vector3d.java @@ -0,0 +1,89 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package cct.vecmath; + +/** + * + * @author vvv900 + */ +public class Vector3d { + + private double[] origin = new double[]{0, 0, 0}; + private double[] dir = new double[]{0, 0, 1.0}; + + public Vector3d() { + } + + public Vector3d(double[] p1, double[] p2) { + origin[0] = p1[0]; + origin[1] = p1[1]; + origin[2] = p1[2]; + dir[0] = p2[0] - p1[0]; + dir[1] = p2[1] - p1[1]; + dir[2] = p2[2] - p1[2]; + } + + public Vector3d(Point3f p1, Point3f p2) { + origin[0] = p1.x; + origin[1] = p1.y; + origin[2] = p1.z; + dir[0] = p2.x - p1.x; + dir[1] = p2.y - p1.y; + dir[2] = p2.z - p1.z; + } + + public Vector3d(Point3d p1, Point3d p2) { + origin[0] = p1.getX(); + origin[1] = p1.getY(); + origin[2] = p1.getZ(); + dir[0] = p2.getX() - p1.getX(); + dir[1] = p2.getY() - p1.getY(); + dir[2] = p2.getZ() - p1.getZ(); + } + + public void setDir(double xNewValue, double yNewValue, double zNewValue) { + dir[0] = xNewValue; + dir[1] = yNewValue; + dir[2] = zNewValue; + } + + public void setDirX(double newValue) { + dir[0] = newValue; + } + + public void setDirY(double newValue) { + dir[1] = newValue; + } + + public void setDirZ(double newValue) { + dir[2] = newValue; + } + + public double[] getDirection() { + return dir; + } + + public double getDirX() { + return dir[0]; + } + + public double getDirY() { + return dir[1]; + } + + public double getDirZ() { + return dir[2]; + } + + public Vector3d crossProduct(Vector3d v) { + Vector3d cross = new Vector3d(); + cross.setDir( + dir[1] * v.getDirZ() - dir[2] * v.getDirY(), + dir[2] * v.getDirX() - dir[0] * v.getDirZ(), + dir[0] * v.getDirY() - dir[1] * v.getDirX()); + return cross; + } +} diff --git a/src/main/java/g03input/BasisSetListeners.java b/src/main/java/g03input/BasisSetListeners.java new file mode 100644 index 0000000..0f37f30 --- /dev/null +++ b/src/main/java/g03input/BasisSetListeners.java @@ -0,0 +1,999 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Apr 2, 2005 + * @author Michael Sheetz + * @author Shashank Jeedigunta @author Sandeep Kumar Seethaapathy + * + */ + +package g03input; + +import javax.swing.*; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +public class BasisSetListeners implements ActionListener,ChangeListener{ + + public static JFrame optionsFrame; + public static JLabel polLabel,diffLabel; + public static JTable allDftTable; //JTable for List all DFT functionals + public static JLabel g631Dfn,g631Ffn,g631Pfn,g631Dfn2,placeLabel; + //public static JTextField g631Text1,g631Text2,g631Text3,g631Text4; + public static JSpinner g631Text1,g631Text2,g631Text3,g631Text4; + public static SpinnerNumberModel g631model1,g631model2,g631model3,g631model4; + //public static JTextField g6311Text1,g6311Text2,g6311Text3,g6311Text4; + public static SpinnerNumberModel g6311model1,g6311model2,g6311model3,g6311model4; + public static JSpinner g6311Text1,g6311Text2,g6311Text3,g6311Text4; + + public static JSpinner d95Text1,d95Text2,d95Text3,d95Text4; + public static SpinnerNumberModel d95model1,d95model2,d95model3,d95model4; + + public static JRadioButton g321Pol1,g321Pol2,g321Diff,g631d1,g631d2,d95vPol1,d95vPol2,g6311d1,g6311d2,d95d1,d95d2; + public static JPanel optPanel,okcancelPanel; + public static JRadioButton d95vd1,d95vd2; + public static JButton d95vokBtn,d95vcancelBtn,d95okBtn,d95cancelBtn,g321okBtn,g321cancelBtn,g631okBtn,g631cancelBtn,g6311okBtn,g6311cancelBtn; + + + public static JRadioButton hfsB,lypB,hfbB,pw9B,xalB,p86B,mpwB,plB,g96B,b95B,pbeB,mpbB,mpeB,vwnB,oB,vw5B; + + + public static JButton doneButton,clearButton,exitButton,doneButton1,exitButton1; + public static JPanel buttonPanel; + public static JPanel donePanel; + + + + + public void stateChanged(ChangeEvent ce) { + System.out.println(ce.getSource()); + if(ce.getSource()==g631Text1) + { + System.out.println(g631Text1.toString()); + } + } + + + + public void actionPerformed(ActionEvent e) + { + // Action Listeners for the Frequently used Basis-Set Options + + //6-31G + if(e.getSource()==G03MenuTree.f631gItem) + { + int ch; + ch = JOptionPane.showConfirmDialog(null,"Add Polarization and/Or Diffuse Functions","6-31G Options",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE); + if(ch==0) + { + JFrame.setDefaultLookAndFeelDecorated(true); + JFrame.setDefaultLookAndFeelDecorated(true); + optionsFrame = new JFrame("6-31G Options"); + JFrame.setDefaultLookAndFeelDecorated(true); + g631Dfn = new JLabel("Set(s) of d functions on Heavy Atoms"); + g631Ffn = new JLabel("Set of f functions on Heavy Atoms"); + g631Pfn = new JLabel("Set(s) of p functions on H Atoms"); + g631Dfn2 = new JLabel("Set of d functions on H Atoms"); + polLabel = new JLabel("Polarization Functions"); + diffLabel = new JLabel("Diffuse Functions"); + placeLabel = new JLabel("Place"); + + g631model1 = + new SpinnerNumberModel(0,0,3,1);//initial,min,max,step + g631model2 = + new SpinnerNumberModel(0,0,1,1);//initial,min,max,step + g631model3 = + new SpinnerNumberModel(0,0,3,1);//initial,min,max,step + g631model4 = + new SpinnerNumberModel(0,0,1,1);//initial,min,max,step + + + + g631Text1 = new JSpinner(g631model1); + g631Text2 = new JSpinner(g631model2); + g631Text3 = new JSpinner(g631model3); + g631Text4 = new JSpinner(g631model4); + + g631Text1.addChangeListener(this); + + g631d1 = new JRadioButton("6-31+G"); + g631d2 = new JRadioButton("6-31++G"); + ButtonGroup Bg631 = new ButtonGroup(); + + Bg631.add(g631d1); + Bg631.add(g631d2); + g631okBtn=new JButton("Ok"); + g631cancelBtn=new JButton("Cancel"); + + optPanel = new JPanel(new GridBagLayout()); + + GridBagConstraints c = new GridBagConstraints(); + c.fill = GridBagConstraints.BOTH; + + c.gridx = 0; + c.weightx=1; + c.insets = new Insets(10,20,0,0); + optPanel.add(polLabel,c); + + + c.gridy=1; + c.insets = new Insets(10,150,0,-10); + optPanel.add(placeLabel,c); + + c.gridx=1; + c.insets = new Insets(10,20,0,0); + optPanel.add(g631Text1,c); + + c.gridx=2; + optPanel.add(g631Dfn,c); + + + c.gridy=2;c.gridx=1; + optPanel.add(g631Text2,c); + + + c.gridx=2; + optPanel.add(g631Ffn,c); + + c.gridy=3;c.gridx=1; + optPanel.add(g631Text3,c); + + + c.gridx=2; + optPanel.add(g631Pfn,c); + + + c.gridy=4;c.gridx=1; + optPanel.add(g631Text4,c); + + + c.gridx=2; + optPanel.add(g631Dfn2,c); + + + c.gridy=5;c.gridx=0; + optPanel.add(diffLabel,c); + + + c.gridy=6;c.gridx=1; + optPanel.add(g631d1,c); + c.gridy=7; + optPanel.add(g631d2,c); + + + okcancelPanel=new JPanel(); + okcancelPanel.add(g631okBtn); + okcancelPanel.add(g631cancelBtn); + g631okBtn.addActionListener(this); + g631cancelBtn.addActionListener(this); + + optionsFrame.getContentPane().setLayout(new BorderLayout()); + optionsFrame.getContentPane().add(optPanel,BorderLayout.CENTER); + optionsFrame.getContentPane().add(okcancelPanel,BorderLayout.SOUTH); + optionsFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + + + + optionsFrame.setSize(500,300); + optionsFrame.setLocation(200,250); + optionsFrame.setVisible(true); + optionsFrame.setResizable(true); + //optionsFrame.getContentPane().add(optPanel); + + } + + if(ch==1) + { + InsertNode.deleteChildren("Bas"); + InsertNode.insertNode("Bas", "6-31G"); + writeBasis("6-31G"); + } + + } + + // 6-31 G OK Btn ---- Doubt + if(e.getSource()== BasisSetListeners.g631okBtn) + { InsertNode.deleteChildren("Bas"); + String g631String1=""; + String g631String2=""; + + + if(!(g631model1.getNumber().intValue()==0 && g631model2.getNumber().intValue()==0 )) + { + g631String2="("; + g631String2+=returnPol(g631model1.getNumber().intValue(),g631model2.getNumber().intValue(),0); + //g631String2+=","; + g631String2+=returnPol(g631model3.getNumber().intValue(),g631model4.getNumber().intValue(),1); + g631String2+=")"; + } + System.out.println(g631String2); + + //g631model1 + if(g631d1.isSelected()) + { + InsertNode.insertNode("Bas", g631d1.getText()); + g631String1=g631d1.getText(); + } + else if(g631d2.isSelected()) + { + InsertNode.insertNode("Bas", g631d2.getText()); + g631String1=g631d2.getText(); + } + else if((!(g631d1.isSelected()))&& + (!(g631d2.isSelected()))) + { + InsertNode.insertNode("Bas", "6-31G"); + g631String1="6-31G"; + } + optionsFrame.dispose(); + writeBasis(g631String1+g631String2); + } + + // 6-31 G Cancel Btn + if(e.getSource()== BasisSetListeners.g631cancelBtn) + { + InsertNode.deleteChildren("Bas"); + InsertNode.insertNode("Bas", "6-31G"); + writeBasis("6-31G"); + optionsFrame.dispose(); + } + + // 6-311G Item + if(e.getSource()==G03MenuTree.f6311gItem) + { + int ch; + ch = JOptionPane.showConfirmDialog(null,"Add Polarization and/Or Diffuse Functions","6-311G Options",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE); + if(ch==0) + { + JFrame.setDefaultLookAndFeelDecorated(true); + JFrame.setDefaultLookAndFeelDecorated(true); + optionsFrame = new JFrame("6-311G Options"); + JFrame.setDefaultLookAndFeelDecorated(true); + ButtonGroup g6311bg1=new ButtonGroup(); + + g631Dfn = new JLabel("Set(s) of d functions on Heavy Atoms"); + g631Ffn = new JLabel("Set of f functions on Heavy Atoms"); + g631Pfn = new JLabel("Set(s) of p functions on H Atoms"); + g631Dfn2 = new JLabel("Set of d functions on H Atoms"); + polLabel = new JLabel("Polarization Functions"); + diffLabel = new JLabel("Diffuse Functions"); + placeLabel = new JLabel("Place"); + g6311model1 = + new SpinnerNumberModel(0,0,3,1);//initial,min,max,step + g6311model2 = + new SpinnerNumberModel(0,0,1,1);//initial,min,max,step + g6311model3 = + new SpinnerNumberModel(0,0,3,1);//initial,min,max,step + g6311model4 = + new SpinnerNumberModel(0,0,1,1);//initial,min,max,step + + + + g6311Text1 = new JSpinner(g6311model1); + g6311Text2 = new JSpinner(g6311model2); + g6311Text3 = new JSpinner(g6311model3); + g6311Text4 = new JSpinner(g6311model4); + + g6311d1 = new JRadioButton("6-311+G"); + g6311d2 = new JRadioButton("6-311++G"); + + g6311bg1.add(g6311d1); + g6311bg1.add(g6311d2); + + g6311okBtn=new JButton("Ok"); + g6311cancelBtn=new JButton("Cancel"); + + optPanel = new JPanel(new GridBagLayout()); + + GridBagConstraints c = new GridBagConstraints(); + c.fill = GridBagConstraints.BOTH; + + c.gridx = 0; + c.weightx=1; + c.insets = new Insets(10,20,0,0); + optPanel.add(polLabel,c); + + + c.gridy=1; + c.insets = new Insets(10,150,0,-10); + optPanel.add(placeLabel,c); + + c.gridx=1; + c.insets = new Insets(10,20,0,0); + optPanel.add(g6311Text1,c); + + c.gridx=2; + optPanel.add(g631Dfn,c); + + + c.gridy=2;c.gridx=1; + optPanel.add(g6311Text2,c); + + + c.gridx=2; + optPanel.add(g631Ffn,c); + + c.gridy=3;c.gridx=1; + optPanel.add(g6311Text3,c); + + + c.gridx=2; + optPanel.add(g631Pfn,c); + + + c.gridy=4;c.gridx=1; + optPanel.add(g6311Text4,c); + + + c.gridx=2; + optPanel.add(g631Dfn2,c); + + + c.gridy=5;c.gridx=0; + optPanel.add(diffLabel,c); + + + c.gridy=6;c.gridx=1; + optPanel.add(g6311d1,c); + c.gridy=7; + optPanel.add(g6311d2,c); + + + okcancelPanel=new JPanel(); + okcancelPanel.add(g6311okBtn); + okcancelPanel.add(g6311cancelBtn); + + g6311okBtn.addActionListener(this); + g6311cancelBtn.addActionListener(this); + + optionsFrame.getContentPane().setLayout(new BorderLayout()); + optionsFrame.getContentPane().add(optPanel,BorderLayout.CENTER); + optionsFrame.getContentPane().add(okcancelPanel,BorderLayout.SOUTH); + optionsFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + + + + optionsFrame.setSize(520,310); + optionsFrame.setLocation(200,250); + optionsFrame.setVisible(true); + optionsFrame.setResizable(true); + //optionsFrame.getContentPane().add(optPanel); + + } + if(ch==1) + { + InsertNode.deleteChildren("Bas"); + InsertNode.insertNode("Bas", "6-311G"); + writeBasis("6-311G"); + } + } + + // 6-311G OK + if(e.getSource()== BasisSetListeners.g6311okBtn) + { + InsertNode.deleteChildren("Bas"); + + String g6311String1=""; + String g6311String2=""; + + + if(!(g6311model1.getNumber().intValue()==0 && g6311model2.getNumber().intValue()==0)) + { + g6311String2="("; + g6311String2+=returnPol(g6311model1.getNumber().intValue(),g6311model2.getNumber().intValue(),0); + //g6311String2+=","; + g6311String2+=returnPol(g6311model3.getNumber().intValue(),g6311model4.getNumber().intValue(),1); + g6311String2+=")"; + } + System.out.println(g6311String2); + if(g6311d1.isSelected()) + { + InsertNode.insertNode("Bas", g6311d1.getText()); + g6311String1=g6311d1.getText(); + + } + else if(g6311d2.isSelected()) + { + InsertNode.insertNode("Bas", g6311d2.getText()); + g6311String1=g6311d2.getText(); + } + else if((!(g6311d1.isSelected()))&& + (!(g6311d2.isSelected()))) + { + InsertNode.insertNode("Bas", "6-311G"); + g6311String1="6-311G"; + } + optionsFrame.dispose(); + writeBasis(g6311String1+g6311String2); + } + + // 6-311G CAncel + if(e.getSource()== BasisSetListeners.g6311cancelBtn) + { // same as NO + InsertNode.deleteChildren("Bas"); + InsertNode.insertNode("Bas", "6-311G"); + writeBasis("6-311G"); + optionsFrame.dispose(); + } + + + // 3-21G OK + if(e.getSource()==g321okBtn) + { + InsertNode.deleteChildren("Bas"); + if(g321Pol1.isSelected()) + { InsertNode.insertNode("Ba", g321Pol1.getText()); + } + if(g321Pol2.isSelected()) + { InsertNode.insertNode("Ba", g321Pol2.getText()); + } + if(g321Diff.isSelected()) + { InsertNode.insertNode("Ba", g321Diff.getText()); + } + if(!(g321Diff.isSelected())&& (!(g321Pol2.isSelected())) + && (!(g321Pol1.isSelected())) + ) + { + // none selected .. just add 3-21G + InsertNode.insertNode("Ba", "3-21G"); + + } + + optionsFrame.dispose(); + + } + + // 3-21 G + + if(e.getSource()==G03MenuTree.f321Menu) + { + int ch; + ch = JOptionPane.showConfirmDialog(null,"Add Polarization and/Or Diffuse Functions","3-21G Options",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE); + if(ch==0) + { + ButtonGroup group321 = new ButtonGroup(); + JFrame.setDefaultLookAndFeelDecorated(true); + optionsFrame = new JFrame("3-21G Options"); + JFrame.setDefaultLookAndFeelDecorated(true); + polLabel = new JLabel("Polarization Functions:"); + diffLabel = new JLabel("Diffuse Functions:"); + g321Pol1 = new JRadioButton("3-21G*"); + g321Pol2 = new JRadioButton("3-21G**(3-21G(d,p))"); + g321Diff = new JRadioButton("3-21+G"); + + group321.add(g321Pol1); + group321.add(g321Pol2); + + optionsFrame.setSize(500,160); + optionsFrame.setLocation(200,250); + optionsFrame.setVisible(true); + optionsFrame.setResizable(true); + optPanel = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.fill = GridBagConstraints.BOTH; + c.gridx=0; + c.weightx=1; + c.weighty=1; + c.insets=new Insets(10,50,10,20); + optPanel.add(polLabel,c); + c.gridx=1; + c.insets = new Insets(10,-100,10,20); + optPanel.add(g321Pol1,c); + //c.insets=new Insets(10,50,10,20); + c.gridy=1;c.gridx=1; + optPanel.add(g321Pol2,c); + c.gridx=0;c.gridy=2; + c.insets=new Insets(10,50,10,20); + optPanel.add(diffLabel,c); + c.gridx=1; + c.insets = new Insets(10,-100,10,20); + optPanel.add(g321Diff,c); + okcancelPanel = new JPanel(); + + g321okBtn = new JButton("OK"); + g321okBtn.addActionListener(this); + g321cancelBtn = new JButton("CANCEL"); + g321cancelBtn.addActionListener(this); + + okcancelPanel.add(g321okBtn); + okcancelPanel.add(g321cancelBtn); + optionsFrame.getContentPane().setLayout(new BorderLayout()); + optionsFrame.getContentPane().add(optPanel,BorderLayout.CENTER); + optionsFrame.getContentPane().add(okcancelPanel,BorderLayout.SOUTH); + optionsFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + } + + if(ch==1) + { InsertNode.deleteChildren("Bas"); + InsertNode.insertNode("Bas", e.getActionCommand()); + } + } + + + + + //3-21G Cancel + if(e.getSource()==g321cancelBtn) + { InsertNode.deleteChildren("Bas"); + InsertNode.insertNode("Ba", "3-21G"); + optionsFrame.dispose(); + } + + + if((e.getSource()==G03MenuTree.fsto3gItem)|| + //(e.getSource()==G03MenuTree.f321MenuItem)|| + (e.getSource()==G03MenuTree.fsto3g1Item)|| + (e.getSource()==G03MenuTree.f621gItem)|| + (e.getSource()==G03MenuTree.f621gdItem)|| + (e.getSource()==G03MenuTree.f431gItem)|| + (e.getSource()==G03MenuTree.f431g1Item)|| + (e.getSource()==G03MenuTree.f431g2Item)|| + (e.getSource()==G03MenuTree.fccpvdItem)|| + (e.getSource()==G03MenuTree.fccpvtItem)|| + (e.getSource()==G03MenuTree.fccpvqItem)|| + (e.getSource()==G03MenuTree.faugccdItem)|| + (e.getSource()==G03MenuTree.faugcctItem)|| + (e.getSource()==G03MenuTree.faugccqItem)|| + (e.getSource()==G03MenuTree.fccpv5Item)|| + (e.getSource()==G03MenuTree.fccpv6Item)|| + (e.getSource()==G03MenuTree.faugcc5Item)|| + (e.getSource()==G03MenuTree.faugcc6Item)|| + (e.getSource()==G03MenuTree.flanl2Item)|| + (e.getSource()==G03MenuTree.f321gItem)|| + (e.getSource()==G03MenuTree.f321g1Item)|| + (e.getSource()==G03MenuTree.f321pgItem)|| + (e.getSource()==G03MenuTree.f321pg1Item)|| + (e.getSource()==G03MenuTree.f321g11Item)|| + (e.getSource()==G03MenuTree.f321pg11Item)) + { + InsertNode.deleteChildren("Bas"); + InsertNode.insertNode("Bas", e.getActionCommand()); + writeBasis(e.getActionCommand()); + } + + + + + /* Action Listeners for the Additional Basis-Set Options */ + + // Petersson et al. Complete Basis Set method basis sets. + // These can have diffuse and polarization functions. + // There appears to be no general method for handling diffuse and + // polarization functions; so these are ignored for now. S. Brozell Nov 2006 + if(e.getSource()==G03MenuTree.acbs631gdaggerItem) + { + InsertNode.deleteChildren("Bas"); + InsertNode.insertNode("Bas", "6-31G(d')"); + writeBasis( "6-31G(d')" ); + } + if(e.getSource()==G03MenuTree.acbs631gdaggerdaggerItem) + { + InsertNode.deleteChildren("Bas"); + InsertNode.insertNode("Bas", "6-31G(d',p')"); + writeBasis( "6-31G(d',p')" ); + } + + + if(e.getSource()==G03MenuTree.ad95Item) + { + int ch; + ch = JOptionPane.showConfirmDialog(null,"Add Polarization and/Or Diffuse Functions","D95 Options",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE); + if(ch==0) + { + JFrame.setDefaultLookAndFeelDecorated(true); + JFrame.setDefaultLookAndFeelDecorated(true); + optionsFrame = new JFrame("D95 Options"); + JFrame.setDefaultLookAndFeelDecorated(true); + g631Dfn = new JLabel("Set(s) of d functions on Heavy Atoms"); + g631Ffn = new JLabel("Set of f functions on Heavy Atoms"); + g631Pfn = new JLabel("Set(s) of p functions on H Atoms"); + g631Dfn2 = new JLabel("Set of d functions on H Atoms"); + polLabel = new JLabel("Polarization Functions"); + diffLabel = new JLabel("Diffuse Functions"); + placeLabel = new JLabel("Place"); + + d95model1 = + new SpinnerNumberModel(0,0,3,1);//initial,min,max,step + d95model2 = + new SpinnerNumberModel(0,0,1,1);//initial,min,max,step + d95model3 = + new SpinnerNumberModel(0,0,3,1);//initial,min,max,step + d95model4 = + new SpinnerNumberModel(0,0,1,1);//initial,min,max,step + + + + d95Text1 = new JSpinner(d95model1); + d95Text2 = new JSpinner(d95model2); + d95Text3 = new JSpinner(d95model3); + d95Text4 = new JSpinner(d95model4); + + + d95d1 = new JRadioButton("D95+"); + d95d2 = new JRadioButton("D95++"); + ButtonGroup Bd95 = new ButtonGroup(); + + Bd95.add(d95d1); + Bd95.add(d95d2); + + d95okBtn=new JButton("Ok"); + d95cancelBtn=new JButton("Cancel"); + + optPanel = new JPanel(new GridBagLayout()); + + GridBagConstraints c = new GridBagConstraints(); + c.fill = GridBagConstraints.BOTH; + + c.gridx = 0; + c.weightx=1; + c.insets = new Insets(10,20,0,0); + optPanel.add(polLabel,c); + + + c.gridy=1; + c.insets = new Insets(10,150,0,-10); + optPanel.add(placeLabel,c); + + c.gridx=1; + c.insets = new Insets(10,20,0,0); + optPanel.add(d95Text1,c); + + c.gridx=2; + optPanel.add(g631Dfn,c); + + + c.gridy=2;c.gridx=1; + optPanel.add(d95Text2,c); + + + c.gridx=2; + optPanel.add(g631Ffn,c); + + c.gridy=3;c.gridx=1; + optPanel.add(d95Text3,c); + + + c.gridx=2; + optPanel.add(g631Pfn,c); + + + c.gridy=4;c.gridx=1; + optPanel.add(d95Text4,c); + + + c.gridx=2; + optPanel.add(g631Dfn2,c); + + + c.gridy=5;c.gridx=0; + optPanel.add(diffLabel,c); + + + c.gridy=6;c.gridx=1; + optPanel.add(d95d1,c); + c.gridy=7; + optPanel.add(d95d2,c); + + + okcancelPanel=new JPanel(); + okcancelPanel.add(d95okBtn); + okcancelPanel.add(d95cancelBtn); + + d95okBtn.addActionListener(this); + d95cancelBtn.addActionListener(this); + optionsFrame.getContentPane().setLayout(new BorderLayout()); + optionsFrame.getContentPane().add(optPanel,BorderLayout.CENTER); + optionsFrame.getContentPane().add(okcancelPanel,BorderLayout.SOUTH); + optionsFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + + + + optionsFrame.setSize(520,310); + optionsFrame.setLocation(200,250); + optionsFrame.setVisible(true); + optionsFrame.setResizable(true); + //optionsFrame.getContentPane().add(optPanel); + + } + if(ch==1) // Pressed No + { + //Add D95 to the tree + InsertNode.deleteChildren("Bas"); + InsertNode.insertNode("Bas", "D95"); + writeBasis("D95"); + } + } + + + if(e.getSource()==d95okBtn) + { + // Add every thing that has been selected + InsertNode.deleteChildren("Bas"); + String d95String1=""; + String d95String2=""; + + if(!(d95model1.getNumber().intValue()==0 && d95model2.getNumber().intValue()==0)) + { + d95String2="("; + + +d95String2+=returnPol(d95model1.getNumber().intValue(),d95model2.getNumber().intValue(),0); + //d95String2+=","; + + +d95String2+=returnPol(d95model3.getNumber().intValue(),d95model4.getNumber().intValue(),1); + d95String2+=")"; + } + System.out.println(d95String2); + + + if(d95d1.isSelected()) //D95+ + { + + InsertNode.insertNode("Bas", d95d1.getText()); + d95String1=d95d1.getText(); + } + else if(d95d2.isSelected()) //D95++ + { + InsertNode.insertNode("Bas", d95d2.getText()); + d95String1=d95d2.getText(); + } + else if((!(d95d1.isSelected())) && + (!(d95d2.isSelected()))) + { + // Just Pressed Ok without selecting + //Same as Cancel Or "No" + InsertNode.insertNode("Bas", "D95"); + d95String1="D95"; + } + writeBasis(d95String1+d95String2); + optionsFrame.dispose(); + } + + if(e.getSource()==d95cancelBtn) + { + // Same as "No" + InsertNode.deleteChildren("Bas"); + InsertNode.insertNode("Bas", "D95"); + writeBasis("D95"); + optionsFrame.dispose(); + } + + + /*if(e.getSource()==G03MenuTree.ad95vMenu) + { + int ch; + ch = JOptionPane.showConfirmDialog(null,"Add Polarization and/Or Diffuse Functions","D95V Options",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE); + if(ch==0) + { + JFrame.setDefaultLookAndFeelDecorated(true); + optionsFrame = new JFrame("D95V Options"); + JFrame.setDefaultLookAndFeelDecorated(true); + polLabel = new JLabel("Polarization Functions:"); + diffLabel = new JLabel("Diffuse Functions:"); + ButtonGroup d95vGroup = new ButtonGroup(); + d95vPol1 = new JRadioButton("D95V(d)"); + d95vPol2 = new JRadioButton("D95V(d,p)"); + d95vd1 = new JRadioButton("D95V+"); + //d95vd2 = new JRadioButton("D95V++"); + + d95vGroup.add(d95vPol1); + d95vGroup.add(d95vPol2); + + d95vokBtn=new JButton("Ok"); + d95vcancelBtn=new JButton("Cancel"); + optionsFrame.setSize(500,160); + optionsFrame.setLocation(200,250); + optionsFrame.setVisible(true); + optionsFrame.setResizable(false); + + optPanel = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.fill = GridBagConstraints.BOTH; + + c.gridx=0; + c.weightx=1; + c.weighty=1; + c.insets=new Insets(10,50,10,20); + optPanel.add(polLabel,c); + c.gridx=1; + c.insets = new Insets(10,-100,10,20); + optPanel.add(d95vPol1,c); + c.gridy=1;c.gridx=1; + optPanel.add(d95vPol2,c); + c.gridx=0;c.gridy=2; + c.insets=new Insets(10,50,10,20); + optPanel.add(diffLabel,c); + c.gridx=1; + c.insets = new Insets(10,-100,10,20); + optPanel.add(d95vd1,c); + c.gridx=1; + c.gridy=3; + optPanel.add(d95vd2,c); + + okcancelPanel=new JPanel(); + okcancelPanel.add(d95vokBtn); + okcancelPanel.add(d95vcancelBtn); + + d95vokBtn.addActionListener(this); + d95vcancelBtn.addActionListener(this); + + optionsFrame.getContentPane().setLayout(new BorderLayout()); + optionsFrame.getContentPane().add(optPanel,BorderLayout.CENTER); + optionsFrame.getContentPane().add(okcancelPanel,BorderLayout.SOUTH); + optionsFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + } + if(ch==1) // Pressed No + { + //Add D95V to the tree + InsertNode.deleteChildren("Bas"); + InsertNode.insertNode("Bas","D95V"); + } + } + */ + if(e.getSource()==d95vokBtn) + { + InsertNode.deleteChildren("Bas"); + // Add every thing that has been selected + if(d95vd1.isSelected()) //D95V+ + { + InsertNode.insertNode("Bas", d95vd1.getText()); + writeBasis(d95vd1.getText()); + } + + if(d95vPol1.isSelected()) //D95(d..) + { + InsertNode.insertNode("Bas", d95vPol1.getText()); + writeBasis(d95vPol1.getText()); + } + if(d95vPol2.isSelected()) //D95(d..) + { + InsertNode.insertNode("Bas", d95vPol2.getText()); + writeBasis(d95vPol2.getText()); + } + if((!(d95vd1.isSelected())) && + (!(d95vPol1.isSelected())) && + (!(d95vPol2.isSelected())) + ) + { + // Just Pressed Ok without selecting + //Same as Cancel Or "No" + InsertNode.insertNode("Bas", "D95V"); + writeBasis("D95V"); + } + + optionsFrame.dispose(); + + } + + if(e.getSource()==d95vcancelBtn) + { + // Same as "No" + InsertNode.deleteChildren("Bas"); + InsertNode.insertNode("Bas", "D95V"); + writeBasis("D95V"); + optionsFrame.dispose(); + } + + + + if( + e.getSource()==G03MenuTree.adgItem || + e.getSource()==G03MenuTree.adg2Item || + e.getSource()==G03MenuTree.adgtItem || + e.getSource()==G03MenuTree.aeprItem || + e.getSource()==G03MenuTree.aepr2Item || + e.getSource()==G03MenuTree.alanItem || + e.getSource()==G03MenuTree.amidiItem || + e.getSource()==G03MenuTree.amtItem || + e.getSource()==G03MenuTree.asddItem || + e.getSource()==G03MenuTree.asdd2Item || + e.getSource()==G03MenuTree.acep4gItem || + e.getSource()==G03MenuTree.acep4g1Item || + e.getSource()==G03MenuTree.acep31gItem || + e.getSource()==G03MenuTree.acep31g1Item || + e.getSource()==G03MenuTree.acep121gItem || + e.getSource()==G03MenuTree.acep121g1Item || + e.getSource()==G03MenuTree.ashcItem || + e.getSource()==G03MenuTree.ashc1Item || + e.getSource()==G03MenuTree.augbsItem || + e.getSource()==G03MenuTree.augbs1Item || + e.getSource()==G03MenuTree.augbs2Item || + e.getSource()==G03MenuTree.augbs3Item || + e.getSource()==G03MenuTree.ad95v11Item || + e.getSource()==G03MenuTree.ad95v1Item || + e.getSource()==G03MenuTree.ad95vp11Item || + e.getSource()==G03MenuTree.ad95vp1Item || + e.getSource()==G03MenuTree.ad95vpItem || + e.getSource()==G03MenuTree.ad95vpp11Item || + e.getSource()==G03MenuTree.ad95vpp1Item || + e.getSource()==G03MenuTree.ad95vppItem ) + + { + InsertNode.deleteChildren("Bas"); + InsertNode.insertNode("Ba", e.getActionCommand()); + writeBasis(e.getActionCommand()); + } + + + + } + + + public static void writeBasis(String basisStr) + { + RouteClass.basisBuffer = new StringBuffer(); + RouteClass.basisBuffer.append(basisStr); + RouteClass.writeRoute(); + + } + + public static String returnPol(int a,int b,int type) + { + String str=""; + if(type==0) + { + if(a==1) + str="d"; + else if(a>1) + str=a+"d"; + + if(b!=0) + str+="f"; + + } + if(type==1) + { + if(a==1) + str=",p"; + else if(a>1) + str=","+a+"p"; + + if(b!=0) + str+="d"; + + } + + + return str; + } + +} diff --git a/src/main/java/g03input/BufferedDisplayMolecule.java b/src/main/java/g03input/BufferedDisplayMolecule.java new file mode 100644 index 0000000..ef6020f --- /dev/null +++ b/src/main/java/g03input/BufferedDisplayMolecule.java @@ -0,0 +1,1560 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Sep 11, 2005 + * @author Michael Sheetz + * @author Sandeep Kumar Seethaapathy @author Shashank Jeedigunta + * + */ +package g03input; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.awt.geom.Ellipse2D; +import java.awt.geom.Line2D; +import java.awt.geom.Rectangle2D; +import java.awt.image.BufferedImage; +import java.util.Hashtable; +import java.util.StringTokenizer; + +public class BufferedDisplayMolecule extends JFrame +{ + DisplayCanvas canvas; + + public BufferedDisplayMolecule() // Constructor + { + super("Geometric Structure"); + canvas = new DisplayCanvas(); + canvas.clearCanvas(); + try + { + G03MenuTree.molBrowser.remove(0); + } + catch(RuntimeException e){ + e.printStackTrace(); + } + G03MenuTree.molBrowser.add(canvas); + addWindowListener(new WindowEventHandler()); + } + + + + // Define window listener class + class WindowEventHandler extends WindowAdapter + { + public void windowClosing(WindowEvent e) + { + System.exit(0); + } + } + + // Define DisplayCanvas class + class DisplayCanvas extends Canvas + { + int i, j, k, k1, k2, k3, index, minIndex; + int natoms, nelem, nbonds, ncoord, natomCoord, nprojectedCoord, ndisplayCoord, nouterCoord, total_ncoord; + int atomDiameter; + int fontStyle, fontSize; + int rotAxis; + int[] bondedAtoms; + int[] bondOrder; + int[] displayOrder; + + double alpha, rotAngle, x_rotAngle, y_rotAngle, z_rotAngle; + double delx, dely, xscale, yscale, scaleFactor, prcnt, min; + double[] atomCoord; + double[] transfCoord; + double[] transfCoord_y; + double[] projectedCoord; + double[] displayCoord; + double[] outerCoord; + double[] imageBounds; + double[] clippingBounds; + double sqDist, dist; + + String atomArray; + String coordArray; + String fontName; + String[] atomSymb; + StringBuffer coordinates; + + Color background; + Color xaxisColor, yaxisColor, zaxisColor, bondColor; + Color[] atomColors; + + Ellipse2D atom; + Rectangle2D xrec, yrec, zrec; + Font font1, font2; + boolean isRotatable; + + BufferedImage offscreenImage; + + // Specify size of display screen + int displayWidth; + int displayHeight; + + double lamda; + double x1, y1, x2, y2, x3, y3, x4, y4; + double x11, x21, y11, y21; + double x12, x22, y12, y22; + double x13, x23, y13, y23; + double mx_init, mx_current, del_mx; + Line2D line; + + Hashtable bondLengths; + + public void clearCanvas() + { + Graphics g=canvas.offscreenImage.getGraphics(); + canvas.offscreenImage.flush(); + update(g); + } + + DisplayCanvas() // Constructor + { + displayWidth = 250; + displayHeight = 250; + + // The coordinate array, coordArray, will be read in as a string from molecular specification section + // of the G03 input file + coordinates = new StringBuffer(); +// coordinates.append("0.000 0.000 0.000 0.000 0.000 1.505 1.047 0.000 -0.651 -1.000 -0.006 -0.484 "); +// coordinates.append("-0.735 0.755 1.898 -0.295 -1.024 1.866 1.242 0.364 2.065 1.938 -0.001 1.499"); + + + for(int i=0;i< GeometryEditor.GeometryReader.atomCoord.length;i++) + { + coordinates.append(GeometryEditor.GeometryReader.atomCoord[i]+" "); + } + + /* + coordinates.append("0.00 0.00 0.00 1.93 0.00 0.00 -1.93 0.00 0.00 0.00 1.93 0.00 0.00 -1.93 0.00 0.00 0.00 1.93 0.00 0.00 -1.93 "); + coordinates.append("3.07 0.00 0.00 -3.07 0.00 0.00 0.00 3.07 0.00 0.00 -3.07 0.00 0.00 0.00 -3.07 0.00 0.00 3.07"); + */ coordArray = new String(coordinates.toString()); + + // Atomic symbols will be read in from molecule specification section of G03 input file +// atomArray = new String("C C O H H H O H"); + atomArray = ""; + // atomSymb manipulated to get atom names (UKY) + for(int p = 0 ;p < GeometryEditor.GeometryReader.atomSymb.length;p++) + { + atomArray += GeometryEditor.GeometryReader.atomSymb[p]+" "; + } + //atomArray = new String("Ba C C C C C C O O O O O O"); +// atomArray = new String("F C C C C C C O O O O O O"); + + // Get number of atoms in molecule + natoms = getAtomCount(atomArray); + + ncoord = 3; + natomCoord = ncoord * natoms; + nelem = natoms * natoms; + + rotAxis = 0; + nprojectedCoord = 2 * natoms; + ndisplayCoord = 2 * natoms; + nouterCoord = 4; + prcnt = 0.60; + alpha = Math.PI/6; + rotAngle = 0; + x_rotAngle = 0; + y_rotAngle = 0; + z_rotAngle = 0; + rotAxis = 1; + isRotatable = false; + + // Set diameter of atom in display + atomDiameter = 35; + + // Set parameters of line segments used to draw the three axes + x1 = 0.145 * displayWidth; // origin + y1 = x1; + x2 = 1.6 * x1; // x-axis + y2 = y1; + x3 = x1; + y3 = 0.4 * y1; // z-axis + x4 = x1 * 1.1 * (1.0 - (Math.cos(alpha))/2); + y4 = y1 * (1.0 + (Math.sin(alpha))/2); // y-axis + + background = new Color(255, 255, 255); + xaxisColor = new Color(200, 0, 25); + yaxisColor = new Color(200, 200, 200); + zaxisColor = new Color(0, 110, 75); + bondColor = new Color(155, 155, 155); + atomColors = new Color[natoms]; + + bondOrder = new int[nelem]; + displayOrder = new int[natoms]; + atomCoord = new double[natomCoord]; + projectedCoord = new double[nprojectedCoord]; + transfCoord = new double[natomCoord]; + transfCoord_y = new double[natoms]; + displayCoord = new double[ndisplayCoord]; + outerCoord = new double[nouterCoord]; + imageBounds = new double[4]; + clippingBounds = new double[4]; + + offscreenImage = new BufferedImage(displayWidth, displayHeight, BufferedImage.TYPE_INT_RGB); + + addMouseListener(new MyMouseListener()); + addMouseMotionListener(new MyMouseMotionListener()); + setSize(displayWidth, displayWidth); + setBackground(background); + + // Set initial clipping bounds + clippingBounds[0] = 0; clippingBounds[1] = 0; clippingBounds[2] = displayWidth; clippingBounds[3] = displayHeight; + + // Construct hashtable for retrieving bond lengths + bondLengths = new Hashtable(); + + // All these new String's are redundant, ie, this works as well: + // bondLengths.put("Ag-Ag", "2.89 0.2 0.1"); + bondLengths.put("Ag-Ag", new String("2.89 0.2 0.1")); + + bondLengths.put("Al-Al", new String("2.87 0.2 0.1")); + bondLengths.put("Al-C", new String("1.96 0.2 0.1")); + + bondLengths.put("As-As", new String("2.11 0.2 0.1")); + bondLengths.put("As-H", new String("1.52 0.2 0.1")); + bondLengths.put("As-Br", new String("2.33 0.2 0.1")); + bondLengths.put("As-C", new String("1.97 0.2 0.1")); + bondLengths.put("As-Cl", new String("2.18 0.2 0.1")); + bondLengths.put("As-F", new String("1.72 0.2 0.1")); + bondLengths.put("As-H", new String("1.53 0.2 0.1")); + bondLengths.put("As-O", new String("1.80 0.2 0.1")); + + bondLengths.put("Au-Au", new String("2.89 0.2 0.1")); + + bondLengths.put("B-B", new String("1.59 0.2 0.1")); + bondLengths.put("B-C", new String("1.58 0.2 0.1")); + bondLengths.put("B-Cl", new String("1.78 0.2 0.1")); + bondLengths.put("B-H", new String("1.22 0.2 0.1")); + + bondLengths.put("Be-Be", new String("2.23 0.2 0.1")); + bondLengths.put("Be-C", new String("1.70 0.2 0.1")); + + bondLengths.put("Bi-Bi", new String("3.10 0.2 0.1")); + bondLengths.put("Bi-C", new String("2.26 0.2 0.1")); + bondLengths.put("Bi-Cl", new String("2.50 0.2 0.1")); + + bondLengths.put("Br-As", new String("2.33 0.2 0.1")); + bondLengths.put("Br-Br", new String("2.29 0.2 0.1")); + bondLengths.put("Br-C", new String("1.95 0.2 0.1")); + bondLengths.put("Br-Cl", new String("2.15 0.2 0.1")); + bondLengths.put("Br-F", new String("1.77 0.2 0.1")); + bondLengths.put("Br-Ge", new String("2.31 0.2 0.1")); + bondLengths.put("Br-H", new String("1.42 0.2 0.1")); + bondLengths.put("Br-I", new String("2.47 0.2 0.1")); + bondLengths.put("Br-N", new String("2.16 0.2 0.1")); + bondLengths.put("Br-P", new String("2.22 0.2 0.1")); + bondLengths.put("Br-S", new String("2.24 0.2 0.1")); + bondLengths.put("Br-Sb", new String("2.53 0.2 0.1")); + bondLengths.put("Br-Si", new String("2.19 0.2 0.1")); + bondLengths.put("Br-Sn", new String("2.53 0.2 0.1")); + + bondLengths.put("C-Al", new String("1.97 0.2 0.1")); + bondLengths.put("C-As", new String("1.97 0.2 0.1")); + bondLengths.put("C-B", new String("1.58 0.2 0.1")); + bondLengths.put("C-Be", new String("1.70 0.2 0.1")); + bondLengths.put("C-Bi", new String("2.26 0.2 0.1")); + bondLengths.put("C-Br", new String("1.95 0.2 0.1")); + bondLengths.put("C-C", new String("1.54 1.35 1.21")); + bondLengths.put("C-Cd", new String("2.11 0.2 0.1")); + bondLengths.put("C-Cl", new String("1.80 0.2 0.1")); + bondLengths.put("C-Co", new String("1.85 0.2 0.1")); + bondLengths.put("C-Cr", new String("1.96 0.2 0.1")); + bondLengths.put("C-F", new String("1.40 0.2 0.1")); + bondLengths.put("C-Fe", new String("1.86 0.2 0.1")); + bondLengths.put("C-Ge", new String("1.96 0.2 0.1")); + bondLengths.put("C-H", new String("1.10 0.2 0.1")); + bondLengths.put("C-Hg", new String("2.08 0.2 0.1")); + bondLengths.put("C-I", new String("2.13 0.2 0.1")); + bondLengths.put("C-In", new String("2.20 0.2 0.1")); + bondLengths.put("C-Mo", new String("2.12 0.2 0.1")); + bondLengths.put("C-N", new String("1.46 1.22 1.17")); + bondLengths.put("C-Ni", new String("1.85 0.2 0.1")); + bondLengths.put("C-O", new String("1.42 1.22 1.15")); + bondLengths.put("C-P", new String("1.85 0.2 0.1")); + bondLengths.put("C-Pb", new String("2.24 0.2 0.1")); + bondLengths.put("C-Pd", new String("2.31 0.2 0.1")); + bondLengths.put("C-S", new String("1.82 1.62 0.1")); + bondLengths.put("C-Sb", new String("2.22 0.2 0.1")); + bondLengths.put("C-Se", new String("1.95 0.2 0.1")); + bondLengths.put("C-Si", new String("1.87 0.2 0.1")); + bondLengths.put("C-Sn", new String("2.14 0.2 0.1")); + bondLengths.put("C-Te", new String("2.19 0.2 0.1")); + bondLengths.put("C-W", new String("2.07 0.2 0.1")); + bondLengths.put("C-Zn", new String("1.93 0.2 0.1")); + + bondLengths.put("Cd-C", new String("2.11 0.2 0.1")); + + bondLengths.put("Cl-As", new String("2.18 0.2 0.1")); + bondLengths.put("Cl-B", new String("1.78 0.2 0.1")); + bondLengths.put("Cl-Bi", new String("2.50 0.2 0.1")); + bondLengths.put("Cl-Br", new String("2.15 0.2 0.1")); + bondLengths.put("Cl-C", new String("1.80 0.2 0.1")); + bondLengths.put("Cl-Cl", new String("1.99 0.2 0.1")); + bondLengths.put("Cl-Cr", new String("2.14 0.2 0.1")); + bondLengths.put("Cl-H", new String("1.29 0.2 0.1")); + bondLengths.put("Cl-Ge", new String("2.13 0.2 0.1")); + bondLengths.put("Cl-F", new String("1.64 0.2 0.1")); + bondLengths.put("Cl-I", new String("2.32 0.2 0.1")); + bondLengths.put("Cl-N", new String("1.90 0.2 0.1")); + bondLengths.put("Cl-O", new String("1.70 0.2 0.1")); + bondLengths.put("Cl-P", new String("2.04 0.2 0.1")); + bondLengths.put("Cl-Pb", new String("2.45 0.2 0.1")); + bondLengths.put("Cl-S", new String("2.05 0.2 0.1")); + bondLengths.put("Cl-Sb", new String("2.33 0.2 0.1")); + bondLengths.put("Cl-Si", new String("2.05 0.2 0.1")); + bondLengths.put("Cl-Sn", new String("2.28 0.2 0.1")); + + bondLengths.put("Cr-C", new String("1.96 0.2 0.1")); + bondLengths.put("Cr-Cl", new String("2.14 0.2 0.1")); + bondLengths.put("Cr-N", new String("2.30 0.2 0.1")); + bondLengths.put("Cr-O", new String("1.93 0.2 0.1")); + + bondLengths.put("F-As", new String("1.72 0.2 0.1")); + bondLengths.put("F-Br", new String("1.77 0.2 0.1")); + bondLengths.put("F-C", new String("1.40 0.2 0.1")); + bondLengths.put("F-Cl", new String("1.64 0.2 0.1")); + bondLengths.put("F-F", new String("1.42 0.2 0.1")); + bondLengths.put("F-Ge", new String("1.74 0.2 0.1")); + bondLengths.put("F-H", new String("0.93 0.2 0.1")); + bondLengths.put("F-I", new String("1.91 0.2 0.1")); + bondLengths.put("F-N", new String("1.32 0.2 0.1")); + bondLengths.put("F-O", new String("1.42 0.2 0.1")); + bondLengths.put("F-P", new String("1.57 0.2 0.1")); + bondLengths.put("F-S", new String("1.56 0.2 0.1")); + bondLengths.put("F-Se", new String("1.71 0.2 0.1")); + bondLengths.put("F-Si", new String("1.58 0.2 0.1")); + bondLengths.put("F-Te", new String("1.82 0.2 0.1")); + + bondLengths.put("Ge-Br", new String("2.31 0.2 0.1")); + bondLengths.put("Ge-C", new String("1.96 0.2 0.1")); + bondLengths.put("Ge-Cl", new String("2.16 0.2 0.1")); + bondLengths.put("Ge-F", new String("1.74 0.2 0.1")); + bondLengths.put("Ge-Ge", new String("2.47 0.2 0.1")); + bondLengths.put("Ge-H", new String("1.54 0.2 0.1")); + bondLengths.put("Ge-I", new String("2.51 0.2 0.1")); + + bondLengths.put("H-As", new String("1.52 0.2 0.1")); + bondLengths.put("H-B", new String("1.22 0.2 0.1")); + bondLengths.put("H-C", new String("1.10 0.2 0.1")); + bondLengths.put("H-Br", new String("1.42 0.2 0.1")); + bondLengths.put("H-Cl", new String("1.29 0.2 0.1")); + bondLengths.put("H-F", new String("0.93 0.2 0.1")); + bondLengths.put("H-Ge", new String("1.54 0.2 0.1")); + bondLengths.put("H-H", new String("0.75 0.2 0.1")); + bondLengths.put("H-I", new String("1.61 2 0.1")); + bondLengths.put("H-N", new String("1.02 0.2 0.1")); + bondLengths.put("H-O", new String("0.96 0.2 0.1")); + bondLengths.put("H-P", new String("1.42 0.2 0.1")); + bondLengths.put("H-S", new String("1.32 0.2 0.1")); + bondLengths.put("H-Sb", new String("1.70 0.2 0.1")); + bondLengths.put("H-Se", new String("1.47 0.2 0.1")); + bondLengths.put("H-Si", new String("1.48 0.2 0.1")); + bondLengths.put("H-Sn", new String("1.71 0.2 0.1")); + bondLengths.put("H-Te", new String("1.66 0.2 0.1")); + + bondLengths.put("He-He", new String("1.08 0.2 0.1")); + + bondLengths.put("Hg-C", new String("2.08 0.2 0.1")); + bondLengths.put("Hg-Hg", new String("3.01 0.2 0.1")); + + bondLengths.put("I-Br", new String("2.47 0.2 0.1")); + bondLengths.put("I-C", new String("2.13 0.2 0.1")); + bondLengths.put("I-Cl", new String("2.32 0.2 0.1")); + bondLengths.put("I-F", new String("1.91 0.2 0.1")); + bondLengths.put("I-Ge", new String("2.51 0.2 0.1")); + bondLengths.put("I-H", new String("1.61 0.2 0.1")); + bondLengths.put("I-I", new String("2.67 0.2 0.1")); + bondLengths.put("I-Pb", new String("2.82 0.2 0.1")); + bondLengths.put("I-Sb", new String("2.70 0.2 0.1")); + bondLengths.put("I-Si", new String("2.44 0.2 0.1")); + bondLengths.put("I-Sn", new String("2.67 0.2 0.1")); + + bondLengths.put("In-In", new String("3.26 0.2 0.1")); + + bondLengths.put("Ir-Ir", new String("2.72 0.2 0.1")); + + bondLengths.put("K-K", new String("4.55 0.2 0.1")); + + bondLengths.put("Li-Li", new String("3.05 0.2 0.1")); + + bondLengths.put("Mg-Mg", new String("3.20 0.2 0.1")); + + bondLengths.put("Mn-Mn", new String("2.74 0.2 0.1")); + + bondLengths.put("Mo-C", new String("2.12 0.2 0.1")); + bondLengths.put("Mo-Mo", new String("2.74 0.2 0.1")); + + bondLengths.put("N-Br", new String("2.16 0.2 0.1")); + bondLengths.put("N-C", new String("1.46 1.22 1.17")); + bondLengths.put("N-Cl", new String("1.90 0.2 0.1")); + bondLengths.put("N-Cr", new String("2.30 0.2 0.1")); + bondLengths.put("N-F", new String("1.32 0.2 0.1")); + bondLengths.put("N-H", new String("1.02 0.2 0.1")); + bondLengths.put("N-N", new String("1.45 1.25 1.14")); + bondLengths.put("N-O", new String("1.43 1.19 0.1")); + bondLengths.put("N-P", new String("1.65 0.2 0.1")); + + bondLengths.put("Na-Na", new String("3.73 0.2 0.1")); + + bondLengths.put("Nb-Nb", new String("2.86 0.2 0.1")); + + bondLengths.put("Nd-Nd", new String("3.64 0.2 0.1")); + + bondLengths.put("Ni-Ni", new String("2.51 0.2 0.1")); + + bondLengths.put("O-As", new String("1.80 0.02 0.1")); + bondLengths.put("O-C", new String("1.42 1.22 1.15")); + bondLengths.put("O-Cl", new String("1.70 0.2 0.1")); + bondLengths.put("O-Cr", new String("1.93 0.2 0.1")); + bondLengths.put("O-F", new String("1.42 0.2 0.1")); + bondLengths.put("O-H", new String("0.96 0.2 0.1")); + bondLengths.put("O-N", new String("1.43 1.19 0.1")); + bondLengths.put("O-O", new String("1.48 1.22 0.1")); + bondLengths.put("O-P", new String("1.67 1.53 0.1")); + bondLengths.put("O-S", new String("1.47 1.46 0.1")); + bondLengths.put("O-Si", new String("1.63 0.2 0.1")); + + bondLengths.put("Os-Os", new String("2.68 0.2 0.1")); + + bondLengths.put("P-Br", new String("2.22 0.2 0.1")); + bondLengths.put("P-C", new String("1.85 0.2 0.1")); + bondLengths.put("P-Cl", new String("2.04 0.2 0.1")); + bondLengths.put("P-F", new String("1.57 0.2 0.1")); + bondLengths.put("P-H", new String("1.42 0.2 0.1")); + bondLengths.put("P-P", new String("2.25 0.2 0.1")); + bondLengths.put("P-N", new String("1.65 0.2 0.1")); + bondLengths.put("P-O", new String("1.67 1.53 0.1")); + bondLengths.put("P-S", new String("1.91 1.87 0.1")); + + bondLengths.put("Pb-C", new String("2.24 0.2 0.1")); + bondLengths.put("Pb-Cl", new String("2.45 0.2 0.1")); + bondLengths.put("Pb-I", new String("2.82 0.2 0.1")); + bondLengths.put("Pb-Pb", new String("2.76 0.2 0.1")); + + bondLengths.put("Rb-Rb", new String("4.95 0.2 0.1")); + + bondLengths.put("S-Br", new String("2.24 0.2 0.1")); + bondLengths.put("S-C", new String("1.82 1.62 0.1")); + bondLengths.put("S-H", new String("1.32 0.2 0.1")); + bondLengths.put("S-O", new String("1.47 1.46 0.1")); + bondLengths.put("S-P", new String("1.91 1.87 0.1")); + bondLengths.put("S-S", new String("2.04 1.52 0.1")); + bondLengths.put("S-F", new String("1.56 0.2 0.1")); + bondLengths.put("S-Cl", new String("2.05 0.2 0.1")); + bondLengths.put("S-Si", new String("2.14 0.2 0.1")); + + bondLengths.put("Sb-Br", new String("2.53 0.2 0.1")); + bondLengths.put("Sb-C", new String("2.22 0.2 0.1")); + bondLengths.put("Sb-Cl", new String("2.33 0.2 0.1")); + bondLengths.put("Sb-H", new String("1.70 0.2 0.1")); + bondLengths.put("Sb-I", new String("2.70 0.2 0.1")); + bondLengths.put("Sb-Sb", new String("2.91 0.2 0.1")); + + bondLengths.put("Se-C", new String("1.95 0.2 0.1")); + bondLengths.put("Se-F", new String("1.71 0.2 0.1")); + bondLengths.put("Se-H", new String("1.47 0.2 0.1")); + bondLengths.put("Se-Se", new String("2.33 2.15 0.1")); + + bondLengths.put("Si-H", new String("1.48 0.2 0.1")); + bondLengths.put("Si-C", new String("1.87 0.2 0.1")); + bondLengths.put("Si-Cl", new String("2.05 0.2 0.1")); + bondLengths.put("Si-F", new String("1.58 0.2 0.1")); + bondLengths.put("Si-Br", new String("2.19 0.2 0.1")); + bondLengths.put("Si-I", new String("2.44 0.2 0.1")); + bondLengths.put("Si-O", new String("1.63 0.2 0.1")); + bondLengths.put("Si-S", new String("2.14 0.2 0.1")); + bondLengths.put("Si-Si", new String("2.33 0.2 0.1")); + + bondLengths.put("Sn-Br", new String("2.53 0.2 0.1")); + bondLengths.put("Sn-C", new String("2.14 0.2 0.1")); + bondLengths.put("Sn-Cl", new String("2.28 0.2 0.1")); + bondLengths.put("Sn-H", new String("1.71 0.2 0.1")); + bondLengths.put("Sn-I", new String("2.67 0.2 0.1")); + + bondLengths.put("Te-C", new String("2.19 0.2 0.1")); + bondLengths.put("Te-F", new String("1.82 0.2 0.1")); + bondLengths.put("Te-H", new String("1.66 0.2 0.1")); + + bondLengths.put("W-C", new String("2.07 0.2 0.1")); + + bondLengths.put("Zn-C", new String("1.93 0.2 0.1")); + + + // Construct image of molecule projected onto x,z-plane + + // Retrieve atomic symbols + atomSymb = getAtomSymbols(atomArray, natoms); + + // Retrieve atom colors + atomColors = getAtomColors(atomSymb, natoms); + + // Retrieve atom coordinates + atomCoord = getAtomCoordinates(coordArray, natomCoord); + + // Set initial values of transformed coordinates equal to the values for atom coordinates + for (i = 0; i < natoms; i++) + { + for (j = 0; j < ncoord; j++) + { + k = (3 * i) + j; + + transfCoord[k] = atomCoord[k]; + } + } + + // Get display coordinates + displayCoord = getDisplayCoord(transfCoord, natoms, alpha, displayWidth, displayHeight); + + // Get bond order for each pair of bonded atoms in molecule + bondOrder = getBondOrder(atomCoord, atomSymb, natoms, bondLengths); + } + + public int getAtomCount(String atomArray) + { + String atomList = atomArray.trim(); + + StringTokenizer stok = new StringTokenizer(atomList); + + return stok.countTokens(); + } + + public String[] getAtomSymbols(String atomArray, int natoms) + { + String[] atomicSymbol = new String[natoms]; + String atomList = atomArray.trim(); + + StringTokenizer stok = new StringTokenizer(atomList); + + int index = 0; + + while (stok.hasMoreTokens()) + { + atomicSymbol[index] = stok.nextToken(); + + index++; + } + + return atomicSymbol; + } + + public double[] getAtomCoordinates(String coordArray, int natomCoord) + { + double[] atomCoordinates = new double[natomCoord]; + String coordList = coordArray.trim(); + + StringTokenizer stok = new StringTokenizer(coordList); + + int index = 0; + + while (stok.hasMoreTokens()) + { + atomCoordinates[index] = Double.parseDouble(stok.nextToken()); + + index++; + } + return atomCoordinates; + } + + public Color[] getAtomColors(String[] atomicSymbol, int natoms) + { + Color[] atomColors = new Color[natoms]; + + for (j = 0; j < natoms; j++) + { + if (atomicSymbol[j].equals("Ag")) + { + atomColors[j] = new Color(192, 192, 192); + } + else if (atomicSymbol[j].equals("Al")) + { + atomColors[j] = new Color(221, 221, 221); + } + else if (atomicSymbol[j].equals("Ar")) + { + atomColors[j] = new Color(0, 153, 153); + } + else if (atomicSymbol[j].equals("As")) + { + atomColors[j] = new Color(0, 153, 255); + } + else if (atomicSymbol[j].equals("Au")) + { + atomColors[j] = new Color(255, 230, 0); + } + else if (atomicSymbol[j].equals("B")) + { + atomColors[j] = new Color(0, 153, 204); + } + else if (atomicSymbol[j].equals("Be")) + { + atomColors[j] = new Color(153, 102, 255); + } + else if (atomicSymbol[j].equals("Br")) + { + atomColors[j] = new Color(180, 40, 0); + } + else if (atomicSymbol[j].equals("C")) + { + atomColors[j] = new Color(0, 0, 0); + } + else if (atomicSymbol[j].equals("Ca")) + { + atomColors[j] = new Color(255, 255, 204); + } + else if (atomicSymbol[j].equals("Cd")) + { + atomColors[j] = new Color(230, 200, 255); + } + else if (atomicSymbol[j].equals("Cl")) + { + atomColors[j] = new Color(0, 230, 0); + } + else if (atomicSymbol[j].equals("Co")) + { + atomColors[j] = new Color(255, 110, 165); + } + else if (atomicSymbol[j].equals("Cr")) + { + atomColors[j] = new Color(51, 204, 204); + } + else if (atomicSymbol[j].equals("Cu")) + { + atomColors[j] = new Color(255, 153, 0); + } + else if (atomicSymbol[j].equals("F")) + { + atomColors[j] = new Color(255, 190, 255); + } + else if (atomicSymbol[j].equals("Fe")) + { + atomColors[j] = new Color(204, 0, 0); + } + else if (atomicSymbol[j].equals("Ga")) + { + atomColors[j] = new Color(0, 205, 85); + } + else if (atomicSymbol[j].equals("Ge")) + { + atomColors[j] = new Color(125, 204, 204); + } + else if (atomicSymbol[j].equals("H")) + { + atomColors[j] = new Color(204, 255, 204); + } + else if (atomicSymbol[j].equals("He")) + { + atomColors[j] = new Color(204, 236, 255); + } + else if (atomicSymbol[j].equals("Hg")) + { + atomColors[j] = new Color(234, 243, 233); + } + else if (atomicSymbol[j].equals("I")) + { + atomColors[j] = new Color(220, 30, 50); + } + else if (atomicSymbol[j].equals("In")) + { + atomColors[j] = new Color(220, 180, 210); + } + else if (atomicSymbol[j].equals("K")) + { + atomColors[j] = new Color(0, 50, 195); + } + else if (atomicSymbol[j].equals("Kr")) + { + atomColors[j] = new Color(155, 255, 204); + } + else if (atomicSymbol[j].equals("Li")) + { + atomColors[j] = new Color(204, 0, 255); + } + else if (atomicSymbol[j].equals("Mg")) + { + atomColors[j] = new Color(155, 155, 155); + } + else if (atomicSymbol[j].equals("Mn")) + { + atomColors[j] = new Color(0, 204, 153); + } + else if (atomicSymbol[j].equals("Mo")) + { + atomColors[j] = new Color(204, 153, 255); + } + else if (atomicSymbol[j].equals("N")) + { + atomColors[j] = new Color(0, 204, 255); + } + else if (atomicSymbol[j].equals("Na")) + { + atomColors[j] = new Color(255, 255, 0); + } + else if (atomicSymbol[j].equals("Nb")) + { + atomColors[j] = new Color(204, 255, 51); + } + else if (atomicSymbol[j].equals("Ne")) + { + atomColors[j] = new Color(204, 255, 255); + } + else if (atomicSymbol[j].equals("Ni")) + { + atomColors[j] = new Color(0, 95, 250); + } + else if (atomicSymbol[j].equals("O")) + { + atomColors[j] = new Color(200, 0, 25); + } + else if (atomicSymbol[j].equals("P")) + { + atomColors[j] = new Color(255, 0, 0); + } + else if (atomicSymbol[j].equals("Pb")) + { + atomColors[j] = new Color(115, 115, 115); + } + else if (atomicSymbol[j].equals("Pd")) + { + atomColors[j] = new Color(240, 240, 230); + } + else if (atomicSymbol[j].equals("Pt")) + { + atomColors[j] = new Color(234, 234, 234); + } + else if (atomicSymbol[j].equals("Rb")) + { + atomColors[j] = new Color(153, 0, 204); + } + else if (atomicSymbol[j].equals("Rh")) + { + atomColors[j] = new Color(51, 102, 210); + } + else if (atomicSymbol[j].equals("Ru")) + { + atomColors[j] = new Color(0, 210, 210); + } + else if (atomicSymbol[j].equals("S")) + { + atomColors[j] = new Color(255, 230, 0); + } + else if (atomicSymbol[j].equals("Sb")) + { + atomColors[j] = new Color(51, 165, 51); + } + else if (atomicSymbol[j].equals("Sc")) + { + atomColors[j] = new Color(0, 255, 0); + } + else if (atomicSymbol[j].equals("Se")) + { + atomColors[j] = new Color(204, 51, 10); + } + else if (atomicSymbol[j].equals("Si")) + { + atomColors[j] = new Color(255, 255, 153); + } + else if (atomicSymbol[j].equals("Sn")) + { + atomColors[j] = new Color(220, 230, 165); + } + else if (atomicSymbol[j].equals("Sr")) + { + atomColors[j] = new Color(246, 250, 165); + } + else if (atomicSymbol[j].equals("Te")) + { + atomColors[j] = new Color(204, 255, 153); + } + else if (atomicSymbol[j].equals("Tc")) + { + atomColors[j] = new Color(51, 102, 153); + } + else if (atomicSymbol[j].equals("Ti")) + { + atomColors[j] = new Color(0, 255, 255); + } + else if (atomicSymbol[j].equals("V")) + { + atomColors[j] = new Color(255, 255, 102); + } + else if (atomicSymbol[j].equals("Xe")) + { + atomColors[j] = new Color(0, 130, 75); + } + else if (atomicSymbol[j].equals("Y")) + { + atomColors[j] = new Color(245, 130, 255); + } + else if (atomicSymbol[j].equals("Zn")) + { + atomColors[j] = new Color(0, 204, 204); + } + else if (atomicSymbol[j].equals("Zr")) + { + atomColors[j] = new Color(140, 204, 204); + } + else + { + atomColors[j] = new Color(255, 255, 230); + } + } + return atomColors; + } + + public int[] getBondOrder(double[] atomCoord, String[] atomSymb, int natoms, Hashtable bondLengths) + { + int nelem, ntokens, index, k1, k2; + double dx, dy, dz, dist; + double[] length; + int[] bondOrder; + String atomPair, bondDistances; + + nelem = natoms * natoms; + ntokens = 3; + + length = new double[ntokens]; + bondOrder = new int[nelem]; + + for (i = 0; i < (natoms-1); i++) + { + k1 = 3 * i; + + for (j = (i+1); j < natoms; j++) + { + index = (i * natoms) + j; + k2 = 3 * j; + + // Compute distance between atom 'i' and atom 'j' + dx = atomCoord[k1] - atomCoord[k2]; + dy = atomCoord[k1+1] - atomCoord[k2+1]; + dz = atomCoord[k1+2] - atomCoord[k2+2]; + + dist = Math.sqrt( (dx*dx) + (dy*dy) + (dz*dz) ); + + atomPair = new String(atomSymb[i] + "-" + atomSymb[j]); + + // Retrieve from hashtable the maximum bond length for atoms pair to be bonded + if (bondLengths.get(atomPair)!= null) + { + bondDistances = new String(bondLengths.get(atomPair)); + } + else + { + bondDistances = "3.0 0.2 0.1"; // default bond distance for undefined atom pairs + } + + if (bondDistances != null) + { + StringTokenizer stok = new StringTokenizer(bondDistances); + + for (int t = 0; t < ntokens; t++) + { + length[t] = Double.parseDouble(stok.nextToken()); + } + + if (dist <= length[0]) + { + if (dist > length[1]) + { + bondOrder[index] = 1; + } + else if ( (dist <= length[1]) && (dist > length[2]) ) + { + bondOrder[index] = 2; + } + else if ( (dist <= length[2]) && (dist > 0) ) + { + bondOrder[index] = 3; + } + } + } + } + } + + return bondOrder; + } + + public double[] getDisplayCoord(double[] coordinates, int natoms, double alpha, int displayWidth, int displayHeight) + { + int ncoord, nelem, finalNdex; + double xmax, ymax, xmin, ymin; + double[] displayCoord; + double[] projectedCoord; + double[] outerCoord; + + ncoord = 2; + nelem = ncoord * natoms; + finalNdex = nelem - 1; + + projectedCoord = new double[nelem]; + outerCoord = new double[4]; + displayCoord = new double[nelem]; + + for (i = 0; i < natoms; i++) + { + j = 2 * i; + k = 3 * i; + + projectedCoord[j] = coordinates[k] - (coordinates[k + 1] * Math.cos(alpha)); + projectedCoord[j + 1] = coordinates[k + 2] - (coordinates[k + 1] * Math.sin(alpha)); + } + + // Retrieve coordinates with extreme values in the x- and y-directions + xmax = projectedCoord[finalNdex-1]; + xmin = xmax; + ymax = projectedCoord[finalNdex]; + ymin = ymax; + + for (j = 0; j < (natoms-1); j++) + { + k = 2 * j; + + if (projectedCoord[k] > xmax) + { + xmax = projectedCoord[k]; + } + + if (projectedCoord[k] < xmin) + { + xmin = projectedCoord[k]; + } + + if (projectedCoord[k+1] > ymax) + { + ymax = projectedCoord[k+1]; + } + + if (projectedCoord[k+1] < ymin) + { + ymin = projectedCoord[k+1]; + } + } + + outerCoord[0] = xmin; + outerCoord[1] = xmax; + outerCoord[2] = ymin; + outerCoord[3] = ymax; + + // Set scale parameter for expanding size of molecule to cover 'prcnt' percent of the display screen + xscale = (prcnt * displayWidth)/(outerCoord[1] - outerCoord[0]); // x-coordinate scale factor + yscale = (prcnt * displayHeight)/(outerCoord[3] - outerCoord[2]); // y-coordinate scale factor + + // Select smallest scale factor for scaling in both the x- and y-directions + if (xscale < yscale) + { + scaleFactor = xscale; + } + else + { + scaleFactor = yscale; + } + + // Set translation parameter for centering molecule on display screen + delx = (displayWidth - ((outerCoord[0] + outerCoord[1])*scaleFactor))/2; + dely = (displayHeight - ((outerCoord[2] + outerCoord[3])*scaleFactor))/2; + + + for (i = 0; i < natoms; i++) + { + j = 2 * i; + + displayCoord[j] = delx + scaleFactor * projectedCoord[j]; + displayCoord[j+1] = dely + scaleFactor * projectedCoord[j+1]; + } + + return displayCoord; + } + + public double[] getImageBounds(double[] displayCoord, int natoms) + { + int ncoord, nelem, finalNdex; + double xmax, ymax, xmin, ymin; + + double[] outerCoord; + + ncoord = 2; + nelem = ncoord * natoms; + finalNdex = nelem - 1; + + // Retrieve coordinates with extreme values in the x- and y-directions + xmax = displayCoord[finalNdex-1]; + xmin = xmax; + ymax = displayCoord[finalNdex]; + ymin = ymax; + + for (j = 0; j < (natoms-1); j++) + { + k = 2 * j; + + if (displayCoord[k] > xmax) + { + xmax = displayCoord[k]; + } + + if (displayCoord[k] < xmin) + { + xmin = displayCoord[k]; + } + + if (displayCoord[k+1] > ymax) + { + ymax = displayCoord[k+1]; + } + + if (displayCoord[k+1] < ymin) + { + ymin = displayCoord[k+1]; + } + } + + imageBounds[0] = xmin; + imageBounds[1] = ymin; + imageBounds[2] = xmax; + imageBounds[3] = ymax; + + return imageBounds; + } + + public double[] getTransformedCoordinates(double[] coordinates, int natoms, int ncoord, double rotAngle, int rotAxis) + { + int nelem, matrixDim, i, j, k, k1, k2; + double phi; + double[] M; + double[] transfCoord; + + nelem = ncoord * natoms; + matrixDim = ncoord * ncoord; + phi = rotAngle; + + M = new double[matrixDim]; + transfCoord = new double[nelem]; + + switch(rotAxis) + { + case 1: + // Define transformation matrix for rotation about x-axis + double[] Mx = { 1, 0, 0, 0, Math.cos(phi), -Math.sin(phi), 0, Math.sin(phi), Math.cos(phi) }; + + for (int index = 0; index < matrixDim; index++) + { + M[index] = Mx[index]; + } + break; + case 2: + // Define transformation matrix for rotation about y-axis + double[] My = { Math.cos(phi), 0, Math.sin(phi), 0, 1, 0, -Math.sin(phi), 0, Math.cos(phi) }; + for (int index = 0; index < matrixDim; index++) + { + M[index] = My[index]; + } + break; + + case 3: + // Define transformation matrix for rotation about z-axis + double[] Mz = { Math.cos(phi), Math.sin(phi), 0, -Math.sin(phi), Math.cos(phi), 0, 0, 0, 1 }; + + for (int index = 0; index < matrixDim; index++) + { + M[index] = Mz[index]; + } + break; + } + + // Apply transformation matrix to coordinates + for (j = 0; j < natoms; j++) + { + k = 3 * j; + + transfCoord[k] = M[0] * coordinates[k] + M[1] * coordinates[k + 1] + M[2] * coordinates[k + 2]; + transfCoord[k + 1] = M[3] * coordinates[k] + M[4] * coordinates[k + 1] + M[5] * coordinates[k + 2]; + transfCoord[k + 2] = M[6] * coordinates[k] + M[7] * coordinates[k + 1] + M[8] * coordinates[k + 2]; + } + + return transfCoord; + } + + // Define paint method + public void paint(Graphics g) + { + double lamda; + String strAtomSymb; + StringBuffer sbSymbol = new StringBuffer(); + + // Retrieve graphics context for offscreen buffered image + Graphics2D offscreen = offscreenImage.createGraphics(); + + // Set background color for offscreen image + offscreen.setColor(background); +// offscreen.fillRect((int)(0.9 * clippingBounds[0]), (int)(0.9 * clippingBounds[1]), (int)(1.1 * clippingBounds[2]), (int)(1.1 * clippingBounds[3])); + offscreen.fillRect(0, 0, displayWidth, displayHeight); + + // Draw Cartesian coordinate axes + + // Draw bounding rectangles for Cartesian coordinate axes + offscreen.setColor(background); // make boundary lines invisible + + // Set parameters and draw rectangles bounding the three axes + double x_rec, y_rec, w_rec, h_rec; + + // x-axis rectangle + x_rec = x1 + 4; + y_rec = y1 - 4; + w_rec = x2 - x_rec; + h_rec = 7; + + xrec = new Rectangle2D.Double(x_rec, y_rec, w_rec, h_rec); + + // y-axis rectangle + x_rec = x4; + y_rec = y1; + w_rec = (x1 - x4) + 1; + h_rec = (y4 - y1); + + yrec = new Rectangle2D.Double(x_rec, y_rec, w_rec, h_rec); + + // z-axis rectangle + x_rec = x1 - 4; + y_rec = y3 - 2; + w_rec = 7; + h_rec = (y1 - y3) - 6; + + zrec = new Rectangle2D.Double(x_rec, y_rec, w_rec, h_rec); + + // Set font parameters for text + fontName = "Arial"; + fontStyle = Font.BOLD; + fontSize = 11; + font1 = new Font(fontName, fontStyle, fontSize); + + // Set font parameters for bonds + fontSize = 14; + font2 = new Font(fontName, fontStyle, fontSize); + + // Draw bonds between bonded atoms in molecule + + // Set color to be used for bonds + offscreen.setColor(bondColor); + + offscreen.setStroke(new BasicStroke(3)); + + for (i = 0; i < (natoms-1); i++) + { + k1 = 2 * i; + + for (j = (i + 1); j < natoms; j++) + { + k2 = 2 * j; + index = (i * natoms) + j; + + if (bondOrder[index] == 1) + { + lamda = 0.5; + + x11 = displayCoord[k1] + (lamda * atomDiameter); + y11 = displayCoord[k1 + 1] + (lamda * atomDiameter); + x21 = displayCoord[k2] + (lamda * atomDiameter); + y21 = displayCoord[k2 + 1] + (lamda * atomDiameter); + + offscreen.draw(new Line2D.Double(x11, y11, x21, y21)); + } + else if (bondOrder[index] == 2) + { + lamda = 0.33; + + x11 = displayCoord[k1] + (lamda * atomDiameter); + y11 = displayCoord[k1 + 1] + (lamda * atomDiameter); + x21 = displayCoord[k2] + (lamda * atomDiameter); + y21 = displayCoord[k2 + 1] + (lamda * atomDiameter); + + x12 = displayCoord[k1] + ((1 - lamda) * atomDiameter); + y12 = displayCoord[k1 + 1] + ((1 - lamda) * atomDiameter); + x22 = displayCoord[k2] + ((1 - lamda) * atomDiameter); + y22 = displayCoord[k2 + 1] + ((1 - lamda) * atomDiameter); + + offscreen.draw(new Line2D.Double(x11, y11, x21, y21)); + offscreen.draw(new Line2D.Double(x12, y12, x22, y22)); + } + else if (bondOrder[index] == 3) + { + lamda = 0.25; + + x11 = displayCoord[k1] + (lamda * atomDiameter); + y11 = displayCoord[k1 + 1] + (lamda * atomDiameter); + x21 = displayCoord[k2] + (lamda * atomDiameter); + y21 = displayCoord[k2 + 1] + (lamda * atomDiameter); + + x12 = displayCoord[k1] + (0.5 * atomDiameter); + y12 = displayCoord[k1 + 1] + (0.5 * atomDiameter); + x22 = displayCoord[k2] + (0.5 * atomDiameter); + y22 = displayCoord[k2 + 1] + (0.5 * atomDiameter); + + x13 = displayCoord[k1] + ((1 - lamda) * atomDiameter); + y13 = displayCoord[k1 + 1] + ((1 - lamda) * atomDiameter); + x23 = displayCoord[k2] + ((1 - lamda) * atomDiameter); + y23 = displayCoord[k2 + 1] + ((1 - lamda) * atomDiameter); + + offscreen.draw(new Line2D.Double(x11, y11, x21, y21)); + offscreen.draw(new Line2D.Double(x12, y12, x22, y22)); + offscreen.draw(new Line2D.Double(x13, y13, x23, y23)); + } + } + } + + // Set background color + offscreen.setColor(background); + + // Draw bounding rectangles for Cartesian coordinate axes + offscreen.draw(xrec); + offscreen.draw(yrec); + offscreen.draw(zrec); + + offscreen.setStroke(new BasicStroke(2)); + offscreen.setFont(font1); + offscreen.setColor(xaxisColor); + offscreen.draw(new Line2D.Double(x1, y1, x2, y2)); // draw x-axis + offscreen.drawString("x", (int)(x2 + 5), (int)(y2 + 4)); + offscreen.setColor(yaxisColor); + offscreen.draw(new Line2D.Double(x1, y1, x4, y4)); // draw y-axis + offscreen.drawString("y", (int)(x4 - 10), (int)(y4 + 6)); + offscreen.setColor(zaxisColor); + offscreen.draw(new Line2D.Double(x1, y1, x3, y3)); // draw z-axis + offscreen.drawString("z", (int)(x1 - 10),(int)(y3 - 1)); + + + // Order display coordinates so that background atoms are not drawn in front of foreground atoms + // Retrieve y-coordinates of transformed coordinates + transfCoord_y = new double[natoms]; + + for (index = 0; index < natoms; index++) + { + k3 = (3 * index) + 1; + + transfCoord_y[index] = transfCoord[k3]; + displayOrder[index] = index; + } + + // Arrange coordinates in the order in which atoms are to be drawn + for (i = 0; i < (natoms - 1); i++) + { + min = transfCoord_y[i]; + minIndex = displayOrder[i]; + + for (j = (i + 1); j < natoms; j++) + { + if (transfCoord_y[j] < min) + { + min = transfCoord_y[j]; + minIndex = displayOrder[j]; + + transfCoord_y[j] = transfCoord_y[i]; + transfCoord_y[i] = min; + + displayOrder[j] = displayOrder[i]; + displayOrder[i] = minIndex; + } + } + } + + // Draw atoms in molecular structure in proper order + for (j = 0; j < natoms; j++) + { + k = 2 * displayOrder[j]; + + if ((atomColors[displayOrder[j]].getRed() == 255) && (atomColors[displayOrder[j]].getGreen() == 255) && (atomColors[displayOrder[j]].getBlue() == 230)) + { + offscreen.setColor(Color.black); + offscreen.draw(new Ellipse2D.Double(displayCoord[k], displayCoord[k+1], atomDiameter, atomDiameter)); + } + + offscreen.setColor(atomColors[displayOrder[j]]); + offscreen.fill(new Ellipse2D.Double(displayCoord[k], displayCoord[k+1], atomDiameter, atomDiameter)); + + offscreen.setFont(font2); + + // Set text color as black for light-colored atoms and white for dark-colored atoms + if ((atomSymb[displayOrder[j]].equals("Ag")) || (atomSymb[displayOrder[j]].equals("Ar")) || (atomSymb[displayOrder[j]].equals("As")) || (atomSymb[displayOrder[j]].equals("B")) || (atomSymb[displayOrder[j]].equals("Be")) || (atomSymb[displayOrder[j]].equals("Br")) || (atomSymb[displayOrder[j]].equals("C")) || (atomSymb[displayOrder[j]].equals("Cl")) || (atomSymb[displayOrder[j]].equals("Co")) || (atomSymb[displayOrder[j]].equals("Cr")) || (atomSymb[displayOrder[j]].equals("Cu")) || (atomSymb[displayOrder[j]].equals("Fe")) || (atomSymb[displayOrder[j]].equals("Ga")) || (atomSymb[displayOrder[j]].equals("Ge")) || (atomSymb[displayOrder[j]].equals("I")) || (atomSymb[displayOrder[j]].equals("K")) || (atomSymb[displayOrder[j]].equals("Li")) || (atomSymb[displayOrder[j]].equals("Mg")) || (atomSymb[displayOrder[j]].equals("Mn")) || (atomSymb[displayOrder[j]].equals("N")) || (atomSymb[displayOrder[j]].equals("Ni")) || (atomSymb[displayOrder[j]].equals("O")) || (atomSymb[displayOrder[j]].equals("P")) || (atomSymb[displayOrder[j]].equals("Pb")) || (atomSymb[displayOrder[j]].equals("As")) || (atomSymb[displayOrder[j]].equals("Rb")) || (atomSymb[displayOrder[j]].equals("Ru")) || (atomSymb[displayOrder[j]].equals("Sb")) || (atomSymb[displayOrder[j]].equals("Sc")) || (atomSymb[displayOrder[j]].equals("Se")) || (atomSymb[displayOrder[j]].equals("Tc")) || (atomSymb[displayOrder[j]].equals("Xe")) || (atomSymb[displayOrder[j]].equals("Zn")) || (atomSymb[displayOrder[j]].equals("Zr")) ) + { + offscreen.setColor(background); + } + else + { + offscreen.setColor(Color.black); + } + + // Set atom edge displacement factor used to center text over atom + sbSymbol.delete(0, sbSymbol.length()); + sbSymbol.append(atomSymb[displayOrder[j]]); + + if (sbSymbol.length() == 2) + { + if (displayOrder[j] > 9) + { + lamda = 0.10; + } + else + { + lamda = 0.15; + } + } + else + { + if (displayOrder[j] > 9) + { + lamda = 0.15; + } + else + { + lamda = 0.25; + } + } + + strAtomSymb = new String(atomSymb[displayOrder[j]] + Integer.toString(displayOrder[j])); + + offscreen.drawString(strAtomSymb, (int)(displayCoord[k] + (lamda*atomDiameter)), (int)(displayCoord[k+1] + 0.65 * atomDiameter)); + +/////// + } + + // Draw on-screen image + Graphics2D onscreen = (Graphics2D)g; + + onscreen.drawImage(offscreenImage, 0, 0, null); + } + } + + class MyMouseListener extends MouseAdapter + { + int rotAxis; + double rotAngle; + double mx_init; + + public void mouseClicked(MouseEvent e) + { + // Determine number of clicks + if (((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) && (e.getClickCount() == 2)) + { + if (canvas.isRotatable == true) + { + canvas.isRotatable = false; + } + + if (canvas.xrec.contains(e.getX(), e.getY())) + { + canvas.rotAxis = 1; + canvas.rotAngle = Math.PI/2; + canvas.x_rotAngle = 0; + canvas.y_rotAngle = 0; + canvas.z_rotAngle = 0; + + // Get coordinate transformation + canvas.transfCoord = canvas.getTransformedCoordinates(canvas.atomCoord, canvas.natoms, canvas.ncoord, canvas.rotAngle, canvas.rotAxis); + // Get display coordinates + canvas.displayCoord = canvas.getDisplayCoord(canvas.transfCoord, canvas.natoms, canvas.alpha, canvas.displayWidth, canvas.displayHeight); + // Recolor coordinate axes + canvas.xaxisColor = new Color(200, 200, 200); + canvas.yaxisColor = new Color(0, 50, 195); + canvas.zaxisColor = new Color(0, 143, 0); + } + else if (canvas.yrec.contains(e.getX(), e.getY())) + { + canvas.rotAxis = 2; + canvas.rotAngle = 0; + canvas.x_rotAngle = 0; + canvas.y_rotAngle = 0; + canvas.z_rotAngle = 0; + + // Get coordinate transformation + canvas.transfCoord = canvas.getTransformedCoordinates(canvas.atomCoord, canvas.natoms, canvas.ncoord, canvas.rotAngle, canvas.rotAxis); + // Get display coordinates + canvas.displayCoord = canvas.getDisplayCoord(canvas.transfCoord, canvas.natoms, canvas.alpha, canvas.displayWidth, canvas.displayHeight); + // Recolor coordinate axes + canvas.xaxisColor = new Color(200, 0, 25); + canvas.yaxisColor = new Color(200, 200, 200); + canvas.zaxisColor = new Color(0, 143, 0); + } + else if (canvas.zrec.contains(e.getX(), e.getY())) + { + canvas.rotAxis = 3; + canvas.rotAngle = Math.PI/2; + canvas.x_rotAngle = 0; + canvas.y_rotAngle = 0; + canvas.z_rotAngle = 0; + + // Get coordinate transformation + canvas.transfCoord = canvas.getTransformedCoordinates(canvas.atomCoord, canvas.natoms, canvas.ncoord, canvas.rotAngle, canvas.rotAxis); + // Get display coordinates + canvas.displayCoord = canvas.getDisplayCoord(canvas.transfCoord, canvas.natoms, canvas.alpha, canvas.displayWidth, canvas.displayHeight); + // Recolor coordinate axes + canvas.xaxisColor = new Color(200, 0, 25); + canvas.yaxisColor = new Color(0, 50, 195); + canvas.zaxisColor = new Color(200, 200, 200); + } + + // Redraw molecule projected onto the selected 2-dimensional plane + canvas.clippingBounds[0] = 0; canvas.clippingBounds[1] = 0; canvas.clippingBounds[2] = canvas.displayWidth; canvas.clippingBounds[3] = canvas.displayHeight; + canvas.repaint((int)canvas.clippingBounds[0], (int)canvas.clippingBounds[1], (int)canvas.clippingBounds[2], (int)canvas.clippingBounds[3]); + } + else if ((e.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK) + { + // Set molecular image to be rotatable + canvas.isRotatable = true; + + // Retrieve initial x-coordinate of mouse + canvas.mx_init = e.getX(); + + if (canvas.xrec.contains(e.getX(), e.getY())) + { + canvas.rotAxis = 1; + + // Recolor coordinate axes + canvas.xaxisColor = new Color(200, 0, 25); + canvas.yaxisColor = new Color(200, 200, 200); + canvas.zaxisColor = new Color(200, 200, 200); + } + else if (canvas.yrec.contains(e.getX(), e.getY())) + { + canvas.rotAxis = 2; + + // Recolor coordinate axes + canvas.xaxisColor = new Color(200, 200, 200); + canvas.yaxisColor = new Color(0, 50, 195); + canvas.zaxisColor = new Color(200, 200, 200); + } + else if (canvas.zrec.contains(e.getX(), e.getY())) + { + canvas.rotAxis = 3; + + // Recolor coordinate axes + canvas.xaxisColor = new Color(200, 200, 200); + canvas.yaxisColor = new Color(200, 200, 200); + canvas.zaxisColor = new Color(0, 143, 0); + } + + // Redraw coordinate axes + // Set clipping bounds for redrawing coordinate axes + canvas.clippingBounds[0] = 0; canvas.clippingBounds[1] = 0; canvas.clippingBounds[2] = canvas.displayWidth; canvas.clippingBounds[3] = canvas.displayHeight; + canvas.repaint((int)canvas.clippingBounds[0], (int)canvas.clippingBounds[1], (int)canvas.clippingBounds[2], (int)canvas.clippingBounds[3]); + } + } + } + + class MyMouseMotionListener extends MouseMotionAdapter + { + public void mouseDragged(MouseEvent e) + { + double mx_current, del_mx, del_360, rotAngle, del_rotAngle; + double[] currentClippingBounds = new double[4]; + + del_360 = canvas.displayWidth; + + // Retrieve current x-coordinate of mouse + mx_current = e.getX(); + + // Compute corresponding angle at which to rotate molecule + del_mx = mx_current - canvas.mx_init; + + del_rotAngle = 0.07 * ((del_mx / del_360) * (Math.PI/180)); + + // Retrieve current clipping bounds + for (int j = 0; j < 4; j++) + { + currentClippingBounds[j] = canvas.clippingBounds[j]; + } + + // Retrieve initial rotation angle of molecule and update by 'del_rotAngle' + if (canvas.isRotatable == true) + { + if (canvas.rotAxis == 1) + { + canvas.x_rotAngle += del_rotAngle; + + // Get coordinate transformation + canvas.transfCoord = canvas.getTransformedCoordinates(canvas.transfCoord, canvas.natoms, canvas.ncoord, canvas.x_rotAngle, canvas.rotAxis); + // Get display coordinates + canvas.displayCoord = canvas.getDisplayCoord(canvas.transfCoord, canvas.natoms, canvas.alpha, canvas.displayWidth, canvas.displayHeight); + canvas.imageBounds = canvas.getImageBounds(canvas.displayCoord, canvas.natoms); + } + else if (canvas.rotAxis == 2) + { + canvas.y_rotAngle += del_rotAngle; + + // Get coordinate transformation + canvas.transfCoord = canvas.getTransformedCoordinates(canvas.transfCoord, canvas.natoms, canvas.ncoord, canvas.y_rotAngle, canvas.rotAxis); + // Get display coordinates + canvas.displayCoord = canvas.getDisplayCoord(canvas.transfCoord, canvas.natoms, canvas.alpha, canvas.displayWidth, canvas.displayHeight); + canvas.imageBounds = canvas.getImageBounds(canvas.displayCoord, canvas.natoms); + } + else if (canvas.rotAxis == 3) + { + canvas.z_rotAngle += del_rotAngle; + + // Get coordinate transformation + canvas.transfCoord = canvas.getTransformedCoordinates(canvas.transfCoord, canvas.natoms, canvas.ncoord, canvas.z_rotAngle, canvas.rotAxis); + // Get display coordinates + canvas.displayCoord = canvas.getDisplayCoord(canvas.transfCoord, canvas.natoms, canvas.alpha, canvas.displayWidth, canvas.displayHeight); + canvas.imageBounds = canvas.getImageBounds(canvas.displayCoord, canvas.natoms); + } + + // Get clipping bounds for redrawing image + canvas.clippingBounds[0] = 0.70 * canvas.imageBounds[0]; + canvas.clippingBounds[1] = 0.70 * canvas.imageBounds[1]; + canvas.clippingBounds[2] = 1.25 * canvas.imageBounds[2]; + canvas.clippingBounds[3] = 1.25 * canvas.imageBounds[3]; + + // Redraw the molecular image rotated about the selected axis + canvas.repaint((int)(0.70 * currentClippingBounds[0]), (int)(0.70 * currentClippingBounds[1]), (int)(1.25 * currentClippingBounds[2]), (int)(1.25 * currentClippingBounds[3])); + } + } + } + + public void update(Graphics g) + { + paint(g); + } + + public static void main(String[] args) + { + new BufferedDisplayMolecule(); + } +} + diff --git a/src/main/java/g03input/ColorTheme.java b/src/main/java/g03input/ColorTheme.java new file mode 100644 index 0000000..ed29825 --- /dev/null +++ b/src/main/java/g03input/ColorTheme.java @@ -0,0 +1,100 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Mar 29, 2005 + * @author Michael Sheetz + * @author Shashank Jeedigunta @author Sandeep Kumar Seethaapathy + * + */ + +package g03input; + +import javax.swing.plaf.ColorUIResource; +import javax.swing.plaf.metal.DefaultMetalTheme; + +/** + * @author Shashank Jeedigunta + * + * TODO To change the template for this generated type comment go to + * Window - Preferences - Java - Code Style - Code Templates + */ +public class ColorTheme extends DefaultMetalTheme +{ + /* + private final ColorUIResource primary1 = + new ColorUIResource(0x0, 0x33, 0x99); + + private final ColorUIResource primary2 = + new ColorUIResource(0xD0, 0xDD, 0xFF); + private final ColorUIResource primary3 = + new ColorUIResource(0x0, 0x99, 0xFF); + + private final ColorUIResource secondary1 = + new ColorUIResource(0x6F, 0x6F, 0x6F); + private final ColorUIResource secondary2 = + new ColorUIResource(0x9F, 0x9F, 0x9F); + private final ColorUIResource secondary3 = + new ColorUIResource(0x1f, 0x7f, 0xDC); + */ + + + + private final ColorUIResource primary3 = new ColorUIResource(0xD9, 0xD9, 0xAA); + private final ColorUIResource primary2 = new ColorUIResource(0xFF, 0xFF, 0xF0); + private final ColorUIResource primary1 = new ColorUIResource(69, 69, 33); //new ColorUIResource(0xF0, 0xF0, 0xE0); + + private final ColorUIResource secondary1 = new ColorUIResource(0x6F, 0x6F, 0x6F); + private final ColorUIResource secondary2 = new ColorUIResource(0x9F, 0x9F, 0x9F); + private final ColorUIResource secondary3 = new ColorUIResource(236,233,216);//new ColorUIResource(0xDD, 0xDD, 0xCC); + + + + // the functions overridden from the base + // class => DefaultMetalTheme + + protected ColorUIResource getPrimary1() { return primary1; } + protected ColorUIResource getPrimary2() { return primary2; } + protected ColorUIResource getPrimary3() { return primary3; } + + protected ColorUIResource getSecondary1() { return secondary1; } + protected ColorUIResource getSecondary2() { return secondary2; } + protected ColorUIResource getSecondary3() { return secondary3; } + + + +} diff --git a/src/main/java/g03input/FreqOptTable.java b/src/main/java/g03input/FreqOptTable.java new file mode 100644 index 0000000..9ca8484 --- /dev/null +++ b/src/main/java/g03input/FreqOptTable.java @@ -0,0 +1,486 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Mar 21, 2005 + * @author Michael Sheetz + * @author Sandeep Kumar Seethaapathy @author Shashank Jeedigunta + * + */ + +package g03input; + + +import javax.swing.*; +import javax.swing.event.TableModelEvent; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableCellRenderer; +import java.awt.*; +import java.awt.event.*; +import java.util.Vector; + +class RadioButtonRenderer implements TableCellRenderer { + public Component getTableCellRendererComponent(JTable table, Object value, + boolean isSelected, boolean hasFocus, int row, int column) { + if (value==null) return null; + return (Component)value; + } +} + +class RadioButtonEditor extends DefaultCellEditor + implements ItemListener { + + public static JRadioButton button; + public RadioButtonEditor(JCheckBox checkBox) { + super(checkBox); + + } + + public Component getTableCellEditorComponent(JTable table, Object value, + boolean isSelected, int row, int column) { + if (value==null) return null; + button = (JRadioButton)value; + System.out.println(row); + G03MenuTree.freOptString=button.getActionCommand(); + System.out.println("sasa"+ value.toString()); + //InsertNode.insertNode("Jo",G03MenuTree.freOptString); + button.addItemListener(this); + System.out.println((Component)value); + System.out.println(value.getClass()); + return (Component)value; + } + + public Object getCellEditorValue() { + button.removeItemListener(this); + return button; + } + + public void itemStateChanged(ItemEvent e) { + + super.fireEditingCanceled(); + + } +} + +public class FreqOptTable extends JFrame implements ItemListener,ActionListener{ +public static JFrame freqOptFrame; +Color bgColor= new Color(236,233,216); +Color foreColor =new Color(0,78,152); +JPanel donePanel; +JButton doneButton,clearButton,exitButton; +public static JTable table; +public static int freqOptCount; +public static int opop; +public static Vector freqOpt; +public static String[] archiveFreq; +public static JTextField stepField; +public static int freqFlag,freqC,freqOptC; + String stepSel; + + + +// List of all JButton in FreqTable + public static JRadioButton FRaman= new JRadioButton("Raman"); + + public static JRadioButton FReadf = new JRadioButton("ReadFC"); + public static JRadioButton FHpmod = new JRadioButton("HPModes"); + public static JRadioButton FAnaly = new JRadioButton("Analytic"); + public static JRadioButton FProje = new JRadioButton("Projected"); + public static JRadioButton FNrama = new JRadioButton("NRaman"); + public static JRadioButton FReada = new JRadioButton("ReadAnharm"); + public static JRadioButton FIntmo = new JRadioButton("IntModes"); + public static JRadioButton FNumer = new JRadioButton("Numerical"); + public static JRadioButton FHinde = new JRadioButton("Hindered Rotor"); + public static JRadioButton FNnram = new JRadioButton("NNRaman"); + public static JRadioButton FModre = new JRadioButton("ModRedundant"); + public static JRadioButton FEnonl = new JRadioButton("EnOnly"); + public static JRadioButton FNoram = new JRadioButton("NoRaman"); + public static JRadioButton FReadi = new JRadioButton("ReadIsotopes"); + public static JRadioButton FCubic = new JRadioButton("Cubic"); + public static JRadioButton FVcd = new JRadioButton("VCD"); + public static JRadioButton FResta = new JRadioButton("Restart"); + public static JRadioButton FStep = new JRadioButton("Step=N"); + public static JRadioButton FVibro = new JRadioButton("VibRot"); + public static JRadioButton FAnhar = new JRadioButton("Anharmonic"); + public static Vector freqClear; +public FreqOptTable(){ + super("Options for Freq"); + if(opop==0) + { + freqClear=new Vector(30); + freqClear.addElement(FRaman); + freqClear.addElement(FReadf); + freqClear.addElement(FHpmod); + freqClear.addElement(FAnaly); + freqClear.addElement(FProje); + freqClear.addElement(FNrama); + freqClear.addElement(FReada); + freqClear.addElement(FIntmo); + freqClear.addElement(FNumer); + freqClear.addElement(FHinde); + freqClear.addElement(FNnram); + freqClear.addElement(FModre); + freqClear.addElement(FEnonl); + freqClear.addElement(FNoram); + freqClear.addElement(FReadi); + freqClear.addElement(FCubic); + freqClear.addElement(FVcd); + freqClear.addElement(FResta); + //freqClear.addElement(FStep); + freqClear.addElement(FVibro); + freqClear.addElement(FAnhar); + + FRaman.addItemListener(this); + FRaman.setBackground(Color.WHITE); + FReadf.addItemListener(this); + FReadf.setBackground(Color.WHITE); + FHpmod.setBackground(Color.WHITE); + FHpmod.addItemListener(this); + FAnaly.setBackground(Color.WHITE); + FAnaly.addItemListener(this); + FProje.setBackground(Color.WHITE); + FProje.addItemListener(this); + FNrama.setBackground(Color.WHITE); + FNrama.addItemListener(this); + FReada.setBackground(Color.WHITE); + FReada.addItemListener(this); + FIntmo.setBackground(Color.WHITE); + FIntmo.addItemListener(this); + FNumer.setBackground(Color.WHITE); + FNumer.addItemListener(this); + FHinde.setBackground(Color.WHITE); + FHinde.addItemListener(this); + FNnram.setBackground(Color.WHITE); + FNnram.addItemListener(this); + FModre.setBackground(Color.WHITE); + FModre.addItemListener(this); + FEnonl.setBackground(Color.WHITE); + FEnonl.addItemListener(this); + FNoram.setBackground(Color.WHITE); + FNoram.addItemListener(this); + FReadi.setBackground(Color.WHITE); + FReadi.addItemListener(this); + FCubic.setBackground(Color.WHITE); + FCubic.addItemListener(this); + FVcd.setBackground(Color.WHITE); + FVcd.addItemListener(this); + FResta.setBackground(Color.WHITE); + FResta.addItemListener(this); + FStep.setBackground(Color.WHITE); + FStep.addItemListener(this); + FVibro.setBackground(Color.WHITE); + FVibro.addItemListener(this); + FAnhar.setBackground(Color.WHITE); + FAnhar.addItemListener(this); + + opop=1; + } + System.out.println(opop); + System.out.println("WQWQWQ"); + JFrame.setDefaultLookAndFeelDecorated(true); + + freqOptFrame = new JFrame("Options for Freq"); + freqOptFrame.setBackground(bgColor); + freqOptFrame.setForeground(foreColor); + DefaultTableModel dm = new DefaultTableModel(); + dm.setDataVector( + new Object[][]{ + {FRaman,FReadf,FHpmod,FAnaly,FProje}, + {FNrama,FReada,FIntmo,FNumer,FHinde}, + {FNnram,FModre,null,FEnonl,null}, + {FNoram,FReadi,null,FCubic,null}, + {FVcd,FResta,null,FStep,null}, + {FVibro,null,null,null,null}, + {FAnhar,null,null,null,null}}, + new Object[]{"Frequency and Intensity","Data Input","Output","Numerical Differentiation","Additional Options"}); + + table = new JTable(dm) { + public void tableChanged(TableModelEvent e) { + + super.tableChanged(e); + repaint(); + + } + }; + + table=new JTable(dm); + + + + + table.getColumn("Frequency and Intensity").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Frequency and Intensity").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + table.getColumn("Data Input").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Data Input").setCellEditor(new RadioButtonEditor(new JCheckBox())); + table.getColumn("Output").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Output").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + table.getColumn("Numerical Differentiation").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Numerical Differentiation").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + table.getColumn("Additional Options").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Additional Options").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + donePanel = new JPanel(); + doneButton = new JButton("Done"); + // clearButton = new JButton("Clear"); + exitButton = new JButton("Exit"); + doneButton.addActionListener(this); + // clearButton.addActionListener(this); + exitButton.addActionListener(this); + + + donePanel.add(doneButton); + //donePanel.add(clearButton); + donePanel.add(exitButton); + + + donePanel.setBackground(bgColor); + donePanel.setForeground(foreColor); + + + table.getTableHeader().setReorderingAllowed(false); + freqOptFrame.getContentPane().setLayout(new BorderLayout()); + JScrollPane scroll = new JScrollPane(table); + freqOptFrame.getContentPane().add( scroll,BorderLayout.CENTER); + freqOptFrame.getContentPane().add(donePanel,BorderLayout.SOUTH); + freqOptFrame.setSize( 600,200); + freqOptFrame.setLocation(200,75); + freqOptFrame.setVisible(true); + + + } + + +public void actionPerformed(ActionEvent e) +{ + if(e.getSource()==doneButton) + { + + System.out.println("The value of freq Flagv = "+freqC); + if(RouteClass.initCount==0) + { + System.out.println(RouteClass.initCount+" \tInside init"); + RouteClass.initBuffer(); + RouteClass.initCount++; + } + if(freqC==0) + { + + + System.out.println(freqC+" \t Inside freQC"); + freqFlag=RouteClass.keyIndex; + RouteClass.keyIndex++; + freqC++; + } + else + { + //System.out.println("Reinitialize"); + RouteClass.keywordBuffer[freqFlag]=new StringBuffer(); + } + RouteClass.keywordBuffer[freqFlag].append("Freq"); + if(!(InsertNode.nodeExists("Freq"))) + InsertNode.insertNode("Job","Freq"); + try { + if(freqOpt.size()>1) + { + RouteClass.keywordBuffer[freqFlag].append("=("); + for(int count=0;count0) + RouteClass.keywordBuffer[freqFlag].append("="+"("+freqOpt.get(0)+")"); + } + } + catch (NullPointerException e1) { + // TODO Auto-generated catch block + //e1.printStackTrace(); + } + //freqFlag=RouteClass.keyIndex; + //RouteClass.keyIndex++; + RouteClass.writeRoute(); + freqOptFrame.dispose(); + System.out.println("Has focus" +table.hasFocus()); + } + if(e.getSource()==exitButton) + { + freqOptFrame.dispose(); + + } + } + +public void itemStateChanged(ItemEvent e) + { + System.out.println("chaeck"); + if((e.getItem()==FRaman)||(e.getItem()==FReadf)|| (e.getItem()==FHpmod)|| + (e.getItem()==FAnaly)|| (e.getItem()==FProje)|| (e.getItem()==FNrama)|| + (e.getItem()==FReada)|| (e.getItem()==FIntmo)|| (e.getItem()==FNumer)|| + (e.getItem()==FHinde)|| (e.getItem()==FNnram)|| (e.getItem()==FModre)|| + (e.getItem()==FEnonl)|| (e.getItem()==FNoram)|| (e.getItem()==FReadi)|| + (e.getItem()==FCubic)|| (e.getItem()==FVcd)|| (e.getItem()==FResta)|| + (e.getItem()==FVibro)||(e.getItem()==FAnhar)) + { + + System.out.println("Coming here"); + if(((JRadioButton)e.getItem()).isSelected()) + { + G03Listener.freqTabF++; + System.out.println("Comin in"); + if(freqOptC==0) + { + freqOpt = new Vector(10); + freqOptC++; + } + System.out.println("\n Item get: = \t "+ RadioButtonEditor.button.getActionCommand()); + if(!(InsertNode.nodeExists("Freq"))) + InsertNode.insertNode("Job","Freq"); + InsertNode.insertNode("Freq", RadioButtonEditor.button.getActionCommand()); + ((JRadioButton)e.getItem()).setEnabled(true); + String freqs = RadioButtonEditor.button.getActionCommand(); + freqOpt.addElement(freqs); + freqOptCount++; + } + else + { + if(InsertNode.nodeExists(((JRadioButton)e.getItem()).getActionCommand())) + InsertNode.deleteNode(((JRadioButton)e.getItem()).getActionCommand()); + freqOpt.removeElement(((JRadioButton)e.getItem()).getActionCommand()); + + } + } + + if((e.getItem()==FStep)) + { + + if(freqOptC==0) + { + G03Listener.freqTabF++; + freqOpt = new Vector(10); + freqOptC++; + } + stepField=new JTextField(3); + stepField.setSize(2,1); + if(((JRadioButton)e.getItem()).isSelected()) + { + //POP UP A FRAME TO GET 'N' + //JTextField stepField; + JPanel txt; + txt = new JPanel(new FlowLayout()); + System.out.println("OOO"); + //stepField = new JTextField(3); + stepField.setSize(2,1); + Object[] obj = new Object[2]; + obj[0] = " Use Step-size of 0.0001N Angstroms "; + JLabel s = new JLabel("for Numerical differentiation with N="); //+stepField; + txt.add(s); + txt.add(stepField); + obj[1] = txt; + int ch= JOptionPane.showConfirmDialog(null,obj,"Option Step=N",JOptionPane.OK_OPTION); + if(ch==0) + { + if(!(InsertNode.nodeExists("Freq"))) + {InsertNode.insertNode("Job","Freq"); + } + //Delete Existing node and then add it + if((InsertNode.nodeExists("Step"))) + { + InsertNode.deleteNode("Step="); + } + InsertNode.insertNode("Freq","Step="+stepField.getText()); + stepSel=new String(); + stepSel=stepField.getText(); + String sa = new String(); + sa = "Step="+stepField.getText(); + freqOpt.addElement(sa); + //freqOptCount++; + } + if(ch==1) // pressed no remove step + { + if((InsertNode.nodeExists("Step"))) + { + //Delete Node if exists + InsertNode.deleteNode("Step"); + } + + } + + } + else + { + if((InsertNode.nodeExists("Step="+stepSel))) + InsertNode.deleteNode("Step"); + + freqOpt.removeElement("Step="+stepSel); + } + } + + + } +public static void addListeners() +{ + FRaman.addItemListener(new FreqOptTable()); + FReadf.addItemListener(new FreqOptTable());FHpmod.addItemListener(new FreqOptTable()); + FAnaly.addItemListener(new FreqOptTable()); + FProje.addItemListener(new FreqOptTable());FNrama.addItemListener(new FreqOptTable());FReada.addItemListener(new FreqOptTable()); + FIntmo.addItemListener(new FreqOptTable()); + FNumer.addItemListener(new FreqOptTable());FHinde.addItemListener(new FreqOptTable());FNnram.addItemListener(new FreqOptTable()); + FModre.addItemListener(new FreqOptTable());FEnonl.addItemListener(new FreqOptTable());FNoram.addItemListener(new FreqOptTable()); + FReadi.addItemListener(new FreqOptTable());FCubic.addItemListener(new FreqOptTable());FVcd.addItemListener(new FreqOptTable()); + FResta.addItemListener(new FreqOptTable());FStep.addItemListener(new FreqOptTable());FVibro.addItemListener(new FreqOptTable()); + FAnhar.addItemListener(new FreqOptTable()); +// +} + public static void main(String[] args) { + FreqOptTable frame = new FreqOptTable(); + frame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + System.exit(0); + } + }); + } + +} diff --git a/src/main/java/g03input/G03Listener.java b/src/main/java/g03input/G03Listener.java new file mode 100644 index 0000000..c0c191b --- /dev/null +++ b/src/main/java/g03input/G03Listener.java @@ -0,0 +1,552 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Apr 10, 2005 + * @author Michael Sheetz + * @author Sandeep Kumar Seethaapathy @author Shashank Jeedigunta + * + */ + + + +package g03input; + +import javafx.application.Platform; +import legacy.editor.commons.Settings; +import org.seagrid.desktop.util.messaging.SEAGridEvent; +import org.seagrid.desktop.util.messaging.SEAGridEventBus; + +import javax.swing.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + + + + +//import GridChem.legacy.editors.commons.Settings; + + +public class G03Listener implements ActionListener,KeyListener{ + JTextField fileNameText; + public static int optTabF,freqTabF,guessTabF,geomTabF,popTabF,pbcTabF; //Flags for the tables + public void actionPerformed(ActionEvent ae) + { + + if(ae.getSource()==G03MenuTree.viewMolStructure) + { + //G03MenuTree.molCharge.setText("charge"); + //G03MenuTree.molMultiplicity.setText("Multiplicity"); + //Try writing a flag that will set if the user uses an exported molecular structure fromNanocad + try { + if(InputFile.inputfetched==1) + showMolEditor.tempmol=InputfileReader.geom; + /* + if(showMolEditor.nanoFlag==1) + showMolEditor.tempmol=showMolEditor.exportedMol; */ + } catch (RuntimeException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + new showMolEditor(); + showMolEditor.molFrame.setVisible(true); + } + /* + if(ae.getSource()== G03MenuTree.nanoItem){ + showMolEditor.doCallNanocad(); + showMolEditor.molFrame.dispose(); + }*/ + + + if(ae.getSource()==G03MenuTree.doneButton) + { + if(!Settings.authenticated) + { + JOptionPane.showMessageDialog(null,"You are not authenticated to use this feature.\nPlease sign in to GridChem to use this feature." , "Access restriction", JOptionPane.ERROR_MESSAGE); + return; + } + showMolEditor.nanoFlag=0; + RouteClass.createInput(); + // change routeBuffer to inputfile string once it is done + + //Copied From SubmitJobsWindow.java + if(RouteValidator.validateRoute()) + { + /*if(legacy.editors.commons.Settings.authenticatedSSH == true) + { + // GridChem.editSSHJobPanel ejp= new GridChem.editSSHJobPanel(-1); + } + else + {*/ + + new InputfileReader(); + int charge, mul, noofelectrons=0,nproc=0,nmem=0; + boolean evenTotalElectrons, evenMultiplicity,validStructure; + charge= InputfileReader.charge; + mul= InputfileReader.spinmult; + + nproc=InputfileReader.nproc; + nmem=InputfileReader.mbRequested; + System.out.println("Length of the Route is #"+ InputfileReader.route.length()+ "and" + + "route is "+InputfileReader.route); + if(InputfileReader.route.length() < 2) + { + JOptionPane.showMessageDialog(null,"Route Section is incomplete","ERROR",JOptionPane.ERROR_MESSAGE); + } + else if(InputfileReader.chrgStr==null || InputfileReader.mulStr==null) + { + JOptionPane.showMessageDialog(null,"Charge or Multiplicity cannot be empty","ERROR",JOptionPane.ERROR_MESSAGE); + } + + else{ + + MolEditorHelp.hashFunction(); + if(GeometryEditor.GeometryReader.atomSymb !=null) + for(int k=0;k { + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType + .EXPORT_GAUSSIAN_EXP, InputFile.tempinput)); + }); + G03MenuTree.mainFrame.dispose(); + }// valid structure is true + + } // else part of noofelectrons=0 + } // else for route + + //} + }//Route Validate + + + + } + if(ae.getSource()==G03MenuTree.clearButton) + { + clearButtonFn(); + } + if (ae.getSource()== G03MenuTree.saveButton) + { + RouteClass.createInput(); + new InputfileReader(); + JFileChooser chooser = new JFileChooser(); + chooser.setDialogTitle("Save as Guassian Input file"); + + int retVal = chooser.showSaveDialog(null); + try + { + if (retVal == JFileChooser.APPROVE_OPTION) + { + File file = chooser.getSelectedFile(); + // save the file data + FileWriter fw = new FileWriter(file); + new InputfileReader(); + String outp = InputFile.tempinput; + System.out.println("*************"); + System.out.println(InputFile.tempinput); + fw.write(outp); + fw.close(); +// changeFileName(file.getName()); + //changeFileName(file.getAbsolutePath()); + /* + String filename = file.getName(); + if (filename.indexOf(".")!=-1) + filename = filename + ".inp"; + + File fileRenamed = new File(filename); + file.renameTo(fileRenamed); + */ + } + } + catch (IOException e) + { + JOptionPane.showMessageDialog(null, "Error writing to file", + "Save File Error", JOptionPane.INFORMATION_MESSAGE); + } + } + if(ae.getSource()==G03MenuTree.dontsave) + { + G03MenuTree.filnamArea.setEditable(true); + } + if(ae.getSource()==G03MenuTree.exitButton) + { + int ch; + ch=JOptionPane.showConfirmDialog(null,"Are you sure?","Exit from Gaussian09 GUI",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE); + if(ch==0) + { + try { + + + if(G03MenuTree.mainFrame != null) + { + G03MenuTree.mainFrame.dispose(); + G03MenuTree.mainFrame = null; + } + +// FIXME-SEAGrid +// else if(stuffInside.mainFrame != null) +// { +// stuffInside.mainFrame.dispose(); +// stuffInside.mainFrame = null; +// } +// else if(optsComponent.mainFrame != null) +// { +// optsComponent.mainFrame.dispose(); +// optsComponent.mainFrame = null; +// } + + + } catch (NullPointerException ex) { + System.out.println(ex); + + } + } + else + { + + } + } + + + + + + + } + public void changeFileName(String f) { + // this.fileNameText = new JTextField(f); + fileNameText.selectAll(); + fileNameText.replaceSelection(f); + // fileNameText.append(f); + } + public void keyTyped(KeyEvent ke) + + { + + G03MenuTree.dontsave.setSelected(true); + } + + public void keyPressed(KeyEvent ke) + { + + } + public void keyReleased(KeyEvent ke) + { + + } + + + + + public static void clearButtonFn() + { + try + { + + System.out.println("Clear"); + InsertNode.deleteChildren("Met"); + InsertNode.deleteChildren("Basis"); + InsertNode.deleteChildren("Jo"); + InsertNode.deleteChildren("Key"); + + if(G03Listener.optTabF>0) + { + for(int h=0;h0) + { + for(int h=0;h< FreqOptTable.freqClear.size();h++) + { + if(((JRadioButton)(FreqOptTable.freqClear.get(h))).isSelected()) + { + System.out.println("Inside Freq clear button"); + ((JRadioButton)(FreqOptTable.freqClear.get(h))).setSelected(false); + FreqOptTable.freqOpt.removeElement((FreqOptTable.freqClear.get(h))); + } + + } + + + if(FreqOptTable.FStep.isSelected()) + { + FreqOptTable.FStep.setSelected(false); + } + FreqOptTable.freqC=0; + FreqOptTable.freqOptC=0; + //FreqOptTable.opop=0; + } + System.out.println("Whether it comes here"); + + if(G03Listener.guessTabF>0) + { + for(int h=0;h0) + { +for(int h=0;h0) + { + for(int j=0;j<8;j++) + { + + + pbcTable.pbcOptions[j].setSelected(false); + pbcTable.selectedIndex[j]=0; + pbcTable.initValues[j]=""; + + } + } + +System.out.println("after PBC"); + + if(G03Listener.geomTabF>0) + { + for(int h=0;hRedesigned Panels + + // Function for getting the linko parameters + void createLinkoPanel() { + noofspLabel = new JLabel("%nproc"); + nooflpLabel = new JLabel("%lproc"); + dynmemLabel = new JLabel("%mem(in MB)"); + filnamLabel = new JLabel("CheckPoint File "); + + + noofspText = new JTextField(5); + nooflpText = new JTextField(5); + dynmemText = new JTextField(5); + filnamArea = new JTextArea(); + + linkoPanel = new JPanel(); + TitledBorder linkTitle = new TitledBorder("LinkO Section"); + linkoPanel.setBorder(linkTitle); + + linkoPanel.setLayout(new BorderLayout()); + + linkDiv1 = new JPanel(); //linkDiv1 contains the memory and processor requirements fields + linkDiv1.setLayout(new FlowLayout()); + linkDiv1.add(noofspLabel); + linkDiv1.add(noofspText); + linkDiv1.add(nooflpLabel); + linkDiv1.add(nooflpText); + linkDiv1.add(dynmemLabel); + linkDiv1.add(dynmemText); + + linkDiv2 = new JPanel(); + linkDiv2.setLayout(new BorderLayout()); + linkDiv2.add(filnamLabel, BorderLayout.WEST); + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + //mainFrame.setSize(screenSize.width-20,screenSize.height-100); + screenWidth = screenSize.width - 200; + screenHeight = screenSize.height - 150; + System.out.println(screenWidth + "Height\t" + screenHeight); + + filnamArea.setPreferredSize(new Dimension(screenWidth / 2, screenHeight / 20)); + filnamArea.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1)); + linkDiv2.add(filnamArea, BorderLayout.CENTER); + + linkoPanel.add(linkDiv1, BorderLayout.NORTH); + linkoPanel.add(linkDiv2, BorderLayout.SOUTH); + + } + + // Function for showing the Route Section + void createRoutePanel() { + routePanel = new JPanel(new BorderLayout()); + TitledBorder routeTitle = new TitledBorder("Route Section"); + routePanel.setBorder(routeTitle); + + JPanel optionPanel = new JPanel();//(new BorderLayout()); + + nRadio = new JRadioButton("Use #N"); + pRadio = new JRadioButton("Use #P"); + tRadio = new JRadioButton("Use #T"); + + routeChoice = new ButtonGroup(); + + routeChoice.add(nRadio); + routeChoice.add(pRadio); + routeChoice.add(tRadio); + + nRadio.addActionListener(new RouteClass()); + pRadio.addActionListener(new RouteClass()); + tRadio.addActionListener(new RouteClass()); + + //Default selection is #N + nRadio.setSelected(true); + + //Add the choices to the optionPanel + optionPanel.add(nRadio);//,BorderLayout.EAST); + optionPanel.add(pRadio);//,BorderLayout.CENTER); + optionPanel.add(tRadio);//,BorderLayout.WEST); + + //Create Route Area + routeArea = new JTextArea(); + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + //mainFrame.setSize(screenSize.width-20,screenSize.height-100); + screenWidth = screenSize.width - 200; + screenHeight = screenSize.height - 150; + System.out.println(screenWidth + "Height\t" + screenHeight); + + // routeArea.setPreferredSize(new Dimension(screenWidth-40,screenHeight/8)); + routeArea.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 0)); + routeArea.setText("#"); + routeArea.setAutoscrolls(true); + //RouteArea cannot be Edited manually... + routeArea.setEditable(false); + routeArea.setLineWrap(true); + routeArea.setRows(3); + + routeArea.setToolTipText("Route Section appears here.The contents cannot be manually altered." + + "
Remove the child nodes from the Tree appearing on the Left side to delete a particular option"); + JScrollPane scrpane = new JScrollPane(routeArea); + scrpane.setAutoscrolls(true); + //scrpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); + //scrpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + System.out.println("Scrollpane visible??"); + // scrpane.setVisible(true); + + /* + //It is a dummy panel, it does nothing + JPanel dpanel=new JPanel(); + JLabel lbl= new JLabel("Route Section cannot be modified"); + Color c = dpanel.getBackground(); + lbl.setForeground(c); + dpanel.add(lbl); + */ + + routePanel.add(optionPanel, BorderLayout.NORTH); + routePanel.add(scrpane, BorderLayout.CENTER); + //routePanel.add(dpanel,BorderLayout.SOUTH); + } + + // Function that takes care of the Job title + void createJobtitlePanel() { + + jobArea = new JTextArea(); + jobArea.setText("default_job"); + jobArea.setToolTipText("Enter the title and description of the Job"); + jobNamePanel = new JPanel(new BorderLayout()); + TitledBorder jobPanelTitle = new TitledBorder("Job Title & Description"); + jobNamePanel.setBorder(jobPanelTitle); + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + //mainFrame.setSize(screenSize.width-20,screenSize.height-100); + screenWidth = screenSize.width - 200; + screenHeight = screenSize.height - 150; + + //dpanel is a dummy panel, it does nothing + /* + JPanel dpanel=new JPanel(); + JLabel lbl= new JLabel("Job Title"); + Color c = dpanel.getBackground(); + lbl.setForeground(c); + dpanel.add(lbl); + + dpanel.setMinimumSize(new Dimension(screenWidth-80,screenHeight/12)); + dpanel.setEnabled(false); + //dpanel.setVisible(false); + */ + System.out.println(screenWidth + "Height\t" + screenHeight); + //jobArea.setPreferredSize(new Dimension(screenWidth-80,screenHeight/12)); + + jobArea.setAutoscrolls(true); + + jobArea.setLineWrap(true); + jobArea.setRows(2); + + jobArea.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1)); + + JScrollPane scrpane = new JScrollPane(jobArea); + scrpane.setAutoscrolls(true); + + + jobNamePanel.add(scrpane, BorderLayout.CENTER); + // jobNamePanel.add(dpanel,BorderLayout.SOUTH); + + } + + // Function for getting Charge and Multiplicity + void createMolPanel() { + //This Panel holds the Charge and Multiplicity of the Molecular specification + JLabel chargeLabel, multiplicityLabel; + chargeLabel = new JLabel("Charge"); + multiplicityLabel = new JLabel("Multiplicity"); + molCharge = new JTextField(5); + molCharge.setToolTipText("Enter the Charge here"); + molMultiplicity = new JTextField(5); + molMultiplicity.setToolTipText("Enter the Multiplicity here"); + viewMolStructure = new JButton("View/Edit Structure"); + viewMolStructure.setToolTipText("Click to View the Current Molecular Structure"); + molPanel = new JPanel(new BorderLayout()); + JPanel mainMolPanel = new JPanel(); + JPanel nanocadLabelPanel = new JPanel(); + + TitledBorder molTitle = new TitledBorder("Molecular Specification"); + molPanel.setBorder(molTitle); + mainMolPanel.add(chargeLabel); + mainMolPanel.add(molCharge); + mainMolPanel.add(multiplicityLabel); + mainMolPanel.add(molMultiplicity); + mainMolPanel.add(viewMolStructure); + + + nanocadNotice.setText("Molecular Specification not selected"); + nanocadLabelPanel.add(nanocadNotice); + + molPanel.add(nanocadLabelPanel, BorderLayout.SOUTH); + molPanel.add(mainMolPanel, BorderLayout.CENTER); + + viewMolStructure.addActionListener(new G03Listener()); + } + + void createOtherPanel() { + importFile = new JButton("Fetch Input"); + editFile = new JButton("Edit File"); + importFile.addActionListener(new InputFile()); + editFile.addActionListener(new InputFile()); + otherItemsPanel = new JPanel(); + TitledBorder otherOptions = new TitledBorder("Input File Options"); + otherItemsPanel.setBorder(otherOptions); + otherItemsPanel.add(importFile); + otherItemsPanel.add(editFile); + + } + + void createhelpPanel() { + helpDonePanel = new JPanel(); + TitledBorder help = new TitledBorder("Help Section"); + helpDonePanel.setBorder(help); + + doneButton = new JButton("Done & Export"); + doneButton.addActionListener(new G03Listener()); + saveButton = new JButton("Save as File"); + saveButton.addActionListener(new G03Listener()); + clearButton = new JButton("CLEAR"); + clearButton.setEnabled(false); + clearButton.addActionListener(new G03Listener()); + exitButton = new JButton("EXIT"); + exitButton.addActionListener(new G03Listener()); + + helpDonePanel.setLayout(new BorderLayout()); + + helpSection = new JPanel(); + //keyoptArea=new JTextPane(); + keyoptArea = new JEditorPane(); + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + //mainFrame.setSize(screenSize.width-20,screenSize.height-100); + screenWidth = screenSize.width - 200; + screenHeight = screenSize.height - 150; + System.out.println(screenWidth + "Height\t" + screenHeight); + + keyoptArea.setPreferredSize(new Dimension(screenWidth - 40, screenHeight / 12)); + keyoptArea.setBackground(Color.WHITE); + Font helpFont = new Font("Garamond", Font.BOLD, 14); + keyoptArea.setFont(helpFont); + htmlKit = new HTMLEditorKit(); + keyoptArea.setEditorKit(htmlKit); + htmlDoc = new HTMLDocument(); + keyoptArea.setDocument(htmlDoc); + //keyoptArea.setStyledDocument(htmlDoc); + //StyledDocument doc = keyoptArea.getStyledDocument(); + //addStylesToDocument(doc); + + //Added June 28'05 + //Content type is set to display html data so that superscripts can be accommodated. + keyoptArea.setContentType("text/html"); + try { + //insertHTML(keyoptArea,"Use Shift + Left Click to modify the Tree that displays the Input selections.",0); + insertHTML(keyoptArea, "Use Shift + Left Click to modify the Tree that displays the Input selections."); + insertHTML(keyoptArea, otherKeyToolTip.molecularTip); + insertHTML(keyoptArea, otherKeyToolTip.molTip); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (BadLocationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + //keyoptArea.setText("Use Shift + Left Click to modify the Tree that displays the Input selections."); + keyoptArea.setToolTipText("Help notes for Input File Selection appears here"); + + keyoptArea.setEditable(false); + JScrollPane scrollPane; + scrollPane = new JScrollPane(keyoptArea); + + buttonPanel = new JPanel(); + buttonPanel.add(doneButton); + buttonPanel.add(saveButton); + buttonPanel.add(clearButton); + buttonPanel.add(exitButton); + + helpSection.add(scrollPane); + keyoptArea.setAutoscrolls(true); + + helpDonePanel.add(helpSection, BorderLayout.CENTER); + helpDonePanel.add(buttonPanel, BorderLayout.SOUTH); + + + } + + // Function for Showing the Molecule and Tree together + void createSplitPanel() { + //molBrowser=new JPanel(); + molBrowser.setMinimumSize(new Dimension(250, 250)); + System.out.println(atomCoordinateParser.atomIndex); + //if(atomCoordinateParser.atomIndex!=0){ + //new DisplayMolecule(); + //JComponent(DisplayMolecule.canvas); + //molBrowser.add(DisplayMolecule.container); + //} + + verticalSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, treeScroll, molBrowser); + verticalSplit.setContinuousLayout(true); + verticalSplit.setOneTouchExpandable(true); + + } + + + public void createtreePanel() { + root = + new DefaultMutableTreeNode("G '09 Input Selections"); + + for (int i = 0; i < key_words.length; i++) { + child = new DefaultMutableTreeNode(key_words[i]); + root.add(child); + /* for(int j=0;j<5;j++) + { + grandChild=new DefaultMutableTreeNode(options[i][j]); + child.add(grandChild); + } + */ + } + + tree = new JTree(root); + tree.setEditable(false); + // treeModel=tree.getSelectionModel(); + tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); + treeScroll = new JScrollPane(tree); + tree.addMouseListener(this); + treeModel = new DefaultTreeModel(root); + + // tree.addTreeSelectionListener(new G03TreeListener()); + // treeModel.addTreeModelListener(new G03TreeListener()); + //tree.addTreeSelectionListener(new G03TreeListener()); + } + + public void createbasePanel() { + /*basePanel=new JPanel(new BorderLayout()); + + basePanel.add(treeScroll,BorderLayout.WEST); + basePanel.add(keyWordPanel,BorderLayout.CENTER); + //NEWLY ADDED + basePanel.add(bottomPanel,BorderLayout.SOUTH); + basePanel.add(mainMenubar,BorderLayout.NORTH); + //END OF NEWLY ADDED + */ + + JPanel routeJobPanel = new JPanel(new BorderLayout()); + + routeJobPanel.add(routePanel, BorderLayout.CENTER); + routeJobPanel.add(jobNamePanel, BorderLayout.SOUTH); + + + routeTitleMolPanel = new JPanel(new BorderLayout()); + + //routeTitleMolPanel.add(jobNamePanel,BorderLayout.CENTER); + routeTitleMolPanel.add(molPanel, BorderLayout.CENTER); + routeTitleMolPanel.add(routeJobPanel, BorderLayout.NORTH); + + + centerBasePanel = new JPanel(new BorderLayout()); + centerBasePanel.add(linkoPanel, BorderLayout.NORTH); + centerBasePanel.add(otherItemsPanel, BorderLayout.SOUTH); + centerBasePanel.add(routeTitleMolPanel, BorderLayout.CENTER); + + horizonSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, verticalSplit, centerBasePanel); + horizonSplit.setContinuousLayout(true); + horizonSplit.setOneTouchExpandable(true); + + basePanel = new JPanel(new BorderLayout()); + basePanel.add(mainMenubar, BorderLayout.NORTH); + //basePanel.add(verticalSplit,BorderLayout.WEST); + basePanel.add(helpDonePanel, BorderLayout.SOUTH); + //basePanel.add(centerBasePanel,BorderLayout.CENTER); + basePanel.add(horizonSplit, BorderLayout.CENTER); + } + + +/* + public static void createtitlePanel() + { + + + + + bgColor= new Color(236,233,216); + foreColor =new Color(0,78,152); + + + + bottomPanel=new JPanel(new BorderLayout()); + titlePanel=new JPanel(new GridBagLayout()); + + pRadio=new JRadioButton("Use #P"); + nRadio=new JRadioButton("Use #N"); + tRadio=new JRadioButton("Use #T"); + + routeChoice = new ButtonGroup(); + + routeChoice.add(nRadio); + routeChoice.add(pRadio); + routeChoice.add(tRadio); + + nRadio.addActionListener(new RouteClass()); + pRadio.addActionListener(new RouteClass()); + tRadio.addActionListener(new RouteClass()); + + GridBagConstraints c = new GridBagConstraints(); + c.fill = GridBagConstraints.BOTH; + + + routeArea= new JTextArea(); + + routeArea.setEditable(false); + routeArea.setLineWrap(true); + JScrollPane scrpane=new JScrollPane(routeArea); + + //routeArea.setAutoscrolls(true); + + routeLabel =new JLabel("Route Section"); + + + + + c.gridx=0; + c.gridy=0; + c.weightx=0.5; + c.insets=new Insets(40,60,40,0); + titlePanel.add(routeLabel,c); + + c.gridx=1; + c.gridwidth=4; + //c.insets=new Insets(20,-200,20,10); + //c.insets=new Insets(20,-60,10,10); + c.insets=new Insets(20,-53,10,10); + titlePanel.add(scrpane,c); + + c.gridwidth=1; + c.gridy=2; + c.ipadx=-10; + c.insets=new Insets(-10,50,10,0); + c.gridx=3; + titlePanel.add(pRadio,c); + c.gridx=2; + c.insets=new Insets(-10,0,10,0); + titlePanel.add(nRadio,c); + c.gridx=4; + c.insets=new Insets(-10,0,10,0); + titlePanel.add(tRadio,c); + /*c.gridx=4; + c.insets=new Insets(-10,0,10,250); + titlePanel.add(noneRadio,c); + + nRadio.setSelected(true); + doneButton = new JButton("DONE"); + doneButton.addActionListener(new G03Listener()); + clearButton = new JButton("CLEAR"); + clearButton.addActionListener(new G03Listener()); + exitButton = new JButton("EXIT"); + exitButton.addActionListener(new G03Listener()); + + ImageIcon exitIcon = new ImageIcon("exit.png"); + exitButton.setIcon(exitIcon); + + ImageIcon doneIcon = new ImageIcon("done.png"); + doneButton.setIcon(doneIcon); + + ImageIcon clearIcon = new ImageIcon("clear.png"); + clearButton.setIcon(clearIcon); + + buttonPanel = new JPanel(); + + buttonPanel.add(doneButton); + buttonPanel.add(clearButton); + buttonPanel.add(exitButton); + + bottomPanel.add(titlePanel,BorderLayout.CENTER); + bottomPanel.add(buttonPanel,BorderLayout.SOUTH); + + }*/ + + public static void createkeyWordPanel() { + /*bgColor= new Color(236,233,216); + foreColor =new Color(0,78,152);*/ + keyWordPanel = new JPanel(new BorderLayout()); + + + mainMenubar = new JMenuBar(); + + + molMenu = new JMenu("Molecular Specification"); + + nanoItem=new JMenuItem("Nanocad Editor"); + jamberooItem=new JMenuItem("Jamberoo Editor"); + //cartItem = new JMenuItem("Cartesian Coordinates"); + //zItem= new JMenuItem("Z-matrix Format"); + + //molMenu.add(cartItem); + molMenu.add(nanoItem); + molMenu.add(jamberooItem); + //molMenu.add(zItem); + // zItem.setEnabled(false); + nanoItem.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + nanocadMain.showNanocad(); + } + }); + jamberooItem.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + JamberooMolecularEditor.showJamberoo(); + } + }); + //cartItem.addActionListener(new MenuListeners()); + // zItem.addActionListener(new MenuListeners()); + + + /* Key word Menus */ + methodMenu = new JMenu("Methods"); + //methodMenu.setBackground(Color.lightGray); + + + mainMenubar.add(molMenu); + mainMenubar.add(methodMenu); + + keyWordMenu = new JMenu("Keywords"); + + //Modified by Uky 06/14/2005 + freqKeyMenu = new JMenu("Common Keywords"); + otherKeyMenuItem = new JMenuItem("Other KeyWords"); + + + keyGeom = new JMenuItem("Geom"); + pbcItem = new JMenuItem("PBC"); + popItem = new JMenuItem("Pop"); + mmMenu = new JMenu("MM Methods"); + mmMenu.setEnabled(false); + mmAmbItem = new JMenuItem("Amber"); + mmAmbItem.setEnabled(false); + genMenu = new JMenu("Gen"); + genMenu.setEnabled(false); + genecpMenu = new JMenu("Gen ECP"); + genecpMenu.setEnabled(false); +// Modified by Uky 06/14/2005 + keyWordMenu.add(freqKeyMenu); + keyWordMenu.add(otherKeyMenuItem); + freqKeyMenu.add(keyGeom); + freqKeyMenu.add(pbcItem); + freqKeyMenu.add(popItem); + + mmAmbItem.addActionListener(new keywordListener()); + pbcItem.addActionListener(new keywordListener()); + keyGeom.addActionListener(new keywordListener()); + popItem.addActionListener(new keywordListener()); + otherKeyMenuItem.addActionListener(new keywordListener()); + + basisSetMenu = new JMenu("Basis Sets"); + //basisSetMenu.setBackground(Color.lightGray); + + //basisSetMenu.addItemListener(new G03InputListeners()); + mainMenubar.add(basisSetMenu); + + jobTypeMenu = new JMenu("Job Types"); + + + mainMenubar.add(jobTypeMenu); + + mainMenubar.add(keyWordMenu); + mainMenubar.add(mmMenu); + mainMenubar.add(genMenu); + mainMenubar.add(genecpMenu); + + commonJobMenu = new JMenu("Common-Used Types"); + keyOptCombination = new JMenuItem("Popular Keyword/Option Combination"); + keyOptCombination.setEnabled(false); + //keyOptCombination.addActionListener(new popKeyOptTable()); + otherJobMenu = new JMenu("Other Types"); + + jcDensity = new JMenu("Density"); + jcDensity.addActionListener(new MenuListeners()); + jcFreq = new JMenuItem("Freq"); + jcFreq.addActionListener(new MenuListeners()); + jcGuess = new JMenuItem("Guess"); + jcGuess.addActionListener(new MenuListeners()); + jcOpt = new JMenuItem("Opt "); + jcOpt.addActionListener(new MenuListeners()); + jcOptFreq = new JMenuItem("OptFreq"); + jcOptFreq.addActionListener(new MenuListeners()); + jcSp = new JMenuItem("SP"); + jcSp.addActionListener(new MenuListeners()); + + + dcurrent = new JMenuItem("Current(default)"); + dAll = new JMenuItem("All"); + dscf = new JMenuItem("SCF"); + dmp2 = new JMenuItem("MP2"); + dci = new JMenuItem("CI"); + dqci = new JMenuItem("QCI"); + dchkpoint = new JMenuItem("Checkpoint"); + dallt = new JMenuItem("AllTransistion"); + dcis = new JMenuItem("CIS=N"); + dtran = new JMenuItem("Transition=(N,[M])"); + + + jcDensity.add(dcurrent); + jcDensity.add(dAll); + jcDensity.add(dscf); + jcDensity.add(dmp2); + jcDensity.add(dci); + jcDensity.add(dqci); + jcDensity.add(dchkpoint); + jcDensity.add(dallt); + jcDensity.add(new JSeparator()); + jcDensity.add(dcis); + jcDensity.add(dtran); + + dcurrent.addActionListener(new MenuListeners()); + dAll.addActionListener(new MenuListeners()); + dscf.addActionListener(new MenuListeners()); + dmp2.addActionListener(new MenuListeners()); + dci.addActionListener(new MenuListeners()); + dqci.addActionListener(new MenuListeners()); + dchkpoint.addActionListener(new MenuListeners()); + dallt.addActionListener(new MenuListeners()); + dcis.addActionListener(new MenuListeners()); + dtran.addActionListener(new MenuListeners()); + + + jlAdmp = new JMenuItem("ADMP"); + jlBomp = new JMenuItem("BOMP"); + jlForce = new JMenuItem("Force"); + jlIrc = new JMenuItem("IRC"); + jlIrcMax = new JMenuItem("IRC-Max"); + jlOptIrcMax = new JMenuItem("Opt_IRC-Max"); + jlPolar = new JMenuItem("Polar"); + jlOptPolar = new JMenuItem("Opt_Polar"); + jlArchive = new JMenuItem("ReArchive"); + jlScan = new JMenuItem("Scan"); + jlStable = new JMenuItem("Stable"); + jlVolume = new JMenuItem("Volume"); + + jlAdmp.addActionListener(new MenuListeners()); + jlBomp.addActionListener(new MenuListeners()); + jlForce.addActionListener(new MenuListeners()); + jlIrc.addActionListener(new MenuListeners()); + jlIrcMax.addActionListener(new MenuListeners()); + jlOptIrcMax.addActionListener(new MenuListeners()); + jlPolar.addActionListener(new MenuListeners()); + jlOptPolar.addActionListener(new MenuListeners()); + jlArchive.addActionListener(new MenuListeners()); + jlScan.addActionListener(new MenuListeners()); + jlStable.addActionListener(new MenuListeners()); + jlVolume.addActionListener(new MenuListeners()); + + + commonJobMenu.add(jcDensity); + commonJobMenu.add(jcFreq); + commonJobMenu.add(jcGuess); + commonJobMenu.add(jcOpt); + commonJobMenu.add(jcOptFreq); + commonJobMenu.add(jcSp); + otherJobMenu.add(jlAdmp); + otherJobMenu.add(jlBomp); + otherJobMenu.add(jlForce); + otherJobMenu.add(jlIrc); + otherJobMenu.add(jlIrcMax); + otherJobMenu.add(jlOptIrcMax); + otherJobMenu.add(jlPolar); + otherJobMenu.add(jlOptPolar); + otherJobMenu.add(jlArchive); + otherJobMenu.add(jlScan); + otherJobMenu.add(jlStable); + otherJobMenu.add(jlVolume); + jobTypeMenu.add(commonJobMenu); + + jobTypeMenu.add(otherJobMenu); + jobTypeMenu.add(keyOptCombination); + freqSubMenu = new JMenu("Frequently-used basis sets"); + addSubMenu = new JMenu("Additional basis sets"); + + + // first level Freq used + fsto3gMenu = new JMenu("STO-3G"); + f321Menu = new JMenu("3-21G"); + + //f321Menu.addActionListener(new BasisSetListeners()); + + f621gMenu = new JMenu("6-21G"); + f431gMenu = new JMenu("4-31G"); + f631gItem = new JMenuItem("6-31G"); + + f631gItem.addActionListener(new BasisSetListeners()); + f6311gItem = new JMenuItem("6-311G"); + f6311gItem.addActionListener(new BasisSetListeners()); + flanl2Item = new JMenuItem("LanL2DZ"); + flanl2Item.addActionListener(new BasisSetListeners()); + fccpvdMenu = new JMenu("cc-pv(D,T,Q)Z"); + + fccpv5Menu = new JMenu("cc-pv(5,6)Z"); + + + //secondlevel freq used + + fsto3gItem = new JMenuItem("STO-3G"); + fsto3g1Item = new JMenuItem("STO-3G*"); + + f321gItem = new JMenuItem("3-21G"); + f321g1Item = new JMenuItem("3-21G*"); + f321g11Item = new JMenuItem("3-21G**"); + f321pgItem = new JMenuItem("3-21+G"); + f321pg1Item = new JMenuItem("3-21+G*"); + f321pg11Item = new JMenuItem("3-21+G**"); + + + f621gItem = new JMenuItem("6-21G"); + f621gdItem = new JMenuItem("6-21G(d)"); + + f431gItem = new JMenuItem("4-31G"); + f431g1Item = new JMenuItem("4-31G*"); + f431g2Item = new JMenuItem("4-31G**"); + + fccpvdItem = new JMenuItem("cc-pVDZ"); + fccpvtItem = new JMenuItem("cc-pVTZ"); + fccpvqItem = new JMenuItem("cc-pVQZ"); + faugccdItem = new JMenuItem("AUG-cc-pVDZ"); + faugcctItem = new JMenuItem("AUG-cc-pVTZ"); + faugccqItem = new JMenuItem("AUG-cc-pVQZ"); + + fccpv5Item = new JMenuItem("cc-pV5Z"); + fccpv6Item = new JMenuItem("cc-pV6Z"); + faugcc5Item = new JMenuItem("AUG-cc-pV5Z"); + faugcc6Item = new JMenuItem("AUG-cc-pV6Z"); + + //Add action listeners for the freq. used Basis Sets Level1 + fsto3gItem.addActionListener(new BasisSetListeners()); + fsto3g1Item.addActionListener(new BasisSetListeners()); + + f321gItem.addActionListener(new BasisSetListeners()); + f321g1Item.addActionListener(new BasisSetListeners()); + f321g11Item.addActionListener(new BasisSetListeners()); + f321pgItem.addActionListener(new BasisSetListeners()); + f321pg1Item.addActionListener(new BasisSetListeners()); + f321pg11Item.addActionListener(new BasisSetListeners()); + + f621gItem.addActionListener(new BasisSetListeners()); + f621gdItem.addActionListener(new BasisSetListeners()); + + f431gItem.addActionListener(new BasisSetListeners()); + f431g1Item.addActionListener(new BasisSetListeners()); + f431g2Item.addActionListener(new BasisSetListeners()); + + fccpvdItem.addActionListener(new BasisSetListeners()); + fccpvtItem.addActionListener(new BasisSetListeners()); + fccpvqItem.addActionListener(new BasisSetListeners()); + faugccdItem.addActionListener(new BasisSetListeners()); + faugcctItem.addActionListener(new BasisSetListeners()); + faugccqItem.addActionListener(new BasisSetListeners()); + fccpvdItem.addActionListener(new BasisSetListeners()); + fccpv5Item.addActionListener(new BasisSetListeners()); + fccpv6Item.addActionListener(new BasisSetListeners()); + faugcc5Item.addActionListener(new BasisSetListeners()); + faugcc6Item.addActionListener(new BasisSetListeners()); + + + //first level additional basis sets + + // Petersson et al. Complete Basis Set method basis sets. + // These can have diffuse and polarization functions. + // There appears to be no general method for handling diffuse and + // polarization functions; so these are ignored for now. S. Brozell Nov 2006 + acbs631gdaggerItem = new JMenuItem("CBS 6-31G\u2020"); + acbs631gdaggerdaggerItem = new JMenuItem("CBS 6-31G\u2020\u2020"); + + acep4Menu = new JMenu("CEP-4G"); + acep31Menu = new JMenu("CEP-31G"); + acep121Menu = new JMenu("CEP-121G"); + ad95Item = new JMenuItem("D95"); + + ad95vMenu = new JMenu("D95V"); + + + adgItem = new JMenuItem("DGDZVP"); + adg2Item = new JMenuItem("DGDZVP2"); + adgtItem = new JMenuItem("DGTZVP"); + aeprItem = new JMenuItem("EPR-II"); + aepr2Item = new JMenuItem("EPR-III"); + alanItem = new JMenuItem("LanL2MB"); + amidiItem = new JMenuItem("MidiX"); + amtItem = new JMenuItem("MTSmall"); + + asddItem = new JMenuItem("SDD"); + asdd2Item = new JMenuItem("SDDAll"); + ashcMenu = new JMenu("SHC(SEC)"); + augbsMenu = new JMenu("UGBS"); + + //secondlevel additional basis set + + acep4gItem = new JMenuItem("CEP-4G"); + acep4g1Item = new JMenuItem("CEP-4G*(Li-Ar only)"); + acep31gItem = new JMenuItem("CEP-31G"); + acep31g1Item = new JMenuItem("CEP-31G*(Li-Ar only)"); + acep121gItem = new JMenuItem("CEP-121G"); + acep121g1Item = new JMenuItem("CEP-121G*(Li-Ar only)"); + + ad95vpItem = new JMenuItem("D-95V+"); + ad95vppItem = new JMenuItem("D-95V++"); + ad95v1Item = new JMenuItem("D-95V*"); + ad95v11Item = new JMenuItem("D-95V**"); + ad95vp1Item = new JMenuItem("D-95V+*"); + ad95vp11Item = new JMenuItem("D-95V+**"); + ad95vpp11Item = new JMenuItem("D-95V++**"); + ad95vpp1Item = new JMenuItem("D-95V++*"); + + + ashcItem = new JMenuItem("SHC"); + ashc1Item = new JMenuItem("SHC*"); + augbsItem = new JMenuItem("UGBS"); + augbs1Item = new JMenuItem("UGBS1P"); + augbs2Item = new JMenuItem("UGBS2P"); + augbs3Item = new JMenuItem("UGBS3P"); + + // Add action listeners for the addn. Basis Sets Level1 + acbs631gdaggerItem.addActionListener(new BasisSetListeners()); + acbs631gdaggerdaggerItem.addActionListener(new BasisSetListeners()); + ad95Item.addActionListener(new BasisSetListeners()); + //ad95vMenu.addActionListener(new BasisSetListeners()); + + adgItem.addActionListener(new BasisSetListeners()); + adg2Item.addActionListener(new BasisSetListeners()); + adgtItem.addActionListener(new BasisSetListeners()); + aeprItem.addActionListener(new BasisSetListeners()); + aepr2Item.addActionListener(new BasisSetListeners()); + alanItem.addActionListener(new BasisSetListeners()); + amidiItem.addActionListener(new BasisSetListeners()); + amtItem.addActionListener(new BasisSetListeners()); + asddItem.addActionListener(new BasisSetListeners()); + asdd2Item.addActionListener(new BasisSetListeners()); + + acep4gItem.addActionListener(new BasisSetListeners()); + acep4g1Item.addActionListener(new BasisSetListeners()); + acep31gItem.addActionListener(new BasisSetListeners()); + acep31g1Item.addActionListener(new BasisSetListeners()); + acep121gItem.addActionListener(new BasisSetListeners()); + acep121g1Item.addActionListener(new BasisSetListeners()); + + ad95vpItem.addActionListener(new BasisSetListeners()); + ad95vppItem.addActionListener(new BasisSetListeners()); + ad95v1Item.addActionListener(new BasisSetListeners()); + ad95v11Item.addActionListener(new BasisSetListeners()); + ad95vp1Item.addActionListener(new BasisSetListeners()); + ad95vp11Item.addActionListener(new BasisSetListeners()); + ad95vpp11Item.addActionListener(new BasisSetListeners()); + ad95vpp1Item.addActionListener(new BasisSetListeners()); + + + ashcItem.addActionListener(new BasisSetListeners()); + ashc1Item.addActionListener(new BasisSetListeners()); + augbsItem.addActionListener(new BasisSetListeners()); + augbs1Item.addActionListener(new BasisSetListeners()); + augbs2Item.addActionListener(new BasisSetListeners()); + augbs3Item.addActionListener(new BasisSetListeners()); + + + basisSetMenu.add(freqSubMenu); + basisSetMenu.add(addSubMenu); + + // adding menuitems to Level1 menus + fsto3gMenu.add(fsto3gItem); + fsto3gMenu.add(fsto3g1Item); + + f321Menu.add(f321gItem); + f321Menu.add(f321g1Item); + f321Menu.add(f321g11Item); + f321Menu.add(f321pgItem); + f321Menu.add(f321pg1Item); + f321Menu.add(f321pg11Item); + + + f621gMenu.add(f621gItem); + f621gMenu.add(f621gdItem); + + f431gMenu.add(f431gItem); + f431gMenu.add(f431g1Item); + f431gMenu.add(f431g2Item); + + fccpvdMenu.add(fccpvdItem); + fccpvdMenu.add(fccpvtItem); + fccpvdMenu.add(fccpvqItem); + fccpvdMenu.add(faugccdItem); + fccpvdMenu.add(faugcctItem); + fccpvdMenu.add(faugccqItem); + + fccpv5Menu.add(fccpv5Item); + fccpv5Menu.add(fccpv6Item); + fccpv5Menu.add(faugcc5Item); + fccpv5Menu.add(faugcc6Item); + + //adding everything to submenu freq used + freqSubMenu.add(fsto3gMenu); + freqSubMenu.add(f321Menu); + freqSubMenu.add(f621gMenu); + freqSubMenu.add(f431gMenu); + freqSubMenu.add(f631gItem); + freqSubMenu.add(f6311gItem); + freqSubMenu.add(flanl2Item); + freqSubMenu.add(fccpvdMenu); + freqSubMenu.add(fccpv5Menu); + + // adding menuitems to Level1 menus + acep4Menu.add(acep4gItem); + acep4Menu.add(acep4g1Item); + acep31Menu.add(acep31gItem); + acep31Menu.add(acep31g1Item); + acep121Menu.add(acep121gItem); + acep121Menu.add(acep121g1Item); + + ad95vMenu.add(ad95vpItem); + ad95vMenu.add(ad95vppItem); + ad95vMenu.add(ad95v1Item); + ad95vMenu.add(ad95v11Item); + ad95vMenu.add(ad95vp1Item); + ad95vMenu.add(ad95vp11Item); + ad95vMenu.add(ad95vpp11Item); + ad95vMenu.add(ad95vpp1Item); + + + ashcMenu.add(ashcItem); + ashcMenu.add(ashc1Item); + augbsMenu.add(augbsItem); + augbsMenu.add(augbs1Item); + augbsMenu.add(augbs2Item); + augbsMenu.add(augbs3Item); + + + // adding every item to ADDN BASIS SET Sub menu + addSubMenu.add(acbs631gdaggerItem); + addSubMenu.add(acbs631gdaggerdaggerItem); + addSubMenu.add(acep4Menu); + addSubMenu.add(acep31Menu); + addSubMenu.add(acep121Menu); + addSubMenu.add(ad95Item); + addSubMenu.add(ad95vMenu); + addSubMenu.add(adgItem); + addSubMenu.add(adg2Item); + addSubMenu.add(adgtItem); + addSubMenu.add(aeprItem); + addSubMenu.add(aepr2Item); + addSubMenu.add(alanItem); + addSubMenu.add(amidiItem); + addSubMenu.add(amtItem); + addSubMenu.add(asddItem); + addSubMenu.add(asdd2Item); + addSubMenu.add(ashcMenu); + addSubMenu.add(augbsMenu); + //basisSetMenu.add(restItem); + //Method Menus + mhfItem = new JMenuItem("HF"); + mcasscfmItem = new JMenuItem("CASSCF MP2"); + mdftMenu = new JMenu("DFT"); + mmpnMenu = new JMenu("MPn"); + mccMenu = new JMenu("CC"); + mciMenu = new JMenu("CI"); + mcasscfItem = new JMenuItem("CASSCF"); + motherMenu = new JMenu("Other"); + + //Level 2 + + + mp2Item = new JMenuItem("MP2"); + mp3Item = new JMenuItem("MP3"); + mp4Item = new JMenuItem("MP4(MP4(SDTQ))"); + mp4dItem = new JMenuItem("MP4(DQ)"); + + + dcHybridFunc = new JMenu("Common Hybrid Functionals"); + doHybridFunc = new JMenu("Other Hybrid Functionals"); + ddHybridFunc = new JMenu("Hybrid Functionals with Dispersion"); + dListAllFunc = new JMenuItem("List All Functionals"); + dListAllFunc.addActionListener(new MenuListeners()); + + + dstdAloneFunc = new JMenu("StandAlone Functionals"); + duserDefinedFunc = new JMenu("User-defined DFT Models"); + comB3ly = new JMenuItem("B3LYP"); + comB3pw = new JMenuItem("B3PW91"); + comB3p8 = new JMenuItem("B3P86"); + comB1ly = new JMenuItem("B1LYP"); + comPbe1 = new JMenuItem("PBE1PBE"); + comMpw1 = new JMenuItem("MPW1PW91"); + + + dcHybridFunc.add(comB3ly); + dcHybridFunc.add(comB3pw); + dcHybridFunc.add(comB3p8); + dcHybridFunc.add(comB1ly); + dcHybridFunc.add(comPbe1); + dcHybridFunc.add(comMpw1); + + mdftMenu.add(dcHybridFunc); + + othB1b9 = new JMenuItem("B1B95"); + othB98 = new JMenuItem("B98"); + othB971 = new JMenuItem("B971"); + othB972 = new JMenuItem("B972"); + othBhan = new JMenuItem("BHandH"); + othBhlyp = new JMenuItem("othBhlyp"); + othLsda = new JMenuItem("LSDA"); + + oMN15 =new JMenuItem("MN15"); + oM11=new JMenuItem("M11"); + oMN12SX=new JMenuItem("MN12SX"); + oPW6b95=new JMenuItem("PW6B95"); + oSOGGA11X=new JMenuItem("SOGGA11X"); + oN12SX=new JMenuItem("N12SX"); + oPW6B95D3=new JMenuItem("PW6B95D3"); + oMO8HX=new JMenuItem("MO8HX"); + oMO6=new JMenuItem("MO6"); + oMO6HF=new JMenuItem("MO6HF"); + oMO5=new JMenuItem("MO5"); + oMO52X=new JMenuItem("MO52X"); + oMO62X=new JMenuItem("MO62X"); + + doHybridFunc.add(othB1b9); + doHybridFunc.add(othB98); + doHybridFunc.add(othB971); + doHybridFunc.add(othB972); + doHybridFunc.add(othBhan); + doHybridFunc.add(othBhlyp); + doHybridFunc.add(othLsda); + + doHybridFunc.add(oMN15); + doHybridFunc.add(oM11); + doHybridFunc.add(oMN12SX); + doHybridFunc.add(oPW6b95); + doHybridFunc.add(oSOGGA11X); + doHybridFunc.add(oN12SX); + doHybridFunc.add(oPW6B95D3); + doHybridFunc.add(oMO8HX); + doHybridFunc.add(oMO6); + doHybridFunc.add(oMO6HF); + doHybridFunc.add(oMO5); + doHybridFunc.add(oMO52X); + doHybridFunc.add(oMO62X); + + mdftMenu.add(doHybridFunc); + + APFD = new JMenuItem("APFD"); + wB97xD = new JMenuItem("wB97xD"); + + ddHybridFunc.add(APFD); + ddHybridFunc.add(wB97xD); + + mdftMenu.add(ddHybridFunc); + + mdftMenu.add(dListAllFunc); + + stdVsxc = new JMenuItem("VSXC"); + stdHcth = new JMenuItem("HCTH"); + stdHct9 = new JMenuItem("HCTH93"); + stdHct14 = new JMenuItem("HCTH147"); + stdHct40 = new JMenuItem("HCTH407"); + + dstdAloneFunc.add(stdVsxc); + dstdAloneFunc.add(stdHcth); + dstdAloneFunc.add(stdHct9); + dstdAloneFunc.add(stdHct14); + dstdAloneFunc.add(stdHct40); + + + mdftMenu.add(dstdAloneFunc); + //Leel2 + mp4sItem = new JMenuItem("MP4(SDQ)"); + mp5Item = new JMenuItem("MP5(UMP5)"); + + ccdItem = new JMenuItem("CCD(CC,QCID)"); + ccsItem = new JMenuItem("CCSD"); + ccsdItem = new JMenuItem("CCSD(T)"); + + cidItem = new JMenuItem("CID"); + cisdcItem = new JMenuItem("CISD(CI,CIDS)"); + cisItem = new JMenuItem("CIS"); + cisdItem = new JMenuItem("CIS(D)"); + sacItem = new JMenuItem("SAC-CI"); + + semiMenu = new JMenu("Semi-empirical"); + am1Item = new JMenuItem("AM1"); + pm3Item = new JMenuItem("PM3"); + pm3mmItem = new JMenuItem("PM3MM"); + cndoItem = new JMenuItem("CNDO"); + indoItem = new JMenuItem("INDO"); + mindoItem = new JMenuItem("MINDO3"); + mndoItem = new JMenuItem("MNDO"); + + tdItem = new JMenuItem("TD(HF)"); + tddItem = new JMenuItem("TD DFT"); + + + bdItem = new JMenuItem("BD"); + + cbsMenu = new JMenu("CBS"); + cbs4Item = new JMenuItem("CBS-4M"); + cbslItem = new JMenuItem("CBS-Lq"); + cbsqItem = new JMenuItem("CBS-Q"); + cbsqbItem = new JMenuItem("CBS-QB3"); + cbsaItem = new JMenuItem("CBS-APNO"); + + gnMenu = new JMenu("Gn"); + g1Item = new JMenuItem("G1"); + g2Item = new JMenuItem("G2"); + g2mp2Item = new JMenuItem("G2MP2"); + g3Item = new JMenuItem("G3"); + g3mp2Item = new JMenuItem("G3MP2"); + g3b3Item = new JMenuItem("G3B3"); + g3mp2b3Item = new JMenuItem("G3MP2B3"); + g4Item=new JMenuItem("G4"); + g4mp2Item=new JMenuItem("G4MP2"); + + + gvbItem = new JMenuItem("GVB"); + ovgfItem = new JMenuItem("OVGF"); + w1Item = new JMenuItem("W1"); + zinItem = new JMenuItem("ZINDO"); + + + semiMenu.add(am1Item); + semiMenu.add(pm3Item); + semiMenu.add(pm3mmItem); + semiMenu.add(cndoItem); + semiMenu.add(indoItem); + semiMenu.add(mindoItem); + semiMenu.add(mndoItem); + + + mmpnMenu.add(mp2Item); + mmpnMenu.add(mp3Item); + mmpnMenu.add(mp4Item); + mmpnMenu.add(mp4dItem); + mmpnMenu.add(mp4sItem); + mmpnMenu.add(mp5Item); + + mccMenu.add(ccdItem); + mccMenu.add(ccsItem); + mccMenu.add(ccsdItem); + + mciMenu.add(cidItem); + mciMenu.add(cisdcItem); + mciMenu.add(cisItem); + mciMenu.add(cisdItem); + mciMenu.add(sacItem); + + motherMenu.add(semiMenu); + motherMenu.add(new JSeparator()); + motherMenu.add(tdItem); + motherMenu.add(tddItem); + motherMenu.add(bdItem); + motherMenu.add(cbsMenu); + motherMenu.add(gnMenu); + motherMenu.add(gvbItem); + motherMenu.add(ovgfItem); + motherMenu.add(w1Item); + motherMenu.add(zinItem); + + + cbsMenu.add(cbs4Item); + cbsMenu.add(cbslItem); + cbsMenu.add(cbsqItem); + cbsMenu.add(cbsqbItem); + cbsMenu.add(cbsaItem); + + gnMenu.add(g1Item); + gnMenu.add(g2Item); + gnMenu.add(g2mp2Item); + gnMenu.add(g3Item); + gnMenu.add(g3mp2Item); + gnMenu.add(g3b3Item); + gnMenu.add(g3mp2b3Item); + gnMenu.add(g4Item); + gnMenu.add(g4mp2Item); + + + methodMenu.add(mhfItem); + methodMenu.add(mdftMenu); + methodMenu.add(mmpnMenu); + methodMenu.add(mccMenu); + methodMenu.add(mciMenu); + methodMenu.add(mcasscfItem); + methodMenu.add(mcasscfmItem); + methodMenu.add(new JSeparator()); + methodMenu.add(motherMenu); + + + + + + + + + + + + + /* Combo panel */ + /*comboPanel = new JPanel(new GridLayout(8,4));*/ + /* + jobArea=new JTextArea(); + jobArea.setText("default_job"); + filnamArea=new JTextArea(); + //filnamArea.setEditable(false); + filnamArea.addKeyListener(new G03Listener()); + noofspText=new JTextField(5); + nooflpText=new JTextField(5); + dynmemText=new JTextField(5); + jobLabel=new JLabel("Job Title"); + filnamLabel=new JLabel("Chk Filename"); + dontsave=new JCheckBox("Save Checkpoint File"); + //dontsave.setSelected(true); + dontsave.addActionListener(new G03Listener()); + // noofspLabel=new JLabel("No. of shared Memory Processors requested"); + // nooflpLabel=new JLabel("No. of Linda Processors requested"); + // dynmemLabel=new JLabel("Dynamic Memory requested(in MB)"); + + noofspLabel=new JLabel("%nproc"); + nooflpLabel=new JLabel("%lproc"); + dynmemLabel=new JLabel("%mem(in MB)"); + + comboPanel = new JPanel(new GridBagLayout()); + + + GridBagConstraints c = new GridBagConstraints(); + c.fill = GridBagConstraints.BOTH; + + + + + c.gridx=0; + c.gridy=0; + c.weightx=0.5; + c.insets=new Insets(10,15,20,5); + comboPanel.add(jobLabel,c); + + c.gridx=1; + // c.insets=new Insets(10,-50,0,-130); + c.insets=new Insets(10,-50,0,-195); + JScrollPane jobSpane=new JScrollPane(jobArea); + jobArea.setLineWrap(true); + comboPanel.add(jobSpane,c); + + c.gridy=2; + c.gridx=0; + c.insets=new Insets(10,15,20,5); + comboPanel.add(filnamLabel,c); + + c.gridx=1; + c.insets=new Insets(10,-50,0,-195); + JScrollPane filSpane=new JScrollPane(filnamArea); + filnamArea.setLineWrap(true); + comboPanel.add(filSpane,c); + + c.gridy=4; + c.insets=new Insets(10,-50,0,-15); + comboPanel.add(dontsave,c); + + + noPanel=new JPanel(); + + + noPanel.add(noofspLabel); + + noPanel.add(noofspText); + + noPanel.add(nooflpLabel); + + noPanel.add(nooflpText); + + noPanel.add(dynmemLabel); + + noPanel.add(dynmemText); + + c.gridy=5; + c.gridwidth=4; + comboPanel.add(noPanel,c); + + + + + + + c.gridy=6; + c.gridx=0; + c.ipadx=0; + c.insets = new Insets(20,10,0,-50); + c.gridwidth=2; + //c.gridheight=144; + c.weightx=1; + c.weighty= 0.5; + + + keyoptArea=new JTextPane(); + keyoptArea.setBackground(Color.WHITE); + Font helpFont = new Font("Garamond", Font.BOLD, 14); + keyoptArea.setFont(helpFont); + keyoptArea.setText("Use Shift + Left Click to modify the Input Tree"); + keyoptArea.setEditable(false); + JScrollPane scrollPane; + scrollPane = new JScrollPane(keyoptArea); + + + importFile=new JButton("Fetch Input"); + editFile=new JButton("Edit File"); + // copyFile=new JButton("Copy Input"); + + importFile.addActionListener(new InputFile()); + editFile.addActionListener(new InputFile()); + // copyFile.addActionListener(new InputFile()); + + + inputPanel=new JPanel(new GridLayout(3,0)); + inputPanel.add(importFile); + inputPanel.add(editFile); + //inputPanel.add(copyFile); + + + /* inputPanel=new JPanel(new GridBagLayout()); + * GridBagConstraints inputc= new GridBagConstraints(); + inputc.gridx=0; + inputc.gridy=0; + inputc.weightx=0.5; + // inputc.insets =new Insets(5,25,0,-35); + inputc.insets =new Insets(30,-20,0,-70); + inputPanel.add(importFile,inputc); + inputc.gridy=1; + inputc.insets =new Insets(5,10,0,-45); + inputPanel.add(editFile,inputc); + inputc.gridy=2; + inputPanel.add(copyFile,inputc); + + */ + /*keyoptArea.setAutoscrolls(true); + //keyoptArea.setLineWrap(true); + + comboPanel.add(scrollPane,c); + c.gridx=3; + c.ipadx=-160; + /*c.insets =new Insets(70,80,40,20); + c.insets =new Insets(70,80,40,10); + comboPanel.add(inputPanel,c); + + + JPanel combPanel=new JPanel(new BorderLayout()); + + combPanel.add(comboPanel,BorderLayout.CENTER); + + + /* Adding all the panels to the KeywordPanel + keyWordPanel.add(combPanel,BorderLayout.CENTER); + + /* End of the Interface */ + + /* Listeners ----> */ + + mhfItem.addActionListener(new MenuMethodListener()); + comB3ly.addActionListener(new MenuMethodListener()); + comB3pw.addActionListener(new MenuMethodListener()); + comB3p8.addActionListener(new MenuMethodListener()); + comB1ly.addActionListener(new MenuMethodListener()); + comPbe1.addActionListener(new MenuMethodListener()); + comMpw1.addActionListener(new MenuMethodListener()); + + othB1b9.addActionListener(new MenuMethodListener()); + othB98.addActionListener(new MenuMethodListener()); + othB971.addActionListener(new MenuMethodListener()); + othB972.addActionListener(new MenuMethodListener()); + othBhan.addActionListener(new MenuMethodListener()); + othBhlyp.addActionListener(new MenuMethodListener()); + othLsda.addActionListener(new MenuMethodListener()); + + oMN15.addActionListener(new MenuMethodListener()); + oM11.addActionListener(new MenuMethodListener()); + oMN12SX.addActionListener(new MenuMethodListener()); + oPW6b95.addActionListener(new MenuMethodListener()); + oSOGGA11X.addActionListener(new MenuMethodListener()); + oN12SX.addActionListener(new MenuMethodListener()); + oPW6B95D3.addActionListener(new MenuMethodListener()); + oMO8HX.addActionListener(new MenuMethodListener()); + oMO6.addActionListener(new MenuMethodListener()); + oMO6HF.addActionListener(new MenuMethodListener()); + oMO5.addActionListener(new MenuMethodListener()); + oMO52X.addActionListener(new MenuMethodListener()); + oMO62X.addActionListener(new MenuMethodListener()); + + APFD.addActionListener(new MenuMethodListener()); + wB97xD.addActionListener(new MenuMethodListener()); + + stdVsxc.addActionListener(new MenuMethodListener()); + stdHcth.addActionListener(new MenuMethodListener()); + stdHct9.addActionListener(new MenuMethodListener()); + stdHct14.addActionListener(new MenuMethodListener()); + stdHct40.addActionListener(new MenuMethodListener()); + + + mp2Item.addActionListener(new MenuMethodListener()); + mp3Item.addActionListener(new MenuMethodListener()); + mp4Item.addActionListener(new MenuMethodListener()); + mp4dItem.addActionListener(new MenuMethodListener()); + mp4sItem.addActionListener(new MenuMethodListener()); + mp5Item.addActionListener(new MenuMethodListener()); + + ccdItem.addActionListener(new MenuMethodListener()); + ccsItem.addActionListener(new MenuMethodListener()); + ccsdItem.addActionListener(new MenuMethodListener()); + + cidItem.addActionListener(new MenuMethodListener()); + cisdcItem.addActionListener(new MenuMethodListener()); + cisItem.addActionListener(new MenuMethodListener()); + cisdItem.addActionListener(new MenuMethodListener()); + sacItem.addActionListener(new MenuMethodListener()); + + tdItem.addActionListener(new MenuMethodListener()); + tddItem.addActionListener(new MenuMethodListener()); + bdItem.addActionListener(new MenuMethodListener()); + gvbItem.addActionListener(new MenuMethodListener()); + mcasscfmItem.addActionListener(new MenuMethodListener()); + mcasscfItem.addActionListener(new MenuMethodListener()); + ovgfItem.addActionListener(new MenuMethodListener()); + w1Item.addActionListener(new MenuMethodListener()); + zinItem.addActionListener(new MenuMethodListener()); + + am1Item.addActionListener(new MenuMethodListener()); + + pm3Item.addActionListener(new MenuMethodListener()); + pm3mmItem.addActionListener(new MenuMethodListener()); + cndoItem.addActionListener(new MenuMethodListener()); + indoItem.addActionListener(new MenuMethodListener()); + + mindoItem.addActionListener(new MenuMethodListener()); + mndoItem.addActionListener(new MenuMethodListener()); + + cbs4Item.addActionListener(new MenuMethodListener()); + cbslItem.addActionListener(new MenuMethodListener()); + cbsqItem.addActionListener(new MenuMethodListener()); + cbsqbItem.addActionListener(new MenuMethodListener()); + cbsaItem.addActionListener(new MenuMethodListener()); + + g1Item.addActionListener(new MenuMethodListener()); + g2Item.addActionListener(new MenuMethodListener()); + g2mp2Item.addActionListener(new MenuMethodListener()); + g3Item.addActionListener(new MenuMethodListener()); + g3mp2Item.addActionListener(new MenuMethodListener()); + g3b3Item.addActionListener(new MenuMethodListener()); + g3mp2b3Item.addActionListener(new MenuMethodListener()); + g4Item.addActionListener( new MenuMethodListener() ); + g4mp2Item.addActionListener( new MenuMethodListener() ); + + + + } + + + public void mouseExited(MouseEvent me) { + + + } + + public void mouseReleased(MouseEvent me) { + + /* + int xCoord = me.getX(); + int yCoord = me.getY(); + System.out.println("into mouseReelesas"); + if (me.isPopupTrigger()){ + //TreePath path = getPathForLocation(xCoord, yCoord); + Object obj = me.getComponent(); + TreePath path = ((JTree) obj).getSelectionPath(); + tree.setSelectionPath(path); + System.out.println(path); + + JPopupMenu popUp = new JPopupMenu();//createPopupMenu(false, true, true); + popUp.add("Remove"); + if(path!=null) + popUp.show((Component)obj, xCoord, yCoord); + } + + */ + + //newly added + + + //end of newly added + + + } + + public void mouseClicked(MouseEvent me) { + if (me.isShiftDown()) { + + Object obj = me.getComponent(); + TreePath path = ((JTree) obj).getSelectionPath(); + System.out.println(path.getLastPathComponent()); + if ((path.getLastPathComponent().toString().equals("Methods")) + || (path.getLastPathComponent().toString().equals("Basis Sets")) + || (path.getLastPathComponent().toString().equals("Job Types")) + || (path.getLastPathComponent().toString().equals("Keywords")) + || (path.getLastPathComponent().toString().equals("G '09 Input Selections")) + ) + JOptionPane.showMessageDialog(this, "Invalid Operation !!!", "ERROR", JOptionPane.ERROR_MESSAGE); + else { + int n = JOptionPane.showConfirmDialog(this, "Are You Sure?", + "Delete the Node", JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE, null); + if (n == JOptionPane.YES_OPTION) { + + DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); + if (node == null) return; + System.out.println("Node Selected" + node.toString()); + DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) (node.getParent()); + System.out.println("ParentNode selected" + parentNode.toString()); + if (parentNode == null) return; + + + // code for removing other keys from Route section when removed from tree + if ( + + //(node.toString()=="Field")|| + + (node.toString() == "TestMO") || + (node.toString() == "TrackIO") || + (node.toString() == "Transformation") || + (node.toString() == "Units")) + + { + otherKeyTable.otherKeys.removeElement(node.toString()); + RouteClass.writeRoute(); + } + if (node.toString() == "Archive") { + otherKeyTable.otherKeys.removeElement(node.toString()); + RouteClass.writeRoute(); + } + if (node.toString() == "Charge") { + otherKeyTable.otherKeys.removeElement(node.toString() + "=" + otherKeyListener.charge_Opt); + RouteClass.writeRoute(); + } + if (node.toString() == "ExtraDensityBasis") { + otherKeyTable.otherKeys.removeElement(node.toString()); + RouteClass.writeRoute(); + } + if (node.toString() == "Constants") { + System.out.println(otherKeyListener.con_Opt); + otherKeyTable.otherKeys.removeElement(node.toString() + "=" + otherKeyListener.con_Opt); + RouteClass.writeRoute(); + } + if (node.toString() == "Complex") { + otherKeyTable.otherKeys.removeElement(node.toString()); + RouteClass.writeRoute(); + } + if (node.toString() == "GFInput") { + otherKeyTable.otherKeys.removeElement(node.toString()); + RouteClass.writeRoute(); + } + if (node.toString() == "GFPrint") { + otherKeyTable.otherKeys.removeElement(node.toString()); + RouteClass.writeRoute(); + } + if (node.toString() == "CounterPoise") { + otherKeyTable.otherKeys.removeElement(node.toString() + "=" + otherKeyListener.counter_Opt); + RouteClass.writeRoute(); + } + if (node.toString() == "ChkBasis") { + otherKeyTable.otherKeys.removeElement("ChkBasis"); + RouteClass.writeRoute(); + } + if (node.toString() == "CPHF") { + otherKeyTable.otherKeys.removeElement(node.toString() + "=" + otherKeyListener.cphfOpt); + RouteClass.writeRoute(); + } + if (node.toString() == "DensityFit") { + otherKeyTable.otherKeys.removeElement(node.toString() + "=" + otherKeyListener.densityOpt); + RouteClass.writeRoute(); + } + if (node.toString() == "FMM") { + otherKeyTable.otherKeys.removeElement(node.toString() + "=" + otherKeyListener.fmmOpt); + RouteClass.writeRoute(); + } + if (node.toString() == "External") { + otherKeyTable.otherKeys.removeElement(node.toString()); + RouteClass.writeRoute(); + } + if (node.toString() == "ExtraBasis") { + otherKeyTable.otherKeys.removeElement(node.toString()); + RouteClass.writeRoute(); + } + + if (node.toString() == "NMR") { + otherKeyTable.otherKeys.removeElement(node.toString() + "=" + otherKeyListener.nmrOpt); + RouteClass.writeRoute(); + } + if (node.toString() == "Output") { + otherKeyTable.otherKeys.removeElement(node.toString() + "= " + otherKeyListener.output_Opt); + RouteClass.writeRoute(); + } + + if (node.toString() == "Iop") { + otherKeyTable.okIop.setSelected(false); + otherKeyTable.otherKeys.removeElement(iopKeymodify.iopOp); + + RouteClass.writeRoute(); + } + if (node.toString() == "Pressure") { + otherKeyTable.otherKeys.removeElement(otherKeyTable.pressureOpt); + RouteClass.writeRoute(); + } + if (node.toString() == "Prop") + + { + System.out.println("In listener for Prop" + otherKeyListener.prop_Opt); + otherKeyTable.otherKeys.removeElement("Prop=" + otherKeyListener.prop_Opt); + RouteClass.writeRoute(); + } + if (node.toString() == "Pseudo") { + otherKeyTable.otherKeys.removeElement("Pseudo=" + otherKeyListener.pseudo_Opt); + RouteClass.writeRoute(); + } + if (node.toString() == "Punch") { + otherKeyTable.otherKeys.removeElement("Pseudo=" + otherKeyListener.punch_Opt); + RouteClass.writeRoute(); + } + if (node.toString() == "Scale") { + otherKeyTable.otherKeys.removeElement(otherKeyTable.scale_Opt); + RouteClass.writeRoute(); + } + + if (node.toString() == "Name") { + otherKeyTable.otherKeys.removeElement(node.toString()); + RouteClass.writeRoute(); + } + + if (node.toString() == "Sparse") { + otherKeyTable.otherKeys.removeElement("Sparse=" + otherKeyListener.sparse_Opt); + RouteClass.writeRoute(); + } + if (node.toString() == "Symmetry") { + otherKeyTable.otherKeys.removeElement("Symmetry=" + otherKeyListener.symm_Opt); + RouteClass.writeRoute(); + } + if (node.toString() == "Temperature") { + otherKeyTable.otherKeys.removeElement(otherKeyTable.temp_Opt); + RouteClass.writeRoute(); + } + + + + + /* if(otherKeyTable.okVector.size()>= 1) + { + for(int h=0;h< otherKeyTable.okVector.size();h++) + { + System.out.println("To check" +node.toString()); + if(((JRadioButton)(otherKeyTable.okVector.get(h))).getActionCommand().toString().equals(node.toString())) + { + if(((JRadioButton)(otherKeyTable.okVector.get(h))).isSelected()) + { + // ((JRadioButton)(otherKeyTable.okVector.get(h))).setSelected(false); + } + + + } + } + } + */ + if (parentNode.toString().equals("Freq")) { + System.out.println(FreqOptTable.table.getSelectionModel().toString()); + for (int h = 0; h < FreqOptTable.freqClear.size(); h++) { + if (((JRadioButton) (FreqOptTable.freqClear.get(h))).getActionCommand().toString().equals(node.toString())) { + if (((JRadioButton) (FreqOptTable.freqClear.get(h))).isSelected()) { + + System.out.println("Test case1 " + (JRadioButton) (FreqOptTable.freqClear.get(h))); + ((JRadioButton) (FreqOptTable.freqClear.get(h))).setSelected(false); + FreqOptTable.freqOpt.removeElement(node.toString()); + } + + } + } + if (FreqOptTable.FStep.isSelected()) { + if (node.toString().startsWith("Step=")) { + FreqOptTable.FStep.setSelected(false); + FreqOptTable.freqOpt.removeElement(node.toString()); + } + } + } + if (parentNode.toString().equals("Guess")) { + for (int h = 0; h < GuessOptTable.guessClear.size(); h++) { + if (((JRadioButton) (GuessOptTable.guessClear.get(h))).isSelected()) { + if (((JRadioButton) (GuessOptTable.guessClear.get(h))).getActionCommand().toString().equals(node.toString())) { + ((JRadioButton) (GuessOptTable.guessClear.get(h))).setSelected(false); + GuessOptTable.guessOpt.removeElement(node.toString()); + } + + } + + } + + } + + if (parentNode.toString().equals("Pop")) { + System.out.println("The deleted node" + node); + // System.out.println(GuessOptTable.table.getSelectionModel().toString()); + + for (int h = 0; h < popOptTable.popClear.size(); h++) { + if (((JRadioButton) (popOptTable.popClear.get(h))).isSelected()) { + if (((JRadioButton) (popOptTable.popClear.get(h))).getActionCommand().toString().equals(node.toString())) { + ((JRadioButton) (popOptTable.popClear.get(h))).setSelected(false); + popOptTable.popOpt.removeElement(node.toString()); + } + + } + + } + + } + if (parentNode.toString().equals("PBC")) { + System.out.println("in PBC"); + //Clear the selected items + for (int j = 0; j < 8; j++) { + System.out.println("Checking For loop" + j); + System.out.println("Option Name" + pbcTable.pbcOptions[j].getLabel()); + System.out.println(node.toString()); + if (pbcTable.pbcOptions[j].getLabel().toString().startsWith(node.toString())) { + System.out.println("IF LOOP ::: " + node.toString()); + pbcTable.pbcOptions[j].setSelected(false); + pbcTable.selectedIndex[j] = 0; + pbcTable.initValues[j] = ""; + } + } + + + } + + + if (node.toString().equals("PBC")) { + System.out.println("in PBC"); + //Clear the selected items + for (int j = 0; j < 8; j++) { + + + pbcTable.pbcOptions[j].setSelected(false); + pbcTable.selectedIndex[j] = 0; + pbcTable.initValues[j] = ""; + + } + + + } + + if (parentNode.toString().equals("Opt ")) { + System.out.println("The deleted node" + node); + // System.out.println(OptTable.table.getSelectionModel().toString()); + + for (int h = 0; h < OptTable.optClear.size(); h++) { + if (((JRadioButton) (OptTable.optClear.get(h))).isSelected()) { + if (((JRadioButton) (OptTable.optClear.get(h))).getActionCommand().toString().equals(node.toString())) { + ((JRadioButton) (OptTable.optClear.get(h))).setSelected(false); + OptTable.optVopt.removeElement(node.toString()); + } + + } + + } + + if (OptTable.OMaxCy.isSelected()) { + if (node.toString().startsWith("MaxCycle=")) { + OptTable.OMaxCy.setSelected(false); + OptTable.optVopt.removeElement(node.toString()); + } + } + + if (OptTable.OMaxSt.isSelected()) { + if (node.toString().startsWith("MaxStep=")) { + OptTable.OMaxSt.setSelected(false); + OptTable.optVopt.removeElement(node.toString()); + } + } + + if (OptTable.OSadd.isSelected()) { + if (node.toString().startsWith("Step=")) { + OptTable.OSadd.setSelected(false); + OptTable.optVopt.removeElement(node.toString()); + } + } + + + if (OptTable.OPathN.isSelected()) { + if (node.toString().startsWith("Path=")) { + OptTable.OPathN.setSelected(false); + OptTable.optVopt.removeElement(node.toString()); + } + } + + if (OptTable.OChkHar.isSelected()) { + if (node.toString().startsWith("CheckHarmonic=")) { + OptTable.OChkHar.setSelected(false); + OptTable.optVopt.removeElement(node.toString()); + } + } + if (OptTable.OInitHar.isSelected()) { + if (node.toString().startsWith("InitialHarmonic=")) { + OptTable.OInitHar.setSelected(false); + OptTable.optVopt.removeElement(node.toString()); + } + } + if (OptTable.OReadHar.isSelected()) { + if (node.toString().startsWith("ReadHarmonic=")) { + OptTable.OReadHar.setSelected(false); + OptTable.optVopt.removeElement(node.toString()); + } + } + } + if (parentNode.toString().equals("Geom")) { + + for (int h = 0; h < geomOptTable.geomClear.size(); h++) { + if (((JRadioButton) (geomOptTable.geomClear.get(h))).isSelected()) { + if (((JRadioButton) (geomOptTable.geomClear.get(h))).getActionCommand().toString().equals(node.toString())) { + ((JRadioButton) (geomOptTable.geomClear.get(h))).setSelected(false); + geomOptTable.geomOpt.removeElement(node.toString()); + } + + } + + } + if (geomOptTable.GeRead.isSelected()) { + if (node.toString().startsWith("ReadHarmonic=")) { + geomOptTable.GeRead.setSelected(false); + geomOptTable.geomOpt.removeElement(node.toString()); + } + } + if (geomOptTable.GeStep.isSelected()) { + if (node.toString().startsWith("Step=")) { + geomOptTable.GeStep.setSelected(false); + geomOptTable.geomOpt.removeElement(node.toString()); + } + } + if (geomOptTable.GeCheck.isSelected()) { + if (node.toString().startsWith("CheckHarmonic=")) { + geomOptTable.GeCheck.setSelected(false); + geomOptTable.geomOpt.removeElement(node.toString()); + } + } + } + RouteClass.rewriteRoute(node.toString(), parentNode.toString()); + System.out.println("Archive testing+ parent " + parentNode.toString()); + + if (InsertNode.nodeExists(node.toString())) + parentNode.remove(node); + ((DefaultTreeModel) tree.getModel()).reload(parentNode); + } else if (n == JOptionPane.NO_OPTION) { + return; + } else { + return; + } + + } + + + } + } + + + public void mousePressed(MouseEvent me) { + + + } + + public void mouseEntered(MouseEvent me) { + + + } + + + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + JFrame.setDefaultLookAndFeelDecorated(true); + JDialog.setDefaultLookAndFeelDecorated(true); + + MetalTheme theme = new ColorTheme(); + // set the chosen theme + MetalLookAndFeel.setCurrentTheme(theme); + // Show name of the theme as window title + // this.setTitle(theme.getName()); + mainFrame = new G03MenuTree(); + try { + UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); + SwingUtilities.updateComponentTreeUI(mainFrame); + } catch (Exception e) { + System.out.println(e); + } + + + mainFrame.setLocation(5, 30); + mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + mainFrame.pack(); + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + //mainFrame.setSize(screenSize.width-20,screenSize.height-100); + screenWidth = screenSize.width - 200; + screenHeight = screenSize.height - 150; + mainFrame.setSize(screenSize.width - 200, screenSize.height - 150); + mainFrame.setResizable(true); + mainFrame.setVisible(true); + } + }); + } + + // Allows you to add content to the Editorpane + + public static void insertHTML + (JEditorPane editor, String html) + throws IOException, BadLocationException { + //assumes editor is already set to "text/html" type + int location; + HTMLEditorKit kit = + (HTMLEditorKit) editor.getEditorKit(); + Document doc = editor.getDocument(); + location = doc.getLength(); + StringReader reader = new StringReader(html); + kit.read(reader, doc, location); + editor.setCaretPosition(editor.getDocument().getLength()); + } + + +} + + + + diff --git a/src/main/java/g03input/GeometryEditor.java b/src/main/java/g03input/GeometryEditor.java new file mode 100644 index 0000000..11faf55 --- /dev/null +++ b/src/main/java/g03input/GeometryEditor.java @@ -0,0 +1,1150 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Sep 12, 2005 + * @author Michael Sheetz + * @author Sandeep Kumar Seethaapathy @author Shashank Jeedigunta + * + */ +package g03input; + +import javax.swing.*; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.ArrayList; +import java.util.StringTokenizer; + +public class GeometryEditor extends JFrame +{ + public static String geom = new String(); + public static String validateGeom; + public static String newGeom; + GeometryReader geomReader; + public static boolean readchk, readallchk, counterpoise; + + public GeometryEditor(){} + public GeometryEditor(String geometryString ) // Constructor + { + geomReader = new GeometryReader(geometryString); + atomCoordinateParser.getCoordinates(); + + + addWindowListener(new WindowEventHandler()); + } + + // Define window listener class + class WindowEventHandler extends WindowAdapter + { + public void windowClosing(WindowEvent e) + + { + System.exit(0); + } + } + + // Define GeometryReader class +public static class GeometryReader + { public static String[] atomSymb; + public static double[] atomCoord; + GeometryReader(String geometryString) // Constructor + { + String str, strAtomID, strToken; + StringBuffer sb, atomicSymbol; + StringTokenizer stok01, stok1, stok2, stok3, stok4,removeExpo; + ArrayList nlineTokens, ncoordTokens, atomID; + ArrayList geomLines, tmpgeomLine, geomTokens, geomCoordTokens, geomVarTokens, geomVariables; + + int i, j, k, ndx, index, index0, index1, charIndex, atomIndex, coordIndex, varIndex, coordTokenIndex; + int bondedAtomIndex, alphaAtomIndex, gammaAtomIndex; + int bondedAtomCoordIndex, alphaAtomCoordIndex, gammaAtomCoordIndex; + int natoms, ncoord, nvarTokens, ntokensRead; + int ngeomLines, ngeomVariables, ngeomTokens; + int nelem, nchar, sblength; + int[] ntokens; + int[][] bondOrder; + + double bondDistance, alpha, gamma, x1, x2, y1, y2, z1, z2, r, nx, ny, nz; + + double[] prerotCoord; + double[] rotCoord; + double[] opTranslation = { 0.0, 0.0, 0.0 }; + double[][] rotMatrix; + + boolean[] formatZCartesian; + boolean finalCoordRead, foundChar; + boolean formatCartesian; + + sb = new StringBuffer(); + atomicSymbol = new StringBuffer(); + + rotCoord = new double[3]; + prerotCoord = new double[3]; + + geomLines = new ArrayList(); + geomTokens = new ArrayList(); + tmpgeomLine = new ArrayList(); + geomCoordTokens = new ArrayList(); + geomVarTokens = new ArrayList(); + geomVariables = new ArrayList(); + + ncoordTokens = new ArrayList(); + + counterpoise = false; + readchk = false; +// readchk = infile.readchk; + readallchk = false; +// readallchk = infile.readallchk; + finalCoordRead = false; + formatCartesian = false; + + natoms = 0; + nelem = 0; + ntokensRead = 0; + coordIndex = 0; + bondedAtomIndex = 0; + alphaAtomIndex = 0; + gammaAtomIndex = 0; + bondDistance = 0.0; + alpha = 0.0; + gamma = 0.0; + geom=geometryString; + System.out.println("Geometry Specification"+geometryString); + stok01 = new StringTokenizer(geom, "\n"); + + + + + newGeom = new String(); + String expo = new String(); + String expo1 = new String(); + while(stok01.hasMoreTokens()) + { + expo = stok01.nextToken(); + + removeExpo = new StringTokenizer(expo); + System.out.println("No of tokens on each line is"+removeExpo.countTokens()); + while(removeExpo.hasMoreTokens()) + { + expo1 = removeExpo.nextToken(); + + int indexCount = expo1.indexOf("E"); + // indexCount = expo1.indexOf("e"); + if(indexCount > 0) + { + newGeom += 0.0+" "; + } + else + { + newGeom += expo1+" "; + } + } + newGeom += "\n"; + } + + + + stok1 = new StringTokenizer(newGeom,"\n"); + System.out.println("No of tokens"+stok1.countTokens()); + // Count total number of individual lines contained in geometry specification + ngeomLines = stok1.countTokens(); + + // Specify length of 'ntokens' integer array + ntokens = new int[ngeomLines]; + + // Set initial capacity of 'zmatLines' array list equal to total number + // of lines in geometry specification + geomLines = new ArrayList(ngeomLines); + + while(stok1.hasMoreTokens()) + { + geomLines.add(stok1.nextToken()); + } + + // Initialize 'formatCartesian' array + formatZCartesian = new boolean[ngeomLines]; + + for (j = 0; j < ngeomLines; j++) + { + formatZCartesian[j] = false; + } + + // Set initial capacity of 'nlineTokens' array list equal to total number + // of lines in geometry specification + nlineTokens = new ArrayList(ngeomLines); + + // Separately tokenize each line of geometry specification + // Initialize total number of tokens in geometry specification + ngeomTokens = 0; + + // Set number of variables specified in geometry specification equal to zero + ngeomVariables = 0; + + for (index = 0; index < ngeomLines; index++) + { + sb.delete(0, sb.length()); + sb.append(geomLines.get(index).toString()); + + stok2 = new StringTokenizer(sb.toString()); + + // Count number of tokens in each individual line of geometry specification + // and place in 'nlineTokens' array list + ntokens[index] = stok2.countTokens(); + + // Set number of atoms equal to number of lines in geometry specification + // if there is no 'Variables' section in the Z-matrix + if ((index == (ngeomLines - 1)) && (finalCoordRead == false)) // if reach end of geometry specification + { // before final coordinate has been read + natoms = ngeomLines; // each line in geometry specification represents an individual atom in the molecule + + finalCoordRead = true; + } + else if ((index > 1) && (ntokens[index] < 4)) + { + // Read variables section of geometry specification, if this section is present + + if (finalCoordRead == false) + { + natoms = index; + finalCoordRead = true; + } + + ndx = sb.indexOf("="); + + if ((ntokens[index] == 1) && (ndx != -1)) + { + geomVarTokens.add(sb.substring(0, ndx)); + geomVarTokens.add(sb.substring(ndx+1)); + + ngeomVariables++; + } + + else if (ntokens[index] == 2) + { + while (stok2.hasMoreTokens()) + { + geomVarTokens.add(stok2.nextToken()); + } + + ngeomVariables++; + } + else if ((ntokens[index] == 3)&& (ndx != -1)) + { + while (stok2.hasMoreTokens()) + { + str = new String(stok2.nextToken()); + + if (!str.equals("=")) + { + geomVarTokens.add(stok2.nextToken()); + } + } + + ngeomVariables++; + } + if ((ntokens[index] == 1) && (ndx == -1)) + { + // additional data unrelated to Z-matrix proper + } + } + } + + ncoord = 3 * natoms; + atomCoord = new double[ncoord]; + atomID = new ArrayList(natoms); + atomSymb = new String[natoms]; + + // Initialize bond order matrix + bondOrder = new int[natoms][natoms]; + + for (j = 0; j < natoms; j++) + { + for (k = 0; k < natoms; k++) + { + bondOrder[j][k] = 0; + } + } + + // Currently have number of tokens present in each line of geometry specification, each separate tokens in the + // coordinates section for the molecule, and each separate token in the variables section for the molecule + + // Read in each separate token in the geometry specification grouped according to number of tokens in each + // line of the coordinate section for the molecule + + for (atomIndex = 0; atomIndex < natoms; atomIndex++) + { + stok3 = new StringTokenizer(geomLines.get(atomIndex).toString()); + + // Remove fragment numbers specification if run incorporates counterpoise corrections + if (ntokens[atomIndex] <= 7) + { + nelem = ntokens[atomIndex]; + } + else if (ntokens[atomIndex] > 7) + { + nelem = 7; + } + + /************* + * + * Note: Must access counterpoise variable from InfileReader class: 'counterpoise = infile.counterpoise' + * // if ((nelem == 4) && (infile.counterpoise == false)) + *************/ +// if ((nelem == 4) && (infile.counterpoise == false)) + if ((nelem == 4) && (counterpoise == false)) + { + formatCartesian = true; + } + + for (index = 0; index < nelem; index++) + { + strToken = stok3.nextToken(); + + // Get number of characters present in this token + nchar = strToken.length(); + + switch(index) + { + case 0: + // Read in first atom from line of molecular specification + atomID.add(strToken); + int tempAtId1=0, tempAtId2=0, tempAtId3=0; + + + for (j = 0; j < nchar; j++) + { + if (Character.isLetter(strToken.charAt(j))) + { + atomicSymbol.append(strToken.charAt(j)); + System.out.println(" # of Characters in atom symbol " + nchar + "Atomic Symbol: "+ atomicSymbol); + } + else if (Character.isDigit(strToken.charAt(j))){ + + // it is number and it could 1 or 2 or 3 character long + + tempAtId1 = Character.getNumericValue(strToken.charAt(0)); + System.out.println("Digit Character 1 in At Symb "+ tempAtId1); + if (nchar == 1) + { + switch (tempAtId1) + { + case 1: atomicSymbol.append("H" ); break; + case 3: atomicSymbol.append("Li"); break; + case 4: atomicSymbol.append("Be"); break; + case 5: atomicSymbol.append("B"); break; + case 6: atomicSymbol.append("C"); break; + case 7: atomicSymbol.append( "N" ); break; + case 8: atomicSymbol.append( "O" ); break; + case 9: atomicSymbol.append( "F" ); break; + } + } + else if (nchar == 2) + { + tempAtId2 = Character.getNumericValue(strToken.charAt(1)); + System.out.println("Digit Character 2 in At Symb "+ tempAtId2); + atomicSymbol.delete(0,atomicSymbol.length()); + if (tempAtId1 == 1) + {switch (tempAtId2) + {case 0: atomicSymbol.append("Ne"); break; + case 1: atomicSymbol.append("Na"); break; + case 2: atomicSymbol.append("Mg"); break; + case 3: atomicSymbol.append("Al"); break; + case 4: atomicSymbol.append("Si"); break; + case 5: atomicSymbol.append("P"); break; + case 6: atomicSymbol.append("S"); break; + case 7: atomicSymbol.append("Cl"); break; + case 8: atomicSymbol.append("Ar"); break; + case 9: atomicSymbol.append("K"); break; + } + } + else if ( tempAtId1 == 2) + {switch (tempAtId2) + {case 0: atomicSymbol.append("Ca"); break; + case 1: atomicSymbol.append("Sc"); break; + case 2: atomicSymbol.append("Ti"); break; + case 3: atomicSymbol.append("V"); break; + case 4: atomicSymbol.append("Cr"); break; + case 5: atomicSymbol.append("Mn"); break; + case 6: atomicSymbol.append("Fe"); break; + case 7: atomicSymbol.append("Co"); break; + case 8: atomicSymbol.append("Ni"); break; + case 9: atomicSymbol.append("Cu"); break; + } + } + else if ( tempAtId1 == 3) + {switch (tempAtId2) + {case 0: atomicSymbol.append("Zn"); break; + case 1: atomicSymbol.append("Ga"); break; + case 2: atomicSymbol.append("Ge"); break; + case 3: atomicSymbol.append("As"); break; + case 4: atomicSymbol.append("Se"); break; + case 5: atomicSymbol.append("Br"); break; + case 6: atomicSymbol.append("Kr"); break; + case 7: atomicSymbol.append("Rb"); break; + case 8: atomicSymbol.append("Sr"); break; + case 9: atomicSymbol.append("Y"); break; + } + } + else if ( tempAtId1 == 4) + {switch (tempAtId2) + {case 0: atomicSymbol.append("Zr"); break; + case 1: atomicSymbol.append("Nb"); break; + case 2: atomicSymbol.append("Mo"); break; + case 3: atomicSymbol.append("Tc"); break; + case 4: atomicSymbol.append("Ru"); break; + case 5: atomicSymbol.append("Rh"); break; + case 6: atomicSymbol.append("Pd"); break; + case 7: atomicSymbol.append("Ag"); break; + case 8: atomicSymbol.append("Cd"); break; + case 9: atomicSymbol.append("In"); break; + } + } + else if ( tempAtId1 == 5) + {switch (tempAtId2) + {case 0: atomicSymbol.append("Sn"); break; + case 1: atomicSymbol.append("Sb"); break; + case 2: atomicSymbol.append("Te"); break; + case 3: atomicSymbol.append("I"); break; + case 4: atomicSymbol.append("Xe"); break; + case 5: atomicSymbol.append("Cs"); break; + case 6: atomicSymbol.append("Ba"); break; + case 7: atomicSymbol.append("La"); break; + case 8: atomicSymbol.append("Ce"); break; + case 9: atomicSymbol.append("Pr"); break; + } + } + else if ( tempAtId1 == 6) + {switch (tempAtId2) + {case 0: atomicSymbol.append("Nd"); break; + case 1: atomicSymbol.append("Pm"); break; + case 2: atomicSymbol.append("Sm"); break; + case 3: atomicSymbol.append("Eu"); break; + case 4: atomicSymbol.append("Gd"); break; + case 5: atomicSymbol.append("Tb"); break; + case 6: atomicSymbol.append("Dy"); break; + case 7: atomicSymbol.append("Ho"); break; + case 8: atomicSymbol.append("Er"); break; + case 9: atomicSymbol.append("Tm"); break; + } + } + else if ( tempAtId1 == 7) + {switch (tempAtId2) + {case 0: atomicSymbol.append("Yb"); break; + case 1: atomicSymbol.append("Lu"); break; + case 2: atomicSymbol.append("Hf"); break; + case 3: atomicSymbol.append("Ta"); break; + case 4: atomicSymbol.append("W"); break; + case 5: atomicSymbol.append("Re"); break; + case 6: atomicSymbol.append("Os"); break; + case 7: atomicSymbol.append("Ir"); break; + case 8: atomicSymbol.append("Pt"); break; + case 9: atomicSymbol.append("Au"); break; + } + } + else if ( tempAtId1 == 8) + {switch (tempAtId2) + {case 0: atomicSymbol.append("Hg"); break; + case 1: atomicSymbol.append("Tl"); break; + case 2: atomicSymbol.append("Pb"); break; + case 3: atomicSymbol.append("Bi"); break; + case 4: atomicSymbol.append("Po"); break; + case 5: atomicSymbol.append("At"); break; + case 6: atomicSymbol.append("Rn"); break; + case 7: atomicSymbol.append("Fr"); break; + case 8: atomicSymbol.append("Ra"); break; + case 9: atomicSymbol.append("Ac"); break; + } + } + else if ( tempAtId1 == 9) + {switch (tempAtId2) + {case 0: atomicSymbol.append("Th"); break; + case 1: atomicSymbol.append("Pa"); break; + case 2: atomicSymbol.append("U"); break; + case 3: atomicSymbol.append("Np"); break; + case 4: atomicSymbol.append("Pu"); break; + case 5: atomicSymbol.append("Am"); break; + case 6: atomicSymbol.append("Cm"); break; + case 7: atomicSymbol.append("Bk"); break; + case 8: atomicSymbol.append("Cf"); break; + case 9: atomicSymbol.append("Es"); break; + } + } + } + System.out.println(" # of Characters in atom symbol " + nchar + " Atomic Symbol by Digit: "+ atomicSymbol); + } + } + + atomSymb[atomIndex] = new String(atomicSymbol.toString()); + System.out.println("AtomIndex: " + atomIndex +" Atomic Symbol: "+ atomSymb[atomIndex] ); + // Clear contents of string buffer + atomicSymbol.delete(0, atomicSymbol.length()); + + // If this is first atom in geometry specification, place + // it at the origin of Cartesian coordinate frame + if ((atomIndex == 0) && (ntokens[atomIndex] == 1)) + { + for (coordIndex = 0; coordIndex < 3; coordIndex++) + { + atomCoord[coordIndex] = 0.0; + } + } + break; + + case 1: + // If geometry format is given as a Z-matrix, read in second (bonded) atom + // from line of Z-matrix + + // If, instead, geometry format is given in Cartesian coordinates, read in x-coordinate + if (formatCartesian == false) + { + // Check if second token is a variable or a numerical value + foundChar = false; + + for (charIndex = 0; charIndex < nchar; charIndex++) + { + if (Character.isLetter(strToken.charAt(charIndex))) + { + foundChar = true; + } + } + + if (foundChar == false) + { + // Check if this line of geometry specification is given in + // Cartesian coordinate format + if (Integer.parseInt(strToken) == 0) + { + formatZCartesian[atomIndex] = true; + } + else + { + // An integer is being used to identify the atom to which this atom is bonded + bondedAtomIndex = Integer.parseInt(strToken) - 1; + } + } + else + { + bondedAtomIndex = atomID.indexOf(strToken); + } + + bondOrder[bondedAtomIndex][atomIndex] = 1; + } + else // If, instead, geometry format is given in Cartesian coordinates, read in + { // x-coordinate directly from geometry specification + // Read in x-coordinate of atom + + coordIndex = 3 * atomIndex; + + // Check if token is a variable or a double value + foundChar = false; + + for (charIndex = 0; charIndex < nchar; charIndex++) + { + if (Character.isLetter(strToken.charAt(charIndex))) + { + foundChar = true; + } + } + + if (foundChar == true) + { + // Retrieve index of x-coordinate variable in 'zmatVarTokens' array list + varIndex = geomVariables.indexOf(strToken); + + // Retrieve value of x-coordinate from 'zmatVarTokens' array list + atomCoord[coordIndex + (index - 1)] = Double.parseDouble(geomVarTokens.get(varIndex + 1).toString()); + } + else + { + // Read in value of x-coordinate directly from current line of Z-matrix + atomCoord[coordIndex + (index - 1)] = Double.parseDouble(strToken); + } + } + break; + + case 2: + // If geometry format is given as a Z-matrix, read in second (bonded) atom + // from line of Z-matrix + if (formatCartesian == false) + { + if (formatZCartesian[atomIndex] == true) + { + coordIndex = 3 * atomIndex; + + // Check if token is a variable or a double value + foundChar = false; + + for (charIndex = 0; charIndex < nchar; charIndex++) + { + if (Character.isLetter(strToken.charAt(charIndex))) + { + foundChar = true; + } + } + + if (foundChar == true) + { + // Retrieve index of x-coordinate variable in 'zmatVarTokens' array list + varIndex = geomVariables.indexOf(strToken); + + // Retrieve value of x-coordinate from 'zmatVarTokens' array list + atomCoord[coordIndex] = Double.parseDouble(geomVarTokens.get(varIndex + 1).toString()); + } + else + { + // Read in value of x-coordinate directly from current line of Z-matrix + atomCoord[coordIndex] = Double.parseDouble(strToken); + } + } + else // Third token in this line of Z-matrix is a bond distance + { + // Read in bond distance directly from current line of Z-matrix + bondDistance = Double.parseDouble(strToken); + + // If this is the second atom in the Z-matrix, place atom along the z-axis a distance + // 'bondDistance' from the first atom + if (nelem == 3) + { + bondedAtomCoordIndex = 3 * bondedAtomIndex; + + atomCoord[coordIndex] = atomCoord[bondedAtomCoordIndex]; + atomCoord[coordIndex + 1] = atomCoord[bondedAtomCoordIndex + 1]; + atomCoord[coordIndex + 2] = atomCoord[bondedAtomCoordIndex + 2] + bondDistance; + } + } + } + else // If, instead, geometry format is given in Cartesian coordinates, read in + { // y-coordinate directly from geometry specification + // Read in y-coordinate of atom + + coordIndex = 3 * atomIndex; + + // Check if token is a variable or a double value + foundChar = false; + + for (charIndex = 0; charIndex < nchar; charIndex++) + { + if (Character.isLetter(strToken.charAt(charIndex))) + { + foundChar = true; + } + } + + if (foundChar == true) + { + // Retrieve index of y-coordinate variable in 'zmatVarTokens' array list + varIndex = geomVariables.indexOf(strToken); + + // Retrieve value of y-coordinate from 'zmatVarTokens' array list + atomCoord[coordIndex + (index - 1)] = Double.parseDouble(geomVarTokens.get(varIndex + 1).toString()); + } + else + { + // Read in value of y-coordinate directly from current line of geometry specification + System.out.println("Check for Expo"+strToken); + atomCoord[coordIndex + (index - 1)] = Double.parseDouble(strToken); + } + } + break; + + case 3: + // If current line of Z-matrix is in Cartesian format, read in y-coordinate + // for this atom directly from current line of Z-matrix + if (formatCartesian == false) + { + if (formatZCartesian[atomIndex] == true) + { + coordIndex = (3 * atomIndex) + 1; + + // Check if token is a variable or a double value + foundChar = false; + + for (charIndex = 0; charIndex < nchar; charIndex++) + { + if (Character.isLetter(strToken.charAt(charIndex))) + { + foundChar = true; + } + } + + if (foundChar == true) + { + // Retrieve index of y-coordinate variable in 'zmatVarTokens' array list + varIndex = geomVariables.indexOf(strToken); + + // Retrieve value of y-coordinate from 'zmatVarTokens' array list + atomCoord[coordIndex] = Double.parseDouble(geomVarTokens.get(varIndex + 1).toString()); + } + else + { + // Read in value of y-coordinate directly from current line of Z-matrix + atomCoord[coordIndex] = Double.parseDouble(strToken); + } + } + else // Fourth token in this line of Z-matrix is a third atom + { + // Read in this third (alpha) atom directly from current line of Z-matrix + // Check if fourth token is a variable or a numerical value + foundChar = false; + + for (charIndex = 0; charIndex < nchar; charIndex++) + { + if (Character.isLetter(strToken.charAt(charIndex))) + { + foundChar = true; + } + } + + if (foundChar == true) + { + alphaAtomIndex = atomID.indexOf(strToken); + } + else + { + // An integer is being used to identify the atom to which this atom is bonded + alphaAtomIndex = Integer.parseInt(strToken) - 1; + } + } + } + else // If, instead, geometry format is given in Cartesian coordinates, read in + { // z-coordinate directly from geometry specification + // Read in z-coordinate of atom + + coordIndex = 3 * atomIndex; + + // Check if token is a variable or a double value + foundChar = false; + + for (charIndex = 0; charIndex < nchar; charIndex++) + { + if (Character.isLetter(strToken.charAt(charIndex))) + { + foundChar = true; + } + } + + if (foundChar == true) + { + // Retrieve index of z-coordinate variable in 'zmatVarTokens' array list + varIndex = geomVariables.indexOf(strToken); + + // Retrieve value of z-coordinate from 'zmatVarTokens' array list + atomCoord[coordIndex + (index - 1)] = Double.parseDouble(geomVarTokens.get(varIndex + 1).toString()); + } + else + { + // Read in value of z-coordinate directly from current line of Z-matrix + atomCoord[coordIndex + (index - 1)] = Double.parseDouble(strToken); + } + } + break; + + case 4: + // If current line of Z-matrix is in Cartesian format, read in z-coordinate + // for this atom directly from current line of Z-matrix + if (formatZCartesian[atomIndex] == true) + { + coordIndex = (3 * atomIndex) + 2; + + // Check if token is a variable or a double value + foundChar = false; + + for (charIndex = 0; charIndex < nchar; charIndex++) + { + if (Character.isLetter(strToken.charAt(charIndex))) + { + foundChar = true; + } + } + + if (foundChar == true) + { + // Retrieve index of z-coordinate variable in 'zmatVarTokens' array list + varIndex = geomVariables.indexOf(strToken); + + // Retrieve value of z-coordinate from 'zmatVarTokens' array list + atomCoord[coordIndex] = Double.parseDouble(geomVarTokens.get(varIndex + 1).toString()); + } + else + { + // Read in value of z-coordinate directly from current line of Z-matrix + atomCoord[coordIndex] = Double.parseDouble(strToken); + } + } + else // Fifth token in this line of Z-matrix is a bond angle + { + // Read in bond angle from current line of Z-matrix + // Check if fifth token is a variable or a numerical value + foundChar = false; + + for (charIndex = 0; charIndex < nchar; charIndex++) + { + if (Character.isLetter(strToken.charAt(charIndex))) + { + foundChar = true; + } + } + + if (foundChar == true) + { + // Retrieve index of bond angle variable in 'zmatVarTokens' array list + varIndex = geomVariables.indexOf(strToken); + + // Retrieve value of bond angle from 'zmatVarTokens' array list + alpha = Double.parseDouble(geomVarTokens.get(varIndex + 1).toString()); + } + else + { + // Read bond angle directly from this line of the Z-matrix + alpha = Double.parseDouble(strToken); + } + } + break; + + case 5: + // Check if sixth token is a variable or a numerical value + foundChar = false; + + for (charIndex = 0; charIndex < nchar; charIndex++) + { + if (Character.isLetter(strToken.charAt(charIndex))) + { + foundChar = true; + } + } + + if (foundChar == true) + { + gammaAtomIndex = atomID.indexOf(strToken); + } + else + { + // An integer is being used to identify the atom to which this atom is bonded + gammaAtomIndex = Integer.parseInt(strToken) - 1; + } + break; + + case 6: + coordIndex = 3 * atomIndex; + // Read in dihedral angle from current line of Z-matrix + // Check if fifth token is a variable or a numerical value + foundChar = false; + + for (charIndex = 0; charIndex < nchar; charIndex++) + { + if (Character.isLetter(strToken.charAt(charIndex))) + { + foundChar = true; + } + } + + if (foundChar == true) + { + // Retrieve index of dihedral angle variable in 'zmatVarTokens' array list + varIndex = geomVariables.indexOf(strToken); + + // Retrieve value of dihedral angle from 'zmatVarTokens' array list + gamma = Double.parseDouble(geomVarTokens.get(varIndex + 1).toString()); + } + else + { + // Read bond angle directly from this line of the Z-matrix + gamma = Double.parseDouble(strToken); + } + break; + } + } + + switch(nelem) + { + case 5: + if (formatZCartesian[atomIndex] == false) + { + coordIndex = 3 * atomIndex; + + // Get unit vectors (nx, ny, and nz) along bond from bonded atom (atom2) to alpha atom (atom1) + alphaAtomCoordIndex = 3 * alphaAtomIndex; + bondedAtomCoordIndex = 3 * bondedAtomIndex; + + x1 = atomCoord[alphaAtomCoordIndex] - atomCoord[bondedAtomCoordIndex]; + y1 = atomCoord[alphaAtomCoordIndex + 1] - atomCoord[bondedAtomCoordIndex + 1]; + z1 = atomCoord[alphaAtomCoordIndex + 2] - atomCoord[bondedAtomCoordIndex + 2]; + + // Compute normalization factor + r = Math.sqrt( (x1 * x1) + (y1 * y1) + (z1 * z1) ); + + // Compute unit vectors along bond + nx = x1/r; + ny = y1/r; + nz = z1/r; + + // Get coordinates of alpha atom relative to axis of rotation before rotation + prerotCoord[0] = nx * bondDistance; + prerotCoord[1] = ny * bondDistance; + prerotCoord[2] = nz * bondDistance; + + // Get unit vectors (nx, ny, and nz) along axis of bond angle rotation through bonded atom + // Rotate about an axis perpendicular to the z-axis and the direction of the bond + + // Compute unit vectors along rotation axis + if (nz == 1.0) + { + nx = -1.0; // rotate counterclockwise about rotation axis + ny = 0.0; + nz = 0.0; + } + else if (nz == -1.0) + { + nx = 1.0; + ny = 0.0; + nz = 0.0; + } + else + { + nx = -y1/r; + ny = x1/r; + nz = 0.0; + } + + // Rotate coordinates counterclockwise by 'alpha' radians about axis of rotation + // Convert bond angle from degrees to radians + alpha = alpha * (Math.PI/180); + + // Compute rotation matrix + rotMatrix = getRotMatrix(alpha, nx, ny, nz); + + // Compute rotated coordinates + rotCoord = getRotatedCoordinates(rotMatrix, prerotCoord); + + // Compute final atomic coordinates for this atom + for (j = 0; j < 3; j++) + { + atomCoord[coordIndex + j] = atomCoord[bondedAtomCoordIndex + j] + rotCoord[j]; + } + } + break; + + case 7: + coordIndex = 3 * atomIndex; + + // Get unit vectors (nx, ny, and nz) along bond from bonded atom (atom3) to alpha atom (atom2) + gammaAtomCoordIndex = 3 * gammaAtomIndex; + alphaAtomCoordIndex = 3 * alphaAtomIndex; + bondedAtomCoordIndex = 3 * bondedAtomIndex; + + x1 = atomCoord[alphaAtomCoordIndex] - atomCoord[bondedAtomCoordIndex]; + y1 = atomCoord[alphaAtomCoordIndex + 1] - atomCoord[bondedAtomCoordIndex + 1]; + z1 = atomCoord[alphaAtomCoordIndex + 2] - atomCoord[bondedAtomCoordIndex + 2]; + + if (bondOrder[gammaAtomIndex][bondedAtomIndex] > 0) + { + rotCoord[0] = atomCoord[gammaAtomIndex]; + rotCoord[1] = atomCoord[gammaAtomIndex + 1]; + rotCoord[2] = atomCoord[gammaAtomIndex + 2]; + } + else + { + // Compute normalization factor + r = Math.sqrt( (x1 * x1) + (y1 * y1) + (z1 * z1) ); + + nx = x1/r; + ny = y1/r; + nz = z1/r; + + // Get coordinates of alpha atom relative to axis of rotation before rotation + prerotCoord[0] = nx * bondDistance; + prerotCoord[1] = ny * bondDistance; + prerotCoord[2] = nz * bondDistance; + + // Get unit vectors (nx, ny, and nz) along axis of bond angle rotation through bonded atom + + // Compute direction numbers for bond vector between gamma atom (atom 1) + // and alpha atom (atom 2) to point from alpha atom to bonded atom + x2 = atomCoord[gammaAtomCoordIndex] - atomCoord[alphaAtomCoordIndex]; + y2 = atomCoord[gammaAtomCoordIndex + 1] - atomCoord[alphaAtomCoordIndex + 1]; + z2 = atomCoord[gammaAtomCoordIndex + 2] - atomCoord[alphaAtomCoordIndex + 2]; + + // Compute direction numbers for rotation axis normal to the plane containing the gamma (atom 1), + // alpha (atom 2), and bonded atoms (atom 3) as cross-product of bond vectors: (r2) x (r1) + nx = (y2 * z1) - (y1 * z2); + ny = (x1 * z2) - (x2 * z1); + nz = (x2 * y1) - (x1 * y2); + + // Compute normalization factor + r = Math.sqrt( (nx * nx) + (ny * ny) + (nz * nz) ); + + // Compute unit vectors along axis of rotation + nx = nx/r; + ny = ny/r; + nz = nz/r; + + // Rotate coordinates counterclockwise by 'alpha' radians about axis of rotation + // Convert bond angle from degrees to radians + alpha = alpha * (Math.PI/180); + + // Compute rotation matrix + rotMatrix = getRotMatrix(alpha, nx, ny, nz); + + // Compute rotated coordinates + rotCoord = getRotatedCoordinates(rotMatrix, prerotCoord); + } + + // If dihedral angle is not zero, rotate bond counterclockwise about an axis defined + // by bond vector pointing from alpha atom (atom 2) to bonded atom (atom 3). + // This is the dihedral rotation axis + if (gamma != 0) + { + // Set pre-rotated coordinates equal to coordinates rotated through the bond angle alpha + for (j = 0; j < 3; j++) + { + prerotCoord[j] = rotCoord[j]; + } + + // Direction numbers along bond between alpha atom and bonded atom are x1, y1, and z1 + + // Compute normalization factor + r = Math.sqrt( (x1 * x1) + (y1 * y1) + (z1 * z1) ); + + // Compute unit vectors along dihedral angle rotation axis + nx = x1/r; + ny = y1/r; + nz = z1/r; + + // Rotate coordinates counterclockwise by 'gamma' radians about axis of rotation + // Convert dihedral angle from degrees to radians + gamma = gamma * (Math.PI/180); + + // Compute rotation matrix + rotMatrix = getRotMatrix(gamma, nx, ny, nz); + + // Compute rotated coordinates + rotCoord = getRotatedCoordinates(rotMatrix, prerotCoord); + } + + // Compute final atomic coordinates for this atom + for (j = 0; j < 3; j++) + { + atomCoord[coordIndex + j] = atomCoord[bondedAtomCoordIndex + j] + rotCoord[j]; + } + break; + } + } + +/////// + validateGeom = ""; + validateGeom += InputfileReader.charge+" "+ InputfileReader.spinmult+"\n"; + + //Eliminate "E-16" for too low values + + for(int p=0;p<3*natoms;p++) + + { + String exponentialCheck = String.valueOf(atomCoord[p]); + int indexNo = exponentialCheck.indexOf("E"); + System.out.println("In the function"+ indexNo); + System.out.println("In the function"+atomCoord[p]); + + if(indexNo>0) + { + atomCoord[p] = 0.0; + } + + } + + + + + + System.out.println(" "); + System.out.println("GeometryEditor_1001:The coordinates of the atoms are:"); + for (j = 0; j < natoms; j++) + { + k = 3 * j; + + System.out.print("atom " + atomSymb[j] + ": " + atomCoord[k] + ", " + atomCoord[k + 1] + ", " + atomCoord[k + 2]+"\n"); + validateGeom += atomSymb[j]+" "+ atomCoord[k] + " " + atomCoord[k+1] + " " + atomCoord[k+2]+ "\n" ; + } +/////// +System.out.println("The constructed structure is"+validateGeom); + } + + public double[][] getRotMatrix(double angle, double nx, double ny, double nz) + { + double[][] rotMatrix = new double[3][3]; + + // Rotation matrix for counterclockwise rotation about axis where the unit vectors + // along the direction of the axis are nx, ny, and nz + rotMatrix[0][0] = (nx * nx) + ( Math.cos(angle) * (1 - nx * nx) ); + rotMatrix[0][1] = ( (nx * ny) * (1 - Math.cos(angle)) ) + (nz * Math.sin(angle)); + rotMatrix[0][2] = ( (nz * nx) * (1 - Math.cos(angle)) ) - (ny * Math.sin(angle)); + + rotMatrix[1][0] = ( (nx * ny) * (1 - Math.cos(angle)) ) - (nz * Math.sin(angle)); + rotMatrix[1][1] = (ny * ny) + ( Math.cos(angle) * (1 - ny * ny) ); + rotMatrix[1][2] = ( (ny * nz) * (1 - Math.cos(angle)) ) + (nx * Math.sin(angle)); + + rotMatrix[2][0] = ( (nz * nx) * (1 - Math.cos(angle)) ) + (ny * Math.sin(angle)); + rotMatrix[2][1] = ( (ny * nz) * (1 - Math.cos(angle)) ) - (nx * Math.sin(angle)); + rotMatrix[2][2] = (nz * nz) + ( Math.cos(angle) * (1 - nz * nz) ); + + return rotMatrix; + } + + public double[] getRotatedCoordinates(double[][] rotMatrix, double[] prerotCoord) + { + double[] rotCoord = new double[3]; + + // Rotate coordinates counterclockwise by the dihedral angle (in radians) about axis of rotation + for (int j = 0; j < 3; j++) + { + rotCoord[j] = 0.0; + + for(int k = 0; k < 3; k++) + { + rotCoord[j] += rotMatrix[j][k] * prerotCoord[k]; + } + } + + return rotCoord; + } + } + + public static void main(String[] args) + { + new GeometryEditor(); + } +} + diff --git a/src/main/java/g03input/GuessOptTable.java b/src/main/java/g03input/GuessOptTable.java new file mode 100644 index 0000000..dfd7bc5 --- /dev/null +++ b/src/main/java/g03input/GuessOptTable.java @@ -0,0 +1,389 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Mar 30, 2005 + * @author Michael Sheetz + * @author Sandeep Kumar Seethaapathy @author Shashank Jeedigunta + * + */ + + +package g03input; + +import javax.swing.*; +import javax.swing.event.TableModelEvent; +import javax.swing.table.DefaultTableModel; +import java.awt.*; +import java.awt.event.*; +import java.util.Vector; + +public class GuessOptTable extends JFrame implements ItemListener,ActionListener { + Color bgColor= new Color(236,233,216); + Color foreColor =new Color(0,78,152); + JPanel donePanel; + JButton doneButton,clearButton,exitButton; + public static JTable table; + JFrame guessOptFrame; + public static JRadioButton GHarri=new JRadioButton("Harris"); + public static JRadioButton GLowsy=new JRadioButton("LowSymm"); + public static JRadioButton GPermu = new JRadioButton("Permute"); + public static JRadioButton GPrint = new JRadioButton("Print"); + public static JRadioButton GProje= new JRadioButton("Projected"); + public static JRadioButton GNosym =new JRadioButton("NoSymm"); + public static JRadioButton GAlter = new JRadioButton("Alter"); + public static JRadioButton GNatur =new JRadioButton("NaturalOrbitals"); + public static JRadioButton GHucke = new JRadioButton("Huckel"); + public static JRadioButton GMix = new JRadioButton("Mix"); + public static JRadioButton GOldhu = new JRadioButton("OldHuckel"); + public static JRadioButton GLocal = new JRadioButton("Local"); + public static JRadioButton GIndo = new JRadioButton("INDO"); + public static JRadioButton GCards= new JRadioButton("Cards"); + public static JRadioButton GAm1 = new JRadioButton("AM1"); + public static JRadioButton GForce = new JRadioButton("ForceAbelianSymmetry"); + public static JRadioButton GCore = new JRadioButton("Core"); + public static JRadioButton GRead = new JRadioButton("Read"); + public static JRadioButton GAlway =new JRadioButton("Always"); + public static JRadioButton GOnly = new JRadioButton("Only"); + public static JRadioButton GDensi =new JRadioButton("DensityMix[=N]"); + public static JRadioButton GTrans = new JRadioButton("Translate"); + public static JRadioButton GNotra=new JRadioButton("NoTranslate"); + public static JRadioButton GAlpha = new JRadioButton("Alpha"); + public static JRadioButton GExtra = new JRadioButton("Extra"); + public static JRadioButton GNoext = new JRadioButton("NoExtra"); + public static Vector guessOpt; + public static Vector guessClear; +public static int guessC,guessOptC; +public static int guessFlag,guessListen; + public GuessOptTable(){ + + guessOptFrame = new JFrame("Guess Options"); + if(guessListen==0) + { + guessClear=new Vector(40); + guessClear.addElement(GHarri); + guessClear.addElement(GLowsy); + guessClear.addElement(GPermu); + guessClear.addElement(GPrint); + guessClear.addElement(GProje); + guessClear.addElement(GNosym); + guessClear.addElement(GAlter); + guessClear.addElement(GNatur); + guessClear.addElement(GHucke); + guessClear.addElement(GMix); + guessClear.addElement(GOldhu); + guessClear.addElement(GLocal); + guessClear.addElement(GIndo); + guessClear.addElement(GCards); + guessClear.addElement(GAm1); + guessClear.addElement(GForce); + guessClear.addElement(GCore); + guessClear.addElement(GRead); + guessClear.addElement(GAlway); + guessClear.addElement(GOnly); + guessClear.addElement(GTrans); + guessClear.addElement(GNotra); + guessClear.addElement(GAlpha); + guessClear.addElement(GExtra); + guessClear.addElement(GNoext); + + GHarri.addItemListener(this); + GHarri.setBackground(Color.WHITE); + GLowsy.addItemListener(this); + GLowsy.setBackground(Color.WHITE); + GPermu.addItemListener(this); + GPermu.setBackground(Color.WHITE); + GPrint.addItemListener(this); + GPrint.setBackground(Color.WHITE); + GProje.addItemListener(this); + GProje.setBackground(Color.WHITE); + GAlter.addItemListener(this); + GAlter.setBackground(Color.WHITE); + GNosym.addItemListener(this); + GNosym.setBackground(Color.WHITE); + GNatur.addItemListener(this); + GNatur.setBackground(Color.WHITE); + GHucke.addItemListener(this); + GHucke.setBackground(Color.WHITE); + GMix.addItemListener(this); + GMix.setBackground(Color.WHITE); + GOldhu.addItemListener(this); + GOldhu.setBackground(Color.WHITE); + GLocal.addItemListener(this); + GLocal.setBackground(Color.WHITE); + GIndo.addItemListener(this); + GIndo.setBackground(Color.WHITE); + GCards.addItemListener(this); + GCards.setBackground(Color.WHITE); + GAm1.addItemListener(this); + GAm1.setBackground(Color.WHITE); + GForce.addItemListener(this); + GForce.setBackground(Color.WHITE); + GCore.addItemListener(this); + GCore.setBackground(Color.WHITE); + GRead.addItemListener(this); + GRead.setBackground(Color.WHITE); + GAlway.addItemListener(this); + GAlway.setBackground(Color.WHITE); + GOnly.addItemListener(this); + GOnly.setBackground(Color.WHITE); + // GSave.addItemListener(this); + // GSave.setBackground(Color.WHITE); + GDensi.addItemListener(this); + GDensi.setBackground(Color.WHITE); + GTrans.addItemListener(this); + GTrans.setBackground(Color.WHITE); + GNotra.addItemListener(this); + GNotra.setBackground(Color.WHITE); + GAlpha.addItemListener(this); + GAlpha.setBackground(Color.WHITE); + GExtra.addItemListener(this); + GExtra.setBackground(Color.WHITE); + GNoext.addItemListener(this); + GNoext.setBackground(Color.WHITE); + guessListen++; + } + + //UIDefaults ui = UIManager.getLookAndFeel().getDefaults(); + + //UIManager.put("RadioButton.focus", ui.getColor("control")); + guessOptFrame.setBackground(bgColor); + guessOptFrame.setForeground(foreColor); + DefaultTableModel dm = new DefaultTableModel(); + dm.setDataVector( + new Object[][]{ + + {GHarri,GLowsy,GPermu,GPrint}, + {GProje,GNosym,GAlter,GNatur}, + {GHucke,null,GMix,null}, + {GOldhu,null,GLocal,null}, + {GIndo,null,GCards,null}, + {GAm1,null,GForce,null}, + {GCore,null,null,null}, + {GRead,null,null,null}, + {GAlway,null,null,null}, + {GOnly,null,null,null}, + // {GSave,null,null,null}, + {GDensi,null,null,null}, + {GTrans,null,null,null}, + {GNotra,null,null,null}, + {GAlpha,null,null,null}, + {GExtra,null,null,null}, + {GNoext,null,null,null},}, + + new Object[]{"Initial Guess","Orbital Symmetry","Orbital Manipulation","Additional Options"}); + + JTable table = new JTable(dm) { + public void tableChanged(TableModelEvent e) { + super.tableChanged(e); + repaint(); + } + }; + + + /*ButtonGroup group1 = new ButtonGroup(); + group1.add((JRadioButton)dm.getValueAt(0,1)); + group1.add((JRadioButton)dm.getValueAt(1,1)); + group1.add((JRadioButton)dm.getValueAt(2,1)); + ButtonGroup group2 = new ButtonGroup(); + group2.add((JRadioButton)dm.getValueAt(3,1)); + group2.add((JRadioButton)dm.getValueAt(4,1));*/ + table.getColumn("Initial Guess").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Initial Guess").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + table.getColumn("Orbital Symmetry").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Orbital Symmetry").setCellEditor(new RadioButtonEditor(new JCheckBox())); + table.getColumn("Orbital Manipulation").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Orbital Manipulation").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + table.getColumn("Additional Options").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Additional Options").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + doneButton = new JButton("Done"); + doneButton.addActionListener(this); + //clearButton = new JButton("Clear"); + exitButton = new JButton("Exit"); + //doneButton.addActionListener() + // clearButton.addActionListener(this); + exitButton.addActionListener(this); + + donePanel = new JPanel(); + donePanel.add(doneButton); + + donePanel.add(exitButton); + + /*table.setBackground(bgColor); + table.setForeground(foreColor); + */ + + + donePanel.setBackground(bgColor); + donePanel.setForeground(foreColor); + + + table.getTableHeader().setReorderingAllowed(false); + + + + guessOptFrame.getContentPane().setLayout(new BorderLayout()); + JScrollPane scroll = new JScrollPane(table); + guessOptFrame.getContentPane().add( scroll,BorderLayout.CENTER); + guessOptFrame.getContentPane().add(donePanel,BorderLayout.SOUTH); + guessOptFrame.setSize( 600,200); + guessOptFrame.setLocation(200,75); + guessOptFrame.setVisible(true); + } + public void actionPerformed(ActionEvent ae) + { if(ae.getSource()==exitButton) + { + guessOptFrame.dispose(); + } + if(ae.getSource()==doneButton){ + System.out.println("The value of freq guessV = "+guessC); + if(RouteClass.initCount==0) + { + System.out.println(RouteClass.initCount+" \tInside init"); + RouteClass.initBuffer(); + RouteClass.initCount++; + } + if(guessC==0) + { + System.out.println(guessC+" \t Inside guessC"); + guessFlag= RouteClass.keyIndex; + RouteClass.keyIndex++; + guessC++; + } + else + { + System.out.println("Guess Check"); + RouteClass.keywordBuffer[guessFlag]=new StringBuffer(); + } + RouteClass.keywordBuffer[guessFlag].append("Guess"); + if(!(InsertNode.nodeExists("Guess"))) + InsertNode.insertNode("Job", "Guess"); + try { + if(guessOpt.size()>1) + { + RouteClass.keywordBuffer[guessFlag].append("=("); + for(int count=0;count0) + RouteClass.keywordBuffer[guessFlag].append("="+"("+guessOpt.get(0)+")"); + } + } catch (NullPointerException e) { + // TODO Auto-generated catch block + // e.printStackTrace(); + } + //guessFlag=RouteClass.keyIndex; + guessOptFrame.dispose(); + RouteClass.writeRoute(); + } + } + + + public void itemStateChanged(ItemEvent e) + {if((e.getItem()==GHarri)|| + (e.getItem()==GLowsy)|| + (e.getItem()==GPermu)|| + (e.getItem()==GPrint)|| + (e.getItem()==GProje)|| + (e.getItem()==GNosym)|| + (e.getItem()==GAlter)|| + (e.getItem()==GNatur)|| + (e.getItem()==GHucke)|| + (e.getItem()==GMix)|| + (e.getItem()==GOldhu)|| + (e.getItem()==GLocal)|| + (e.getItem()==GIndo)|| + (e.getItem()==GCards)|| + (e.getItem()==GAm1)|| + (e.getItem()==GForce)|| + (e.getItem()==GRead)|| + (e.getItem()==GAlway)|| + (e.getItem()==GOnly)|| + // (e.getItem()==GSave)|| + (e.getItem()==GTrans)|| + (e.getItem()==GNotra)|| + (e.getItem()==GAlpha)|| + (e.getItem()==GExtra)|| + (e.getItem()==GNoext)) + { + G03Listener.guessTabF++; + if(((JRadioButton)e.getItem()).isSelected()) + { + if(guessOptC==0) + { + guessOpt = new Vector(10); + guessOptC++; + } + if(!(InsertNode.nodeExists("Guess"))) + + InsertNode.insertNode("Jo", "Guess"); + InsertNode.insertNode("Guess", RadioButtonEditor.button.getActionCommand()); + String guess = RadioButtonEditor.button.getActionCommand(); + guessOpt.addElement(guess); + //guessOptCount++; + }//System.out.println(e.getActionCommand()); + + else + { + if(InsertNode.nodeExists(((JRadioButton) e.getItem()).getActionCommand())) + InsertNode.deleteNode(((JRadioButton) e.getItem()).getActionCommand()); + guessOpt.removeElement(((JRadioButton)e.getItem()).getActionCommand()); + } + } + } + + public static void main(String[] args) { + GuessOptTable frame = new GuessOptTable(); + frame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + System.exit(0); + } + }); + } +} diff --git a/src/main/java/g03input/InputFile.java b/src/main/java/g03input/InputFile.java new file mode 100644 index 0000000..c3d93ed --- /dev/null +++ b/src/main/java/g03input/InputFile.java @@ -0,0 +1,434 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Apr 6, 2005 + * @author Michael Sheetz + * @author Shashank Jeedigunta @author Sandeep Kumar Seethaapathy + * + */ + +package g03input; + +import javax.swing.*; +import javax.swing.filechooser.FileFilter; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.*; +import java.util.regex.Pattern; + +public class InputFile extends JFrame implements ActionListener { + + private static JFileChooser inputChooser; + private static FileFilter inputFilter; + public static JFrame inputFrame; + public static JMenuBar inputBar; + public static JMenu fileMenu,editMenu,molEditor; + public static JMenuItem open,close,save,saveas,cut,copy,paste,selectall; + public static JPanel inputPanel,textPanel; + public static JTextArea inputText; + public static String tempinput=""; + public static int inputsaved=0,choiceclose,inputfetched; + + + public InputFile() + { + textPanel=new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.fill=GridBagConstraints.BOTH; + + + JFrame.setDefaultLookAndFeelDecorated(true); + JDialog.setDefaultLookAndFeelDecorated(true); + inputFrame = new JFrame("Input File"); + inputFrame.setSize(500,250); + inputFrame.setLocation(25,50); + + inputFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + //mainFrame.setSize(screenSize.width-20,screenSize.height-100); + //molFrame.setSize(screenSize.width-280,screenSize.height-240); + + + inputPanel = new JPanel(new BorderLayout()); + + inputBar = new JMenuBar(); + fileMenu = new JMenu("File"); + editMenu = new JMenu("Edit"); + + + open = new JMenuItem("Open"); + close = new JMenuItem("Close"); + save = new JMenuItem("Save"); + saveas = new JMenuItem("SaveAs"); + + cut = new JMenuItem("Cut"); + copy = new JMenuItem("Copy"); + paste = new JMenuItem("Paste"); + selectall = new JMenuItem("Select All"); + + + fileMenu.add(open); + fileMenu.add(save); + fileMenu.add(new JSeparator()); + fileMenu.add(close); + editMenu.add(cut); + editMenu.add(copy); + editMenu.add(paste); + editMenu.add(new JSeparator()); + editMenu.add(selectall); + + + cut.addActionListener(this); + copy.addActionListener(this); + paste.addActionListener(this); + selectall.addActionListener(this); + save.addActionListener(this); + close.addActionListener(this); + open.addActionListener(this); + + + inputBar.add(fileMenu); + inputBar.add(editMenu); + + + inputPanel.add(inputBar,BorderLayout.NORTH); + + inputText = new JTextArea("",35,70); + + System.out.println(tempinput); + if(tempinput!=null) + { + inputText.setText(tempinput); + inputText.setCaretPosition(tempinput.length()); + } + // + else + inputText.setCaretPosition(0); + inputText.setMargin(new Insets(5,5,5,5)); + inputText.setLineWrap(true); + // StyledDocument styledDoc = inputText.getStyledDocument(); + + + // + JScrollPane mScroll = new JScrollPane(inputText); + mScroll.setWheelScrollingEnabled(true); + + inputPanel.add(mScroll,BorderLayout.CENTER); + //inputPanel.add(textPanel,BorderLayout.CENTER); + inputFrame.getContentPane().add(inputPanel); + //molFrame.getContentPane().add(textPanel); + inputFrame.pack(); + inputFrame.setResizable(true); + inputFrame.setVisible(false); + } + + + + public static void getFile(String filepath) + { + // copies the file from user specified location to + // the buffer tempinput + try + { + // Open the file that is the first + FileInputStream fstream = new FileInputStream(filepath); + + DataInputStream in = new DataInputStream(fstream); + tempinput=""; + while (in.available() !=0) + { + // Print file line to screen + tempinput+=in.readLine(); + tempinput+="\n"; + } + + in.close(); + } + + catch (Exception e) + { + JOptionPane.showMessageDialog(null,"File input error","Error",JOptionPane.ERROR_MESSAGE); + } + + inputfetched=1; + new InputfileReader(); + + + + /*Give the Geometry Section of the file to MolEditor for Display + It will be saved in tempmolFromInput String */ + showMolEditor.tempmol = new String(InputfileReader.geom); + G03MenuTree.nanocadNotice.setText("Molecular Specification Imported from Inputfile"); + // System.out.println("This is a test"+showMolEditor.tempmolFromInput); + } + + public void doFetchInputFile() + { + // Open a FileChooser with *.com Filter + + inputChooser = new JFileChooser(); + inputFilter = new FileFilter() + { + public boolean accept(File f) + { + if(f.isDirectory()) return true; + return f.getName().endsWith(".com"); + } + + public String getDescription() + { + return "(*.com) Input Files"; + } + + }; + inputChooser.setFileFilter(inputFilter); + + int state = inputChooser.showOpenDialog(null); + File file = inputChooser.getSelectedFile(); + + if(file != null && + state == JFileChooser.APPROVE_OPTION) { + // JOptionPane.showMessageDialog( + // null, file.getPath()); + getFile(file.getPath()); + + } + else if(state == JFileChooser.CANCEL_OPTION) { + JOptionPane.showMessageDialog( + null, "Input File Selection Canceled"); + } + + + } + + void replaceMolFile(){ + BufferedReader br= new BufferedReader(new StringReader(InputFile.tempinput)); + boolean matchedcharge=false,matchedmol=false; + StringBuffer molString=new StringBuffer(); + String temp="$"; + System.out.println("InputFile.java -> Inside replaceMolFile"); + + //Reads the input file until the charge and multiplicity are obtained + while(matchedcharge==false) + { + try { + temp=br.readLine(); + + if(temp==null) //EOF no luck + { + System.out.println("InputFile.java -> Inside replaceMolFile -> temp== null EOF"); + break; + } + + matchedmol=Pattern.matches("[A-Z][a-z]?[\\s]+[\\+|\\-]?[0-9]+\\.?[0-9]+[\\s]+[\\+|\\-]?[0-9]+\\.?[0-9]+[\\s]+[\\+|\\-]?[0-9]+\\.?[0-9]+[\\s]*",temp); + + if(matchedmol==true) // Charge & multiplicity not yet entered Mol. Specification exists + { + System.out.println("InputFile.java -> Inside replaceMolFile -> Found Mol Specification Getting out of the Loop"); + break; + + } + + matchedcharge= Pattern.matches("[\\s]*[\\+|\\-]?[0-9]+\\.?[0-9]*[\\s]*[\\+|\\-]?[0-9]+\\.?[0-9]*[\\s]*",temp); + + System.out.println("InputFile.java -> Inside replaceMolFile -> Still in the Loop"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + while(temp!=null) // Till the end of file + { + System.out.println("InputFile.java -> Inside replaceMolFile() -> Second Loop"); + try { + if(matchedmol!=true) + { temp=br.readLine(); + System.out.println("InputFile.java -> Inside replaceMolFile() -> Second Loop -> matchedmol is not true"); + matchedmol=true; + } + + molString.append(temp+"\n"); + System.out.println("InputFile.java -> Inside replaceMolFile() -> Second Loop-> Appended the temp"+temp+"$$"); + temp=br.readLine(); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + + } + + showMolEditor.tempmol = molString.toString(); + /*inputString.append(tempmol); + InputFile.tempinput=inputString.toString(); + */ + + } + + + + + public void actionPerformed(ActionEvent ae) + { + if(ae.getSource()== G03MenuTree.importFile) + { + + //Code to check if the input file needs to be overwritten if there are GUI selections + // Uky 09/08/05 + + if((G03MenuTree.nooflpText.getText().toString().length() > 0)|| + (G03MenuTree.noofspText.getText().toString().length() > 0)|| + (G03MenuTree.dynmemText.getText().toString().length() > 0)|| + (RouteClass.routeBuffer.toString().length() > 4)|| + (G03MenuTree.molCharge.getText().toString().length() > 0) || + (G03MenuTree.molMultiplicity.getText().toString().length() > 0) || + (G03MenuTree.filnamArea.getText().toString().length() > 0)|| + (G03MenuTree.nooflpText.getText().toString().length() > 0)) + + { + int inputChoice = JOptionPane.showConfirmDialog(null,"GUI selections already made for Input File. Do you still want to Fetch an input File","Overwrite Warning",JOptionPane.YES_NO_OPTION); + if(inputChoice == 0) + { + doFetchInputFile(); + } + else + { + } + } + else + { + if(inputfetched == 0) + { + doFetchInputFile(); + } + else + { + // input already fetched .. overwrite it?? + int inputChoice = JOptionPane.showConfirmDialog(null,"You just fetched an Input File. Do you still want to fetch another input file and overwrite the existing one?","Overwrite Warning",JOptionPane.YES_NO_OPTION); + if(inputChoice == 0) + { + doFetchInputFile(); + } + else + { + // Do nothing.. the file first fetched will remain the same. + + } + + + + + + } + } + //inputfetched = 0; + + } + + + + + /* Commented for modi + doFetchInputFile(); + } Commented for modi */ + + if(ae.getSource()== open) + { + inputFrame.dispose(); + doFetchInputFile(); + new InputFile(); + inputFrame.setVisible(true); + } + if(ae.getSource()== G03MenuTree.editFile) + { + + RouteClass.createInput(); + new InputFile(); + inputFrame.setVisible(true); + + + } + + if(ae.getSource()== G03MenuTree.copyFile) + { + + + + } + + if(ae.getSource()==cut) + inputText.cut(); + if(ae.getSource()==copy) + inputText.copy(); + if(ae.getSource()==paste) + inputText.paste(); + if(ae.getSource()==selectall) + inputText.selectAll(); + if(ae.getSource()==save) + { tempinput=inputText.getText(); + + if(InputFile.inputfetched==1) + new InputfileReader(); // Added on Sep 15 2005 @ UKY + + else // file not imported + { + System.out.println("InputFile.java -> About to Replace the Mol"); + replaceMolFile(); + + } + inputsaved=1; + } + if(ae.getSource()==close) + { + if(inputText.getText().length()==0 || (inputText.getText().length()==tempinput.length())) + inputsaved=1; + + if(inputsaved==0) // not saved + choiceclose= JOptionPane.showConfirmDialog(null,"The Changes you made will not be saved.Do you want to continue?","Do you want to Continue?",JOptionPane.YES_NO_OPTION); + if(choiceclose==0||inputsaved==1) + inputFrame.dispose(); + inputsaved=0; + } + + } +} diff --git a/src/main/java/g03input/InputfileReader.java b/src/main/java/g03input/InputfileReader.java new file mode 100644 index 0000000..4f050f9 --- /dev/null +++ b/src/main/java/g03input/InputfileReader.java @@ -0,0 +1,412 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Sep 15, 2005 + * @author Michael Sheetz + * @author Sandeep Kumar Seethaapathy @author Shashank Jeedigunta + * + */ +package g03input; + +import javax.swing.*; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.ArrayList; +import java.util.NoSuchElementException; +import java.util.StringTokenizer; + +public class InputfileReader extends JFrame +{ + public static int nproc, mbRequested, charge, spinmult; + String chkfileName = new String(); + public static String route = new String(); + String title = new String(); + public static String geom = new String(); + public static String chrgStr,mulStr; + boolean readchk = false; + boolean readallchk = false; + + InfileReader infile; + + public InputfileReader() // Constructor + { + infile = new InfileReader(); + + addWindowListener(new WindowEventHandler()); + } + + // Define window listener class + class WindowEventHandler extends WindowAdapter + { + public void windowClosing(WindowEvent e) + { + System.exit(0); + } + } + + // Define readZmatrix class + class InfileReader + { + InfileReader() // Constructor + { + int i, j, k, index; + +////// + StringBuffer sbInfile = new StringBuffer(); + /* sbInfile.append("%nproc=8\n"); + sbInfile.append("%mem=2500MB\n"); + sbInfile.append("%chk=ZnO_wurtzite\n"); + sbInfile.append("#HF/6-31G(d) Opt=ModRedundant\n"); +// sbInfile.append("#HF/6-31G(d) Opt=ModRedundant Geom=Check\n"); +// sbInfile.append("#HF/6-31G(d) Opt=ModRedundant Geom=AllCheck\n"); + sbInfile.append("\n"); + sbInfile.append("Optimization of wurtzite crystal structure\n"); + sbInfile.append("\n"); + sbInfile.append("0 1\n"); + /* sbInfile.append("C1\n"); + sbInfile.append("C2 C1 1.34\n"); + sbInfile.append("C3 C2 1.52 C1 120.0 \n"); + sbInfile.append("H1 C1 1.09 C2 120.0 C3 0.0\n"); + sbInfile.append("H2 C1 1.09 C2 120.0 C3 180.0\n"); + sbInfile.append("H3 C2 1.09 C1 120.0 C3 180.0\n"); + sbInfile.append("H4 C3 1.09 C2 109.5 C1 180.0\n"); + sbInfile.append("H5 C3 1.09 C2 109.5 C1 60.0\n"); + sbInfile.append("H6 C3 1.09 C2 109.5 C1 -60.0\n"); + sbInfile.append("\n"); + + */ + /* sbInfile.append("C 0.07707692307692304 -0.13453846153846155 -0.41484615384615386"+"\n"+ + "C -1.1679230769230768 0.7184615384615385 -0.19184615384615383"+"\n"+ + "N 0.11807692307692305 -1.2305384615384616 0.6011538461538461"); */ +////// + +// Note: 'strInfile' will be read in directly from JTextArea instead of from the above StringBuffer 'sbInfile' + + String strInfile=""; + strInfile = new String(InputFile.tempinput.toString().trim());// + "\n" + "\n"); + // strInfile = new String(sbInfile.toString().trim());// + "\n" + "\n"); + String substr, strInfileLine, strToken, strRouteToken; + + String[] strInputFile; + String[] routeTokens; + + StringBuffer sbMem = new StringBuffer(); + StringBuffer sbMemUnits = new StringBuffer(); + StringBuffer sbQSM = new StringBuffer(); + StringBuffer sbGeom = new StringBuffer(); + + StringTokenizer stok; + + ArrayList inputFileTokens = new ArrayList(); + ArrayList blankLineIndex = new ArrayList(); + + double memconvfactor = 0.0; + + int nblankLines, nInfileTokens, nInfileLines, nrouteTokens; + int chrIndex, tokenIndex, geomIndex; + int nblanklinesRead = 0; + + int[] lineNumbers; + int[] newlineIndex; + int[] blanklineTerminatedLineNumbers; + + boolean foundRoute = false; + boolean foundTitle = false; + boolean foundQSM = false; + boolean foundGeom = false; + boolean counterpoise = false; + + // Tokenize input file on newline only as delimiter and return delimiter (number + // of consecutive newline characters will count number of blank lines) + stok = new StringTokenizer(strInfile, "\n", true); + + // Determine total number of tokens in input file + nInfileTokens = stok.countTokens(); + + lineNumbers = new int[nInfileTokens]; + newlineIndex = new int[nInfileTokens]; + + // Initialize newlineIndex + for (j = 0; j < nInfileTokens; j++) + { + newlineIndex[j] = 0; + } + + while (stok.hasMoreTokens()) + { + strToken = new String(stok.nextToken()); + + inputFileTokens.add(strToken); + } + + index = 0; + nblankLines = 0; + + for (j = 1; j < nInfileTokens; j++) + { + if (inputFileTokens.get(j).toString().equals("\n")) + { + newlineIndex[index] = j; + + if (index > 0) + { + if (((newlineIndex[index] - newlineIndex[index - 1]) == 1) && (newlineIndex[index] != 0)) + { + nblankLines++; + } + } + + index++; + } + } + + blanklineTerminatedLineNumbers = new int[nblankLines]; + + k = 0; + + for (j = 1; j < nInfileTokens; j++) + { + if (((newlineIndex[j] - newlineIndex[j - 1]) == 1) && (newlineIndex[j] != 0)) + { + blanklineTerminatedLineNumbers[k] = (newlineIndex[j] - k)/2; + + k++; + } + } + + // Tokenize input file a second time using newline only as delimiter but do not return newline delimiter + stok = new StringTokenizer(strInfile, "\n"); + + // Determine total number of tokens in input file + nInfileLines = stok.countTokens(); + + // Read infile tokens into the string array 'strInputFile' + strInputFile = new String[nInfileLines]; + + index = 0; + + while (stok.hasMoreTokens()) + { + strInputFile[index] = new String(stok.nextToken()); + + index++; + } + + for (index = 0; index < nInfileLines; index++) + { + if (Character.toString(strInputFile[index].charAt(0)).equals("%")) + { + if ((strInputFile[index].substring(1, 6)).equals("nproc")) + { + substr = new String(strInputFile[index].substring((strInputFile[index].indexOf("=") + 1))); + + nproc = Integer.parseInt(substr); + } + else if ((strInputFile[index].substring(1, 4)).equals("mem")) + { + substr = new String(strInputFile[index].substring((strInputFile[index].indexOf("=") + 1))); + + for (k = 0; k < substr.length(); k++) + { + if (Character.isDigit(substr.charAt(k))) + { + sbMem.append(Character.toString(substr.charAt(k))); + } + else if (Character.isLetter(substr.charAt(k))) + { + sbMemUnits.append(Character.toString(substr.charAt(k))); + } + } + + + if ((sbMemUnits.toString()).equalsIgnoreCase("mb")) + { + memconvfactor = 1.0; + } + else if ((sbMemUnits.toString()).equalsIgnoreCase("gb")) + { + memconvfactor = 1000.0; + } + else if ((sbMemUnits.toString()).equalsIgnoreCase("kb")) + { + memconvfactor = 0.001; + } + else if ((sbMemUnits.toString()).equalsIgnoreCase("mw")) + { + memconvfactor = 8.0; + } + else if ((sbMemUnits.toString()).equalsIgnoreCase("gw")) + { + memconvfactor = 8000.0; + } + else if ((sbMemUnits.toString()).equalsIgnoreCase("kw")) + { + memconvfactor = 0.008; + } + + mbRequested = (int)(memconvfactor * Integer.parseInt(sbMem.toString())); + } + } + else if (Character.toString(strInputFile[index].charAt(0)).equals("#")) + { + route = new String(strInputFile[index]); + + foundRoute = true; + nblanklinesRead++; + + // Tokenize route section of input file + stok = new StringTokenizer(route); + + nrouteTokens = stok.countTokens(); + routeTokens = new String[nrouteTokens]; + + tokenIndex = 0; + + while (stok.hasMoreTokens()) + { + routeTokens[tokenIndex] = stok.nextToken(); + + tokenIndex++; + } + + for (tokenIndex = 0; tokenIndex < nrouteTokens; tokenIndex++) + { + strRouteToken = new String(routeTokens[tokenIndex].toLowerCase()); + + if (strRouteToken.indexOf("geom") != -1) + { + if (strRouteToken.indexOf("check") != -1) + { + if (strRouteToken.indexOf("allcheck") != -1) + { + readchk = true; + foundTitle = true; + foundQSM = true; + foundGeom = true; + } + else + { + readallchk = true; + foundGeom = true; + } + } + } + if (strRouteToken.indexOf("counterpoise") != -1) + { + counterpoise = true; + } + } + } + else if ((foundRoute == true) && (foundTitle == false)) + { + title = new String(strInputFile[index]); + + foundTitle = true; + nblanklinesRead++; + } + else if ((foundTitle == true) && (foundQSM == false)) + { + sbQSM.append(strInputFile[index]); + + while (sbQSM.indexOf(",") != -1) + { + k = sbQSM.indexOf(","); + + sbQSM.replace(k, k+1, " "); + } + + stok = new StringTokenizer(sbQSM.toString()); + + // Retrieve first two tokens - charge on molecule and spin multiplicity + + try { + chrgStr=stok.nextToken(); + charge = Integer.parseInt(chrgStr); + + System.out.println("Charge"+chrgStr+"><"); + //charge = Integer.parseInt(stok.nextToken()); + mulStr=stok.nextToken(); + System.out.println("Mul"+mulStr+"><"); + spinmult = Integer.parseInt(mulStr); + } catch (NoSuchElementException e) { + // TODO Auto-generated catch block + chrgStr=null; + mulStr=null; + System.out.println("Charge Multiplicity not entered"); + e.printStackTrace(); + } + + + foundQSM = true; + } + else if ((foundQSM == true) && (foundGeom == false)) + { + geomIndex = (2 * (blanklineTerminatedLineNumbers[(nblanklinesRead - 1)]) + (nblanklinesRead + 2)); + System.out.println("Index is$$$###"+geomIndex); + for (k = geomIndex; k < nInfileTokens; k++) + { + sbGeom.append(inputFileTokens.get(k).toString()); + } + + while (sbGeom.indexOf(",") != -1) + { + k = sbGeom.indexOf(","); + + sbGeom.replace(k, k+1, " "); + } + + geom = sbGeom.toString(); + System.out.println("Molecular Co-ordinates\n" + geom); + + foundGeom = true; + } + } + + if (!geom.equals("")) + { + new GeometryEditor(geom); // uncommented on Sep 13 @ 3.40 + } + } + } + + public static void main(String[] args) + { + new InputfileReader(); + } +} + diff --git a/src/main/java/g03input/InsertNode.java b/src/main/java/g03input/InsertNode.java new file mode 100644 index 0000000..d913ef6 --- /dev/null +++ b/src/main/java/g03input/InsertNode.java @@ -0,0 +1,187 @@ + +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Apr 2, 2005 + * @author Michael Sheetz + * @author Shashank Jeedigunta @author Sandeep Kumar Seethaapathy + * + */ + + +package g03input; + +import javax.swing.text.Position; +import javax.swing.tree.*; +import java.util.Enumeration; + + +public class InsertNode { + + public static void insertNode(String prefix,String nodeName){ + + + int startRow = 0; + + /* Expand the tree if it is not ...*/ + TreePath path2= G03MenuTree.tree.getNextMatch("G '09", startRow, Position.Bias.Forward); + Enumeration el=G03MenuTree.root.children(); + TreeNode nod = (TreeNode)el.nextElement(); + TreePath path1 = path2.pathByAddingChild(nod); + G03MenuTree.tree.scrollPathToVisible(path1); + /* End of Expansion */ + + /*Add new Node now */ + System.out.println(prefix); + TreePath path = G03MenuTree.tree.getNextMatch(prefix, startRow, Position.Bias.Forward); + MutableTreeNode node = (MutableTreeNode)path.getLastPathComponent(); + DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(nodeName); + + // Insert new node as last child of node + DefaultTreeModel model = (DefaultTreeModel)G03MenuTree.tree.getModel(); + model.insertNodeInto(newNode, node, node.getChildCount()); + + /* Scroll down to show the node*/ + G03MenuTree.tree.scrollPathToVisible(new TreePath(newNode.getPath())); + } + public static boolean nodeExists(String str) + { + int startRow = 0; + TreePath path2= G03MenuTree.tree.getNextMatch("G '09", startRow, Position.Bias.Forward); + Enumeration el=G03MenuTree.root.children(); + TreeNode nod = (TreeNode)el.nextElement(); + TreePath path1 = path2.pathByAddingChild(nod); + G03MenuTree.tree.scrollPathToVisible(path1); + TreePath path3=G03MenuTree.tree.getNextMatch(str, startRow, Position.Bias.Forward); + if(path3==null) + return false; + else + return true; + } + + public static void deleteChildren(String prefix) + { + int startRow = 0; + + /* Expand the tree if it is not ...*/ + TreePath path2= G03MenuTree.tree.getNextMatch("G '09", startRow, Position.Bias.Forward); + Enumeration el=G03MenuTree.root.children(); + TreeNode nod = (TreeNode)el.nextElement(); + TreePath path1 = path2.pathByAddingChild(nod); + G03MenuTree.tree.scrollPathToVisible(path1); + + TreePath path = G03MenuTree.tree.getNextMatch(prefix, startRow, Position.Bias.Forward); + MutableTreeNode node = (MutableTreeNode)path.getLastPathComponent(); + System.out.println("Node name:" +node +"Path"+ path); + DefaultTreeModel model = (DefaultTreeModel)G03MenuTree.tree.getModel(); + + System.out.println(node.getChildCount()); + int p=node.getChildCount(); + //Get all the children + if(!(node.isLeaf())) + for(int i=0;i0) + { + System.out.println("HDFDFSDSGF"); + System.out.println(MenuMethodListener.exchng); + MenuMethodListener.exchngFlag=1; + MenuMethodListener.corrFlag=1; + + System.out.println("FLAG VAL"+ MenuMethodListener.exchngFlag); + if(MenuMethodListener.exchng.get("HFS(S)").toString().equals("1")) + { + System.out.println(":D"); + hfsB.setSelected(true); + } + else if(MenuMethodListener.exchng.get("HFB(B)").equals(new Integer(1))) + hfbB.setSelected(true); + else if(MenuMethodListener.exchng.get("Xalpha(XA)").equals(new Integer(1))) + xalB.setSelected(true); + else if(MenuMethodListener.exchng.get("MPW").equals(new Integer(1))) + mpwB.setSelected(true); + else if(MenuMethodListener.exchng.get("G96").equals(new Integer(1))) + g96B.setSelected(true); + else if(MenuMethodListener.exchng.get("PBE").equals(new Integer(1))) + pbeB.setSelected(true); + else if(MenuMethodListener.exchng.get("MPBE").equals(new Integer(1))) + mpeB.setSelected(true); + else if(MenuMethodListener.exchng.get("O").equals(new Integer(1))) + oB.setSelected(true); + + if(MenuMethodListener.corr.get("LYP").equals(new Integer(1))) + lypB.setSelected(true); + if(MenuMethodListener.corr.get("PW91").equals(new Integer(1))) + pw9B.setSelected(true); + if(MenuMethodListener.corr.get("P86").equals(new Integer(1))) + p86B.setSelected(true); + if(MenuMethodListener.corr.get("PL").equals(new Integer(1))) + plB.setSelected(true); + if(MenuMethodListener.corr.get("B95").equals(new Integer(1))) + b95B.setSelected(true); + if(MenuMethodListener.corr.get("MPBE").equals(new Integer(1))) + mpbB.setSelected(true); + if(MenuMethodListener.corr.get("VWN").equals(new Integer(1))) + vwnB.setSelected(true); + if(MenuMethodListener.corr.get("VWN5").equals(new Integer(1))) + vw5B.setSelected(true); + + + } + + + + + + + JFrame.setDefaultLookAndFeelDecorated(true); + dftFrame = new JFrame("DFT Functionals"); + DefaultTableModel dftModel = new DefaultTableModel(); + dftModel.setDataVector( + new Object[][]{ + {hfsB,lypB}, + {hfbB,pw9B}, + {xalB,p86B}, + {mpwB,plB}, + {g96B,b95B}, + {pbeB,mpbB}, + {mpeB,vwnB}, + {oB,vw5B}}, + new Object[]{"Exchange Functionals","Correlation Functionals"}); + + + allDftTable = new JTable(dftModel) { + public void tableChanged(TableModelEvent e) { + + super.tableChanged(e); + repaint(); + + } + + + + }; + + allDftTable.getColumn("Exchange Functionals").setCellRenderer(new RadioButtonRenderer()); + allDftTable.getColumn("Exchange Functionals").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + allDftTable.getColumn("Correlation Functionals").setCellRenderer(new RadioButtonRenderer()); + allDftTable.getColumn("Correlation Functionals").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + + + + donePanel = new JPanel(); + dftdoneButton = new JButton("Done"); + dftdoneButton.addActionListener(new MenuMethodListener()); + exitButton = new JButton("Exit"); + + donePanel.add(dftdoneButton); + + donePanel.add(exitButton); + allDftTable.getTableHeader().setReorderingAllowed(false); + dftFrame.getContentPane().setLayout(new BorderLayout()); + JScrollPane scroll = new JScrollPane(allDftTable); + dftFrame.getContentPane().add( scroll,BorderLayout.CENTER); + dftFrame.getContentPane().add(donePanel,BorderLayout.SOUTH); + dftFrame.setSize(450,200); + dftFrame.setLocation(200,260); + dftFrame.setResizable(true); + dftFrame.setVisible(true); + } + + + + + if(e.getSource() == G03MenuTree.jcDensity) + { + System.out.println("Hi"); + + String str = new String() ;//\\"\n"; + int oldlen=0;//str.length(); + str+=jDenHelp; + int newlen=str.length(); + System.out.println(newlen); + /* // StyledDocument doc =G03MenuTree.keyoptArea.getStyledDocument(); + + // Style style = G03MenuTree.keyoptArea.addStyle("Blue", null); + StyleConstants.setForeground(style, Color.BLUE); + StyleConstants.setFontFamily(style,"Arial"); + StyleConstants.setFontSize(style,12); + G03MenuTree.keyoptArea.setText(str); + // doc.setParagraphAttributes(oldlen,newlen-oldlen,G03MenuTree.keyoptArea.getStyle("Blue"), true); + */ + G03MenuTree.keyoptArea.setEditable(false); + + } + + if(e.getSource() == G03MenuTree.jcFreq) + { + + new FreqOptTable(); + + + + } + if(e.getSource() == G03MenuTree.jcGuess) + { + /* System.out.println("Hi"); + + String str = new String() ;//\\"\n"; + int oldlen=0;//str.length(); + str+=jGuessHelp; + int newlen=str.length(); + System.out.println(newlen); + StyledDocument doc =G03MenuTree.keyoptArea.getStyledDocument(); + Style style = G03MenuTree.keyoptArea.addStyle("Blue", null); + StyleConstants.setForeground(style, Color.BLUE); + StyleConstants.setFontFamily(style,"Arial"); + StyleConstants.setFontSize(style,12); + G03MenuTree.keyoptArea.setText(str); + doc.setParagraphAttributes(oldlen,newlen-oldlen,G03MenuTree.keyoptArea.getStyle("Blue"), true); + G03MenuTree.keyoptArea.setEditable(false); + */ + new GuessOptTable(); + + } + if(e.getSource() == G03MenuTree.jcOpt) + { + /* + System.out.println("Hi"); + + String str = new String() ;//\\"\n"; + int oldlen=0;//str.length(); + str+=jOptHelp; + int newlen=str.length(); + System.out.println(newlen); + StyledDocument doc =G03MenuTree.keyoptArea.getStyledDocument(); + Style style = G03MenuTree.keyoptArea.addStyle("Blue", null); + StyleConstants.setForeground(style, Color.BLUE); + StyleConstants.setFontFamily(style,"Arial"); + StyleConstants.setFontSize(style,12); + G03MenuTree.keyoptArea.setText(str); + doc.setParagraphAttributes(oldlen,newlen-oldlen,G03MenuTree.keyoptArea.getStyle("Blue"), true); + G03MenuTree.keyoptArea.setEditable(false); + */ + new OptTable(); + } + + + if(e.getSource() == G03MenuTree.jcOptFreq) + { + String str = new String() ;//\\"\n"; + int oldlen=0;//str.length(); + str+=jOptFreqHelp; + int newlen=str.length(); + /* System.out.println(newlen); + StyledDocument doc =G03MenuTree.keyoptArea.getStyledDocument(); + Style style = G03MenuTree.keyoptArea.addStyle("Blue", null); + StyleConstants.setForeground(style, Color.BLUE); + StyleConstants.setFontFamily(style,"Arial"); + StyleConstants.setFontSize(style,12); + G03MenuTree.keyoptArea.setText(str); + doc.setParagraphAttributes(oldlen,newlen-oldlen,G03MenuTree.keyoptArea.getStyle("Blue"), true);*/ + G03MenuTree.keyoptArea.setEditable(false); + optfreq="optfreq"; + } + if(e.getSource() == G03MenuTree.jcSp) + { + System.out.println("Hi"); + + String str = new String() ;//\\"\n"; + int oldlen=0;//str.length(); + str+=jSpHelp; + int newlen=str.length(); + System.out.println(newlen); + /* StyledDocument doc =G03MenuTree.keyoptArea.getStyledDocument(); + Style style = G03MenuTree.keyoptArea.addStyle("Blue", null); + StyleConstants.setForeground(style, Color.BLUE); + StyleConstants.setFontFamily(style,"Arial"); + StyleConstants.setFontSize(style,12); + G03MenuTree.keyoptArea.setText(str); + doc.setParagraphAttributes(oldlen,newlen-oldlen,G03MenuTree.keyoptArea.getStyle("Blue"), true); + */ G03MenuTree.keyoptArea.setEditable(false); + + } + + + /* Density Sub Menu Listeners*/ + if(e.getSource()==G03MenuTree.dcis) + { + JTextField dcistext=new JTextField(3); + + JPanel dcispane=new JPanel(new GridBagLayout()); + GridBagConstraints c=new GridBagConstraints(); + JLabel dcislabel=new JLabel(" for state N="); + + Object[] obj=new Object[2]; + c.insets=new Insets(0,0,0,0); + dcispane.add(dcislabel,c);//,BorderLayout.WEST); + c.insets=new Insets(0,0,0,90); + dcispane.add(dcistext,c);//,BorderLayout.CENTER); + obj[0]="Use total unrelaxed density"; + + + obj[1]=dcispane; + + + int choice=JOptionPane.showConfirmDialog(null, obj, + "Enter the value of N", + JOptionPane.OK_OPTION); + if(choice==0) + { + if(RouteClass.initCount==0) + { + System.out.println(RouteClass.initCount+" \tInside init"); + RouteClass.initBuffer(); + RouteClass.initCount++; + } + if(denC==0) + { + System.out.println(denC+" \t Inside freQC"); + denFlag= RouteClass.keyIndex; + RouteClass.keyIndex++; + denC++; + } + else + { + //System.out.println("Reinitialize"); + RouteClass.keywordBuffer[denFlag]=new StringBuffer(); + } + if(!(InsertNode.nodeExists("Density"))) + InsertNode.insertNode("Job", "Density"); + InsertNode.deleteChildren("Den"); + InsertNode.insertNode("Density", "CIS=" + dcistext.getText()); + RouteClass.keywordBuffer[denFlag].append("Density="); + RouteClass.keywordBuffer[denFlag].append("(CIS=("+dcistext.getText()+"))"); + RouteClass.writeRoute(); + + } + + } + + if(e.getSource()==G03MenuTree.dtran) + { + JTextField dtrantextm=new JTextField(3); + JTextField dtrantextn=new JTextField(3); + JPanel dtranPanel = new JPanel(new GridBagLayout()); + GridBagConstraints c=new GridBagConstraints(); + + JLabel lbl1=new JLabel("M="); + c.insets=new Insets(0,-80,0,0); + c.gridy=0; + dtranPanel.add(lbl1,c); + c.insets=new Insets(0,-80,0,0); + dtranPanel.add(dtrantextm,c); + //c.gridy=0; + + JLabel lbl2=new JLabel("(ground state :M =0) "); + c.insets=new Insets(0,-30,0,0); + dtranPanel.add(lbl2,c); + c.gridy=1; + c.insets=new Insets(0,-30,0,0); + dtranPanel.add(new JLabel("and state N ="),c); + c.insets=new Insets(0,0,0,0); + dtranPanel.add(dtrantextn,c); + + + Object[] obj=new Object[2]; + + obj[0]="Use CIS transition density between state"; + obj[1]=dtranPanel; + + //JOptionPane.showOptionDialog(null,"Enter the value of N",JOptionPane.OK_CANCEL_OPTION); + + int choice= JOptionPane.showConfirmDialog(null, obj, + "Enter the value of M and N ", + JOptionPane.OK_OPTION); + if(choice==0) + { + if(RouteClass.initCount==0) + { + System.out.println(RouteClass.initCount+" \tInside init"); + RouteClass.initBuffer(); + RouteClass.initCount++; + } + if(denC==0) + { + System.out.println(denC+" \t Inside freQC"); + denFlag= RouteClass.keyIndex; + RouteClass.keyIndex++; + denC++; + } + else + { + //System.out.println("Reinitialize"); + RouteClass.keywordBuffer[denFlag]=new StringBuffer(); + } + if(!(InsertNode.nodeExists("Density"))) + InsertNode.insertNode("Job", "Density"); + InsertNode.deleteChildren("Den"); + InsertNode.insertNode("Density", "Transition=(" + dtrantextn.getText() + ",[" + dtrantextm.getText() + "])"); + RouteClass.keywordBuffer[denFlag].append("Density="); + RouteClass.keywordBuffer[denFlag].append("(Transition=("+dtrantextn.getText()+",["+dtrantextm.getText()+"]))"); + RouteClass.writeRoute(); + + } + + } + /*if(e.getSource()==G03MenuTree.dCurrent) + { + if(RouteClass.initCount==0) + { + System.out.println(RouteClass.initCount+" \tInside init"); + RouteClass.initBuffer(); + RouteClass.initCount++; + } + if(denC==0) + { + System.out.println(denC+" \t Inside freQC"); + denFlag=RouteClass.keyIndex; + RouteClass.keyIndex++; + denC++; + } + else + { + //System.out.println("Reinitialize"); + RouteClass.keywordBuffer[denFlag]=new StringBuffer(); + } + + if(!(InsertNode.nodeExists("Density"))) + InsertNode.insertNode("Job","Density"); + InsertNode.deleteChildren("Den"); + InsertNode.insertNode("Density",e.getActionCommand()); + RouteClass.keywordBuffer[denFlag].append("Density="); + RouteClass.keywordBuffer[denFlag].append(e.getActionCommand()); + RouteClass.writeRoute(); + + }*/ + + if(e.getSource()==G03MenuTree.dAll || + e.getSource()==G03MenuTree.dscf || + e.getSource()==G03MenuTree.dmp2 || + e.getSource()==G03MenuTree.dci || + e.getSource()==G03MenuTree.dqci || + e.getSource()==G03MenuTree.dchkpoint|| + e.getSource()==G03MenuTree.dallt || + e.getSource()==G03MenuTree.dcurrent + ) + { + if(RouteClass.initCount==0) + { + System.out.println(RouteClass.initCount+" \tInside init"); + RouteClass.initBuffer(); + RouteClass.initCount++; + } + if(denC==0) + { + System.out.println(denC+" \t Inside freQC"); + denFlag= RouteClass.keyIndex; + RouteClass.keyIndex++; + denC++; + } + else + { + //System.out.println("Reinitialize"); + RouteClass.keywordBuffer[denFlag]=new StringBuffer(); + } + + if(!(InsertNode.nodeExists("Density"))) + InsertNode.insertNode("Job", "Density"); + InsertNode.deleteChildren("Den"); + InsertNode.insertNode("Density", e.getActionCommand()); + if(e.getActionCommand().equals("Current(default)")) + { + RouteClass.keywordBuffer[denFlag].append("Density"); + //RouteClass.keywordBuffer[denFlag].append(e.getActionCommand()); + RouteClass.writeRoute(); + + } + else + { + RouteClass.keywordBuffer[denFlag].append("Density="); + RouteClass.keywordBuffer[denFlag].append(e.getActionCommand()); + RouteClass.writeRoute(); + } + } + + + if(e.getSource()==G03MenuTree.jcOptFreq) + { + if(!(InsertNode.nodeExists(e.getActionCommand()))) + { + InsertNode.insertNode("Job", e.getActionCommand()); + optfreqflag=1; + RouteClass.writeRoute(); + } + } + + + + + if( e.getSource()==G03MenuTree.jcSp || + e.getSource()==G03MenuTree.jlAdmp || + e.getSource()==G03MenuTree.jlArchive || + e.getSource()==G03MenuTree.jlBomp || + e.getSource()==G03MenuTree.jlForce || + e.getSource()==G03MenuTree.jlIrc || + e.getSource()==G03MenuTree.jlIrcMax || + e.getSource()==G03MenuTree.jlPolar|| + e.getSource()==G03MenuTree.jlScan || + e.getSource()==G03MenuTree.jlStable || + e.getSource()==G03MenuTree.jlVolume) + { + if(!(InsertNode.nodeExists(e.getActionCommand()))) + { + InsertNode.insertNode("Job", e.getActionCommand()); + if(RouteClass.initCount==0) + { + System.out.println(RouteClass.initCount+" \tInside init"); + RouteClass.initBuffer(); + RouteClass.initCount++; + } + RouteClass.keywordBuffer[RouteClass.keyIndex]=new StringBuffer(); + RouteClass.keywordBuffer[RouteClass.keyIndex].append(e.getActionCommand()); + RouteClass.keyIndex++; + RouteClass.writeRoute(); + } + } + + if(e.getSource()==G03MenuTree.jlOptIrcMax) + { + /* if(!(InsertNode.nodeExists(e.getActionCommand()))) + {InsertNode.insertNode("Job",e.getActionCommand()); + if(RouteClass.initCount==0) + { + System.out.println(RouteClass.initCount+" \tInside init"); + RouteClass.initBuffer(); + RouteClass.initCount++; + } + RouteClass.keywordBuffer[RouteClass.keyIndex]=new StringBuffer(); + RouteClass.keywordBuffer[RouteClass.keyIndex].append("Opt IRC-Max"); + RouteClass.keyIndex++; + RouteClass.writeRoute(); + }*/ + + if(!(InsertNode.nodeExists(e.getActionCommand()))) + { + InsertNode.insertNode("Job", e.getActionCommand()); + optircmaxflag=1; + RouteClass.writeRoute(); + } + + + } + + if(e.getSource()==G03MenuTree.jlOptPolar) + { + if(!(InsertNode.nodeExists(e.getActionCommand()))) + { + InsertNode.insertNode("Job", e.getActionCommand()); + optpolarflag=1; + RouteClass.writeRoute(); + } + + + /* if(!(InsertNode.nodeExists(e.getActionCommand()))) + {InsertNode.insertNode("Job",e.getActionCommand()); + + if(RouteClass.initCount==0) + { + System.out.println(RouteClass.initCount+" \tInside init"); + RouteClass.initBuffer(); + RouteClass.initCount++; + } + RouteClass.keywordBuffer[RouteClass.keyIndex]=new StringBuffer(); + RouteClass.keywordBuffer[RouteClass.keyIndex].append("Opt Polar"); + RouteClass.keyIndex++; + RouteClass.writeRoute(); + }*/ + } +} + + + + + + + + +} diff --git a/src/main/java/g03input/MenuMethodListener.java b/src/main/java/g03input/MenuMethodListener.java new file mode 100644 index 0000000..999d06b --- /dev/null +++ b/src/main/java/g03input/MenuMethodListener.java @@ -0,0 +1,606 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Mar 17, 2005 + * @author Michael Sheetz + * @author Shashank Jeedigunta @author Sandeep Kumar Seethaapathy + * + */ + + +package g03input; + +import javax.swing.*; +import javax.swing.tree.DefaultMutableTreeNode; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.Hashtable; + +public class MenuMethodListener extends JFrame implements ActionListener,ItemListener { + +public static int selectOpt; +//public static Vector corrFunctionals = new Vector(); +//public static Vector exchngFunctionals= new Vector(); +public static Hashtable exchng + = new Hashtable(); +public static Hashtable corr = new Hashtable(); +public static int exchngFlag=0,corrFlag=0; +public static int count=0; +public static int flag; +public static int onOk=0; +public static String str="",str1=""; +public static String fnName="",cfnName=""; +public static String exchngName="",corrName="",restrictione="",restrictionc=""; + + DefaultMutableTreeNode child; + DefaultMutableTreeNode grandChild; + public static JFrame listAllFrame; + public static JPanel listAllPanel; + public static JRadioButton restrictc,restricto,unRestrict; + public static JLabel listAllLabel; + public static JButton listAllok; + public static ButtonGroup restGroup; + + + + + + + + /** + * Why is there duplicated code: + * RunFrame::createThreeOptionFrame + * is the same as + * MenuMethodListener::showOptionsFrame + */ + public void showOptionsFrame() + { + JFrame.setDefaultLookAndFeelDecorated(true); + listAllFrame = new JFrame("Select Wavefunction Type"); + listAllPanel = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + listAllLabel = new JLabel("Run calculation as"); + restrictc = new JRadioButton("R - Restricted closed-shell"); + restricto = new JRadioButton("RO - Restricted Open-shell"); + unRestrict = new JRadioButton("U - Unrestricted open-shell"); + + listAllok = new JButton("OK"); + restGroup=new ButtonGroup(); + + restGroup.add(restrictc); + restGroup.add(restricto); + restGroup.add(unRestrict); + + restrictc.setSelected(true); + + + listAllok.addActionListener(this); + + c.gridx=0; + c.gridy=0; + c.weightx=0.5; + //c.weighty=0.15; + c.insets= new Insets(0,10,10,100); + listAllPanel.add(listAllLabel,c); + + c.insets= new Insets(0,-90,10,-20); + c.gridy=1; + c.gridx=0; + listAllPanel.add(restrictc,c); + c.gridy=2; + c.gridx=0; + listAllPanel.add(restricto,c); + c.gridy=3; + c.gridx=0; + listAllPanel.add(unRestrict,c); + c.gridy=4; + c.gridx=0; + c.insets = new Insets(0,90,10,90); + listAllPanel.add(listAllok,c); + + listAllFrame.getContentPane().add(listAllPanel); + listAllFrame.pack(); + listAllFrame.setLocation(200,200); + listAllFrame.setSize(300,225); + listAllFrame.setVisible(true); + //listAllFrame.setResizable(false); + listAllFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + + } + + + + + + + public void actionPerformed(ActionEvent e) + { // if(count==0) {createHTable();count++;} + if(e.getSource()==MenuListeners.dftdoneButton) + { + count++; + + InsertNode.deleteChildren("Me"); + RouteClass.methodBuffer = new StringBuffer(); + if(exchngName.equals("HFS(S)")|| + exchngName.equals("HFB(B)")|| + exchngName.equals("Xalpha(XA)") ) + { + + + if(corrName.length()>2) + { + // Remove extra (B) (S) (XA) + exchng.put(exchngName,new Integer(1)); + int findex,lindex; + findex=exchngName.indexOf("("); + lindex=exchngName.indexOf(")"); + if(lindex>findex) // checking + exchngName= exchngName.substring(findex+1,lindex); + + } + else { + // corrname exists + exchng.put(exchngName,new Integer(1)); + int findex,lindex; + findex=exchngName.indexOf("("); + lindex=exchngName.indexOf(")"); + if(lindex>findex) // checking + exchngName= exchngName.substring(0,findex); + + + } + + + System.out.println(exchng); + InsertNode.insertNode("Me",restrictione+exchngName); + + RouteClass.methodBuffer.append(restrictione+exchngName); + //RouteClass.writeRoute(); + + } + else + { + if(corrName.length()<2) + { // Pop an error + + JOptionPane.showMessageDialog(null,"You need to select a Correlation Functional","Error",JOptionPane.ERROR_MESSAGE); + + } + + else + { // if they select corrName + + InsertNode.insertNode("Me",restrictione+exchngName); + + RouteClass.methodBuffer.append(restrictione+exchngName); + } + + + } + if(corrName.length()>2){ + InsertNode.insertNode("Me",restrictionc+corrName); + + corr.put(corrName,new Integer(1)); + System.out.println(corr); + RouteClass.methodBuffer.append(restrictionc+corrName);} + RouteClass.writeRoute(); + MenuListeners.dftFrame.dispose(); + } + + + + + + + + if(e.getSource()== listAllok) + { + String restriction=""; + //Do entire Stuff + if(unRestrict.isSelected()) + { + restriction="U"; + + } + else if(restrictc.isSelected()) + { + restriction="R"; + + } + else if(restricto.isSelected()) + { + restriction="RO"; + + } + + if(flag==1) //exchange + restrictione=restriction; + if(flag==2) + restrictionc=restriction; + + + listAllFrame.dispose(); + + } + if(e.getSource()== RunFrame.ok1) + { + if(RunFrame.unRest.isSelected()) + selectOpt=1; + else if(RunFrame.restClose.isSelected()) + selectOpt=2; + else + selectOpt=3; + RunFrame.runFrame1.dispose(); + if(selectOpt==1) + str="U"; + else if(selectOpt==2) + str="R"; + else if(selectOpt==3) + str="RO"; + + InsertNode.deleteChildren("Me"); + InsertNode.insertNode("Me",str+str1); + + //RouteSection methods + + RouteClass.methodBuffer = new StringBuffer(); + RouteClass.methodBuffer.append(str+str1); + RouteClass.writeRoute(); + } + + if(e.getSource()== RunFrame.ok2) + { selectOpt=0; + if(RunFrame.restOpen.isSelected()) + selectOpt=1; + else if(RunFrame.restClose.isSelected()) + selectOpt=2; + RunFrame.runFrame2.dispose(); + + if(selectOpt==1) + str="U"; + else if(selectOpt==2) + str="R"; + + InsertNode.deleteChildren("Me"); + InsertNode.insertNode("Me",str+str1); + + // RouteSection methods + + RouteClass.methodBuffer = new StringBuffer(); + RouteClass.methodBuffer.append(str+str1); + RouteClass.writeRoute(); + + + } + + + if(e.getSource()==G03MenuTree.comB3ly|| + e.getSource()==G03MenuTree.comB3p8 || e.getSource()==G03MenuTree.comB1ly || + e.getSource()==G03MenuTree.comPbe1 || e.getSource()==G03MenuTree.comMpw1 || + e.getSource()==G03MenuTree.comB3pw || e.getSource()==G03MenuTree.mhfItem || + e.getSource()==G03MenuTree.mp2Item || e.getSource()== G03MenuTree.othB1b9 || + e.getSource()== G03MenuTree.othB98 || e.getSource()== G03MenuTree.othB971 || + e.getSource()== G03MenuTree.othB972 || e.getSource()== G03MenuTree.othBhan || + e.getSource()== G03MenuTree.othBhlyp || e.getSource()== G03MenuTree.othLsda || + (e.getSource()==G03MenuTree.oMN15)|| (e.getSource()==G03MenuTree.oM11)|| (e.getSource()==G03MenuTree.oMN12SX)|| + (e.getSource()==G03MenuTree.oPW6b95)||(e.getSource()==G03MenuTree.oSOGGA11X)||(e.getSource()==G03MenuTree.oN12SX)|| + (e.getSource()==G03MenuTree.oPW6B95D3)|| (e.getSource()==G03MenuTree.oMO8HX)|| (e.getSource()==G03MenuTree.oMO6)|| + (e.getSource()==G03MenuTree.oMO6HF)|| (e.getSource()==G03MenuTree.oMO5)|| (e.getSource()==G03MenuTree.oMO52X)|| + (e.getSource()==G03MenuTree.oMO62X)||(e.getSource()==G03MenuTree.APFD)|| (e.getSource()==G03MenuTree.wB97xD)|| + e.getSource()== G03MenuTree.stdVsxc || e.getSource()== G03MenuTree.stdHcth || e.getSource()== G03MenuTree.stdHct9 || + e.getSource()== G03MenuTree.stdHct14 || e.getSource()== G03MenuTree.stdHct40 + ) + { + System.out.println("Eureka!!!"); + G03MenuTree.basisSetMenu.setEnabled(true); + RunFrame.createThreeOptionFrame(); + str1=e.getActionCommand(); + + System.out.println(selectOpt); + } + + + if(e.getSource()== G03MenuTree.pm3Item || + e.getSource()== G03MenuTree.am1Item|| + e.getSource()== G03MenuTree.mindoItem|| + e.getSource()== G03MenuTree.mndoItem ) + + { + //Semi Emperical Disable the Basis Set Menu. + G03MenuTree.basisSetMenu.setEnabled(false); + RunFrame.createThreeOptionFrame(); + str1=e.getActionCommand(); + System.out.println(selectOpt); + // if a basis set is already selected delete it.... + InsertNode.deleteChildren("Basis"); + RouteClass.basisBuffer= new StringBuffer(); + + + } + + + + if(e.getSource()== G03MenuTree.mp3Item || + e.getSource()== G03MenuTree.mp4Item || + e.getSource()== G03MenuTree.mp4dItem || + e.getSource()== G03MenuTree.mp4sItem || + e.getSource()== G03MenuTree.ccdItem || + e.getSource()== G03MenuTree.ccsItem || + e.getSource()== G03MenuTree.ccsdItem || + e.getSource()== G03MenuTree.cidItem || + e.getSource()== G03MenuTree.cisdcItem || + e.getSource()== G03MenuTree.cisItem|| + e.getSource()== G03MenuTree.cisdItem|| + e.getSource()== G03MenuTree.sacItem || + e.getSource()== G03MenuTree.tdItem || + e.getSource()== G03MenuTree.tddItem || + e.getSource()== G03MenuTree.bdItem || + e.getSource()== G03MenuTree.gvbItem || + e.getSource()== G03MenuTree.ovgfItem || + e.getSource()== G03MenuTree.w1Item || + e.getSource()== G03MenuTree.zinItem || + e.getSource()== G03MenuTree.g1Item || + e.getSource()== G03MenuTree.g2Item || + e.getSource()== G03MenuTree.g2mp2Item || + e.getSource()== G03MenuTree.g3Item || + e.getSource()== G03MenuTree.g3mp2Item || + e.getSource()== G03MenuTree.g3b3Item || + e.getSource()== G03MenuTree.g3mp2b3Item|| + e.getSource()== G03MenuTree.g4Item || + e.getSource()== G03MenuTree.g4mp2Item || + e.getSource()==G03MenuTree.mcasscfItem|| + e.getSource()==G03MenuTree.mcasscfmItem + + ) + { + G03MenuTree.basisSetMenu.setEnabled(true); + RunFrame.createTwoOptionFrame(); + str1=e.getActionCommand(); + System.out.println(selectOpt); + } + + + if( e.getSource()== G03MenuTree.pm3mmItem || + e.getSource()== G03MenuTree.cndoItem || + e.getSource()== G03MenuTree.indoItem || + e.getSource()== G03MenuTree.cbs4Item || + e.getSource()== G03MenuTree.cbsaItem || + e.getSource()== G03MenuTree.cbslItem || + e.getSource()== G03MenuTree.cbsqItem || + e.getSource()== G03MenuTree.cbsqbItem ) + { + //Semi Emperical disable the Basis Set Menu. & + // CBS Menu Item + G03MenuTree.basisSetMenu.setEnabled(false); + RunFrame.createTwoOptionFrame(); + str1=e.getActionCommand(); + System.out.println(selectOpt); +// if a basis set is already selected delete it.... + InsertNode.deleteChildren("Basis"); + RouteClass.basisBuffer= new StringBuffer(); + + } + + + + if(e.getSource()== G03MenuTree.mp5Item) + { + InsertNode.deleteChildren("Me"); + InsertNode.insertNode("Me",e.getActionCommand()); + G03MenuTree.basisSetMenu.setEnabled(true); + } + + + + + + + + + + +} + + public void itemStateChanged(ItemEvent ie) + { + if(ie.getItem()==MenuListeners.hfsB || + ie.getItem()==MenuListeners.lypB || + ie.getItem()==MenuListeners.hfbB || + ie.getItem()==MenuListeners.pw9B || + ie.getItem()==MenuListeners.xalB || + ie.getItem()==MenuListeners.p86B || + ie.getItem()==MenuListeners.mpwB || + ie.getItem()==MenuListeners.plB || + ie.getItem()==MenuListeners.g96B || + ie.getItem()==MenuListeners.b95B || + ie.getItem()==MenuListeners.pbeB || + ie.getItem()==MenuListeners.mpbB || + ie.getItem()==MenuListeners.mpeB || + ie.getItem()==MenuListeners.vwnB || + ie.getItem()==MenuListeners.oB || + ie.getItem()==MenuListeners.vw5B) + { + System.out.println("Eureka!!!"); + + + if(ie.getItem()==MenuListeners.hfsB || + ie.getItem()==MenuListeners.hfbB || + + ie.getItem()==MenuListeners.xalB || + + ie.getItem()==MenuListeners.mpwB || + + ie.getItem()==MenuListeners.g96B || + + ie.getItem()==MenuListeners.pbeB || + + ie.getItem()==MenuListeners.mpeB || + + ie.getItem()==MenuListeners.oB ) + { + // Exchange Functionals + flag=1; + if(((JRadioButton)ie.getItem()).isSelected()) + { + + + if(exchngFlag>1) + { //Show an Error + + JOptionPane.showMessageDialog(null,"You can select only one Exchange Functional","Error",JOptionPane.ERROR_MESSAGE); + ((JRadioButton)ie.getItem()).setSelected(false); + exchngFlag--; + } + else{ + // Only one Item Selected + fnName=ie.getItem().toString(); + System.out.print(fnName); + exchngName= RadioButtonEditor.button.getActionCommand(); + //fnName=ie.getItem(); + //exchngName=exchng.get(fnName).toString(); + //System.out.println(exchngName); + showOptionsFrame(); + } + + exchngFlag++; + } + + else //deselected + { + + if(exchngName.equals(RadioButtonEditor.button.getActionCommand())) + { + exchngName=""; + } + exchngFlag--; + } + + + + } + + if( ie.getItem()==MenuListeners.lypB || + + ie.getItem()==MenuListeners.pw9B || + + ie.getItem()==MenuListeners.p86B || + + ie.getItem()==MenuListeners.plB || + + ie.getItem()==MenuListeners.b95B || + + ie.getItem()==MenuListeners.mpbB || + + ie.getItem()==MenuListeners.vwnB || + + ie.getItem()==MenuListeners.vw5B) + { + // Correlation Function + flag=2; + if(((JRadioButton)ie.getItem()).isSelected()) + { + corrFlag++; + + if(corrFlag>1) + { //Show an Error + + JOptionPane.showMessageDialog(null,"You can select only one Correlational Functional","Error",JOptionPane.ERROR_MESSAGE); + ((JRadioButton)ie.getItem()).setSelected(false); + corrFlag--; + } + else{ + // Only one Item Selected + //cfnName=ie.getItem().toString(); + corrName= RadioButtonEditor.button.getActionCommand(); + //corrName=corr.get(cfnName).toString(); + System.out.println(corrName); + showOptionsFrame(); + } + + + } + + else //deselected + { + if(corrName.equals(RadioButtonEditor.button.getActionCommand())) + { + corrName=""; + } + corrFlag--; + } + + + } + + } + + } + + + + + public static void createHTable() + { + exchng.put("HFS(S)",new Integer(0)); + exchng.put("HFB(B)",new Integer(0)); + exchng.put("Xalpha(XA)",new Integer(0)); + exchng.put("MPW",new Integer(0)); + exchng.put("G96",new Integer(0)); + exchng.put("PBE",new Integer(0)); + exchng.put("MPBE",new Integer(0)); + exchng.put("O",new Integer(0)); + + corr.put("LYP",new Integer(0)); + corr.put("PW91",new Integer(0)); + corr.put("P86",new Integer(0)); + corr.put("PL",new Integer(0)); + corr.put("B95",new Integer(0)); + corr.put("MPBE",new Integer(0)); + corr.put("VWN",new Integer(0)); + corr.put("VWN5",new Integer(0)); + + + + + } + +} + diff --git a/src/main/java/g03input/MethodListener.java b/src/main/java/g03input/MethodListener.java new file mode 100644 index 0000000..4280994 --- /dev/null +++ b/src/main/java/g03input/MethodListener.java @@ -0,0 +1,92 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Mar 16, 2005 + * @author Michael Sheetz + * @author Shashank Jeedigunta @author Sandeep Kumar Seethaapathy + * + */ + + + +package g03input; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + + +public class MethodListener implements ActionListener { + + + public void actionPerformed(ActionEvent e) + { + if((e.getSource()==G03MenuTree.mhfItem)||(e.getSource()==G03MenuTree.mp2Item)||(e.getSource()==G03MenuTree.am1Item)|| + (e.getSource()==G03MenuTree.pm3Item)||(e.getSource()==G03MenuTree.mindoItem)||(e.getSource()==G03MenuTree.mndoItem)|| + (e.getSource()==G03MenuTree.comB3ly)||(e.getSource()==G03MenuTree.comB3pw)||(e.getSource()==G03MenuTree.comB3p8)|| + (e.getSource()==G03MenuTree.comB1ly)||(e.getSource()==G03MenuTree.comPbe1)||(e.getSource()==G03MenuTree.comMpw1)|| + (e.getSource()==G03MenuTree.othB1b9)||(e.getSource()==G03MenuTree.othB98)||(e.getSource()==G03MenuTree.othB971)|| + (e.getSource()==G03MenuTree.othB972)||(e.getSource()==G03MenuTree.othBhan)||(e.getSource()==G03MenuTree.othBhlyp)|| + (e.getSource()==G03MenuTree.othLsda)||(e.getSource()==G03MenuTree.stdVsxc)||(e.getSource()==G03MenuTree.stdHcth)|| + (e.getSource()==G03MenuTree.oMN15)|| (e.getSource()==G03MenuTree.oM11)|| (e.getSource()==G03MenuTree.oMN12SX)|| + (e.getSource()==G03MenuTree.oPW6b95)||(e.getSource()==G03MenuTree.oSOGGA11X)||(e.getSource()==G03MenuTree.oN12SX)|| + (e.getSource()==G03MenuTree.oPW6B95D3)|| (e.getSource()==G03MenuTree.oMO8HX)|| (e.getSource()==G03MenuTree.oMO6)|| + (e.getSource()==G03MenuTree.oMO6HF)|| (e.getSource()==G03MenuTree.oMO5)|| (e.getSource()==G03MenuTree.oMO52X)|| + (e.getSource()==G03MenuTree.oMO62X)||(e.getSource()==G03MenuTree.APFD)|| (e.getSource()==G03MenuTree.wB97xD)|| + (e.getSource()==G03MenuTree.stdHct9)||(e.getSource()==G03MenuTree.stdHct14)||(e.getSource()==G03MenuTree.stdHct40)) + + { + RunFrame.createThreeOptionFrame(); + } + + if((e.getSource()==G03MenuTree.mp3Item)||(e.getSource()==G03MenuTree.mp4Item)||(e.getSource()==G03MenuTree.mp5Item)||(e.getSource()==G03MenuTree.ccdItem)|| + (e.getSource()==G03MenuTree.ccsItem)||(e.getSource()==G03MenuTree.ccsdItem)||(e.getSource()==G03MenuTree.cidItem)|| + (e.getSource()==G03MenuTree.cisdcItem)||(e.getSource()==G03MenuTree.cisItem)||(e.getSource()==G03MenuTree.cisdItem)|| + (e.getSource()==G03MenuTree.sacItem)||(e.getSource()==G03MenuTree.tdItem)||(e.getSource()==G03MenuTree.tddItem)|| + (e.getSource()==G03MenuTree.bdItem)||(e.getSource()==G03MenuTree.gvbItem)||(e.getSource()==G03MenuTree.ovgfItem)|| + (e.getSource()==G03MenuTree.w1Item)||(e.getSource()==G03MenuTree.zinItem)||(e.getSource()==G03MenuTree.pm3mmItem)|| + (e.getSource()==G03MenuTree.cndoItem)||(e.getSource()==G03MenuTree.indoItem)||(e.getSource()==G03MenuTree.cbs4Item)|| + (e.getSource()==G03MenuTree.cbslItem)||(e.getSource()==G03MenuTree.cbsqItem)||(e.getSource()==G03MenuTree.cbsqbItem)|| + (e.getSource()==G03MenuTree.cbsaItem)||(e.getSource()==G03MenuTree.g1Item)||(e.getSource()==G03MenuTree.g2Item)|| + (e.getSource()==G03MenuTree.g2mp2Item)||(e.getSource()==G03MenuTree.g3Item)||(e.getSource()==G03MenuTree.g3mp2Item)|| + (e.getSource()==G03MenuTree.g3b3Item)||(e.getSource()==G03MenuTree.g3mp2b3Item)|| (e.getSource()==G03MenuTree.g4Item) || + (e.getSource()==G03MenuTree.g4mp2Item)) + { + RunFrame.createTwoOptionFrame(); + } +} +} diff --git a/src/main/java/g03input/MolEditorHelp.java b/src/main/java/g03input/MolEditorHelp.java new file mode 100644 index 0000000..3efa35a --- /dev/null +++ b/src/main/java/g03input/MolEditorHelp.java @@ -0,0 +1,170 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * + * @author Michael Sheetz + * @author Sandeep Kumar Seethaapathy @author Shashank Jeedigunta + * + */ + + + + +package g03input; + +import java.util.Hashtable; + + +public class MolEditorHelp { + + public static Hashtable htAtomicNumber; + + + public static void hashFunction() + { + htAtomicNumber = new Hashtable(); + + htAtomicNumber.put("H", new Integer(1) ); + htAtomicNumber.put("He", new Integer(2) ); + htAtomicNumber.put("Li", new Integer(3) ); + htAtomicNumber.put("Be", new Integer(4) ); + htAtomicNumber.put("B", new Integer(5) ); + htAtomicNumber.put("C", new Integer(6) ); + htAtomicNumber.put("N", new Integer(7) ); + htAtomicNumber.put("O", new Integer(8) ); + htAtomicNumber.put("F", new Integer(9) ); + htAtomicNumber.put("Ne", new Integer(10) ); + htAtomicNumber.put("Na", new Integer(11) ); + htAtomicNumber.put("Mg", new Integer(12) ); + htAtomicNumber.put("Al", new Integer(13) ); + htAtomicNumber.put("Si", new Integer(14) ); + htAtomicNumber.put("P", new Integer(15) ); + htAtomicNumber.put("S", new Integer(16) ); + htAtomicNumber.put("Cl", new Integer(17) ); + htAtomicNumber.put("Ar", new Integer(18) ); + htAtomicNumber.put("K", new Integer(19) ); + htAtomicNumber.put("Ca", new Integer(20)); + htAtomicNumber.put("Sc", new Integer(21) ); + htAtomicNumber.put("Ti", new Integer(22) ); + htAtomicNumber.put("V", new Integer(23) ); + htAtomicNumber.put("Cr", new Integer(24) ); + htAtomicNumber.put("Mn", new Integer(25) ); + htAtomicNumber.put("Fe", new Integer(26) ); + htAtomicNumber.put("Co", new Integer(27) ); + htAtomicNumber.put("Ni", new Integer(28) ); + htAtomicNumber.put("Cu", new Integer(29) ); + htAtomicNumber.put("Zn", new Integer(30) ); + htAtomicNumber.put("Ga", new Integer(31) ); + htAtomicNumber.put("Ge", new Integer(32) ); + htAtomicNumber.put("As", new Integer(33) ); + htAtomicNumber.put("Se", new Integer(34) ); + htAtomicNumber.put("Br", new Integer(35) ); + htAtomicNumber.put("Kr", new Integer(36) ); + htAtomicNumber.put("Rb", new Integer(37) ); + htAtomicNumber.put("Sr", new Integer(38) ); + htAtomicNumber.put("Y", new Integer(39) ); + htAtomicNumber.put("Zr", new Integer(40) ); + htAtomicNumber.put("Nb", new Integer(41) ); + htAtomicNumber.put("Mo", new Integer(42) ); + htAtomicNumber.put("Tc", new Integer(43) ); + htAtomicNumber.put("Ru", new Integer(44) ); + htAtomicNumber.put("Rh", new Integer(45) ); + htAtomicNumber.put("Pd", new Integer(46) ); + htAtomicNumber.put("Ag", new Integer(47) ); + htAtomicNumber.put("Cd", new Integer(48) ); + htAtomicNumber.put("In", new Integer(49) ); + htAtomicNumber.put("Sn", new Integer(50) ); + htAtomicNumber.put("Sb", new Integer(51) ); + htAtomicNumber.put("Te", new Integer(52) ); + htAtomicNumber.put("I", new Integer(53) ); + htAtomicNumber.put("Xe", new Integer(54) ); + htAtomicNumber.put("Cs", new Integer(55) ); + htAtomicNumber.put("Ba", new Integer(56) ); + htAtomicNumber.put("La", new Integer(57) ); + htAtomicNumber.put("Ce", new Integer(58) ); + htAtomicNumber.put("Pr", new Integer(59) ); + htAtomicNumber.put("Nd", new Integer(60) ); + htAtomicNumber.put("Pm", new Integer(61) ); + htAtomicNumber.put("Sm", new Integer(62) ); + htAtomicNumber.put("Eu", new Integer(63) ); + htAtomicNumber.put("Gd", new Integer(64) ); + htAtomicNumber.put("Tb", new Integer(65) ); + htAtomicNumber.put("Dy", new Integer(66) ); + htAtomicNumber.put("Ho", new Integer(67) ); + htAtomicNumber.put("Er", new Integer(68) ); + htAtomicNumber.put("Tm", new Integer(69) ); + htAtomicNumber.put("Yb", new Integer(70) ); + htAtomicNumber.put("Lu", new Integer(71) ); + htAtomicNumber.put("Hf", new Integer(72) ); + htAtomicNumber.put("Ta", new Integer(73) ); + htAtomicNumber.put("W", new Integer(74) ); + htAtomicNumber.put("Re", new Integer(75) ); + htAtomicNumber.put("Os", new Integer(76) ); + htAtomicNumber.put("Ir", new Integer(77) ); + htAtomicNumber.put("Pt", new Integer(78) ); + htAtomicNumber.put("Au", new Integer(79) ); + htAtomicNumber.put("Hg", new Integer(80) ); + htAtomicNumber.put("Tl", new Integer(81) ); + htAtomicNumber.put("Pb", new Integer(82) ); + htAtomicNumber.put("Bi", new Integer(83) ); + htAtomicNumber.put("Po", new Integer(84) ); + htAtomicNumber.put("At", new Integer(85) ); + htAtomicNumber.put("Rn", new Integer(86) ); + htAtomicNumber.put("Fr", new Integer(87) ); + htAtomicNumber.put("Ra", new Integer(88) ); + htAtomicNumber.put("Ac", new Integer(89) ); + htAtomicNumber.put("Th", new Integer(90) ); + htAtomicNumber.put("Pa", new Integer(91) ); + htAtomicNumber.put("U", new Integer(92) ); + htAtomicNumber.put("Np", new Integer(93) ); + htAtomicNumber.put("Pu", new Integer(94) ); + htAtomicNumber.put("Am", new Integer(95) ); + htAtomicNumber.put("Cm", new Integer(96) ); + htAtomicNumber.put("Bk", new Integer(97) ); + htAtomicNumber.put("Cf", new Integer(98) ); + htAtomicNumber.put("Es", new Integer(99) ); + htAtomicNumber.put("Fm", new Integer(100) ); + htAtomicNumber.put("Md", new Integer(101) ); + htAtomicNumber.put("No", new Integer(102) ); + htAtomicNumber.put("Lr", new Integer(103) ); + htAtomicNumber.put("Tv", new Integer(0) ); + + + } + +} diff --git a/src/main/java/g03input/OptTable.java b/src/main/java/g03input/OptTable.java new file mode 100644 index 0000000..88954c8 --- /dev/null +++ b/src/main/java/g03input/OptTable.java @@ -0,0 +1,1024 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Mar 22, 2005 + * @author Michael Sheetz + * @author Sandeep Kumar Seethaapathy @author Shashank Jeedigunta + * + */ + + +package g03input; + + +import javax.swing.*; +import javax.swing.event.TableModelEvent; +import javax.swing.table.DefaultTableModel; +import java.awt.*; +import java.awt.event.*; +import java.util.Vector; + + +public class OptTable extends JFrame implements ItemListener,ActionListener{ + Color bgColor= new Color(236,233,216); + Color foreColor =new Color(0,78,152); + JPanel donePanel; + JButton doneButton,clearButton,exitButton; + public static JTable table; + JFrame OptFrame; + public static int optListen; + public static int optC,optFlag,optionsC; + public static Vector optClear; + public static Vector optVopt; + public static String maxSel,maxSt,readN,chkN,sadN,iharN,pathN,maxCy; + + // Opt Table Radio Buttons + public static JRadioButton OMaxCy =new JRadioButton("MaxCycle=N"); + public static JRadioButton ORedun =new JRadioButton("Redundant"); + public static JRadioButton OEstmF =new JRadioButton("EstmFC"); + public static JRadioButton OTight =new JRadioButton("Tight"); + public static JRadioButton OMicro=new JRadioButton("Micro"); + public static JRadioButton OHFErr=new JRadioButton("HFError"); + public static JRadioButton OMaxSt =new JRadioButton("MaxStep=N"); + public static JRadioButton OZMatr=new JRadioButton("Z-Matrix"); + public static JRadioButton OReadFC=new JRadioButton("ReadFC"); + public static JRadioButton OVery=new JRadioButton("VeryTight"); + public static JRadioButton ONoMic=new JRadioButton("NoMicro"); + public static JRadioButton OFineG=new JRadioButton("FineGridError"); + public static JRadioButton ONatur=new JRadioButton("NaturalOrbitals"); + public static JRadioButton OCarte=new JRadioButton("Cartesian"); + public static JRadioButton OEigen=new JRadioButton("EigenTest"); + public static JRadioButton OQuadM=new JRadioButton("QuadMacro"); + public static JRadioButton OSG1Er=new JRadioButton("SG1Error"); + public static JRadioButton OTS =new JRadioButton("TS"); + public static JRadioButton OStar=new JRadioButton("StarOnly"); + public static JRadioButton ONoEig=new JRadioButton("NoEigenTest"); + public static JRadioButton ONoQua=new JRadioButton("NoQuadMacro"); + public static JRadioButton OReadErr=new JRadioButton("ReadError"); + public static JRadioButton OSadd=new JRadioButton("Saddle=N"); + public static JRadioButton OFCCard=new JRadioButton("FCCards"); + public static JRadioButton OExper=new JRadioButton("Expert"); + public static JRadioButton OCheck=new JRadioButton("CheckCoordinates"); + public static JRadioButton OQST2=new JRadioButton("QST2"); + public static JRadioButton ORCFC=new JRadioButton("RCFC"); + public static JRadioButton ONoExp=new JRadioButton("NoExpert"); + public static JRadioButton OLinear=new JRadioButton("Linear"); + public static JRadioButton OQST3=new JRadioButton("QST3"); + public static JRadioButton OCalcH=new JRadioButton("CalcHHFC"); + public static JRadioButton OLoose=new JRadioButton("Loose"); + public static JRadioButton ONoLinear=new JRadioButton("NoLinear"); + public static JRadioButton OPathN=new JRadioButton("Path=N"); + public static JRadioButton OCalcFc=new JRadioButton("CalcFC"); + public static JRadioButton OTrust=new JRadioButton("TrustUpdate"); + public static JRadioButton OOptRe=new JRadioButton("OptReactant"); + public static JRadioButton OCalcAll=new JRadioButton("CalcAll"); + public static JRadioButton ONoTrust=new JRadioButton("NoTrustUpdate"); + public static JRadioButton ONoOpt=new JRadioButton("NoOptReactant"); + public static JRadioButton OVCD=new JRadioButton("VCD"); + public static JRadioButton ORFO=new JRadioButton("RFO"); + public static JRadioButton OBioMol=new JRadioButton("BioMolecular"); + public static JRadioButton ONoRam=new JRadioButton("NoRaman"); + public static JRadioButton OGDIIS=new JRadioButton("GDIIS"); + public static JRadioButton OOptProd=new JRadioButton("OptProduct"); + public static JRadioButton ONewton=new JRadioButton("Newton"); + public static JRadioButton ONoOptPro=new JRadioButton("NoOptProduct"); + public static JRadioButton ONRScale=new JRadioButton("NRScale"); + public static JRadioButton OConical=new JRadioButton("Conical"); + public static JRadioButton ONoNRS=new JRadioButton("NoNRScale"); + public static JRadioButton ORestart=new JRadioButton("Restart"); + public static JRadioButton OEF=new JRadioButton("EF"); + public static JRadioButton ONoFreeze=new JRadioButton("NoFreeze"); + public static JRadioButton OSteep=new JRadioButton("Steep"); + public static JRadioButton OModRed=new JRadioButton("ModRedundant"); + public static JRadioButton OUpdate=new JRadioButton("UpdateMethod=keyword"); + public static JRadioButton OInitHar=new JRadioButton("InitialHarmonic=N"); + public static JRadioButton OBig=new JRadioButton("Big"); + public static JRadioButton OChkHar=new JRadioButton("ChkHarmonic=N"); + public static JRadioButton OSmall=new JRadioButton("Small"); + public static JRadioButton OReadHar=new JRadioButton("ReadHarmonic=N"); + + + + public OptTable(){ + + OptFrame = new JFrame("Opt Options" ); + + + //UIDefaults ui = UIManager.getLookAndFeel().getDefaults(); + + //UIManager.put("RadioButton.focus", ui.getColor("control")); + + DefaultTableModel dm = new DefaultTableModel(); + + OMaxCy.setBackground(Color.WHITE); + ORedun.setBackground(Color.WHITE);OEstmF.setBackground(Color.WHITE);OTight.setBackground(Color.WHITE);OMicro.setBackground(Color.WHITE);OHFErr.setBackground(Color.WHITE); + + OMaxSt.setBackground(Color.WHITE);OZMatr.setBackground(Color.WHITE);OReadFC.setBackground(Color.WHITE);OVery.setBackground(Color.WHITE);ONoMic.setBackground(Color.WHITE);OFineG.setBackground(Color.WHITE); + + ONatur.setBackground(Color.WHITE);OCarte.setBackground(Color.WHITE);OStar.setBackground(Color.WHITE);OEigen.setBackground(Color.WHITE);OQuadM.setBackground(Color.WHITE);OSG1Er.setBackground(Color.WHITE); + + OTS.setBackground(Color.WHITE);OFCCard.setBackground(Color.WHITE);ONoEig.setBackground(Color.WHITE);ONoQua.setBackground(Color.WHITE);OReadErr.setBackground(Color.WHITE); + + OSadd.setBackground(Color.WHITE);ORCFC.setBackground(Color.WHITE);OExper.setBackground(Color.WHITE);OCheck.setBackground(Color.WHITE); + OQST2.setBackground(Color.WHITE);OCalcH.setBackground(Color.WHITE);ONoExp.setBackground(Color.WHITE);OLinear.setBackground(Color.WHITE); + OQST3.setBackground(Color.WHITE);OCalcFc.setBackground(Color.WHITE);OLoose.setBackground(Color.WHITE);ONoLinear.setBackground(Color.WHITE); + OPathN.setBackground(Color.WHITE);OCalcAll.setBackground(Color.WHITE);OTrust.setBackground(Color.WHITE); + OOptRe.setBackground(Color.WHITE);OVCD.setBackground(Color.WHITE);ONoTrust.setBackground(Color.WHITE); + ONoOpt.setBackground(Color.WHITE);ONoRam.setBackground(Color.WHITE);ORFO.setBackground(Color.WHITE); + OBioMol.setBackground(Color.WHITE);OGDIIS.setBackground(Color.WHITE); + OOptProd.setBackground(Color.WHITE);ONewton.setBackground(Color.WHITE); + ONoOptPro.setBackground(Color.WHITE);ONRScale.setBackground(Color.WHITE); + OConical.setBackground(Color.WHITE);ONoNRS.setBackground(Color.WHITE); + ORestart.setBackground(Color.WHITE);OEF.setBackground(Color.WHITE); + ONoFreeze.setBackground(Color.WHITE);OSteep.setBackground(Color.WHITE); + OModRed.setBackground(Color.WHITE);OUpdate.setBackground(Color.WHITE); + OInitHar.setBackground(Color.WHITE);OBig.setBackground(Color.WHITE); + OChkHar.setBackground(Color.WHITE);OSmall.setBackground(Color.WHITE); + OReadHar.setBackground(Color.WHITE); + + //-----ItemListeners + if(optListen==0) + { + optClear=new Vector(60); + //optClear.addElement(OMaxCy); + optClear.addElement(ORedun);optClear.addElement(OEstmF); + optClear.addElement(OTight); + optClear.addElement(OMicro); + optClear.addElement(OHFErr); + //optClear.addElement(OMaxSt); + optClear.addElement(OZMatr); + optClear.addElement(OReadFC); + optClear.addElement(OVery); + optClear.addElement(ONoMic); + optClear.addElement(OFineG); + optClear.addElement(ONatur); + optClear.addElement(OCarte); + optClear.addElement(OEigen); + optClear.addElement(OQuadM); + optClear.addElement(OSG1Er); + optClear.addElement(OTS); + optClear.addElement(OStar); + optClear.addElement(ONoEig); + optClear.addElement(ONoQua); + optClear.addElement(OReadErr); + //optClear.addElement(OSadd); + optClear.addElement(OFCCard); + optClear.addElement(OExper); + optClear.addElement(OQST2); + optClear.addElement(ORCFC); + optClear.addElement(ONoExp); + optClear.addElement(OLinear); + optClear.addElement(OQST3); + optClear.addElement(OCalcH); + optClear.addElement(OLoose); + optClear.addElement(ONoLinear); + //optClear.addElement(OPathN); + optClear.addElement(OCalcFc); + optClear.addElement(OTrust); + optClear.addElement(OOptRe); + optClear.addElement(OCalcAll); + optClear.addElement(ONoTrust); + optClear.addElement(ONoOpt); + optClear.addElement(OVCD); + optClear.addElement(ORFO); + optClear.addElement(OBioMol); + optClear.addElement(ONoRam); + optClear.addElement(OGDIIS); + optClear.addElement(OOptProd); + optClear.addElement(ONewton); + optClear.addElement(ONoOptPro); + + optClear.addElement(ONRScale); + optClear.addElement(OConical); + optClear.addElement(ONoNRS); + optClear.addElement(ORestart); + + optClear.addElement(OEF); + optClear.addElement(ONoFreeze); + optClear.addElement(OSteep); + optClear.addElement(OModRed); + optClear.addElement(OUpdate); + // optClear.addElement(OInitHar); + + optClear.addElement(OBig); + //optClear.addElement(OChkHar); + optClear.addElement(OSmall); + //optClear.addElement(OReadHar); + + OMaxCy.addItemListener(this); + ORedun.addItemListener(this);OEstmF.addItemListener(this);OTight.addItemListener(this);OMicro.addItemListener(this);OHFErr.addItemListener(this); + OMaxSt.addItemListener(this);OZMatr.addItemListener(this);OReadFC.addItemListener(this);OVery.addItemListener(this);ONoMic.addItemListener(this);OFineG.addItemListener(this); + + ONatur.addItemListener(this);OCarte.addItemListener(this);OStar.addItemListener(this);OEigen.addItemListener(this);OQuadM.addItemListener(this);OSG1Er.addItemListener(this); + + OTS.addItemListener(this);OFCCard.addItemListener(this);ONoEig.addItemListener(this);ONoQua.addItemListener(this);OReadErr.addItemListener(this); + + OSadd.addItemListener(this);ORCFC.addItemListener(this);OExper.addItemListener(this);OCheck.addItemListener(this); + OQST2.addItemListener(this);OCalcH.addItemListener(this);ONoExp.addItemListener(this);OLinear.addItemListener(this); + OQST3.addItemListener(this);OCalcFc.addItemListener(this);OLoose.addItemListener(this);ONoLinear.addItemListener(this); + OPathN.addItemListener(this);OCalcAll.addItemListener(this);OTrust.addItemListener(this); + OOptRe.addItemListener(this);OVCD.addItemListener(this);ONoTrust.addItemListener(this); + ONoOpt.addItemListener(this);ONoRam.addItemListener(this);ORFO.addItemListener(this); + OBioMol.addItemListener(this);OGDIIS.addItemListener(this); + OOptProd.addItemListener(this);ONewton.addItemListener(this); + ONoOptPro.addItemListener(this);ONRScale.addItemListener(this); + OConical.addItemListener(this);ONoNRS.addItemListener(this); + ORestart.addItemListener(this);OEF.addItemListener(this); + ONoFreeze.addItemListener(this);OSteep.addItemListener(this); + OModRed.addItemListener(this);OUpdate.addItemListener(this); + OInitHar.addItemListener(this);OBig.addItemListener(this); + OChkHar.addItemListener(this);OSmall.addItemListener(this); + OReadHar.addItemListener(this); + optListen++; + } + + /* if(InsertNode.nodeExists("Opt ")) + InsertNode.deleteNode("Opt "); + RouteClass.keywordBuffer[optFlag]=new StringBuffer(); + RouteClass.writeRoute(); + */ + dm.setDataVector( + + new Object[][]{ + {OMaxCy,ORedun,OEstmF,OTight,OMicro,OHFErr}, + + {OMaxSt,OZMatr,OReadFC,OVery,ONoMic,OFineG}, + + {ONatur,OCarte,OStar,OEigen,OQuadM,OSG1Er}, + + {OTS,null,OFCCard,ONoEig,ONoQua,OReadErr}, + + {OSadd,null,ORCFC,OExper,OCheck,null}, + {OQST2,null,OCalcH,ONoExp,OLinear,null}, + {OQST3,null,OCalcFc,OLoose,ONoLinear,null}, + {OPathN,null,OCalcAll,null,OTrust,null}, + {OOptRe,null,OVCD,null,ONoTrust,null}, + {ONoOpt,null,ONoRam,null,ORFO,null}, + {OBioMol,null,null,null,OGDIIS,null}, + {OOptProd,null,null,null,ONewton,null}, + {ONoOptPro,null,null,null,ONRScale,null}, + {OConical,null,null,null,ONoNRS,null}, + {ORestart,null,null,null,OEF,null}, + {ONoFreeze,null,null,null,OSteep,null}, + {OModRed,null,null,null,OUpdate,null}, + {OInitHar,null,null,null,OBig,null}, + {OChkHar,null,null,null,OSmall,null}, + {OReadHar,null,null,null,null,null}, + + }, + + new Object[]{"General Procedural","Coordinate System Selection","Initial Force Constants","Convergence","Numerical Algorithms","Error Interpretation"}); + + JTable table = new JTable(dm) { + public void tableChanged(TableModelEvent e) { + super.tableChanged(e); + repaint(); + } + }; + + + /*ButtonGroup group1 = new ButtonGroup(); + group1.add((JRadioButton)dm.getValueAt(0,1)); + group1.add((JRadioButton)dm.getValueAt(1,1)); + group1.add((JRadioButton)dm.getValueAt(2,1)); + ButtonGroup group2 = new ButtonGroup(); + group2.add((JRadioButton)dm.getValueAt(3,1)); + group2.add((JRadioButton)dm.getValueAt(4,1));*/ + table.getColumn("General Procedural").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("General Procedural").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + table.getColumn("Coordinate System Selection").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Coordinate System Selection").setCellEditor(new RadioButtonEditor(new JCheckBox())); + table.getColumn("Initial Force Constants").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Initial Force Constants").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + table.getColumn("Convergence").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Convergence").setCellEditor(new RadioButtonEditor(new JCheckBox())); + table.getColumn("Numerical Algorithms").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Numerical Algorithms").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + table.getColumn("Error Interpretation").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Error Interpretation").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + + + + doneButton = new JButton("Done"); + doneButton.addActionListener(this); + //clearButton = new JButton("Clear"); + exitButton = new JButton("Cancel"); + //doneButton.addActionListener(this); + // clearButton.addActionListener(this); + exitButton.addActionListener(this); + + donePanel = new JPanel(); + donePanel.add(doneButton); + donePanel.add(exitButton); + + /*table.setBackground(bgColor); + table.setForeground(foreColor); + */ + + + donePanel.setBackground(bgColor); + donePanel.setForeground(foreColor); + + + table.getTableHeader().setReorderingAllowed(false); + + + + OptFrame.getContentPane().setLayout(new BorderLayout()); + + + JScrollPane scroll = new JScrollPane(table); + OptFrame.getContentPane().add( scroll,BorderLayout.CENTER); + OptFrame.getContentPane().add(donePanel,BorderLayout.SOUTH); + OptFrame.setSize(600,200); + OptFrame.setLocation(200,75); + OptFrame.setVisible(true); + } + public void actionPerformed(ActionEvent ae) + { + if(ae.getSource()==doneButton){ + //InsertNode.deleteChildren("Op"); + System.out.println("The value of freq guessV = "+optC); + if(RouteClass.initCount==0) + { + System.out.println(RouteClass.initCount+" \tInside init"); + RouteClass.initBuffer(); + RouteClass.initCount++; + } + if(optC==0) + { + System.out.println(optC+" \t Inside optC"); + optFlag= RouteClass.keyIndex; + RouteClass.keyIndex++; + optC++; + } + else + { + System.out.println("opt Check"); + RouteClass.keywordBuffer[optFlag]=new StringBuffer(); + } + RouteClass.keywordBuffer[optFlag].append("Opt"); + + System.out.println("Checking opt table man"+ RouteClass.keywordBuffer[optFlag]); + + if(!(InsertNode.nodeExists("Opt"))) + InsertNode.insertNode("Job","Opt"); + try { + if(optionsC!=0) + { + if(optVopt.size()>1) + { + + RouteClass.keywordBuffer[optFlag].append("=("); + for(int count=0;count0) + RouteClass.keywordBuffer[optFlag].append("="+"("+optVopt.get(0)+")"); + } + } + }catch (NullPointerException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + //optFlag=RouteClass.keyIndex; + //RouteClass.keyIndex++; + RouteClass.writeRoute(); + OptFrame.dispose(); + } + + if(ae.getSource()==exitButton) + { + OptFrame.dispose(); + } + + + + } + + + + public void itemStateChanged(ItemEvent e) + { + if((e.getItem()==ORedun)|| (e.getItem()==OEstmF)|| + (e.getItem()==OTight)|| (e.getItem()==OMicro)|| (e.getItem()==OHFErr)|| + (e.getItem()==OZMatr)|| (e.getItem()==OReadFC)||(e.getItem()==OVery)|| + (e.getItem()==ONoMic)|| (e.getItem()==OFineG)|| + (e.getItem()==ONatur)|| (e.getItem()==OCarte)|| (e.getItem()==OEigen)|| + (e.getItem()==OQuadM)|| (e.getItem()==OSG1Er)|| (e.getItem()==OTS)|| + (e.getItem()==OStar)||(e.getItem()==ONoEig) || + (e.getItem()==ONoQua)|| (e.getItem()==OReadErr)|| (e.getItem()==OFCCard)|| + (e.getItem()==OExper)|| (e.getItem()==OCheck)|| (e.getItem()==OQST2)|| + (e.getItem()==ORCFC)||(e.getItem()==ONoExp) || + (e.getItem()==OLinear)|| (e.getItem()==OQST3)|| (e.getItem()==OCalcH)|| + (e.getItem()==OLoose)|| (e.getItem()==ONoLinear)|| + (e.getItem()==OCalcFc)||(e.getItem()==OTrust) || + (e.getItem()==OCalcAll)|| (e.getItem()==ONoTrust)|| (e.getItem()==ONoOpt)|| + (e.getItem()==OVCD)|| (e.getItem()==ORFO)|| (e.getItem()==OBioMol)|| + (e.getItem()==ONoRam)||(e.getItem()==OGDIIS) || + (e.getItem()==OOptProd)|| (e.getItem()==ONewton)|| (e.getItem()==ONoOptPro)|| + (e.getItem()==ONRScale)|| (e.getItem()==OConical)|| (e.getItem()==ONoNRS)|| + (e.getItem()==ONoFreeze)||(e.getItem()==OSteep) || + (e.getItem()==OModRed)|| (e.getItem()==OUpdate)|| (e.getItem()==OBig)|| + (e.getItem()==OSmall) + ) + + + + { + + System.out.println("Test case for opt 2"+(JRadioButton)e.getItem()); + if(((JRadioButton)e.getItem()).isSelected()) + + + { + G03Listener.optTabF++; + if(optionsC==0) + { + System.out.println("Options QQQQq"); + optVopt=new Vector(10); + optionsC++; + } + System.out.println("OPPPOPOPP"); + if((!(InsertNode.nodeExists("Opt ")))|| MenuListeners.optfreq.equals("optfreq")) + InsertNode.insertNode("Job","Opt "); + InsertNode.insertNode("Opt ", RadioButtonEditor.button.getActionCommand()); + ((JRadioButton)e.getItem()).setEnabled(true); + String opts = RadioButtonEditor.button.getActionCommand(); + optVopt.addElement(opts); + } + else + { + System.out.println("Deleted node is in Opt "+((JRadioButton)e.getItem()).getActionCommand()); + if(InsertNode.nodeExists(((JRadioButton)e.getItem()).getActionCommand())) + InsertNode.deleteNode(((JRadioButton)e.getItem()).getActionCommand()); + optVopt.removeElement(((JRadioButton)e.getItem()).getActionCommand()); + + + } + } + + //if MaxCycle=N + + if(e.getItem()==OMaxCy) + { + if(optionsC==0) + { + G03Listener.optTabF++; + optVopt=new Vector(10); + optionsC++; + } + + if(((JRadioButton)e.getItem()).isSelected()) + { + JTextField stepField; + JPanel txt; + txt = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + ((JRadioButton)e.getItem()).setEnabled(true); + stepField = new JTextField(3); + stepField.setSize(2,1); + Object[] obj = new Object[2]; + obj[0] = "Set maximum number of optimization"; + JLabel s = new JLabel("steps to N ="); //+stepField; + c.insets=new Insets(0,0,0,0); + txt.add(s,c); + c.insets = new Insets(0,0,0,110); + txt.add(stepField,c); + obj[1] = txt; + int ch=JOptionPane.showConfirmDialog(null,obj,"MaxCycle=N",JOptionPane.OK_OPTION); + G03MenuTree.freOptString=""; + if(ch==0) + { + if(!(InsertNode.nodeExists("Opt "))) + {InsertNode.insertNode("Job","Opt "); + } + // Delete Existing node and then add it + if(InsertNode.nodeExists("MaxCycle")) + { + InsertNode.deleteNode("MaxCycle"); + } + InsertNode.insertNode("Opt ","MaxCycle="+stepField.getText()); + + maxCy = new String(); + maxCy = "MaxCycle="+stepField.getText(); + optVopt.addElement(maxCy); + } + if(ch==1) // pressed no remove step + { + if((InsertNode.nodeExists("MaxCycle"))) + { + //Delete Node if exists + InsertNode.deleteNode("MaxCycle"); + optVopt.removeElement("MaxCycle="+maxCy); + } + + } + } + + else // if it is deselected + { + if((InsertNode.nodeExists("MaxCycle"))) + InsertNode.deleteNode("MaxCycle"); + System.out.println("TTTTTT"+maxCy); + optVopt.removeElement("MaxCycle="+maxCy); + + } + } + + //End of MaxCycle + + //MaxStep=N + + if(e.getItem()== OMaxSt) + { + if(optionsC==0) + { + G03Listener.optTabF++; + optVopt=new Vector(10); + optionsC++; + } + + if(((JRadioButton)e.getItem()).isSelected()) + { + JTextField stepField; + JPanel txt; + txt = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + ((JRadioButton)e.getItem()).setEnabled(true); + System.out.println("OOO"); + stepField = new JTextField(3); + stepField.setSize(2,1); + Object[] obj = new Object[2]; + stepField.setText("30"); + obj[0] = "Set maximum size of optimization"; + JLabel s = new JLabel("steps to N ="); //+stepField; + c.insets=new Insets(0,0,0,0); + txt.add(s,c); + c.insets = new Insets(0,0,0,110); + txt.add(stepField,c); + obj[1] = txt; + int ch=JOptionPane.showConfirmDialog(null,obj,"MaxStep=N",JOptionPane.OK_OPTION); + G03MenuTree.freOptString=""; + + if(ch==0) + { // Pressed Yes + if(!(InsertNode.nodeExists("Opt "))) + {InsertNode.insertNode("Job","Opt "); + } + // Delete Existing + if(InsertNode.nodeExists("MaxStep=")) + InsertNode.deleteNode("MaxStep="); + + InsertNode.insertNode("Opt ","MaxStep="+stepField.getText()); + + maxSt = new String(); + maxSt = stepField.getText(); + optVopt.addElement("MaxStep="+maxSt); + } + if(ch==1) // pressed no remove step + { + if((InsertNode.nodeExists("MaxStep"))) + { + //Delete Node if exists + InsertNode.deleteNode("MaxStep"); + optVopt.removeElement("MaxStep="+maxSt); + } + + } + } + else + {if((InsertNode.nodeExists("MaxStep"))) + InsertNode.deleteNode("MaxStep"); + System.out.println("TTTTTT"+maxSel); + optVopt.removeElement("MaxStep="+maxSt); + + } + } + + //End of MaxStep=N + + //if Saddle=N + + if(e.getItem()==OSadd) + { + if(optionsC==0) + { + G03Listener.optTabF++; + optVopt=new Vector(10); + optionsC++; + } + if(((JRadioButton)e.getItem()).isSelected()) + { + JTextField stepField; + JPanel txt; + txt = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + + ((JRadioButton)e.getItem()).setEnabled(true); + System.out.println("OOO"); + stepField = new JTextField(3); + + Object[] obj = new Object[2]; + + obj[0] = "Optimize to a saddle point"; + JLabel s = new JLabel("of order N ="); //+stepField; + c.insets=new Insets(0,0,0,0); + txt.add(s,c); + c.insets = new Insets(0,0,0,110); + txt.add(stepField,c); + obj[1] = txt; + int ch=JOptionPane.showConfirmDialog(null,obj,"Saddle=N",JOptionPane.OK_OPTION); + G03MenuTree.freOptString=""; + if(ch==0) + { + if(!(InsertNode.nodeExists("Opt "))) + { + InsertNode.insertNode("Job","Opt "); + + } + //Delete Existing and then write + if(InsertNode.nodeExists("Saddle")) + InsertNode.deleteNode("Saddle"); + InsertNode.insertNode("Opt ","Saddle="+stepField.getText()); + maxSel=new String(); + maxSel=stepField.getText(); + sadN = new String(); + sadN = stepField.getText(); + optVopt.addElement("Saddle="+sadN); + } + + if(ch==1) + { //Pressed No + if(InsertNode.nodeExists("Saddle")) + InsertNode.deleteNode("Saddle"); + optVopt.removeElement("Saddle="+sadN); + } + + + } + else { + if((InsertNode.nodeExists("Saddle"))) + InsertNode.deleteNode("Saddle"); + optVopt.removeElement("Saddle="+sadN); + + } + + + }//End of Saddle + + //Path=N + + if(e.getItem()=="Path") + { + if(optionsC==0) + { + G03Listener.optTabF++; + optVopt=new Vector(10); + optionsC++; + } + + if(((JRadioButton)e.getItem()).isSelected()) + { + JTextField stepField; + JPanel txt; + txt = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + ((JRadioButton)e.getItem()).setEnabled(true); + System.out.println("OOO"); + stepField = new JTextField(3); + + Object[] obj = new Object[2]; + + obj[0] = "Simultaneously optimize a transition"; + + JLabel s = new JLabel("state and an M="); //+stepField; + c.insets=new Insets(0,0,0,0); + txt.add(s,c); + c.insets = new Insets(0,0,0,0); + JLabel s1 = new JLabel("-point reaction path"); + + txt.add(stepField,c); + + c.insets = new Insets(0,0,0,30); + txt.add(s1,c); + obj[1] = txt; + + + int ch=JOptionPane.showConfirmDialog(null,obj,"Path=N",JOptionPane.OK_OPTION); + G03MenuTree.freOptString=""; + if(ch==0) + { + if(!(InsertNode.nodeExists("Opt "))) + InsertNode.insertNode("Job","Opt "); + + //Delete Existing and Write + if(InsertNode.nodeExists("Path")) + InsertNode.deleteNode("Path="); + InsertNode.insertNode("Opt ","Path="+stepField.getText()); + maxSel=new String(); + maxSel=stepField.getText(); + pathN = new String(); + pathN = stepField.getText(); + optVopt.addElement("Path="+pathN); + + } + if(ch==1) // pressed no remove step + { + if((InsertNode.nodeExists("Path"))) + { + //Delete Node if exists + InsertNode.deleteNode("Path"); + optVopt.removeElement("Path="+pathN); + } + + } + + } + else{ + if((InsertNode.nodeExists("Path"))) + InsertNode.deleteNode("Path"); + System.out.println("TTTTTT"+maxSel); + optVopt.removeElement("Path="+pathN); + } + } + + //End of Path=N + + //InitialHarmonic=N + if(e.getItem()==OInitHar) + { + if(optionsC==0) + { + G03Listener.optTabF++; + optVopt=new Vector(10); + optionsC++; + } + + if(((JRadioButton)e.getItem()).isSelected()) + { + JTextField stepField; + JPanel txt; + txt = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + ((JRadioButton)e.getItem()).setEnabled(true); + System.out.println("OOO"); + stepField = new JTextField(3); + stepField.setSize(2,1); + Object[] obj = new Object[2]; + + obj[0] = "Add harmonic contraints to intial structure with force"; + JLabel s = new JLabel("constant N/1000 Hartree/Bohr*Bohr with N ="); //+stepField; + c.insets=new Insets(0,0,0,0); + txt.add(s,c); + c.insets = new Insets(0,0,0,30); + txt.add(stepField,c); + obj[1] = txt; + int ch=JOptionPane.showConfirmDialog(null,obj,"InitialHarmonic=N",JOptionPane.OK_OPTION); + G03MenuTree.freOptString=""; + if(ch==0) + { + if(!(InsertNode.nodeExists("Opt "))) + {InsertNode.insertNode("Job","Opt "); + } + + if((InsertNode.nodeExists("InitialHarmonic"))) + { + //Delete Node if exists + InsertNode.deleteNode("InitialHarmonic"); + } + InsertNode.insertNode("Opt ","InitialHarmonic="+stepField.getText()); + maxSel=new String(); + maxSel=stepField.getText(); + iharN = new String(); + iharN = stepField.getText(); + optVopt.addElement("InitialHarmonic=N"+iharN); + } + if(ch==1) // pressed no remove step + { + if((InsertNode.nodeExists("InitialHarmonic"))) + { + //Delete Node if exists + InsertNode.deleteNode("InitialHarmonic"); + optVopt.removeElement("InitialHarmonic"+iharN); + } + + } + } + else{if((InsertNode.nodeExists("InitialHarmonic"))) + InsertNode.deleteNode("InitialHarmonic"); + System.out.println("TTTTTT"+maxSel); + optVopt.removeElement("InitialHarmonic="+iharN); + } + }// InitialHarmonic + + //ChkHarmonic + if(e.getItem()==OChkHar) + { + + if(optionsC==0) + { + G03Listener.optTabF++; + optVopt=new Vector(10); + optionsC++; + } + + if(((JRadioButton)e.getItem()).isSelected()) + { + JTextField stepField; + JPanel txt; + txt = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + ((JRadioButton)e.getItem()).setEnabled(true); + System.out.println("OOO"); + stepField = new JTextField(3); + stepField.setSize(2,1); + Object[] obj = new Object[3]; + + obj[0] = "Add harmonic contraints to intial structure"; + obj[1] = "saved on the chk file with force constant"; + + JLabel s = new JLabel("N/1000 Hartree/Bohr*Bohr with N ="); //+stepField; + c.insets=new Insets(0,0,0,0); + txt.add(s,c); + c.insets = new Insets(0,0,0,30); + txt.add(stepField,c); + obj[2] = txt; + int ch=JOptionPane.showConfirmDialog(null,obj,"ChkHarmonic=N",JOptionPane.OK_OPTION); + G03MenuTree.freOptString=""; + if(ch==0) + { + if(!(InsertNode.nodeExists("Opt "))) + {InsertNode.insertNode("Job","Opt "); + } + if((InsertNode.nodeExists("ChkHarmonic"))) + { + //Delete Node if exists + InsertNode.deleteNode("ChkHarmonic"); + } + InsertNode.insertNode("Opt ","ChkHarmonic="+stepField.getText()); + maxSel=new String(); + maxSel=stepField.getText(); + chkN = new String(); + chkN = stepField.getText(); + optVopt.addElement("ChkHarmonic="+chkN); + } + if(ch==1) // pressed no remove step + { + if((InsertNode.nodeExists("ChkHarmonic"))) + { + //Delete Node if exists + InsertNode.deleteNode("ChkHarmonic"); + optVopt.removeElement("ChkHarmonic="+chkN); + } + + } + + } + + else{ + if((InsertNode.nodeExists("ChkHarmonic"))) + InsertNode.deleteNode("ChkHarmonic"); + System.out.println("TTTTTT"+maxSel); + optVopt.removeElement("ChkHarmonic="+chkN); + } + } //end of chkharmonic + + //ReadHarmonic + + if(e.getItem()==OReadHar) + { + + if(optionsC==0) + { + G03Listener.optTabF++; + optVopt=new Vector(10); + optionsC++; + } + + if(((JRadioButton)e.getItem()).isSelected()) + { + JTextField stepField; + JPanel txt; + txt = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + ((JRadioButton)e.getItem()).setEnabled(true); + System.out.println("OOO"); + stepField = new JTextField(3); + stepField.setSize(2,1); + Object[] obj = new Object[3]; + + obj[0] = "Add harmonic contraints to a structure read in"; + obj[1] = " from the input stream with force constant"; + + JLabel s = new JLabel(" N/1000 Hartree/Bohr*Bohr with N ="); //+stepField; + c.insets=new Insets(0,0,0,0); + txt.add(s,c); + c.insets = new Insets(0,0,0,30); + txt.add(stepField,c); + obj[2] = txt; + int ch=JOptionPane.showConfirmDialog(null,obj,"ReadHarmonic=N",JOptionPane.OK_OPTION); + G03MenuTree.freOptString=""; + + if(ch==0) + { + if(!(InsertNode.nodeExists("Opt "))) + {InsertNode.insertNode("Job","Opt "); + } + + if((InsertNode.nodeExists("ReadHarmonic"))) + { + //Delete Node if exists + InsertNode.deleteNode("ReadHarmonic"); + } + InsertNode.insertNode("Opt ","ReadHarmonic="+stepField.getText()); + readN= new String(); + readN = stepField.getText(); + optVopt.addElement("ReadHarmonic="+readN); + + } + if(ch==1) // pressed no remove step + { + if((InsertNode.nodeExists("ReadHarmonic"))) + { + //Delete Node if exists + InsertNode.deleteNode("ReadHarmonic"); + optVopt.removeElement("ReadHarmonic="+readN); + } + + } + + } + + else{ + if((InsertNode.nodeExists("ReadHarmonic"))) + InsertNode.deleteNode("ReadHarmonic"); + + optVopt.removeElement("ReadHarmonic="+readN); + } + } //end of Read Harmonic + + + + + + + }//end of ITemStateChanged + public static void main(String[] args) { + OptTable frame = new OptTable(); + frame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + System.exit(0); + } + }); + } +} + diff --git a/src/main/java/g03input/RouteClass.java b/src/main/java/g03input/RouteClass.java new file mode 100644 index 0000000..3918e82 --- /dev/null +++ b/src/main/java/g03input/RouteClass.java @@ -0,0 +1,588 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Apr 4, 2005 + * @author Michael Sheetz + * @author Shashank Jeedigunta @author Sandeep Kumar Seethaapathy + * + */ + + +package g03input; + + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + + +public class RouteClass implements ActionListener{ + public static int initCount=0; + public static StringBuffer routeBuffer= new StringBuffer(); + public static StringBuffer poundOpt=null; + public static StringBuffer methodBuffer=null; + public static StringBuffer basisBuffer=null; + public static StringBuffer[] keywordBuffer=null; + public static final int KEYWORD_BUFFER_LENGTH = 15; + public static RouteClass rt; + public static int keyIndex; + + + public static void createInput(){ + if(InputFile.inputfetched==0){ + try { + InputFile.tempinput=""; + if(!(G03MenuTree.noofspText.getText().length()<1)) + { + InputFile.tempinput+="%nproc="+G03MenuTree.noofspText.getText(); + InputFile.tempinput+="\n"; + } + if(!(G03MenuTree.nooflpText.getText().length()<1)) + { + InputFile.tempinput+="%nprocl="+G03MenuTree.nooflpText.getText(); + InputFile.tempinput+="\n"; + } + if(!(G03MenuTree.dynmemText.getText().length()<1)) + { + InputFile.tempinput+="%mem="+G03MenuTree.dynmemText.getText()+"MB"; + InputFile.tempinput+="\n"; + } + if(!(G03MenuTree.filnamArea.getText().length()<1)) + { + InputFile.tempinput+="%Chk="+G03MenuTree.filnamArea.getText(); + InputFile.tempinput+="\n"; + } + } catch (NullPointerException exc) { + + exc.printStackTrace(); + } + + // InputFile.tempinput+="\n"; // Modified Sept 15,2005 + InputFile.tempinput+=routeBuffer; + InputFile.tempinput+="\n\n"; + InputFile.tempinput+=G03MenuTree.jobArea.getText(); + InputFile.tempinput+="\n\n"; + + //Newly added on Sept 15,2005 @ UKY after separating charge and mul from tempmol + + InputFile.tempinput+=G03MenuTree.molCharge.getText()+" "+G03MenuTree.molMultiplicity.getText()+"\n"; + + + //End of Newly added on Sept 15,2005 @ UKY after separating charge and mul from tempmol + + System.out.println("In RouteClass"+ showMolEditor.tempmol); + InputFile.tempinput+= showMolEditor.tempmol; + + InputFile.tempinput+="\n"; + } + } + + public RouteClass() + { + + routeBuffer = new StringBuffer(); + methodBuffer = new StringBuffer(); + basisBuffer = new StringBuffer(); + poundOpt = new StringBuffer("# "); + keywordBuffer = new StringBuffer[KEYWORD_BUFFER_LENGTH]; + } + + public void actionPerformed(ActionEvent ae) + { + if(ae.getSource()==G03MenuTree.nRadio) + { + + + poundOpt = new StringBuffer(); + poundOpt.append("# "); + //poundOpt.replace(0,1,"# "); + //new RouteClass(); + writeRoute(); + } + if(ae.getSource()==G03MenuTree.pRadio) + { + + + poundOpt = new StringBuffer(); + poundOpt.append("#P "); + //new RouteClass(); + writeRoute(); + } + if(ae.getSource()==G03MenuTree.tRadio) + { + + + poundOpt = new StringBuffer(); + poundOpt.append("#T "); + //new RouteClass(); + writeRoute(); + } + } + public static void initBuffer() + { + RouteClass.keywordBuffer = new StringBuffer[KEYWORD_BUFFER_LENGTH]; + for(int i = 0; i < keywordBuffer.length; i++) + { + RouteClass.keywordBuffer[i]=new StringBuffer(); + } + } + + public static void rewriteRoute(String nodeName,String parent) + { + if(parent.equals("Methods")) + { + InsertNode.deleteChildren("Methods"); + MenuMethodListener.createHTable(); + MenuMethodListener.count=0; + MenuMethodListener.exchngFlag=0; + MenuMethodListener.corrFlag=0; + + + methodBuffer = new StringBuffer(); + writeRoute(); + + } + else if(parent.equals("Basis Sets")) + { + + basisBuffer= new StringBuffer(); + writeRoute(); + + + } + else if(parent.equals("Job Types")) + { + if(nodeName.equals("Freq")) + { + keywordBuffer[FreqOptTable.freqFlag]=new StringBuffer(); + FreqOptTable.freqC=0; + writeRoute(); + } + + + if(nodeName.equals("Opt ")) + { + keywordBuffer[OptTable.optFlag]=new StringBuffer(); + OptTable.optC=0; + + writeRoute(); + } + + if(nodeName.equals("OptFreq")) + { + // Direct Child but name is Different + MenuListeners.optfreqflag=0; + writeRoute(); + } + + if(nodeName.equals("Opt_IRC-Max")) + { + MenuListeners.optircmaxflag=0; + writeRoute(); + } + + if(nodeName.equals("Opt_Polar")) + { + MenuListeners.optpolarflag=0; + writeRoute(); + + + } + + + + else{ + //Directly Children + //keywordBuffer[RouteClass.keyIndex]; + int index; + int lastindex; + System.out.println("nodeName"+nodeName+"$$"); + for(int i=0;i1) + routeBuffer.append("/"+basisBuffer); + } catch (NullPointerException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + routeBuffer.append(" "); + System.out.println(keyIndex); + /*if(keyIndex>1) + { + System.out.println("buffer"+keywordBuffer[keyIndex-1]); + System.out.println("index"+keyIndex); + System.out.println("0"+keywordBuffer[0]); + System.out.println("1"+keywordBuffer[1]); + System.out.println("2"+keywordBuffer[2]); + } + //routeBuffer.append(keywordBuffer[0][0]);*/ + for(int key=0;key0) + for(int key=0;key-1) + return true; + + return false; + } + + +} diff --git a/src/main/java/g03input/RunFrame.java b/src/main/java/g03input/RunFrame.java new file mode 100644 index 0000000..b493d64 --- /dev/null +++ b/src/main/java/g03input/RunFrame.java @@ -0,0 +1,166 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following f +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Mar 16, 2005 + * @author Michael Sheetz + * @author Sandeep Kumar Seethaapathy @author Shashank Jeedigunta + * + */ + + +package g03input; + +import javax.swing.*; +import java.awt.*; + +public class RunFrame extends JFrame{ +public static JFrame runFrame1,runFrame2; +public static JPanel panel1,panel2; +public static JRadioButton unRest,restClose,restOpen; +public static JButton ok1,ok2; +public static JLabel frameHead; +public static ButtonGroup mOpt; + +/** + * Why is there duplicated code: + * RunFrame::createThreeOptionFrame + * is the same as + * MenuMethodListener::showOptionsFrame + */ +public static void createThreeOptionFrame() +{ + JFrame.setDefaultLookAndFeelDecorated(true); + runFrame1 = new JFrame("Select Wavefunction Type"); + panel1 = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + frameHead = new JLabel("Run calculation as"); + restClose = new JRadioButton("R - Restricted closed-shell"); + restOpen = new JRadioButton("RO - Restricted Open-shell"); + unRest = new JRadioButton("U - Unrestricted open-shell"); + ok1 = new JButton("OK"); + mOpt=new ButtonGroup(); + + mOpt.add(restClose); + mOpt.add(restOpen); + mOpt.add(unRest); + restClose.setSelected(true); + + + ok1.addActionListener(new MenuMethodListener()); + c.gridx=0; + c.gridy=0; + c.weightx=0.5; + //c.weighty=0.15; + c.insets= new Insets(0,10,10,100); + panel1.add(frameHead,c); + + c.insets= new Insets(0,-90,10,-20); + c.gridy=1; + c.gridx=0; + panel1.add(restClose,c); + c.gridy=2; + c.gridx=0; + panel1.add(restOpen,c); + c.gridy=3; + c.gridx=0; + panel1.add(unRest,c); + c.gridy=4; + c.gridx=0; + c.insets = new Insets(0,90,10,90); + panel1.add(ok1,c); + + runFrame1.getContentPane().add(panel1); + runFrame1.pack(); + runFrame1.setLocation(200,200); + runFrame1.setSize(300,225); + runFrame1.setVisible(true); + runFrame1.setResizable(true); + runFrame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + + +} + +public static void createTwoOptionFrame() +{ + JFrame.setDefaultLookAndFeelDecorated(true); + runFrame2 = new JFrame("Select Wavefunction Type"); + panel2 = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + frameHead = new JLabel("Run calculation as"); + + restClose = new JRadioButton("R - Restricted closed-shell"); + restOpen = new JRadioButton("U - Unrestricted open-shell"); + ok2 = new JButton("OK"); + + mOpt=new ButtonGroup(); + mOpt.add(restClose); + mOpt.add(restOpen); + restClose.setSelected(true); + c.gridx=0; + c.weightx=0.5; + //c.weighty=0.5; + c.insets= new Insets(0,10,10,100); + panel2.add(frameHead,c); + c.insets= new Insets(0,-90,10,-20); + c.gridy=1; + c.gridx=0; + panel2.add(restClose,c); + c.gridy=2; + panel2.add(restOpen,c); + c.gridy=3; + c.gridx=0; + c.insets = new Insets(0,90,10,90); + panel2.add(ok2,c); + ok2.addActionListener(new MenuMethodListener()); + runFrame2.getContentPane().add(panel2); + runFrame2.pack(); + runFrame2.setLocation(200,200); + runFrame2.setSize(300,200); + runFrame2.setVisible(true); + runFrame2.setResizable(true); + runFrame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + +} + + + + + +} + + diff --git a/src/main/java/g03input/atomCoordinateParser.java b/src/main/java/g03input/atomCoordinateParser.java new file mode 100644 index 0000000..ad87e88 --- /dev/null +++ b/src/main/java/g03input/atomCoordinateParser.java @@ -0,0 +1,114 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * + * @author Michael Sheetz + * @author Shashank Jeedigunta @author Sandeep Kumar Seethaapathy + * + */ +package g03input; + + +import javax.swing.*; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.StringReader; +import java.util.regex.Pattern; + +public class atomCoordinateParser { +public static int count; +public static String atomArray=" "; +public static String coordinates=" "; +public static int atomIndex=0; +public static void getCoordinates() +{ +//StringReader reader=new StringReader(showMolEditor.tempmolFromInput); + StringReader reader=new StringReader(GeometryEditor.validateGeom); +BufferedReader br= new BufferedReader(reader); +BufferedReader br1= new BufferedReader(reader); // Buffered Reader to Read the no. of lines + +String temp=""; +try { + + atomArray=""; + coordinates=""; + atomIndex=0; + temp=br.readLine(); + boolean matched = Pattern.matches("[\\s]*[\\+|\\-]?[0-9]+\\.?[0-9]*[\\s]*[\\+|\\-]?[0-9]+\\.?[0-9]*[\\s]*",temp); //Charge and Multiplicity + if(matched){ + temp=br.readLine(); + while(temp!=null){ + boolean molmatched = + Pattern.matches("[\\w]?[\\s]+[\\+|\\-]?[0-9]+\\.?[0-9]+[\\s]+[\\+|\\-]?[0-9]+\\.?[0-9]+[\\s]+[\\+|\\-]?[0-9]+\\.?[0-9]+[\\s]*",temp); + //Pattern.matches("[A-Z][a-z]?[\\s]+[\\+|\\-]?[0-9]+\\.?[0-9]+[\\s]+[\\+|\\-]?[0-9]+\\.?[0-9]+[\\s]+[\\+|\\-]?[0-9]+\\.?[0-9]+[\\s]*",temp); + String[] tempArray=temp.split("[\\s]+"); + System.out.println("AtomCoordParser_79:"+tempArray); + atomArray+=tempArray[0]+" "; //Stores the Atom Name + coordinates+=tempArray[1]+" "+tempArray[2]+" "+tempArray[3]+" "; + atomIndex++; + if((molmatched==false)){ + JOptionPane.showMessageDialog(null,"Incoherent Molecular Specification, missing Atom ID or Coordinates","Error",JOptionPane.ERROR_MESSAGE); + System.out.println("G03GUI:atomCoordintaeParser:Matched incoherent input line:"+temp); + break; + } + temp=br.readLine(); + } + new BufferedDisplayMolecule(); // Show the new Molecule + + } + else{ + JOptionPane.showMessageDialog(null,"Incoherent Charge and Multiplicity","Error",JOptionPane.ERROR_MESSAGE); + } + +} catch (IOException e) { + // TODO Auto-generated catch blockzx + e.printStackTrace(); +} +catch(ArrayIndexOutOfBoundsException e) +{ + e.printStackTrace(); +} +} +/* + public static void main(String args[]) + { + getCoordinates(); + + } +*/ +} diff --git a/src/main/java/g03input/geomOptTable.java b/src/main/java/g03input/geomOptTable.java new file mode 100644 index 0000000..73dc417 --- /dev/null +++ b/src/main/java/g03input/geomOptTable.java @@ -0,0 +1,641 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Mar 30, 2005 + * @author Michael Sheetz + * @author Shashank Jeedigunta @author Sandeep Kumar Seethaapathy + * + */ + + +package g03input; + +import javax.swing.*; +import javax.swing.event.TableModelEvent; +import javax.swing.table.DefaultTableModel; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.Vector; + +public class geomOptTable implements ItemListener,ActionListener{ + Color bgColor= new Color(236,233,216); + Color foreColor =new Color(0,78,152); + JPanel donePanel; + JButton doneButton,clearButton,exitButton; + public static JTable table; + JFrame geomOptFrame; + public static int geomC,geomFlag,geomOptC,geomListen; + public static Vector geomClear; + public static Vector geomOpt; + public static String geoSt,geoRe,geoCh,geoIh; + public static JRadioButton GeCheck =new JRadioButton("Checkpoint"); + public static JRadioButton GeDist = new JRadioButton("Distance"); + public static JRadioButton GeKeep =new JRadioButton("KeepConstants"); + public static JRadioButton GeModea = new JRadioButton("ModelA"); + public static JRadioButton GeAll= new JRadioButton("AllCheck"); + public static JRadioButton GeAng = new JRadioButton("Angle"); + public static JRadioButton GeKeepd =new JRadioButton("KeepDefinition"); + public static JRadioButton GeModeb =new JRadioButton("ModelB"); + public static JRadioButton GeStep =new JRadioButton("Step=N"); + public static JRadioButton GeCang =new JRadioButton("CAngle"); + public static JRadioButton GeRedun = new JRadioButton("NewRedundant"); + public static JRadioButton GePrin =new JRadioButton("Print"); + public static JRadioButton GeModr =new JRadioButton("ModRedundant"); + public static JRadioButton Gedihed = new JRadioButton("Dihedral"); + public static JRadioButton Gecrow =new JRadioButton("Crowd"); + public static JRadioButton GeModi = new JRadioButton("Modify"); + public static JRadioButton Gecdih = new JRadioButton("CDihedral"); + public static JRadioButton GeIndep =new JRadioButton("Independent"); + public static JRadioButton GeConn = new JRadioButton("Connect"); + public static JRadioButton GePrint =new JRadioButton("PrintInputOrient"); + public static JRadioButton GeMod = new JRadioButton("ModConnect"); + public static JRadioButton GeZmco = new JRadioButton("ZMConnect"); + public static JRadioButton GeIhar = new JRadioButton("IHarmonic=N"); + public static JRadioButton GeChk = new JRadioButton("ChkHarmonic=N"); + public static JRadioButton GeRead =new JRadioButton("ReadHarmonic=N"); + + + public geomOptTable(){ + //geomOpt= new Vector(10); + geomOptFrame=new JFrame("Geom Options"); + if(geomListen==0) + { + geomClear=new Vector(30); + geomClear.addElement(GeCheck); + geomClear.addElement(GeDist); + geomClear.addElement(GeKeep); + geomClear.addElement(GeModea); + geomClear.addElement(GeAll); + geomClear.addElement(GeAng); + geomClear.addElement(GeKeepd); + geomClear.addElement(GeModeb); + //geomClear.addElement(GeStep); + geomClear.addElement(GeCang); + geomClear.addElement(GeRedun); + geomClear.addElement(GePrin); + geomClear.addElement(GeModr); + geomClear.addElement(Gedihed); + geomClear.addElement(GeDist); + geomClear.addElement(Gecrow); + geomClear.addElement(GeModi); + geomClear.addElement(Gecdih); + geomClear.addElement(GeIndep); + geomClear.addElement(GeConn); + geomClear.addElement(GePrint); + geomClear.addElement(GeMod); + geomClear.addElement(GeZmco); + // geomClear.addElement(GeIhar); + //geomClear.addElement(GeChk); + // geomClear.addElement(GeRead); + GeCheck.setBackground(Color.WHITE); + GeCheck.addItemListener(this); + GeDist.setBackground(Color.WHITE); + GeDist.addItemListener(this); + GeKeep.setBackground(Color.WHITE); + GeKeep.addItemListener(this); + GeModea.setBackground(Color.WHITE); + GeModea.addItemListener(this); + GeAll.setBackground(Color.WHITE); + GeAll.addItemListener(this); + GeAng.setBackground(Color.WHITE); + GeAng.addItemListener(this); + GeKeepd.setBackground(Color.WHITE); + GeKeepd.addItemListener(this); + GeModeb.setBackground(Color.WHITE); + GeModeb.addItemListener(this); + GeStep.setBackground(Color.WHITE); + GeStep.addItemListener(this); + GeCang.setBackground(Color.WHITE); + GeCang.addItemListener(this); + GeRedun.setBackground(Color.WHITE); + GeRedun.addItemListener(this); + GePrin.setBackground(Color.WHITE); + GePrin.addItemListener(this); + GeModr.setBackground(Color.WHITE); + GeModr.addItemListener(this); + Gedihed.setBackground(Color.WHITE); + Gedihed.addItemListener(this); + Gecrow.setBackground(Color.WHITE); + Gecrow.addItemListener(this); + + GeModi.setBackground(Color.WHITE); + GeModi.addItemListener(this); + Gecdih.setBackground(Color.WHITE); + Gecdih.addItemListener(this); + GeIndep.setBackground(Color.WHITE); + GeIndep.addItemListener(this); + GeConn.setBackground(Color.WHITE); + GeConn.addItemListener(this); + GePrint.setBackground(Color.WHITE); + GePrint.addItemListener(this); + GeMod.setBackground(Color.WHITE); + GeMod.addItemListener(this); + GeZmco.setBackground(Color.WHITE); + GeZmco.addItemListener(this); + GeIhar.setBackground(Color.WHITE); + GeIhar.addItemListener(this); + GeChk.setBackground(Color.WHITE); + GeChk.addItemListener(this); + GeRead.setBackground(Color.WHITE); + GeRead.addItemListener(this); + geomListen++; + } + + + + + //UIDefaults ui = UIManager.getLookAndFeel().getDefaults(); + + //UIManager.put("RadioButton.focus", ui.getColor("control")); + + DefaultTableModel dm = new DefaultTableModel(); + dm.setDataVector( + new Object[][]{ + + + {GeCheck,GeDist,GeKeep,GeModea}, + {GeAll,GeAng,GeKeepd,GeModeb}, + {GeStep,GeCang,GeRedun,GePrin}, + {GeModr,Gedihed,Gecrow,null}, + {GeModi,Gecdih,GeIndep,null}, + {GeConn,GePrint,null,null}, + {GeMod,null,null,null}, + {GeZmco,null,null,null}, + {GeIhar,null,null,null}, + {GeChk,null,null,null}, + {GeRead,null,null,null}, + }, + + new Object[]{"Item Selection","Output Related","Geometric Specification and Checking","Model Builder"}); + + JTable table = new JTable(dm) { + public void tableChanged(TableModelEvent e) { + super.tableChanged(e); + repaint(); + } + }; + + table.getColumn("Item Selection").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Item Selection").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + table.getColumn("Output Related").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Output Related").setCellEditor(new RadioButtonEditor(new JCheckBox())); + table.getColumn("Geometric Specification and Checking").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Geometric Specification and Checking").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + table.getColumn("Model Builder").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Model Builder").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + doneButton = new JButton("Done"); + doneButton.addActionListener(this); + // clearButton = new JButton("Clear"); + exitButton = new JButton("Exit"); + + donePanel = new JPanel(); + donePanel.add(doneButton); + //donePanel.add(clearButton); + donePanel.add(exitButton); + exitButton.addActionListener(this); + donePanel.setBackground(bgColor); + donePanel.setForeground(foreColor); + table.getTableHeader().setReorderingAllowed(false); + geomOptFrame.getContentPane().setLayout(new BorderLayout()); + JScrollPane scroll = new JScrollPane(table); + geomOptFrame.getContentPane().add( scroll,BorderLayout.CENTER); + geomOptFrame.getContentPane().add(donePanel,BorderLayout.SOUTH); + geomOptFrame.setSize( 600,200); + geomOptFrame.setLocation(200,75); + geomOptFrame.setVisible(true); + } + + public void itemStateChanged(ItemEvent e) + { + + if((e.getItem()==GeCheck)|| + (e.getItem()==GeDist)|| + (e.getItem()==GeKeep)|| + (e.getItem()==GeModea)|| + (e.getItem()==GeAll)|| + (e.getItem()==GeAng)|| + (e.getItem()==GeKeepd)|| + (e.getItem()==GeModeb)|| + //(e.getItem()==GeStep)|| + (e.getItem()==GeCang)|| + (e.getItem()==GeRedun)|| + (e.getItem()==GePrin)|| + (e.getItem()==GeModr)|| + (e.getItem()==Gedihed)|| + (e.getItem()==Gecrow)|| + (e.getItem()==GeModi)|| + (e.getItem()==Gecdih)|| + (e.getItem()==GeIndep)|| + (e.getItem()==GeConn)|| + (e.getItem()==GePrint)|| + (e.getItem()==GeMod)|| + (e.getItem()==GeZmco)) + + { + G03Listener.geomTabF++; + if(((JRadioButton)e.getItem()).isSelected()) + { + if(geomOptC==0) + { + geomOpt= new Vector(10); + geomOptC++; + } + if(!(InsertNode.nodeExists("Geom"))) + + InsertNode.insertNode("Key","Geom"); + InsertNode.insertNode("Geom", RadioButtonEditor.button.getActionCommand()); + String geoms = RadioButtonEditor.button.getActionCommand(); + geomOpt.addElement(geoms); + + }//System.out.println(e.getActionCommand()); + + else + { + if(InsertNode.nodeExists(((JRadioButton)e.getItem()).getActionCommand())) + InsertNode.deleteNode(((JRadioButton)e.getItem()).getActionCommand()); + geomOpt.removeElement(((JRadioButton)e.getItem()).getActionCommand()); + } + } + + if(e.getItem()==GeStep) + { + if(((JRadioButton)e.getItem()).isSelected()) + { + G03Listener.geomTabF++; + if(geomOptC==0) + { + geomOpt= new Vector(10); + geomOptC++; + } + + JTextField stepField; + JPanel txt; + txt = new JPanel(new FlowLayout()); + stepField = new JTextField(3); + stepField.setSize(2,1); + Object[] obj = new Object[2]; + obj[0] = " Use Step-size of 0.0001N Angstroms "; + JLabel s = new JLabel("for Numerical differentiation with N="); //+stepField; + txt.add(s); + txt.add(stepField); + obj[1] = txt; + int ch= JOptionPane.showConfirmDialog(null,obj,"Option Step=N",JOptionPane.OK_OPTION); + if(ch==0) + { + if(!(InsertNode.nodeExists("Geom"))) + {InsertNode.insertNode("Key","Geom"); + } + //Delete Existing node and then add it + if((InsertNode.nodeExists("Step"))) + { + InsertNode.deleteNode("Step="); + } + InsertNode.insertNode("Geom","Step="+stepField.getText()); + + geoSt = new String(); + geoSt = stepField.getText(); + geomOpt.addElement("Step="+geoSt); + } + if(ch==1) // pressed no remove step + { + if((InsertNode.nodeExists("MaxStep"))) + { + //Delete Node if exists + InsertNode.deleteNode("Step="); + geomOpt.removeElement("Step="+geoSt); + } + + } + } + else + { + if((InsertNode.nodeExists("Step="))) + InsertNode.deleteNode("Step="); + geomOpt.removeElement("Step="+geoSt); + } + } + + if(e.getItem()==GeRead) + { + G03Listener.geomTabF++; + if(((JRadioButton)e.getItem()).isSelected()) + { + if(geomOptC==0) + { + geomOpt= new Vector(10); + geomOptC++; + } + + JTextField stepField; + JPanel txt; + txt = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + System.out.println("OOO"); + stepField = new JTextField(3); + stepField.setSize(2,1); + Object[] obj = new Object[3]; + + obj[0] = "Add harmonic contraints to a structure read in"; + obj[1] = " from the input stream with force constant"; + + JLabel s = new JLabel(" N/1000 Hartree/Bohr*Bohr with N ="); //+stepField; + c.insets=new Insets(0,0,0,0); + txt.add(s,c); + c.insets = new Insets(0,0,0,30); + txt.add(stepField,c); + obj[2] = txt; + int ch = JOptionPane.showConfirmDialog(null,obj,"ReadHarmonic=N",JOptionPane.OK_OPTION); + if(ch==0) + { + if(!(InsertNode.nodeExists("Geom"))) + {InsertNode.insertNode("Key","Geom"); + } + //Delete Existing node and then add it + if((InsertNode.nodeExists("Step"))) + { + InsertNode.deleteNode("Step="); + } + InsertNode.insertNode("Geom","ReadHarmonic="+stepField.getText()); + geoRe = new String(); + geoRe = stepField.getText(); + geomOpt.addElement("ReadHarmonic="+geoRe); + + + + + } + if(ch==1) // pressed no remove step + { + if((InsertNode.nodeExists("ReadH"))) + { + //Delete Node if exists + InsertNode.deleteNode("ReadH"); + geomOpt.removeElement("ReadHarmonic="+geoRe); + } + + } + } + else + { + if((InsertNode.nodeExists("ReadHarmonic="))) + InsertNode.deleteNode("ReadHarmonic="); + geomOpt.removeElement("ReadHarmonic="+geoRe); + } + } + + if(e.getItem()==GeChk) + { + G03Listener.geomTabF++; + if(((JRadioButton)e.getItem()).isSelected()) + { + if(geomOptC==0) + { + geomOpt= new Vector(10); + geomOptC++; + } + + JTextField stepField; + JPanel txt; + txt = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + stepField = new JTextField(3); + stepField.setSize(2,1); + Object[] obj = new Object[3]; + obj[0] = "Add harmonic contraints to a structure read in"; + obj[1] = " from the input stream with force constant"; + JLabel s = new JLabel(" N/1000 Hartree/Bohr*Bohr with N ="); //+stepField; + c.insets=new Insets(0,0,0,0); + txt.add(s,c); + c.insets = new Insets(0,0,0,30); + txt.add(stepField,c); + obj[2] = txt; + int ch = JOptionPane.showConfirmDialog(null,obj,"CheckHarmonic=N",JOptionPane.OK_OPTION); + + if(ch==0) + { + if(!(InsertNode.nodeExists("Geom"))) + {InsertNode.insertNode("Key","Geom"); + } + //Delete Existing node and then add it + if((InsertNode.nodeExists("Check"))) + { + InsertNode.deleteNode("Check="); + } + InsertNode.insertNode("Geom","CheckHarmonic="+stepField.getText()); + geoCh = new String(); + geoCh = stepField.getText(); + geomOpt.addElement("CheckHarmonic="+geoCh); + + + + + + + } + if(ch==1) // pressed no remove step + { + if((InsertNode.nodeExists("CheckHarmonic"))) + { + //Delete Node if exists + InsertNode.deleteNode("CheckHarmonic"); + geomOpt.removeElement("CheckHarmonic="+geoCh); + } + + } + } + else + { + if((InsertNode.nodeExists("CheckHarmonic"))) + InsertNode.deleteNode("CheckHarmonic"); + geomOpt.removeElement("CheckHarmonic="+geoCh); + } + } + + if(e.getItem()==GeIhar) + { + G03Listener.geomTabF++; + if(((JRadioButton)e.getItem()).isSelected()) + { + if(geomOptC==0) + { + geomOpt= new Vector(10); + geomOptC++; + } + + JTextField stepField; + JPanel txt; + txt = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + stepField = new JTextField(3); + stepField.setSize(2,1); + Object[] obj = new Object[3]; + obj[0] = "Add harmonic contraints to a structure read in"; + obj[1] = " from the input stream with force constant"; + JLabel s = new JLabel(" N/1000 Hartree/Bohr*Bohr with N ="); //+stepField; + c.insets=new Insets(0,0,0,0); + txt.add(s,c); + c.insets = new Insets(0,0,0,30); + txt.add(stepField,c); + obj[2] = txt; + int ch = JOptionPane.showConfirmDialog(null,obj,"InitialHarmonic=N",JOptionPane.OK_OPTION); + if(ch==0) + { + if(!(InsertNode.nodeExists("Geom"))) + {InsertNode.insertNode("Key","Geom"); + } + //Delete Existing node and then add it + if((InsertNode.nodeExists("Initial"))) + { + InsertNode.deleteNode("Initial"); + } + InsertNode.insertNode("Geom","InitialHarmonic="+stepField.getText()); + geoIh = new String(); + geoIh = stepField.getText(); + geomOpt.addElement("CheckHarmonic="+geoIh); + + } + if(ch==1) // pressed no remove step + { + if((InsertNode.nodeExists("InitialHarmonic"))) + { + //Delete Node if exists + InsertNode.deleteNode("InitialHarmonic"); + geomOpt.removeElement("CheckHarmonic="+geoIh); + } + + } + } + else + { + if((InsertNode.nodeExists("InitialHarmonic"))) + InsertNode.deleteNode("InitialHarmonic"); + geomOpt.removeElement("CheckHarmonic="+geoIh); + } + } + } + public void actionPerformed(ActionEvent e) + { + if(e.getSource()==exitButton) + { + geomOptFrame.dispose(); + } + if(e.getSource()==doneButton) + { + + System.out.println("The value of freq Flagv = "+geomC); + if(RouteClass.initCount==0) + { + System.out.println(RouteClass.initCount+" \tInside init"); + RouteClass.initBuffer(); + RouteClass.initCount++; + } + if(geomC==0) + { + System.out.println(geomC+" \t Inside geomC"); + geomFlag= RouteClass.keyIndex; + RouteClass.keyIndex++; + geomC++; + } + else + { + //System.out.println("Reinitialize the Geom Buffer"); + RouteClass.keywordBuffer[geomFlag]=new StringBuffer(); + } + //RouteClass.keywordBuffer[geomFlag].append("Geom"); + try { + if(geomOpt.size()>1) + { + RouteClass.keywordBuffer[geomFlag].append("Geom"); + RouteClass.keywordBuffer[geomFlag].append("=("); + for(int count=0;count0) + RouteClass.keywordBuffer[geomFlag].append("Geom"); + RouteClass.keywordBuffer[geomFlag].append("="+"("+geomOpt.get(0)+")"); + } + } catch (NullPointerException e1) { + // TODO Auto-generated catch block + //e1.printStackTrace(); + } + //geomFlag=RouteClass.keyIndex; + //RouteClass.keyIndex++; + RouteClass.writeRoute(); + geomOptFrame.dispose(); + } + if(e.getSource()==exitButton) + { + geomOptFrame.dispose(); + } + } + + + + + + } + + + + + + + + + + + + + + + diff --git a/src/main/java/g03input/iopKey.java b/src/main/java/g03input/iopKey.java new file mode 100644 index 0000000..42a411c --- /dev/null +++ b/src/main/java/g03input/iopKey.java @@ -0,0 +1,314 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ +/* + * Created on Sep 6, 2005 + * + * TODO To change the template for this generated file go to + * Window - Preferences - Java - Code Style - Code Templates + */ +package g03input; + +/** + * @author SandeepKumar Seethaapathy + * @author Shashank Jeedigunta + * + * TODO To change the template for this generated type comment go to + * Window - Preferences - Java - Code Style - Code Templates + */ + + +import javax.swing.*; +import javax.swing.event.TableModelEvent; +import javax.swing.event.TableModelListener; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableModel; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Vector; + +class iopKey implements ActionListener, TableModelListener +{ +public static JFrame iopFrame; +JTable table; +public static Vector columns; +public static Vector< Vector > rows; +DefaultTableModel tabModel; +JScrollPane scrollPane; +JLabel lblMessage; +JButton cmdAdd,cmdDelete,cmdSetValue,cmdGetValue; +JPanel mainPanel,buttonPanel; +public static String oV[],oP[],oN[]; +public static String iopOp; +public static int iopFlag; + public static void main(String[] args) + { +iopKey t=new iopKey(); + } + +iopKey() +{ + iopFlag++; + + + oV = new String[20]; + oP = new String[20]; + oN = new String[20]; + +rows=new Vector< Vector >(); +columns= new Vector(); +String[] columnNames = +{ +"Ov", +"Op", +"N" +}; +addColumns(columnNames); + +tabModel=new DefaultTableModel(); +tabModel.setDataVector(rows,columns); + +table = new JTable(tabModel); +scrollPane= new JScrollPane(table);//ScrollPane + +table.setRowSelectionAllowed(false); + +table.getModel().addTableModelListener(this); + +lblMessage=new JLabel(""); + + +buttonPanel=new JPanel(); +cmdAdd=new JButton("Add Row"); +cmdDelete=new JButton("Delete") ; +cmdSetValue=new JButton("Set Values"); +cmdGetValue=new JButton("Done"); + +buttonPanel.add(cmdAdd); +buttonPanel.add(cmdDelete); +buttonPanel.add(cmdSetValue); +buttonPanel.add(cmdGetValue); + +cmdAdd.addActionListener(this); +cmdDelete.addActionListener(this); +cmdSetValue.addActionListener(this); +cmdGetValue.addActionListener(this); + +mainPanel=new JPanel(); +iopFrame=new JFrame("Options for Iop"); +iopFrame.setSize(400,150); +//iopFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); +mainPanel.setLayout(new BorderLayout()); +mainPanel.add("Center",scrollPane); +mainPanel.add("South",buttonPanel); +mainPanel.setBackground(Color.white); +buttonPanel.setBackground(Color.white); +table.getParent().setBackground(Color.white); +iopFrame.getContentPane().add(mainPanel); +iopFrame.setVisible(true); + +} + public void addColumns(String[] colName)//Table Columns +{ +for(int i=0;i r=new Vector(); +r=createBlankElement(); +rows.addElement(r); +table.addNotify(); + +} + +public Vector createBlankElement() +{ +Vector t = new Vector(); +t.addElement(" "); +t.addElement(" "); +t.addElement(" "); +return t; +} + + void deleteRow(int index) + { + if(index!=-1)//At least one Row in Table + { + rows.removeElementAt(index); + table.addNotify(); + } + + }//Delete Row + + public void tableChanged(TableModelEvent source) { + String msg=""; + TableModel tabMod = (TableModel)source.getSource(); + switch (source.getType()) + { + case TableModelEvent.UPDATE: + /* msg="Table Value Updated for cell "+table.getSelectedRow()+","+table.getSelectedColumn()+"\nWhich is "+table.getValueAt(table.getSelectedRow(),table.getSelectedColumn()).toString(); + JOptionPane.showMessageDialog(null,msg,"Table Example",JOptionPane.INFORMATION_MESSAGE);*/ + break; + + } + + }//Table Changed Method + +public void selectCell(int row,int col) + { + if(row!=-1 && col !=-1) + { + table.setRowSelectionInterval(row,row); + table.setColumnSelectionInterval(col,col); + } + } + +public void actionPerformed(ActionEvent source) + { + if (source.getSource()==(JButton) cmdAdd) + { + addRow(); + } + if (source.getSource()==(JButton) cmdDelete) + { + deleteRow(table.getSelectedRow()); + } + if (source.getSource()==(JButton) cmdSetValue) + { + for(int i=0;i0) + { + selectCell(i,j); + table.setValueAt(CName,i,j); + } + } + if(j==1){ + String CName=JOptionPane.showInputDialog(null,"Enter Value for oP["+i+"]",""+JOptionPane.INFORMATION_MESSAGE); + if(!CName.trim().equals("") && table.getRowCount()>0) + { + selectCell(i,j); + table.setValueAt(CName,i,j); + } + + } + if(j==2){ + String CName=JOptionPane.showInputDialog(null,"Enter Value for oN["+i+"]",""+JOptionPane.INFORMATION_MESSAGE); + if(!CName.trim().equals("") && table.getRowCount()>0) + { + selectCell(i,j); + table.setValueAt(CName,i,j); + } + } + + } + } + else + { + continue; + } + } + + } + + if (source.getSource()==(JButton) cmdGetValue) + { + iopOp ="Iop"; + if(table.getRowCount()>0) + { + for(int u = 0;u Enter the PG=group value here "); + G03MenuTree.keyoptArea.setText(G03MenuTree.keyoptArea.getText()+ otherKeyToolTip.symmpgTip); + //Insert into the Tree + if(!(InsertNode.nodeExists("Symmetry"))) + InsertNode.insertNode("Key", "Symmetry"); + } + + else{ + //Disable the textfield + otherKeyTable.symmetryPGText.setText(""); + otherKeyTable.symmetryPGText.setEnabled(false); + //Insert into the Tree + if((InsertNode.nodeExists("Symmetry"))) + InsertNode.deleteNode("Symmetry"); + } + return true; + } + + + else if(ie.getSource()== otherKeyTable.symmetryOptions[10]) + { + if(otherKeyTable.symmetryOptions[10].isSelected()){ + + //Enable the Combo Box + otherKeyTable.symmetryAxisCombo.setEnabled(true); + otherKeyTable.symmetryAxisCombo.setToolTipText(" Choose the Axis value here "); + G03MenuTree.keyoptArea.setText(G03MenuTree.keyoptArea.getText()+ otherKeyToolTip.symmaxisTip); + //Insert into the Tree + if(!(InsertNode.nodeExists("Symmetry"))) + InsertNode.insertNode("Key", "Symmetry"); + + return true; + } + + else + { + otherKeyTable.symmetryAxisCombo.setEnabled(false); + if((InsertNode.nodeExists("Symmetry"))) + InsertNode.deleteNode("Symmetry"); + return false; + } + } + + + else // Any Item other than ComboBox or TextField + { + for(int j=0;j<9;j++) + if(ie.getSource()== otherKeyTable.symmetryOptions[j]) + { + if(otherKeyTable.symmetryOptions[j].isSelected()) + { + // any other symmetry + if(!(InsertNode.nodeExists("Symmetry"))) + InsertNode.insertNode("Key", "Symmetry"); + //Show that particular Tooltip + G03MenuTree.keyoptArea.setText(G03MenuTree.keyoptArea.getText()+ otherKeyToolTip.symmetryOptionTips[j]); + return true; + } + } + + if(ie.getSource()== otherKeyTable.symmetryOptions[11]){ + // any other symmetry + if(otherKeyTable.symmetryOptions[11].isSelected()) + { + if(!(InsertNode.nodeExists("Symmetry"))) + InsertNode.insertNode("Key", "Symmetry"); + //Show that particular Tooltip + G03MenuTree.keyoptArea.setText(G03MenuTree.keyoptArea.getText()+ otherKeyToolTip.symmonTip); + return true; + } + } + + } + return false; + } + + boolean isPunchItemChanged(ItemEvent ie){ + System.out.println("In Punch ItemListener"); + for(int j=0;j<9;j++) + if(ie.getSource()== otherKeyTable.punchOptions[j]) + { + // any other symmetry + if(!(InsertNode.nodeExists("Punch"))) + InsertNode.insertNode("Key", "Punch"); + //Show that particular Tooltip + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea, otherKeyToolTip.punchOptionTips[j]); + return true; + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (BadLocationException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + + } + + return false; + } + + boolean isPropItemChanged(ItemEvent ie){ + System.out.println("In Prop ItemListener"); + for(int j=0;j<10;j++) + if(ie.getSource()== otherKeyTable.propOptions[j]) + { + // any other symmetry + if(!(InsertNode.nodeExists("Prop"))) + InsertNode.insertNode("Key", "Prop"); + //Show that particular Tooltip + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea, otherKeyToolTip.propOptionTips[j]); + return true; + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (BadLocationException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + + } + + return false; + } + + boolean isOutputItemChanged(ItemEvent ie) + { + + if(ie.getSource().toString().equals(otherKeyTable.outputOptions[0].toString())) + { + //WFN=() + if(otherKeyTable.outputOptions[0].isSelected()) + { + //Enable the TextField + otherKeyTable.outputWFNText.setEnabled(true); + otherKeyTable.outputWFNText.setToolTipText(" Enter the filename.wfn"); + + //Insert into the Tree + if(!(InsertNode.nodeExists("Output"))) + InsertNode.insertNode("Key", "Output"); + + return true; + } + + else{ + //Disable the textfield + otherKeyTable.outputWFNText.setText(""); + otherKeyTable.outputWFNText.setEnabled(false); + + + } + } + + + + + for(int j=1;j<3;j++) + if(ie.getSource()== otherKeyTable.outputOptions[j]) + { + if(otherKeyTable.outputOptions[j].isSelected()){ + // any other option + if(!(InsertNode.nodeExists("Output"))) + InsertNode.insertNode("Key", "Output"); + + return true; + } + } + + + return false; + } + + + + boolean isSparseItemChanged(ItemEvent ie) + { + + if(ie.getSource().toString().equals(otherKeyTable.sparseOptions[3].toString())) + { + //N=() + if(otherKeyTable.sparseOptions[3].isSelected()) + { + //Enable the TextField + otherKeyTable.sparseNText.setEnabled(true); + otherKeyTable.sparseNText.setToolTipText(" Enter the value of N "); + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea, otherKeyToolTip.sparseOptionTips[3]); + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (BadLocationException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + //Insert into the Tree + if(!(InsertNode.nodeExists("Sparse"))) + InsertNode.insertNode("Key", "Sparse"); + + return true; + } + + else{ + //Disable the textfield + otherKeyTable.sparseNText.setText(""); + otherKeyTable.sparseNText.setEnabled(false); + + + } + } + + + + + for(int j=0;j<3;j++) + if(ie.getSource()== otherKeyTable.sparseOptions[j]) + { + if(otherKeyTable.sparseOptions[j].isSelected()){ + // any other symmetry + if(!(InsertNode.nodeExists("Sparse"))) + InsertNode.insertNode("Key", "Sparse"); + //Show that particular Tooltip + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea, otherKeyToolTip.sparseOptionTips[j]); + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (BadLocationException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + return true; + } + } + + + return false; + } + + + + public void actionPerformed(ActionEvent e) + { + if(e.getSource() == otherKeyTable.doneButton) + { + RouteClass.writeRoute(); + otherKeyTable.otherKeyFrame.hide(); + } + + //code for a Clear Button + + if(e.getSource() == otherKeyTable.clearButton) + { + for(int h=0;h< otherKeyTable.okVector.size();h++) + { + if(((JRadioButton)(otherKeyTable.okVector.get(h))).isSelected()) + { + ((JRadioButton)(otherKeyTable.okVector.get(h))).setSelected(false); + if(InsertNode.nodeExists((((JRadioButton) (otherKeyTable.okVector.get(h))).getActionCommand().toString()))){ + InsertNode.deleteNode((((JRadioButton) (otherKeyTable.okVector.get(h))).getActionCommand().toString())); + } + } + + } + otherKeyTable.otherKeys.removeAllElements(); + RouteClass.writeRoute(); + otherKeyTable.otherKeyFrame.dispose(); + /* + + if(otherKeyTable.okArc.isSelected()) + { + + if(InsertNode.nodeExists("Archive")) + { + InsertNode.deleteNode("Archive"); + } + otherKeyTable.okArc.setSelected(false); + otherKeyTable.otherKeyFrame.dispose(); + otherKeyTable.otherKeyFrame.getContentPane().add(otherKeyTable.scroll,BorderLayout.CENTER); + otherKeyTable.otherKeyFrame.getContentPane().add(otherKeyTable.donePanel,BorderLayout.SOUTH); + } + if(otherKeyTable.okCha.isSelected()) + { + otherKeyTable.okCha.setSelected(false); + if(InsertNode.nodeExists("Charge")) + { + InsertNode.deleteNode("Charge"); + } + }*/ + /* otherKeyTable.otherKeys.removeAllElements(); + RouteClass.writeRoute(); + /*{okArc,okCha,okChk,okCom,okCon}, + {okCou,okCph,okDen,okExt,okExtB}, + {okExtD,okFie,okFmm,okGfi,okGfp}, + {okInt,okIop,okNam,okOut,okPre}, + {okPro,okPse,okPun,okSca,okSpa}, + {okSym,okTem,okTesM,okTra,okTrans}, + {okUni,okNmr,null,null,null},}, + } + */ + } + //counter + if(e.getSource()== otherKeyTable.counterOK) + { + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + otherKeyTable.otherKeys.addElement("CounterPoise="+ otherKeyListener.counter_Opt); + if(!(InsertNode.nodeExists("CounterPoise"))) + InsertNode.insertNode("Key", "CounterPoise"); + otherKeyTable.counterFrame.dispose(); + } + + + + + //To be integrated + + if(e.getSource() == otherKeyTable.exitButton) + { + otherKeyTable.otherKeyFrame.dispose(); + } + if(e.getSource()== otherKeyTable.chargeOK) + { + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + otherKeyTable.otherKeys.addElement("Charge="+ otherKeyListener.charge_Opt); + if(!(InsertNode.nodeExists("Charge"))) + InsertNode.insertNode("Key", "Charge"); + otherKeyTable.chargeFrame.dispose(); + } + + + //code to get constant + if(e.getSource()== otherKeyTable.constantOK) + { + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + otherKeyTable.otherKeys.addElement("Constants="+ otherKeyListener.con_Opt); + if(!(InsertNode.nodeExists("Constants"))) + InsertNode.insertNode("Key", "Constants"); + otherKeyTable.constantsFrame.dispose(); + } + + + + + if(e.getSource()== otherKeyTable.cphfOK) + { + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + if(cphfOpt.equals("Grid")) + { + cphfOpt = "(Grid="+ otherKeyTable.grid.getText().toString()+")"; + } + if(cphfOpt.equals("MaxInv")) + { + cphfOpt = "(MaxInv="+ otherKeyTable.max.getText().toString()+")"; + } + if(cphfOpt.equals("Conver")) + { + cphfOpt = "(Conver="+ otherKeyTable.conver.getText().toString()+")"; + } + otherKeyTable.otherKeys.addElement("CPHF="+ otherKeyListener.cphfOpt); + if(!(InsertNode.nodeExists("CPHF"))) + InsertNode.insertNode("Key", "CPHF"); + otherKeyTable.cphfFrame.dispose(); + } + + //nmr + if(e.getSource()== otherKeyTable.nmrOk) + { + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + otherKeyTable.otherKeys.addElement("NMR="+ otherKeyListener.nmrOpt); + if(!(InsertNode.nodeExists("NMR"))) + InsertNode.insertNode("Key", "NMR"); + otherKeyTable.nmrFrame.dispose(); + } + + + + if(e.getSource()== otherKeyTable.densityOK) + { + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + if(densityOpt.equals("InvToler")) + { + densityOpt = "(MaxInv="+ otherKeyTable.invToler.getText().toString()+")"; + } + if(densityOpt.equals("Convergence")) + { + densityOpt = "(Convergence="+ otherKeyTable.converDen.getText().toString()+")"; + } + otherKeyTable.otherKeys.addElement("DensityFit="+ otherKeyListener.densityOpt); + if(!(InsertNode.nodeExists("DensityFit"))) + InsertNode.insertNode("Key", "DensityFit"); + otherKeyTable.densityFrame.dispose(); + } + + + if(e.getSource()== otherKeyTable.fmmOK) + { + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + if(fmmOpt.equals("Lmax")) + { + fmmOpt = "(Lmax="+ otherKeyTable.lmax.getText().toString()+")"; + } + if(fmmOpt.equals("Levels")) + { + fmmOpt = "(Levels="+ otherKeyTable.level.getText().toString()+")"; + } + if(fmmOpt.equals("Tolerance")) + { + fmmOpt = "(Tolerance="+ otherKeyTable.tol.getText().toString()+")"; + } + if(fmmOpt.equals("BoxLen")) + { + fmmOpt = "(BoxLen="+ otherKeyTable.box.getText().toString()+")"; + } + otherKeyTable.otherKeys.addElement("FMM="+ otherKeyListener.fmmOpt); + if(!(InsertNode.nodeExists("FMM"))) + InsertNode.insertNode("Key", "FMM"); + otherKeyTable.fmmFrame.dispose(); + } + + + + //To be integrated + + // PROP + + if(e.getSource() == otherKeyTable.propDone){ + + for(int i=0;i<4;i++) + { + //Check the CheckBoxes that is selected in the ButtonGroup + //Add it to the RouteSection. + if(otherKeyTable.propOptions[i].isSelected()) + { + + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + + + prop_Opt1= otherKeyTable.propOptions[i].getText().toString(); + + } + } + + for(int i=4;i<10;i++) + { + //Check the CheckBoxes that is selected in the ButtonGroup + //Add it to the RouteSection. + if(otherKeyTable.propOptions[i].isSelected()) + { + + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + + + prop_Opt2= otherKeyTable.propOptions[i].getText().toString(); + + } + } + + + if(prop_Opt2.length()==0 && prop_Opt1.length()!=0) //Input Source is not selected + { + otherKeyTable.otherKeys.addElement("Prop="+prop_Opt1); + prop_Opt=prop_Opt1; + System.out.println("checking3"+prop_Opt); + } + else if(prop_Opt1.length()==0 && prop_Opt2.length()!=0) //Property Selection is not selected + { + otherKeyTable.otherKeys.addElement("Prop="+prop_Opt2); + prop_Opt=prop_Opt2; + System.out.println("checking2"+prop_Opt); + } + + else if (prop_Opt1.length()!=0 && prop_Opt2.length()!=0) + { + // If both of them are selected + otherKeyTable.otherKeys.addElement("Prop=("+prop_Opt1+","+prop_Opt2+")"); + prop_Opt="("+prop_Opt1+","+prop_Opt2+")"; + System.out.println("checking"+prop_Opt); + + } + + else + { // None selected + + otherKeyTable.okPro.setSelected(false); + + } + otherKeyTable.propFrame.dispose(); + } + + + + + + + //PUNCH + + if(e.getSource() == otherKeyTable.punchDone){ + for(int i=0;i< otherKeyTable.punchOptions.length;i++) + { + //Check the CheckBoxes that is selected in the ButtonGroup + //Add it to the RouteSection. + if(otherKeyTable.punchOptions[i].isSelected()) + { + + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + + + punch_Opt= otherKeyTable.punchoptions[i]; + + + otherKeyTable.otherKeys.addElement("Punch= "+punch_Opt); + otherKeyTable.punchFrame.dispose(); + + } + + + + } + + + } + + + // PSEUDO + + if(e.getSource() == otherKeyTable.pseudoDone){ + System.out.println("Pseudo... before for..."); + for(int i=0;i< otherKeyTable.pseudoOptions.length;i++) + { + //Check the CheckBoxes that is selected in the ButtonGroup + //Add it to the RouteSection. + if(otherKeyTable.pseudoOptions[i].isSelected()) + { + + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + + + pseudo_Opt= otherKeyTable.pseudooptions[i]; + + + otherKeyTable.otherKeys.addElement("Pseudo="+pseudo_Opt); + otherKeyTable.pseudoFrame.dispose(); + System.out.println("Pseudo... Frame Disposed..."); + } + + + + } + + + } + + + + + //Sparse + + if(e.getSource() == otherKeyTable.sparseDone){ + for(int i=0;i< otherKeyTable.sparseOptions.length;i++) + { + //Check the RadioButton that is selected in the ButtonGroup + //Add it to the RouteSection. + if(otherKeyTable.sparseOptions[i].isSelected()) + { + + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + + if(i==3) // Option N=... + { + sparse_Opt="(N="+ otherKeyTable.sparseNText.getText()+")"; + } + else{ + sparse_Opt= otherKeyTable.sparseoptions[i]; + } + + otherKeyTable.otherKeys.addElement("Sparse="+sparse_Opt); + otherKeyTable.sparseFrame.dispose(); + + if(!(InsertNode.nodeExists("Sparse"))) + InsertNode.insertNode("Key", "Sparse"); + + + } + + + + } + + + } + + //Output + + if(e.getSource() == otherKeyTable.outputDone){ + for(int i=0;i< otherKeyTable.outputOptions.length;i++) + { + //Check the RadioButton that is selected in the ButtonGroup + //Add it to the RouteSection. + if(otherKeyTable.outputOptions[i].isSelected()) + { + + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + + if(i==0) // Option N=... + { + output_Opt="(WFN="+ otherKeyTable.outputWFNText.getText()+")"; + } + else{ + output_Opt= otherKeyTable.outputoptions[i]; + } + + otherKeyTable.otherKeys.addElement("Output= "+output_Opt); + otherKeyTable.outputFrame.dispose(); + + if(!(InsertNode.nodeExists("Output"))) + InsertNode.insertNode("Key", "Output"); + + + } + + + + } + + + } + + + + //Symmetry + if(e.getSource() == otherKeyTable.symmetryDone){ + for(int i=0;i< otherKeyTable.symmetryOptions.length;i++) + { + //Check the RadioButton that is selected in the ButtonGroup + //Add it to the RouteSection. + if(otherKeyTable.symmetryOptions[i].isSelected()) + { + + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + + if(i==9) // Option PG=group + { + symm_Opt="(PG="+ otherKeyTable.symmetryPGText.getText()+")"; + } + else if(i==10) //Axis == X,Y,Z + { + int new_index= otherKeyTable.symmetryAxisCombo.getSelectedIndex(); + char axis='X'; + if(new_index==0)axis='X'; + else if (new_index==1)axis='Y'; + else if (new_index==2)axis='Z'; + symm_Opt="(Axis="+axis+")"; + } + else{ + symm_Opt= otherKeyTable.options[i]; + } + + otherKeyTable.otherKeys.addElement("Symmetry="+symm_Opt); + otherKeyTable.symmetryFrame.dispose(); + + if(!(InsertNode.nodeExists("Symmetry"))) + InsertNode.insertNode("Key", "Symmetry"); + + } + + + + } + + + } + + + + + + + + + + + } + +} diff --git a/src/main/java/g03input/otherKeyTable.java b/src/main/java/g03input/otherKeyTable.java new file mode 100644 index 0000000..05a4466 --- /dev/null +++ b/src/main/java/g03input/otherKeyTable.java @@ -0,0 +1,1986 @@ +/* + + Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + + Developed by: + + Center for Computational Sciences, University of Kentucky + + http://www.ccs.uky.edu/ + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal with the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or + sell copies of the Software, and to permit persons to whom + the Software is furnished to do so, subject to the following + conditions: + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. + 3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. + */ + + +/** + * + * @author Michael Sheetz + * @author Shashank Jeedigunta @author Sandeep Kumar Seethaapathy + * + */ + + + + +package g03input; + +import javax.swing.*; +import javax.swing.event.TableModelEvent; +import javax.swing.table.DefaultTableModel; +import javax.swing.text.BadLocationException; +import java.awt.*; +import java.awt.event.*; +import java.io.IOException; +import java.util.Vector; + + +public class otherKeyTable extends JFrame implements ItemListener,ActionListener +{ + Color bgColor= new Color(236,233,216); + Color foreColor =new Color(0,78,152); + public static JPanel donePanel; + + JTextField tempText,pressureText,scaleText; //Temperature, Pressure, Scale + + /*Other Keywords --> Symmetry Options */ + public static JScrollPane scroll; + public static DefaultTableModel dm; + public static JTable table; + public static JFrame symmetryFrame; + public static JTextField symmetryPGText; + public static JComboBox symmetryAxisCombo; + static JRadioButton[] symmetryOptions; //Options for Symmetry + static ButtonGroup symmetryGroup; + public static JButton symmetryDone; + public static String options[] = { "Int", "NoInt", "Grad","NoGrad", "SCF","NoSCF", + "Loose","Tight","Follow","PG = ","Axis","On"}; + + + /*Other Keywords --> SPARSE Options */ + public static JFrame sparseFrame; + public static JTextField sparseNText; + //static JRadioButton[] sparseOptions; //Options for Symmetry + static JCheckBox[] sparseOptions=new JCheckBox[4]; + static ButtonGroup sparseGroup; + public static JButton sparseDone; + public static String sparseoptions[] = { "Loose", "Medium", "Tight","N"}; + + + /*Other Keywords --> PUNCH Options */ + public static JFrame punchFrame; + static JCheckBox[] punchOptions=new JCheckBox[9]; + static ButtonGroup punchGroup; + public static JButton punchDone; + public static String punchoptions[] = { "Archive", "Title", "Coord","Derivatives","MO","NaturalOrbitals","HondoInput","GAMESSInput","All"}; + + /*Other Keywords --> PSEUDO Options */ + public static JFrame pseudoFrame; + public static String pseudooptions[] = { "Read", "Old", "CHF","SHC","LANL1","LANL2"}; + static JCheckBox[] pseudoOptions=new JCheckBox[6]; + static ButtonGroup pseudoGroup; + public static JButton pseudoDone; + + + /*Other Keywords --> PROP Options */ + public static JFrame propFrame; + public static String propoptions[] = { "EFG", "Potential", "Field","EPR","Read","Opt","FitCharge","Dipole","Grid","(Read,Opt)"}; + static JCheckBox[] propOptions=new JCheckBox[10]; + static ButtonGroup propertyGroup; + static ButtonGroup propInputGroup; + public static JButton propDone; + + /*Other Keywords --> Output Options */ + public static JFrame outputFrame; + public static JTextField outputWFNText; + static JCheckBox[] outputOptions=new JCheckBox[3]; + static ButtonGroup outputGroup; + public static JButton outputDone; + public static String outputoptions[] = {"WFN=", "Pickett", "ReadAtoms"}; + + //Other Keywords-Pressure options + public static String pressureOpt,scale_Opt,temp_Opt; + + + public static JButton doneButton,clearButton,exitButton; + + public static JFrame otherKeyFrame; + public static JFrame chargeFrame,constantsFrame,counterFrame,cphfFrame,densityFrame,fmmFrame,nmrFrame; + public static JRadioButton angOpt,bohrOpt,soOpt,checkOpt,con98Opt,con86Opt,con79Opt,newOpt,oldOpt; + public static JButton chargeOK,constantOK,counterOK; + + + + //to be integrated + //public static JTable iopTable; + public static JRadioButton gridOpt,rdfOpt,eqsOpt,simulOpt,sepOpt,xyOpt,zveOpt,aoOpt,moOpt,maxOpt,conOpt,canOpt,modOpt,iterOpt,convOpt,invOpt; + public static JRadioButton lmaxOpt,levelOpt,tolOpt,boxOpt,allnearOpt; + public static JTextField grid,max,conver,invToler,converDen,lmax,level,tol,box; + public static JButton cphfOK,densityOK,fmmOK,nmrOk; + + public static JRadioButton spinOpt,csgtOpt,giaoOpt,igaimOpt,singleOpt,allOpt,printOpt; + + + + public static Vector otherKeys; //should be accessible by the route section + static int otherFlag; + public static String chargeOpt = ""; //To be accessible to otherKeyListener + //Used to store the option of the Keyword "Charge" + // +//Code for Clearing + + + public static Vector okVector; + + + + public static JRadioButton okArc=new JRadioButton("Archive"); + public static JRadioButton okCha = new JRadioButton("Charge"); + public static JRadioButton okChk = new JRadioButton("ChkBasis"); + public static JRadioButton okCom= new JRadioButton("Complex"); + public static JRadioButton okCon =new JRadioButton("Constants"); + public static JRadioButton okCou = new JRadioButton("CounterPoise"); + public static JRadioButton okCph = new JRadioButton("CPHF"); + public static JRadioButton okDen = new JRadioButton("DensityFit"); + public static JRadioButton okExt = new JRadioButton("External"); + public static JRadioButton okExtB = new JRadioButton("ExtraBasis"); + public static JRadioButton okExtD = new JRadioButton("ExtraDensityBasis"); + public static JRadioButton okFie= new JRadioButton("Field"); + public static JRadioButton okFmm = new JRadioButton("FMM"); + public static JRadioButton okGfi = new JRadioButton("GFInput"); + public static JRadioButton okGfp = new JRadioButton("GFPrint"); + public static JRadioButton okInt = new JRadioButton("Integral"); + public static JRadioButton okIop =new JRadioButton("IOp"); + public static JRadioButton okNam = new JRadioButton("Name"); + public static JRadioButton okOut = new JRadioButton("Output"); + public static JRadioButton okPre = new JRadioButton("Pressure"); + public static JRadioButton okPro = new JRadioButton("Prop"); + public static JRadioButton okPse= new JRadioButton("Pseudo"); + public static JRadioButton okPun = new JRadioButton("Punch"); + public static JRadioButton okSca = new JRadioButton("Scale"); + public static JRadioButton okSpa = new JRadioButton("Sparse"); + public static JRadioButton okSym = new JRadioButton("Symmetry"); + public static JRadioButton okTem =new JRadioButton("Temperature"); + public static JRadioButton okTesM= new JRadioButton("TestMO"); + public static JRadioButton okTra = new JRadioButton("TrackIO"); + public static JRadioButton okTrans = new JRadioButton("Transformation"); + public static JRadioButton okUni = new JRadioButton("Units"); + public static JRadioButton okNmr = new JRadioButton("NMR"); + + public static Vector otherKey; //popOpt + public static int otherKeyListen; // Counts the no. of times table has been initialized + + public otherKeyTable(){ + + otherKeyFrame = new JFrame("Additional Keywords"); + if(otherKeyListen==0) + { + okVector = new Vector(40); + okArc.addItemListener(this); + okArc.setBackground(Color.WHITE); + okVector.addElement(okArc); + + okCha.addItemListener(this); + okCha.setBackground(Color.WHITE); + okVector.addElement(okCha); + + okChk.addItemListener(this); + okChk.setBackground(Color.WHITE); + okVector.addElement(okChk); + + okCom.addItemListener(this); + okCom.setBackground(Color.WHITE); + okVector.addElement(okCom); + + okCon.setBackground(Color.WHITE); + okCon.addItemListener(this); + okVector.addElement(okCon); + + okCou.setBackground(Color.WHITE); + okCou.addItemListener(this); + okVector.addElement(okCou); + + okCph.setBackground(Color.WHITE); + okCph.addItemListener(this); + okVector.addElement(okCph); + + + okDen.setBackground(Color.WHITE); + //updated + okDen.addItemListener(this); + okVector.addElement(okDen); + + + okExt.addItemListener(this); + okExt.setBackground(Color.WHITE); + okVector.addElement(okExt); + + okExtB.addItemListener(this); + okExtB.setBackground(Color.WHITE); + okVector.addElement(okExtB); + + + okExtD.addItemListener(this); + okExtD.setBackground(Color.WHITE); + okVector.addElement(okExtD); + + + okFie.addItemListener(this); + okFie.setBackground(Color.WHITE); + okVector.addElement(okFie); + okFie.setEnabled(false); + + okFmm.addItemListener(this); + okFmm.setBackground(Color.WHITE); + okVector.addElement(okFmm); + + + okGfi.addItemListener(this); + okGfi.setBackground(Color.WHITE); + okVector.addElement(okGfi); + + okGfp.addItemListener(this); + okGfp.setBackground(Color.WHITE); + okVector.addElement(okGfp); + + + okInt.addItemListener(this); + okInt.setBackground(Color.WHITE); + okVector.addElement(okInt); + okInt.setEnabled(false); + okIop.addItemListener(this); + okIop.setBackground(Color.WHITE); + okVector.addElement(okIop); + + okNam.addItemListener(this); + okNam.setBackground(Color.WHITE); + okVector.addElement(okNam); + + okOut.addItemListener(this); + okOut.setBackground(Color.WHITE); + okVector.addElement(okOut); + + + okPre.addItemListener(this); + okPre.setBackground(Color.WHITE); + okVector.addElement(okPre); + + + okPro.addItemListener(this); + okPro.setBackground(Color.WHITE); + okVector.addElement(okPro); + + okPse.addItemListener(this); + okPse.setBackground(Color.WHITE); + okVector.addElement(okPse); + + + okPun.addItemListener(this); + okPun.setBackground(Color.WHITE); + okVector.addElement(okPun); + okSca.addItemListener(this); + okSca.setBackground(Color.WHITE); + okVector.addElement(okSca); + okSpa.addItemListener(this); + okSpa.setBackground(Color.WHITE); + okVector.addElement(okSpa); + okSym.addItemListener(this); + okSym.setBackground(Color.WHITE); + okVector.addElement(okSym); + okTem.addItemListener(this); + okTem.setBackground(Color.WHITE); + okVector.addElement(okTem); + okTesM.addItemListener(this); + okTesM.setBackground(Color.WHITE); + okVector.addElement(okTesM); + okTesM.setEnabled(false); + okTra.addItemListener(this); + + okTra.setBackground(Color.WHITE); + okVector.addElement(okTra); + okTrans.addItemListener(this); + okTra.setEnabled(false); + okTrans.setBackground(Color.WHITE); + okVector.addElement(okTrans); + okUni.addItemListener(this); + okTrans.setEnabled(false); + okUni.setBackground(Color.WHITE); + okVector.addElement(okUni); + okUni.setEnabled(false); + // updated + okNmr.addItemListener(this); + okNmr.setBackground(Color.WHITE); + okVector.addElement(okNmr); + otherKeyListen++; + } + + otherKeyFrame.setBackground(bgColor); + otherKeyFrame.setForeground(foreColor); + dm = new DefaultTableModel(); + dm.setDataVector( + new Object[][]{ + {okArc,okCha,okChk,okCom,okCon}, + {okCou,okCph,okDen,okExt,okExtB}, + {okExtD,okFie,okFmm,okGfi,okGfp}, + {okInt,okIop,okNam,okOut,okPre}, + {okPro,okPse,okPun,okSca,okSpa}, + {okSym,okTem,okTesM,okTra,okTrans}, + {okUni,okNmr,null,null,null},}, + new Object[]{"1","2","3","4","5"}); + + table = new JTable(dm) { + public void tableChanged(TableModelEvent e) { + super.tableChanged(e); + repaint(); + } + }; + + table.getColumn("1").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("1").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + table.getColumn("2").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("2").setCellEditor(new RadioButtonEditor(new JCheckBox())); + table.getColumn("3").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("3").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + table.getColumn("4").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("4").setCellEditor(new RadioButtonEditor(new JCheckBox())); + table.getColumn("5").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("5").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + + + + doneButton = new JButton("Done"); + doneButton.addActionListener(new otherKeyListener()); + clearButton = new JButton("Clear"); + clearButton.addActionListener(new otherKeyListener()); + exitButton = new JButton("Exit"); + exitButton.addActionListener(new otherKeyListener()); + + donePanel = new JPanel(); + donePanel.add(doneButton); + donePanel.add(clearButton); + donePanel.add(exitButton); + donePanel.setBackground(bgColor); + donePanel.setForeground(foreColor); + table.getTableHeader().setReorderingAllowed(false); + otherKeyFrame.getContentPane().setLayout(new BorderLayout()); + scroll= new JScrollPane(table); + otherKeyFrame.getContentPane().add( scroll,BorderLayout.CENTER); + otherKeyFrame.getContentPane().add(donePanel,BorderLayout.SOUTH); + otherKeyFrame.setSize( 600,200); + otherKeyFrame.setLocation(200,75); + otherKeyFrame.setVisible(true); + } + public void actionPerformed(ActionEvent ae) + { + if(ae.getSource()==exitButton) + { + otherKeyFrame.dispose(); + } + + if(ae.getSource()==doneButton) + { + + + + } + + } + + + public void itemStateChanged(ItemEvent e) + { + + if( + (e.getItem()==okArc)|| + (e.getItem()==okCha)|| + (e.getItem()==okChk)|| + (e.getItem()==okCom)|| + (e.getItem()==okCon)|| + (e.getItem()==okCou)|| + (e.getItem()==okCph)|| + (e.getItem()==okDen)|| + (e.getItem()==okExt)|| + (e.getItem()==okExtB)|| + (e.getItem()==okExtD)|| + (e.getItem()==okFie)|| + (e.getItem()==okFmm)|| + (e.getItem()==okGfi)|| + (e.getItem()==okGfp)|| + (e.getItem()==okInt)|| + (e.getItem()==okIop)|| + (e.getItem()==okNam)|| + (e.getItem()==okOut)|| + (e.getItem()==okPre)|| + (e.getItem()==okPro)|| + (e.getItem()==okPse)|| + (e.getItem()==okPun)|| + (e.getItem()==okSca)|| + (e.getItem()==okSpa)|| + (e.getItem()==okSym)|| + (e.getItem()==okTem)|| + (e.getItem()==okTesM)|| + (e.getItem()==okTra)|| + (e.getItem()==okTrans)|| + (e.getItem()==okUni)|| + (e.getItem()==okNmr) + ) + + { + + if(((JRadioButton)e.getItem()).isSelected()) + { + if(RadioButtonEditor.button.getActionCommand()=="Archive" && (okArc.isSelected()==true)) + { + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + otherKeyTable.otherKeys.addElement("Archive"); + if(!(InsertNode.nodeExists("Archive"))) + InsertNode.insertNode("Key","Archive"); + + } + + if(RadioButtonEditor.button.getActionCommand()=="Charge" && (okCha.isSelected()==true)) + { + if(okCha.isSelected()==true){ + // Charge is selected popup a window with the list of options + + JFrame.setDefaultLookAndFeelDecorated(true); + chargeFrame = new JFrame("Options for Charge"); + JPanel panel1 = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + + JLabel optionLabel=new JLabel("Select an option"); + angOpt = new JRadioButton("Angstroms"); + bohrOpt = new JRadioButton("Bohrs"); + soOpt = new JRadioButton("StandardOrientation"); + soOpt.addItemListener(new otherKeyListener()); + checkOpt = new JRadioButton("Check"); + + chargeOK = new JButton("OK"); + ButtonGroup chargeOpt=new ButtonGroup(); + + chargeOpt.add(angOpt); + chargeOpt.add(bohrOpt); + chargeOpt.add(soOpt); + chargeOpt.add(checkOpt); + + angOpt.setSelected(true); + + angOpt.addItemListener(new otherKeyListener()); + bohrOpt.addItemListener(new otherKeyListener()); + checkOpt.addItemListener(new otherKeyListener()); + + chargeOK.addActionListener(new otherKeyListener()); + c.gridy=0; + c.gridx=0; + c.weightx=0.5; + c.insets= new Insets(10,-20,10,90); + panel1.add(optionLabel,c); + + c.gridx=0; + c.gridy=1; + c.weightx=0.5; + // c.weighty=0.15; + c.insets= new Insets(0,-90,10,90); + panel1.add(angOpt,c); + + + c.gridy=2; + c.gridx=0; + panel1.add(bohrOpt,c); + c.gridy=3; + c.gridx=0; + panel1.add(soOpt,c); + c.gridy=4; + c.gridx=0; + panel1.add(checkOpt,c); + c.gridy=5; + c.gridx=0; + c.insets = new Insets(0,90,10,90); + panel1.add(chargeOK,c); + + chargeFrame.getContentPane().add(panel1); + chargeFrame.pack(); + chargeFrame.setLocation(200,200); + chargeFrame.setSize(250,225); + chargeFrame.setVisible(true); + chargeFrame.setResizable(true); + chargeFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);} + } + if(RadioButtonEditor.button.getActionCommand()=="ChkBasis" && (okChk.isSelected()==true)) + { + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea,otherKeyToolTip.chkBasis); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + //G03MenuTree.keyoptArea.setText(G03MenuTree.keyoptArea.getText()+otherKeyToolTip.chkBasis); + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherFlag ++; + } + otherKeyTable.otherKeys.addElement("ChkBasis"); + + //Insert into the Tree + InsertNode.insertNode("Key", RadioButtonEditor.button.getActionCommand()); + } + + //To be integrated + if(RadioButtonEditor.button.getActionCommand()=="Complex" && (okCom.isSelected()==true)) + { + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea,otherKeyToolTip.complex); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + // G03MenuTree.keyoptArea.setText(G03MenuTree.keyoptArea.getText()+otherKeyToolTip.complex); + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherFlag ++; + } + otherKeyTable.otherKeys.addElement("Complex"); + + //Insert into the Tree + InsertNode.insertNode("Key", RadioButtonEditor.button.getActionCommand()); + } + + if(RadioButtonEditor.button.getActionCommand()=="Constants" && (okCon.isSelected()==true)) + { + // Charge is selected popup a window with the list of options + + JFrame.setDefaultLookAndFeelDecorated(true); + constantsFrame = new JFrame("Options for Constants"); + JPanel panel1 = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + + JLabel optionLabel=new JLabel("Select an option"); + con98Opt = new JRadioButton("1998"); + con86Opt = new JRadioButton("1986"); + con79Opt = new JRadioButton("1979"); + + constantOK = new JButton("OK"); + ButtonGroup constantOpt=new ButtonGroup(); + + constantOpt.add(con98Opt); + constantOpt.add(con86Opt); + constantOpt.add(con79Opt); + + + con98Opt.setSelected(true); + + con98Opt.addItemListener(new otherKeyListener()); + con86Opt.addItemListener(new otherKeyListener()); + con79Opt.addItemListener(new otherKeyListener()); + + constantOK.addActionListener(new otherKeyListener()); + c.gridy=0; + c.gridx=0; + c.weightx=0.5; + c.insets= new Insets(10,-20,10,90); + panel1.add(optionLabel,c); + + c.gridx=0; + c.gridy=1; + c.weightx=0.5; + // c.weighty=0.15; + c.insets= new Insets(0,-90,10,90); + panel1.add(con98Opt,c); + + c.gridy=2; + c.gridx=0; + panel1.add(con86Opt,c); + c.gridy=3; + c.gridx=0; + panel1.add(con79Opt,c); + c.gridy=4; + c.gridx=0; + c.insets = new Insets(0,90,10,90); + panel1.add(constantOK,c); + + constantsFrame.getContentPane().add(panel1); + constantsFrame.pack(); + constantsFrame.setLocation(200,200); + constantsFrame.setSize(250,225); + constantsFrame.setVisible(true); + constantsFrame.setResizable(true); + constantsFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + } + + if(RadioButtonEditor.button.getActionCommand()=="CounterPoise" && (okCou.isSelected()==true)) + { + // Charge is selected popup a window with the list of options + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea,otherKeyToolTip.counter); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + //G03MenuTree.keyoptArea.setText(G03MenuTree.keyoptArea.getText()+otherKeyToolTip.counter); + JFrame.setDefaultLookAndFeelDecorated(true); + counterFrame = new JFrame("Options for Counterpoise"); + JPanel panel1 = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + + JLabel optionLabel=new JLabel("Select an option"); + newOpt = new JRadioButton("NewGhost"); + oldOpt = new JRadioButton("OldGhost"); + + + counterOK = new JButton("OK"); + ButtonGroup counterOpt=new ButtonGroup(); + + counterOpt.add(newOpt); + counterOpt.add(oldOpt); + newOpt.setSelected(true); + newOpt.addItemListener(new otherKeyListener()); + oldOpt.addItemListener(new otherKeyListener()); + counterOK.addActionListener(new otherKeyListener()); + + c.gridy=0; + c.gridx=0; + c.weightx=0.5; + c.insets= new Insets(10,-20,10,90); + panel1.add(optionLabel,c); + + c.gridx=0; + c.gridy=1; + c.weightx=0.5; + // c.weighty=0.15; + c.insets= new Insets(0,-90,10,90); + panel1.add(newOpt,c); + + c.gridy=2; + c.gridx=0; + panel1.add(oldOpt,c); + c.gridy=3; + c.gridx=0; + c.insets = new Insets(0,90,10,90); + panel1.add(counterOK,c); + + counterFrame.getContentPane().add(panel1); + counterFrame.pack(); + counterFrame.setLocation(200,200); + counterFrame.setSize(250,190); + counterFrame.setVisible(true); + counterFrame.setResizable(true); + counterFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + } + + //CPHF + if(RadioButtonEditor.button.getActionCommand()=="CPHF" && (okCph.isSelected()==true)) + { + // Charge is selected popup a window with the list of options + //G03MenuTree.keyoptArea.setText(G03MenuTree.keyoptArea.getText()+otherKeyToolTip.cphf); + JFrame.setDefaultLookAndFeelDecorated(true); + cphfFrame = new JFrame("Options for CPHF"); + JPanel panel1 = new JPanel(new GridLayout(2,5)); + JPanel panel2 = new JPanel(new FlowLayout()); + JPanel panel3 = new JPanel(new FlowLayout()); + GridBagConstraints c = new GridBagConstraints(); + + JLabel l1 = new JLabel(" = "); + JLabel l2 = new JLabel(" = "); + JLabel l3 = new JLabel(" = "); + + + JLabel optionLabel = new JLabel("Select an option"); + gridOpt = new JRadioButton("Grid"); + grid = new JTextField(10); + //grid.setEditable(false); + rdfOpt = new JRadioButton("RdFreq"); + eqsOpt = new JRadioButton("EqSolv"); + simulOpt = new JRadioButton("Simultaneous"); + sepOpt = new JRadioButton("Separate"); + xyOpt = new JRadioButton("XY"); + zveOpt = new JRadioButton("ZVector"); + aoOpt = new JRadioButton("AO"); + moOpt = new JRadioButton("MO"); + maxOpt = new JRadioButton("MaxInv"); + max = new JTextField(10); + //max.setEditable(false); + conOpt = new JRadioButton("Conver"); + conver = new JTextField(10); + //conver.setEditable(false); + canOpt = new JRadioButton("Canonical"); + modOpt = new JRadioButton("MOD"); + + + cphfOK = new JButton("OK"); + ButtonGroup cphfOpt=new ButtonGroup(); + + cphfOpt.add(gridOpt); + cphfOpt.add(rdfOpt); + cphfOpt.add(eqsOpt); + cphfOpt.add(simulOpt); + cphfOpt.add(sepOpt); + cphfOpt.add(xyOpt); + cphfOpt.add(zveOpt); + cphfOpt.add(aoOpt); + cphfOpt.add(moOpt); + cphfOpt.add(maxOpt); + cphfOpt.add(conOpt); + cphfOpt.add(canOpt); + cphfOpt.add(modOpt); + + gridOpt.addItemListener(new otherKeyListener()); + rdfOpt.addItemListener(new otherKeyListener()); + eqsOpt.addItemListener(new otherKeyListener()); + simulOpt.addItemListener(new otherKeyListener()); + sepOpt.addItemListener(new otherKeyListener()); + xyOpt.addItemListener(new otherKeyListener()); + zveOpt.addItemListener(new otherKeyListener()); + aoOpt.addItemListener(new otherKeyListener()); + moOpt.addItemListener(new otherKeyListener()); + maxOpt.addItemListener(new otherKeyListener()); + conOpt.addItemListener(new otherKeyListener()); + canOpt.addItemListener(new otherKeyListener()); + modOpt.addItemListener(new otherKeyListener()); + panel2.add(gridOpt); + panel2.add(l1); + panel2.add(grid); + panel2.add(maxOpt); + panel2.add(l2); + panel2.add(max); + panel2.add(conOpt); + panel2.add(l3); + panel2.add(conver); + panel3.add(cphfOK); + cphfOK.addActionListener(new otherKeyListener()); + panel1.add(rdfOpt); + panel1.add(eqsOpt); + panel1.add(simulOpt); + panel1.add(sepOpt); + panel1.add(xyOpt); + panel1.add(zveOpt); + panel1.add(aoOpt); + panel1.add(moOpt); + panel1.add(canOpt); + panel1.add(modOpt); + cphfFrame.getContentPane().setLayout(new BorderLayout()); + cphfFrame.getContentPane().add(panel1,BorderLayout.NORTH); + cphfFrame.getContentPane().add(panel2,BorderLayout.CENTER); + cphfFrame.getContentPane().add(panel3,BorderLayout.SOUTH); + cphfFrame.pack(); + cphfFrame.setLocation(200,200); + cphfFrame.setSize(620,150); + cphfFrame.setVisible(true); + cphfFrame.setResizable(true); + cphfFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + } + + if(RadioButtonEditor.button.getActionCommand()== "DensityFit" && (okDen.isSelected()==true)) + { + // Charge is selected popup a window with the list of options + JFrame.setDefaultLookAndFeelDecorated(true); + densityFrame = new JFrame("Options for DensityFit"); + JPanel panel1 = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + JLabel optionLabel = new JLabel("Select an option"); + + iterOpt = new JRadioButton("Iterative"); + invOpt = new JRadioButton("InvToler"); + convOpt = new JRadioButton("Convergence"); + + invToler = new JTextField(10); + converDen = new JTextField(10); + + invToler.setEditable(false); + converDen.setEditable(false); + JLabel l1 = new JLabel("="); + JLabel l2 = new JLabel("="); + + densityOK = new JButton("OK"); + ButtonGroup densityOpt=new ButtonGroup(); + + densityOpt.add(iterOpt); + densityOpt.add(invOpt); + densityOpt.add(convOpt); + + iterOpt.addItemListener(new otherKeyListener()); + invOpt.addItemListener(new otherKeyListener()); + convOpt.addItemListener(new otherKeyListener()); + + densityOK.addActionListener(new otherKeyListener()); + c.gridy=0; + c.gridx=0; + c.weightx=0.5; + c.insets= new Insets(10,-20,10,90); + panel1.add(optionLabel,c); + + c.gridx=0; + c.gridy=1; + c.weightx=0.5; + // c.weighty=0.15; + c.insets= new Insets(0,-90,10,90); + panel1.add(iterOpt,c); + + c.gridy=2; + c.gridx=0; + // c.insets= new Insets(0,-90,10,90); + panel1.add(invOpt,c); + c.gridx=1; + c.insets = new Insets(0,-90,10,90); + panel1.add(l1,c); + c.gridx=2; + c.insets = new Insets(0,-90,10,90); + panel1.add(invToler,c); + + + c.gridy=3; + c.gridx=0; + panel1.add(convOpt,c); + c.gridx=1; + c.insets = new Insets(0,-90,10,90); + panel1.add(l2,c); + c.gridx=2; + c.insets = new Insets(0,-90,10,90); + panel1.add(converDen,c); + + + c.gridy=4; + c.gridx=0; + c.insets = new Insets(0,90,10,90); + panel1.add(densityOK,c); + + densityFrame.getContentPane().add(panel1); + densityFrame.pack(); + densityFrame.setLocation(200,200); + densityFrame.setSize(365,210); + densityFrame.setVisible(true); + densityFrame.setResizable(true); + densityFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + //G03MenuTree.keyoptArea.setText(G03MenuTree.keyoptArea.getText()+otherKeyToolTip.densityFit); + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea,otherKeyToolTip.densityFit); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + + + if(RadioButtonEditor.button.getActionCommand()== "FMM" && (okFmm.isSelected()==true)) + { + // Charge is selected popup a window with the list of options + JFrame.setDefaultLookAndFeelDecorated(true); + fmmFrame = new JFrame("Options for FMM"); + JPanel panel1 = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + JLabel optionLabel = new JLabel("Select an option"); + + + lmaxOpt = new JRadioButton("Lmax"); + levelOpt = new JRadioButton("Levels"); + tolOpt = new JRadioButton("Tolerance"); + boxOpt = new JRadioButton("BoxLen"); + allnearOpt = new JRadioButton("AllNearField"); + + lmax = new JTextField(10); + level = new JTextField(10); + tol = new JTextField(10); + box = new JTextField(10); + + + lmax.setEditable(false); + level.setEditable(false); + tol.setEditable(false); + box.setEditable(false); + + JLabel l1 = new JLabel("="); + JLabel l2 = new JLabel("="); + JLabel l3 = new JLabel("="); + JLabel l4 = new JLabel("="); + fmmOK = new JButton("OK"); + ButtonGroup fmmOpt=new ButtonGroup(); + + fmmOpt.add(lmaxOpt); + fmmOpt.add(levelOpt); + fmmOpt.add(tolOpt); + fmmOpt.add(boxOpt); + + lmaxOpt.addItemListener(new otherKeyListener()); + levelOpt.addItemListener(new otherKeyListener()); + tolOpt.addItemListener(new otherKeyListener()); + boxOpt.addItemListener(new otherKeyListener()); + + fmmOK.addActionListener(new otherKeyListener()); + c.gridy=0; + c.gridx=0; + c.weightx=0.5; + c.insets= new Insets(10,-20,10,90); + panel1.add(optionLabel,c); + + c.gridx=0; + c.gridy=1; + c.weightx=0.5; + // c.weighty=0.15; + c.insets= new Insets(0,-90,10,90); + panel1.add(lmaxOpt,c); + c.gridx=1; + c.insets= new Insets(0,-90,10,90); + panel1.add(l1,c); + c.gridx=2; + panel1.add(lmax,c); + + c.gridy=2; + c.gridx=0; + // c.insets= new Insets(0,-90,10,90); + panel1.add(levelOpt,c); + c.gridx=1; + c.insets = new Insets(0,-90,10,90); + panel1.add(l2,c); + c.gridx=2; + c.insets = new Insets(0,-90,10,90); + panel1.add(level,c); + + + c.gridy=3; + c.gridx=0; + panel1.add(tolOpt,c); + c.gridx=1; + c.insets = new Insets(0,-90,10,90); + panel1.add(l3,c); + c.gridx=2; + c.insets = new Insets(0,-90,10,90); + panel1.add(tol,c); + + + c.gridy=4; + c.gridx=0; + panel1.add(boxOpt,c); + c.gridx=1; + c.insets = new Insets(0,-90,10,90); + panel1.add(l4,c); + c.gridx=2; + c.insets = new Insets(0,-90,10,90); + panel1.add(box,c); + + + c.gridy=5; + c.gridx=0; + panel1.add(allnearOpt,c); + + c.gridy=6; + c.gridx=0; + c.insets = new Insets(0,90,10,90); + panel1.add(fmmOK,c); + + fmmFrame.getContentPane().add(panel1); + fmmFrame.pack(); + fmmFrame.setLocation(200,200); + fmmFrame.setSize(375,285); + fmmFrame.setVisible(true); + fmmFrame.setResizable(true); + fmmFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea,otherKeyToolTip.fmm); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + //G03MenuTree.keyoptArea.setText(G03MenuTree.keyoptArea.getText()+otherKeyToolTip.fmm); + } + if(RadioButtonEditor.button.getActionCommand()=="NMR" && (okNmr.isSelected()==true)) + { + + JFrame.setDefaultLookAndFeelDecorated(true); + JPanel panel1 = new JPanel(); + JPanel panel2 = new JPanel(); + + nmrFrame = new JFrame("Select Options for NMR"); + nmrOk = new JButton("OK"); + + spinOpt = new JRadioButton("SpinSpin"); + csgtOpt = new JRadioButton("CSGT"); + giaoOpt = new JRadioButton("GIAO"); + igaimOpt = new JRadioButton("IGAIM"); + singleOpt = new JRadioButton("SingleOrigin"); + allOpt = new JRadioButton("All"); + printOpt = new JRadioButton("PrintEigenvectors"); + ButtonGroup nmrOpt=new ButtonGroup(); + + nmrOpt.add(spinOpt); + nmrOpt.add(csgtOpt); + nmrOpt.add(giaoOpt); + nmrOpt.add(igaimOpt); + nmrOpt.add(singleOpt); + nmrOpt.add(allOpt); + nmrOpt.add(printOpt); + + spinOpt.addItemListener(new otherKeyListener()); + csgtOpt.addItemListener(new otherKeyListener()); + giaoOpt.addItemListener(new otherKeyListener()); + igaimOpt.addItemListener(new otherKeyListener()); + singleOpt.addItemListener(new otherKeyListener()); + allOpt.addItemListener(new otherKeyListener()); + printOpt.addItemListener(new otherKeyListener()); + + + panel1.add(spinOpt); + panel1.add(csgtOpt); + panel1.add(giaoOpt); + panel1.add(igaimOpt); + panel1.add(singleOpt); + panel1.add(allOpt); + panel1.add(printOpt); + + nmrOk.addActionListener(new otherKeyListener()); + panel2.add(nmrOk); + nmrFrame.getContentPane().setLayout(new BorderLayout()); + nmrFrame.getContentPane().add(panel1,BorderLayout.CENTER); + nmrFrame.getContentPane().add(panel2,BorderLayout.SOUTH); + nmrFrame.pack(); + nmrFrame.setLocation(200,200); + nmrFrame.setSize(520,150); + nmrFrame.setVisible(true); + nmrFrame.setResizable(true); + nmrFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + } + + if(RadioButtonEditor.button.getActionCommand()=="External" && (okExt.isSelected()==true)) + { + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea,otherKeyToolTip.external); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + otherKeyTable.otherKeys.addElement("External"); + if(!(InsertNode.nodeExists("External"))) + InsertNode.insertNode("Key","External"); + //G03MenuTree.keyoptArea.setText(G03MenuTree.keyoptArea.getText()+otherKeyToolTip.external); + } + if(RadioButtonEditor.button.getActionCommand()=="ExtraBasis" && (okExtB.isSelected()==true)) + { + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea,otherKeyToolTip.extrabasis); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + otherKeyTable.otherKeys.addElement("ExtraBasis"); + if(!(InsertNode.nodeExists("ExtraBasis"))) + InsertNode.insertNode("Key","ExtraBasis"); + //G03MenuTree.keyoptArea.setText(G03MenuTree.keyoptArea.getText()+otherKeyToolTip.extrabasis); + } + if(RadioButtonEditor.button.getActionCommand()=="ExtraDensityBasis" && (okExtD.isSelected()==true)) + { + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea,otherKeyToolTip.extradensitybasis); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + otherKeyTable.otherKeys.addElement("ExtraDensityBasis"); + if(!(InsertNode.nodeExists("ExtraDensityBasis"))) + InsertNode.insertNode("Key","ExtraDensityBasis"); + + //G03MenuTree.keyoptArea.setText(G03MenuTree.keyoptArea.getText()+otherKeyToolTip.extradensitybasis); + } + + if(RadioButtonEditor.button.getActionCommand()=="GFInput" && (okGfi.isSelected()==true)) + { + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea,otherKeyToolTip.GFInput); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + otherKeyTable.otherKeys.addElement("GFInput"); + if(!(InsertNode.nodeExists("GFInput"))) + InsertNode.insertNode("Key","GFInput"); + // G03MenuTree.keyoptArea.setText(G03MenuTree.keyoptArea.getText()+otherKeyToolTip.GFInput); + } + + if(RadioButtonEditor.button.getActionCommand()=="GFPrint" && (okGfp.isSelected()==true)) + { + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + otherKeyTable.otherKeys.addElement("GFPrint"); + if(!(InsertNode.nodeExists("GFPrint"))) + InsertNode.insertNode("Key","GFPrint"); + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea,otherKeyToolTip.GFPrint); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + + + //G03MenuTree.keyoptArea.setText(G03MenuTree.keyoptArea.getText()+otherKeyToolTip.GFPrint); + } + + if(RadioButtonEditor.button.getActionCommand()=="Name" && (okNam.isSelected()==true)) + { + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea,otherKeyToolTip.Name); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + + + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + otherKeyTable.otherKeys.addElement("Name"); + if(!(InsertNode.nodeExists("Name"))) + InsertNode.insertNode("Key","Name"); + //G03MenuTree.keyoptArea.setText(G03MenuTree.keyoptArea.getText()+otherKeyToolTip.Name); + } + + if(RadioButtonEditor.button.getActionCommand()=="Integral" && (okInt.isSelected()==true)) + { + + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea,otherKeyToolTip.Integral); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + otherKeyTable.otherKeys.addElement("Integral"); + if(!(InsertNode.nodeExists("Integral"))) + InsertNode.insertNode("Key","Integral"); + //G03MenuTree.keyoptArea.setText(G03MenuTree.keyoptArea.getText()+otherKeyToolTip.Integral); + } + + + + // if(RadioButtonEditor.button.getActionCommand()=="IOp" && (okIop.isSelected()==false)) + + + + + if(RadioButtonEditor.button.getActionCommand()=="IOp" && (okIop.isSelected()==true)) + { + + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherKeyTable.otherFlag++; + } + //if(iopKeymodify.iopFlag==0) + //{ + + new iopKeymodify(); + //} + //else + //{ + //iopKeymodify.iopFrame.show(); + // } + /* if(!(InsertNode.nodeExists("Iop"))) + InsertNode.insertNode("Key","Iop"); */ + + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea,otherKeyToolTip.IOp); + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (BadLocationException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + + //************************** + //Paste the other ifz here + //************************** + + + // To be integrated + if(RadioButtonEditor.button.getActionCommand()=="Temperature") + { + //G03MenuTree.keyoptArea.setText(G03MenuTree.keyoptArea.getText()+otherKeyToolTip.tempTip); + + + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea,otherKeyToolTip.tempTip); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + + + tempText=new JTextField(5); + tempText.setText("298.15"); + String message="Enter the value of Temperature"; + int result = JOptionPane.showOptionDialog(this, + new Object[] { message, tempText}, + "Temperature=N", JOptionPane.OK_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE, + null, null, null); + if(result==0) + { + if(otherKeyTable.otherFlag==0) + { + otherKeyTable.otherKeys = new Vector(); + otherFlag ++; + } + temp_Opt = "Temperature="+tempText.getText(); + otherKeyTable.otherKeys.addElement("Temperature="+tempText.getText()); + + //Insert into the Tree + InsertNode.insertNode("Key", RadioButtonEditor.button.getActionCommand()); + } + + else //Cancel Option + { + otherKeyTable.okTem.setSelected(false); + } + + } + + //SYMMETRY + if(RadioButtonEditor.button.getActionCommand()=="Symmetry") + { + symmetryFrame=new JFrame("Options for Symmetry"); + + + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea,otherKeyToolTip.symmetryTip); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + + + //G03MenuTree.keyoptArea.setText(G03MenuTree.keyoptArea.getText()+otherKeyToolTip.symmetryTip); + symmetryPGText = new JTextField(10); + symmetryAxisCombo=new JComboBox(); + symmetryDone=new JButton("Done"); + symmetryAxisCombo.addItem("X"); + symmetryAxisCombo.addItem("Y"); + symmetryAxisCombo.addItem("Z"); + + + symmetryOptions= new JRadioButton[12]; + symmetryGroup = new ButtonGroup(); + for(int i=0;i(); + otherFlag ++; + } + scale_Opt = "Scale="+scaleText.getText(); + otherKeyTable.otherKeys.addElement(scale_Opt); + + //Insert into the Tree + InsertNode.insertNode("Key", RadioButtonEditor.button.getActionCommand()); + } + } + + else //Cancel Option + { + otherKeyTable.okSca.setSelected(false); + } + + } + + //If it is PUNCH + + if(RadioButtonEditor.button.getActionCommand()=="Punch") + { + punchFrame=new JFrame("Options for Punch"); + + // Display the message in Help Area + + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea, otherKeyToolTip.punchTip); + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (BadLocationException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + + + punchDone=new JButton("Done"); + //punchOptions= new JCheckBox[9]; + punchGroup = new ButtonGroup(); + for(int i=0;i(); + otherFlag ++; + } + pressureOpt = "Pressure="+pressureText.getText(); + otherKeyTable.otherKeys.addElement(pressureOpt); + + //Insert into the Tree + InsertNode.insertNode("Key", RadioButtonEditor.button.getActionCommand()); + } + } + + else //Cancel Option + { + otherKeyTable.okPre.setSelected(false); + } + + } + + // If it is Output + if(RadioButtonEditor.button.getActionCommand()=="Output") + { + outputFrame=new JFrame("Options for Output"); + + try { + G03MenuTree.insertHTML(G03MenuTree.keyoptArea, otherKeyToolTip.outputTip); + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (BadLocationException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + outputWFNText = new JTextField(10); + + outputDone=new JButton("Done"); + + outputOptions= new JCheckBox[3]; + outputGroup = new ButtonGroup(); + for(int i=0;i>>>"+otherKeyListener.symm_Opt); + otherKeys.removeElement("Symmetry= "+otherKeyListener.symm_Opt); + InsertNode.deleteNode(RadioButtonEditor.button.getActionCommand()); + } + if(RadioButtonEditor.button.getActionCommand()=="Sparse") + { + System.out.println("Tracking>>>>"+otherKeyListener.sparse_Opt); + //if(okSpa.isSelected()==false) + //{ + otherKeys.removeElement("Sparse="+otherKeyListener.sparse_Opt); + RouteClass.writeRoute(); + //} + if(InsertNode.nodeExists("Sparse")) + InsertNode.deleteNode(RadioButtonEditor.button.getActionCommand()); + + } + if(RadioButtonEditor.button.getActionCommand()=="Output") + { + + otherKeys.removeElement("Output= "+otherKeyListener.output_Opt); + InsertNode.deleteNode(RadioButtonEditor.button.getActionCommand()); + } + if(RadioButtonEditor.button.getActionCommand()=="Scale") + { + otherKeys.removeElement("Scale="+scaleText.getText()); + InsertNode.deleteNode(RadioButtonEditor.button.getActionCommand()); + } + if(RadioButtonEditor.button.getActionCommand()=="Punch") + { + otherKeys.removeElement("Punch= "+otherKeyListener.punch_Opt); + InsertNode.deleteNode(RadioButtonEditor.button.getActionCommand()); + } + if(RadioButtonEditor.button.getActionCommand()=="Pseudo") + { + otherKeys.removeElement("Pseudo= "+otherKeyListener.pseudo_Opt); + InsertNode.deleteNode(RadioButtonEditor.button.getActionCommand()); + } + if(RadioButtonEditor.button.getActionCommand()=="Prop") + { + otherKeys.removeElement("Prop= "+otherKeyListener.prop_Opt); + System.out.println("PROP OPT "+otherKeyListener.prop_Opt); + InsertNode.deleteNode(RadioButtonEditor.button.getActionCommand()); + } + if(RadioButtonEditor.button.getActionCommand()=="Pressure") + { + otherKeys.removeElement("Pressure="+pressureText.getText()); + InsertNode.deleteNode(RadioButtonEditor.button.getActionCommand()); + } + + + /* else + { + otherKeys.removeElement(RadioButtonEditor.button.getActionCommand()); + InsertNode.deleteNode(RadioButtonEditor.button.getActionCommand()); + } */ + } + + + + + } // End of IF + + + } + + + public static void main(String[] args) { + otherKeyTable frame = new otherKeyTable(); + frame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + System.exit(0); + } + }); + } +} + + diff --git a/src/main/java/g03input/otherKeyToolTip.java b/src/main/java/g03input/otherKeyToolTip.java new file mode 100644 index 0000000..6dedfd8 --- /dev/null +++ b/src/main/java/g03input/otherKeyToolTip.java @@ -0,0 +1,224 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * + * @author Michael Sheetz + * @author Shashank Jeedigunta @author Sandeep Kumar Seethaapathy + * + */ + + +package g03input; + + +public class otherKeyToolTip { + public static String charSO = "
Standard Orientation :
Use the %KJob=L301 Link0 command to determine the standard orientation for the molecule."; + public static String chkBasis = "
CheckBasis:
Used to request that the basis set be retrieved from the checkpoint" + + "file instead of from the input stream. This is quite useful when running a large number of multi-step"+ + "jobs that all use the same basis set or multi-step jobs involving general basis sets (user-defined basis"+ + "functions and/or ECP's) since only a single copy of the basis set need be included in the input stream."+ + "
ChkBasis, by default, will also retrieve any density fitting set that is contained in the checkpoint file."; + + public static String complex = "
Complex:
Used to request that the molecular orbitals be allowed to become Complex.
" + + "Note: This keyword may only be used for closed-shell singlet states."; +public static String counter = "
Counterpoise:
Used to compute counterposie corrections on an energy, optimization, or frequency calculation or" + + "BOMD.This keyword takes an integer valuse, counterpoise = N, where N = the number of fragments or monomers in the " + + "molecular structure. "+ + "Note: When using this keyword, an additional integer must be placed at the end of each atom specification in the " + + "molecular structure section indicating which fragment or monomer the atom belong to."; + + + +public static String Name = "
Name:

Specifies the username that is stroed in the archive entry for the calculation."; + +public static String densityFit = "
DensityFit:
Controls density fitting for the coulomb problem.
"+ + "Note:Density fitting basis sets must be specified as part of the model chemistry in the route section of the" + + "input file"; +public static String external = "
External:
Requests a calculation using an externalprogram primarily for use in ONIOM calculaitons"; +public static String extrabasis = "
ExtraBasis:
Used to indicate that additional basis functions are being added to the basis set
" + + "specified in the route section of the input file. These extra basis functions are specified in a separate section
"+ + "of the input file."+ + "Use this keyword primarily to supply basis functions for elements that are not defined in any of the G03 standard basis
"+ + "sets. Note, however, that attempting to redefine any of the built-in basis sets already defined in G03 will result in error"; +public static String extradensitybasis = "
ExtraDensityBasis:
Used to indicate that additional basis functions are being added to the density fitting basis set specified in the \n" + + "route section of the input file.Note that this keyword will be ignored if no density fitting basis set has been specified \n" + + "in the route section of the input file"; +public static String fieldmplusn = "
Requests that a finite field involving electric multipoles be added to the calculation, where M identifies the multipole \n" + + "and N specifies the magnitude ofthe field as N*0.0001 au.Note that the direction of the field(+/-) is parallel(+) o anti-parallel(-) to \n " + + "the default direction determined by the stardard orientation for the molecule"; + +public static String fieldmn = "

Fieldmn:
Requests that a finite perturbation involving a Fermi contact term be added to the calculation, where M identifies the atom number \n"+ + "corresponding to the ordering in the molecular specification section of the input file and N specifies the magnitude of the perturbation \n "+ + "as N*0.0001 times the spin density on atom M."; +public static String fmm= "
FMM:
Forces the use of tge Fast Multipole Method if possible.\n"+ +"Note that G0 will generally invoke FMM automatically if it gives even a modest gain in performance.Consequently,"+ +"users will rarely need to control FMM maually in unusual special cases, such as computations on nearly linear" + +"polypeptides or long carbon nanotubes."; +public static String GFInput = "
GFInput:
This is an output generation keyword that is used to print the current basis set in a form"+ +"suitable for use as general basis set input so that it can be used in adding to or modifying a standard basis set."; +public static String GFPrint = "
GFPrint:
This is an output generation keyword that is used to print the current basis set in tabular form."; + +public static String Integral = "
Integral:
Used to modify the method of computation and use of two-electron integrals and their derivatives."; + +public static String IOp = "
Iop:
Used to set internal options to specific values.\n"+ +"The syntax for this keyword is IOp(Ov1/Op1=N1, Ov2/Ov2=N2,...), which sets option number Op1(Op2,...) to the value N1 \n"+ +"(N2,...) for every occurence of overlay Ov1(Ov2,...).\n" + +"Note that IOp values that are explicitly set in the route section do not get passed to any subsequent automatically- \n"+ +"generated job steps; e.g., the frequency job in a Opt Freq calculation or an inherently multi-step methods as those using \n"+ +"the G2 or CBS method.\n" + +"Consequently, if you wanterd to specify, say, an alternative grid for a DFT Opt Freq run, you would have to use an option to \n"+ +"the Int=Grid keyword in place of using the Iop keyword.\n"+ +"Note also that archiving is automatically turned off when using this keyword.\n"+ +"A complete list of options that can be used with this keyword can be found in the Gaussian 09 IOps Reference or online at http://www.gaussian/com "; + + + + + +public static String NMR = "
NMR:
Requests that NMR shielding tensors and magnetic susceptibilities be predicted."+ +"Note that this properties keyword is applicable for HF, all DFT, and MP2 calculations and that NMR may be combined with the SCRF keyword in G03"; + + +public static String SpinSpin = "
SpinSpin:
Compute spin-spin coupling constants in addition to the usual" + + "NMR properties. This option is available onlyfor HF and DFT calculations."; + + +public static String CGST = "
CGST:
Compute NMR properties using the continous set of gauge transformations (CGST) methoid only."; + +public static String GIAO = "
GIAO:

Compute NMR properties using Gauge-Independent Atomic Orbital(GIAO) method only. This is the default option for this keyword."; + +public static String IGAIM = "
IGAIM:

Use atomic centers as guage origins"; + + +public static String SingleOrigin = "
SingleOrigin:
Use a single gauge origin. Note that the use of the option is not recommended"; + + +public static String All = "
All:

Compute properties using all three methods - CGST,GIAO, and SingleOrigin.
"; + +public static String PrintEigenvectors = "
PrintEigenvectors:

Print the eigenvectors of te NMR shielding tenso for each atom in the molecular structure."; + + + + + //To be integrated + public static String tempTip="
Temperature:
Used to specify the temperature (in degrees Kelvin) to be used " + + "for thermochemistry analysis."; + //Tooltips for Other Keywords -> SYMMETRY + public static String symmetryTip="
Symmetry:
Requests the sparse matrix storage be used to enhance"; + public static String symmpgTip="
Symmetry>PG:
Use no more symmetry than that found in the point group specified by group"; + public static String symmaxisTip="
Symmetry>Axis:
Specify axis (X|Y|Z) to help specify the subgroup"; + public static String symmonTip="
Symmetry>On:
Turn on symmetry when it would otherwise be turned off"; + public static String[] symmetryOptionTips={"
Symmetry>Int:
Enables use of integral symmetry.", + "
Symmetry>NoInt:
Disables use of integral symmetry.", + "
Symmetry>Grad:
Enables use of symmetry in evaluation of integral derivatives.", + "
Symmetry>NoGrad:
Disables use of symmetry in evaluation of integral derivatives.", + "
Symmetry>SCF:
Enables use of N-cubed symmetry in SCF, which is used by default only" + + "for GVB calculations", + "
Symmetry>NoSCF:
Disables use of N-cubed symmetry in SCF", + "
Symmetry>Loose:
Requests the use of looser cutoffs in determining symmetry at" + + "the first point.\n This option is designed to be used with suboptimal geometries", + "
Symmetry>Tight:
Requests the use of the regular (default) criteria at the first point", + "
Symmetry>Follow:
Attempt to follow point group/orientation during optimization" + }; + + //Tooltips for Other Keywords -> SPARSE + public static String sparseTip="
Sparse:
Requests that sparse matrix storage be used to enhance performance" + + "of large calculations" + + "

The cutoff value for considering a matrix element to be a zero is determined by the options for this keyword

"; + public static String[] sparseOptionTips={"
Sparse > Loose:
Set cutoff value at 5 * 10 -5 ", + "
Sparse > Medium:
Set cutoff value at 5 * 10 -7.
Default value for all semi-emperical methods ", + "
Sparse > Tight:
Set cutoff value at 10 -10.
Default value for all DFT methods ", + "
Sparse > N:
Set cutoff value at 10 -N" + }; + + public static String scaleTip="
Scale:
Used to specify the frequency scale factor to use for thermochemistry analysis"; + + public static String punchTip="
Punch:
Request that useful information be \"punched\" at various points in" + + "the computation and sent to a seperate output file. The selected options determines what information will be " + + "output to this file.

Combinations of options are distinct and non-interacting in that Punch (MO, GAMESSInput) , " + + "for example, will send both the MO and GAMESS input information to an output file but soed not format the MO" + + "information in a GAMESS input format.

" + + "

Note that all options for this keyword can be combined with the exception of MO and Natural Orbitals. "; + + public static String[] punchOptionTips={"
Punch > Archive
Requests that a summary of all of the important results in the computation be punched.", + "
Punch > Title
Punches the title section", + "
Punch > Coord
Punches the atomic numbers and Cartesian Coordinates in a form that can be read" + + "back into Gaussian", + "
Punch > Derivatives
Punches the energy, nuclear coordinate derivatives, and second derivatives" + + "in a format (6F12.8) suitable for later use with Opt= FCCArds.", + "
Punch > MO
Punches the orbitals in a format suitable for Guess=Cards ", + "
Punch > NaturalOrbitals
Punches the natural orbitals corresponding to the destiny specified with the " + + "keyword Destiny .", + "
Punch > HondoInput
Punches the input deck for Hondo.", + "
Punch > GAMESSInput
Punches the input deck for GAMESS.", + "
Punch > All
Punches everything with the exception of natural orbitals"}; + + public static String pseudoTip="
Pseudo:
Requests that a model potential be substituted for the core electrons"; + + public static String propTip="
Prop:
Requests computation of electrostatic properties." + + "

The density used for this electrostatic analysis is controlled by the keyword Density

."; + + + public static String[] propOptionTips={"
Prop > EFG
Requests computation of the potential,field and field gradient(default).", + "
Prop > Potential
Requests computation of the potential but not the field or the field gradient.", + "
Prop > Field
Requests computation of the potential and field but not the field gradient.", + "
Prop > EPR
Requests computation of the anisotropic hyperfine coupling constants (spin-dipole EPR terms).", + "","", + "
Prop > FitCharge
Fit atomic charges to the electrostatic potential at the Van der Waals surface.", + "
Prop > Dipole
Constrain fitted charges to the dipole moment.", + "","" + }; + + public static String pressTip="
Pressure:
Specifies the pressure (in atm) that is to be used for thermochemical analysis."; + + public static String outputTip="
Output:
Requests output of unformatted Fortran file whose content is controlled by the option used with this keyword."; + + public static String molecularTip="
Once you Validate the molecular specification, the molecular structure gets displayed in the GUI
"+ + " View/Edit Molecular Structure --> File -> Validate "; + public static String molTip="
To project the molecular structure onto a given plane, double click the axis perpendicular to that plane.
"+ + "To rotate the molecule about a given axis, right click on that axis and drag mouse across display screen."; + + + public static void main(String args[]) + { + + } + + + +} diff --git a/src/main/java/g03input/pbcTable.java b/src/main/java/g03input/pbcTable.java new file mode 100644 index 0000000..dec46f7 --- /dev/null +++ b/src/main/java/g03input/pbcTable.java @@ -0,0 +1,344 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Apr 8, 2005 + * @author Michael Sheetz + * @author Shashank Jeedigunta @author Sandeep Kumar Seethaapathy + * + */ + + + +package g03input; + +import javax.swing.*; +import javax.swing.event.TableModelEvent; +import javax.swing.table.DefaultTableModel; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.Vector; + + +class MyCellEditor extends DefaultCellEditor { + JTextField textfield; + + public MyCellEditor( JTextField t ) { + super(t); + textfield = t; + } +} + +public class pbcTable extends JFrame implements ItemListener,ActionListener{ + public static JTable pbctable; + + JFrame pbcFrame; + public static JRadioButton[] pbcOptions= {new JRadioButton("CellRange="), + new JRadioButton("GammaOnly"), + new JRadioButton("NKPoint="), + new JRadioButton("NCellMax="), + new JRadioButton("NCellMin="), + new JRadioButton("NCellDFT="), + new JRadioButton("NCellK="), + new JRadioButton("NCellE2=") + }; + + public static JTextField[] pbcText=new JTextField[8]; + public static JButton doneButton,exitButton; + public static JPanel donePanel; + public static DefaultTableModel dm; + public static String[] initValues= {"","","","","","","",""}; + public static Vector pbcOpt; + public static int pbcC,pbcOptC,pbcOptCount; + public static int pbcFlag,pbcListen ; + public static Vector selectedRows; + public static int selectedIndex[] =new int[8]; + static int k=0,lindex; + String Value=""; + + public pbcTable(){ + + pbcFrame = new JFrame("PBC Options"); + + if(pbcListen==0) + { + for(int i=0;i0) + //{ + + int smallIndex=9; + for(int ll=0;ll<8;ll++) + { + if(selectedIndex[ll]==1) + { + if(ll0) + RouteClass.keywordBuffer[pbcFlag].append("="+"("+pbcOpt.get(0)+")"); + } + */ + pbcFrame.dispose(); + RouteClass.writeRoute(); + } + + if(ae.getSource()==exitButton) + { + pbcFrame.dispose(); + } + + + } + + + public void itemStateChanged(ItemEvent e) + { + + System.out.println("ITE<>"); + for(int i=0;i<8;i++) + { + System.out.println("Inside for in itemstate changed"); + if(e.getItem()==pbcOptions[i]) + { + System.out.println("Inside e.getItem() ... OptionSelected is"+pbcOptions[i]); + + if(((JRadioButton)e.getItem()).isSelected()) + { + G03Listener.pbcTabF++; + if(pbcOptC==0) + { + pbcOpt = new Vector(8); + pbcOptC++; + } + + //pbcText[i].setEnabled(true); + // pbcText[1].setEnabled(false); + + + if(!(InsertNode.nodeExists("PBC"))) + InsertNode.insertNode("Key","PBC"); + + String pbcOptionName =new String(((JRadioButton)e.getItem()).getActionCommand().toString()); + if(pbcOptionName.endsWith("=")) + pbcOptionName=pbcOptionName.substring(0,pbcOptionName.length()-1); + InsertNode.insertNode("PBC",pbcOptionName); + // String pbcOptionName =RadioButtonEditor.button.getActionCommand(); + selectedIndex[i]=1;// index of the item selected + + pbcOpt.addElement(pbcOptionName); + //pbcCount++; + } + + else // deselected + { + String pbcOName =new String(((JRadioButton)e.getItem()).getActionCommand().toString()); + if(pbcOName.endsWith("=")) + pbcOName=pbcOName.substring(0,pbcOName.length()-1); + + if(InsertNode.nodeExists(pbcOName)) + InsertNode.deleteNode(pbcOName); + + pbcOpt.removeElement(((JRadioButton)e.getItem()).getActionCommand().toString()); + selectedIndex[i]=0; + + } + + + } + + } + + + } + +} + + + + diff --git a/src/main/java/g03input/popKeyOptTable.java b/src/main/java/g03input/popKeyOptTable.java new file mode 100644 index 0000000..7eea94d --- /dev/null +++ b/src/main/java/g03input/popKeyOptTable.java @@ -0,0 +1,142 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Mar 29, 2005 + * @author Michael Sheetz + * @author Sandeep Kumar Seethaapathy @author Shashank Jeedigunta + * + */ + + + +package g03input; + +import javax.swing.*; +import javax.swing.event.TableModelEvent; +import javax.swing.table.DefaultTableModel; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +public class popKeyOptTable extends JFrame implements ActionListener{ + public static JFrame keyOptFrame; + public static JPanel helpPanel; + public static JTextArea helpTextArea; + public void actionPerformed(ActionEvent e) + { + if(e.getSource()==G03MenuTree.keyOptCombination) + { + + Color bgColor= new Color(236,233,216); + Color foreColor =new Color(0,78,152); + JPanel donePanel; + JButton doneButton,clearButton,exitButton; + JTable table; + JFrame.setDefaultLookAndFeelDecorated(true); + keyOptFrame = new JFrame("Options for Freq"); + keyOptFrame.setBackground(bgColor); + keyOptFrame.setForeground(foreColor); + DefaultTableModel dm = new DefaultTableModel(); + dm.setDataVector( + new Object[][]{ + {new JRadioButton("Opt=ReadFC"),null}, + {new JRadioButton("Opt=CalcHFFC"),null}, + {new JRadioButton("Opt=CalcFC"),null}, + {new JRadioButton("Opt=CalcAll"),null}}, + new Object[]{"Geometry Optimization","l"}); + table = new JTable(dm) { + public void tableChanged(TableModelEvent e) { + super.tableChanged(e); + repaint(); + } + }; + + + + table.getColumn("Geometry Optimization").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Geometry Optimization").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + table.getColumn("l").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("l").setCellEditor(new RadioButtonEditor(new JCheckBox())); + donePanel = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + + c.gridy=0; + c.gridx=0; + c.insets = new Insets(10,60,80,100); + helpTextArea = new JTextArea(); + donePanel.add(helpTextArea,c); + + + c.gridx=0; + c.gridy=1; + c.insets = new Insets(0,0,0,0); + doneButton = new JButton("Done"); + //clearButton = new JButton("Clear"); + exitButton = new JButton("Exit"); + donePanel.add(doneButton,c); + c.gridx=2; + //donePanel.add(clearButton,c); + c.gridx=3; + donePanel.add(exitButton,c); + c.gridx=4; + donePanel.setBackground(bgColor); + donePanel.setForeground(foreColor); + table.getTableHeader().setReorderingAllowed(false); + + keyOptFrame.getContentPane().setLayout(new BorderLayout()); + + + + JScrollPane scroll = new JScrollPane(table); + scroll.add(helpTextArea); + keyOptFrame.getContentPane().add( scroll,BorderLayout.NORTH); + keyOptFrame.getContentPane().add(donePanel,BorderLayout.CENTER); + keyOptFrame.setSize( 600,200); + keyOptFrame.setLocation(200,75); + keyOptFrame.setVisible(true); + helpPanel=new JPanel(new GridBagLayout()); + + + + // helpPanel.add(helpTextArea,c); + //keyOptFrame.getContentPane().add(helpPanel,BorderLayout.SOUTH); + } + } +} + diff --git a/src/main/java/g03input/popOptTable.java b/src/main/java/g03input/popOptTable.java new file mode 100644 index 0000000..92eb8f9 --- /dev/null +++ b/src/main/java/g03input/popOptTable.java @@ -0,0 +1,352 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Apr 8, 2005 + * @author Michael Sheetz + * @author Sandeep Kumar Seethaapathy @author Shashank Jeedigunta + * + */ + + + + +package g03input; + +import javax.swing.*; +import javax.swing.event.TableModelEvent; +import javax.swing.table.DefaultTableModel; +import java.awt.*; +import java.awt.event.*; +import java.util.Vector; + + +public class popOptTable extends JFrame implements ItemListener,ActionListener +{ + Color bgColor= new Color(236,233,216); + Color foreColor =new Color(0,78,152); + JPanel donePanel; + JButton doneButton,clearButton,exitButton; + public static JTable table; + JFrame popOptFrame; + public static JRadioButton PNone=new JRadioButton("None"); + public static JRadioButton PMini=new JRadioButton("Minimal"); + public static JRadioButton PRegu = new JRadioButton("Reg"); + public static JRadioButton PFull = new JRadioButton("Full"); + public static JRadioButton PBond= new JRadioButton("Bonding"); + public static JRadioButton PNatur =new JRadioButton("Natural Orbitals"); + public static JRadioButton PNaturS = new JRadioButton("NaturalSpinOrbitals"); + public static JRadioButton PAlpha = new JRadioButton("AlphaNatural"); + public static JRadioButton PBeta = new JRadioButton("BetaNatural"); + public static JRadioButton PSpin = new JRadioButton("SpinNatural"); + public static JRadioButton PNbo = new JRadioButton("NBO"); + public static JRadioButton PNpa= new JRadioButton("NPA"); + public static JRadioButton PNboRe = new JRadioButton("NBORead"); + public static JRadioButton PNboD = new JRadioButton("NBODel"); + public static JRadioButton PSavNB = new JRadioButton("SaveNBOs"); + public static JRadioButton PSaveLMNOs = new JRadioButton("SaveLMNOs"); + public static JRadioButton PSavmix =new JRadioButton("SaveMixed"); + public static Vector popOpt; + public static Vector popClear; + public static int popOptC; + public static int popFlag,popListen,popC; + public popOptTable(){ + + popOptFrame = new JFrame("Pop Options"); + if(popListen==0) + { + popClear=new Vector(40); + popClear.addElement(PNone); + popClear.addElement(PMini); + popClear.addElement(PRegu); + popClear.addElement(PFull); + popClear.addElement(PBond); + popClear.addElement(PNatur); + popClear.addElement(PNaturS); + popClear.addElement(PAlpha); + popClear.addElement(PBeta); + popClear.addElement(PSpin); + popClear.addElement(PNbo); + popClear.addElement(PNpa); + popClear.addElement(PNboRe); + popClear.addElement(PNboD); + popClear.addElement(PSavNB); + popClear.addElement(PSaveLMNOs); + popClear.addElement(PSavmix); + + PNone.addItemListener(this); + PNone.setBackground(Color.WHITE); + PMini.addItemListener(this); + PMini.setBackground(Color.WHITE); + PRegu.addItemListener(this); + PRegu.setBackground(Color.WHITE); + PFull.addItemListener(this); + PFull.setBackground(Color.WHITE); + PBond.addItemListener(this); + PBond.setBackground(Color.WHITE); + PNatur.setBackground(Color.WHITE); + PNatur.addItemListener(this); + PNaturS.setBackground(Color.WHITE); + PNaturS.addItemListener(this); + PAlpha.setBackground(Color.WHITE); + PAlpha.addItemListener(this); + PBeta.setBackground(Color.WHITE); + PBeta.addItemListener(this); + PSpin.setBackground(Color.WHITE); + PSpin.addItemListener(this); + PNbo.setBackground(Color.WHITE); + + PNbo.addItemListener(this); + PNpa.addItemListener(this); + PNpa.setBackground(Color.WHITE); + PNboRe.addItemListener(this); + + PNboRe.setBackground(Color.WHITE); + + PNboD.addItemListener(this); + PNboD.setBackground(Color.WHITE); + PSavNB.setBackground(Color.WHITE); + PSavNB.addItemListener(this); + PSaveLMNOs.setBackground(Color.WHITE); + PSaveLMNOs.addItemListener(this); + PSavmix.setBackground(Color.WHITE); + PSavmix.addItemListener(this); + + popListen++; + } + + //UIDefaults ui = UIManager.getLookAndFeel().getDefaults(); + + //UIManager.put("RadioButton.focus", ui.getColor("control")); + popOptFrame.setBackground(bgColor); + popOptFrame.setForeground(foreColor); + DefaultTableModel dm = new DefaultTableModel(); + dm.setDataVector( + new Object[][]{ + + {PNone,PBond,PNatur,PNbo}, + {PMini,null,PNaturS,PNpa}, + {PRegu,null,PAlpha,PNboRe}, + {PFull,null,PBeta,PNboD}, + {null,null,null,PSavNB}, + {null,null,null,PSaveLMNOs}, + {null,null,null,PSavmix}, + {null,null,null,null},}, + + new Object[]{"OutputFile","Bonding Analysis","Natural Orbitals","Natural Bond Orbitals"}); + + JTable table = new JTable(dm) { + public void tableChanged(TableModelEvent e) { + super.tableChanged(e); + repaint(); + } + }; + + table.getColumn("OutputFile").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("OutputFile").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + table.getColumn("Bonding Analysis").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Bonding Analysis").setCellEditor(new RadioButtonEditor(new JCheckBox())); + table.getColumn("Natural Orbitals").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Natural Orbitals").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + table.getColumn("Natural Bond Orbitals").setCellRenderer(new RadioButtonRenderer()); + table.getColumn("Natural Bond Orbitals").setCellEditor(new RadioButtonEditor(new JCheckBox())); + + doneButton = new JButton("Done"); + doneButton.addActionListener(this); + //clearButton = new JButton("Clear"); + exitButton = new JButton("Exit"); + //doneButton.addActionListener() + // clearButton.addActionListener(this); + exitButton.addActionListener(this); + + donePanel = new JPanel(); + donePanel.add(doneButton); + + // donePanel.add(clearButton); + donePanel.add(exitButton); + + /*table.setBackground(bgColor); + table.setForeground(foreColor); + */ + + + donePanel.setBackground(bgColor); + donePanel.setForeground(foreColor); + + + table.getTableHeader().setReorderingAllowed(false); + + + + popOptFrame.getContentPane().setLayout(new BorderLayout()); + JScrollPane scroll = new JScrollPane(table); + popOptFrame.getContentPane().add( scroll,BorderLayout.CENTER); + popOptFrame.getContentPane().add(donePanel,BorderLayout.SOUTH); + popOptFrame.setSize( 600,200); + popOptFrame.setLocation(200,75); + popOptFrame.setVisible(true); + } + public void actionPerformed(ActionEvent ae) + { + if(ae.getSource()==exitButton) + { + popOptFrame.dispose(); + } + System.out.println("flagwwwww"+popOptC); + if(ae.getSource()==doneButton){ + + if(RouteClass.initCount==0) + { + System.out.println(RouteClass.initCount+" \tInside init"); + RouteClass.initBuffer(); + RouteClass.initCount++; + } + if(popC==0) + { + System.out.println(popOptC+" \t Inside guessC"); + popFlag= RouteClass.keyIndex; + + RouteClass.keyIndex++; + System.out.println("flag"+ RouteClass.keyIndex); + popC++; + } + else + { + System.out.println("flag"+popFlag); + RouteClass.keywordBuffer[popFlag]=new StringBuffer(); + } + RouteClass.keywordBuffer[popFlag].append("Pop"); + if(!(InsertNode.nodeExists("Pop"))) + InsertNode.insertNode("Key", "Pop"); + try { + if(popOpt.size()>1) + { + RouteClass.keywordBuffer[popFlag].append("=("); + System.out.println("inside si" + popOpt.size()); + for(int count=0;count0) + RouteClass.keywordBuffer[popFlag].append("="+"("+popOpt.get(0)+")"); + } + //guessFlag=RouteClass.keyIndex; + System.out.println("buffer"+ RouteClass.keywordBuffer[popFlag]); + popOptFrame.dispose(); + RouteClass.writeRoute(); + } catch (NullPointerException e) { + // TODO Auto-generated catch block + // e.printStackTrace(); + } + } + } + + + public void itemStateChanged(ItemEvent e) + + + {if((e.getItem()==PNone)|| + (e.getItem()==PBond)|| + (e.getItem()==PNatur)|| + (e.getItem()==PNbo)|| + (e.getItem()==PMini)|| + (e.getItem()==PNaturS)|| + (e.getItem()==PNbo)|| + (e.getItem()==PNpa)|| + (e.getItem()==PRegu)|| + (e.getItem()==PAlpha)|| + (e.getItem()==PNboRe)|| + (e.getItem()==PFull)|| + (e.getItem()==PBeta)|| + (e.getItem()==PNboD)|| + (e.getItem()==PSavNB)|| + (e.getItem()==PSaveLMNOs)|| + (e.getItem()==PSavmix)) + { + + if(((JRadioButton)e.getItem()).isSelected()) + { + if(popOptC==0) + { + G03Listener.popTabF++; + popOpt = new Vector(10); + popOptC++; + } + if(!(InsertNode.nodeExists("Pop"))) + + InsertNode.insertNode("Key", "Pop"); + InsertNode.insertNode("Pop", RadioButtonEditor.button.getActionCommand()); + String guess = RadioButtonEditor.button.getActionCommand(); + popOpt.addElement(guess); + System.out.println("size of the vector"+popOpt.size()); + //popOptCount++; + }//System.out.println(e.getActionCommand()); + + else + { + if(InsertNode.nodeExists(((JRadioButton) e.getItem()).getActionCommand())) + InsertNode.deleteNode(((JRadioButton) e.getItem()).getActionCommand()); + popOpt.removeElement(((JRadioButton)e.getItem()).getActionCommand()); + } + } + } + + public static void main(String[] args) { + popOptTable frame = new popOptTable(); + frame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + System.exit(0); + } + }); + } + } + + + + + diff --git a/src/main/java/g03input/showMolEditor.java b/src/main/java/g03input/showMolEditor.java new file mode 100644 index 0000000..f5eecca --- /dev/null +++ b/src/main/java/g03input/showMolEditor.java @@ -0,0 +1,611 @@ +/* + +Copyright (c) 2005, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky, + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. +*/ + + +/** + * Created on Apr 2, 2005 + * @author Michael Sheetz + * @author Shashank Jeedigunta @author Sandeep Kumar Seethaapathy + * + */ + +package g03input; + +import nanocad.newNanocad; +import legacy.editor.commons.Settings; +import nanocad.nanocadFrame2; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.io.*; +import java.util.regex.Pattern; + + +public class showMolEditor extends JFrame implements ActionListener,WindowListener,ComponentListener{ + + + public static JFrame molFrame; + public static JMenuBar molBar; + public static JMenu fileMenu,editMenu,molEditor; + public static JMenuItem open,close,validate,save,saveas,cut,copy,paste + ,selectall,openmol,viewcur; + public static JPanel molPanel,textPanel; + public static JTextArea molText; + public static String tempmol=""; + public static String exportedMol=""; + // public static String tempmolFromInput=""; + public static JFileChooser inputChooser; + static int saved=0,choiceclose,inputfileOverWrite; + public static int nanoFlag; + // From ---lixh_4/27/05 + + public static String defaultDirStr = Settings.defaultDirStr; + public static String fileSeparator = Settings.fileSeparator; + public static String txtDir = defaultDirStr + fileSeparator + "txt"; + + + // + + + + + nanocadFrame2 nanWin; + public showMolEditor() + { + textPanel=new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.fill=GridBagConstraints.BOTH; + + + JFrame.setDefaultLookAndFeelDecorated(true); + JDialog.setDefaultLookAndFeelDecorated(true); + molFrame = new JFrame("Molecular Specification"); + molFrame.setSize(500,250); + molFrame.setLocation(25,50); + + molFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + + + molPanel = new JPanel(new BorderLayout()); + + molBar = new JMenuBar(); + fileMenu = new JMenu("File"); + editMenu = new JMenu("Edit"); + molEditor = new JMenu("Molecular Editor"); + + + open = new JMenuItem("Open"); + close = new JMenuItem("Close"); + save = new JMenuItem("Save/DisplayMol"); + //validate=new JMenuItem("Validate"); + saveas = new JMenuItem("SaveAs"); + + cut = new JMenuItem("Cut"); + copy = new JMenuItem("Copy"); + paste = new JMenuItem("Paste"); + selectall = new JMenuItem("Select All"); + + openmol = new JMenuItem("Molecular Editor"); + viewcur=new JMenuItem("View Current Structure"); + + openmol.setEnabled(true); + openmol.addActionListener(this); + viewcur.setEnabled(true); + fileMenu.add(open); + fileMenu.add(save); + // fileMenu.add(validate); + fileMenu.add(new JSeparator()); + fileMenu.add(close); + editMenu.add(cut); + editMenu.add(copy); + editMenu.add(paste); + editMenu.add(new JSeparator()); + editMenu.add(selectall); + + //validate.addActionListener(this); + cut.addActionListener(this); + copy.addActionListener(this); + paste.addActionListener(this); + selectall.addActionListener(this); + save.addActionListener(this); + close.addActionListener(this); + open.addActionListener(this); + + molEditor.add(openmol); + molEditor.add(viewcur); + + molBar.add(fileMenu); + molBar.add(editMenu); + molBar.add(molEditor); + + molPanel.add(molBar,BorderLayout.NORTH); + + molText = new JTextArea("",35,70); + + System.out.println(tempmol); + + if(tempmol!=null) + { + if(InputFile.inputfetched==0) + { + molText.setText(tempmol); + molText.setCaretPosition(tempmol.length()); + } + + /* If input file is fetched, then get the tempmol from InputFile */ + if(InputFile.inputfetched==1) + { + molText.setText(tempmol); + molText.setCaretPosition(tempmol.length()); + } + /*else + { + molText.setText(tempmol); + molText.setCaretPosition(tempmol.length()); + }*/ + + } + // + else + molText.setCaretPosition(0); + molText.setMargin(new Insets(5,5,5,5)); + + + // + JScrollPane mScroll = new JScrollPane(molText); + mScroll.setWheelScrollingEnabled(true); + + + molPanel.add(mScroll,BorderLayout.CENTER); + molFrame.getContentPane().add(molPanel); + //molFrame.getContentPane().add(textPanel); + molFrame.pack(); + molFrame.setResizable(true); + //molFrame.setVisible(true); + molFrame.setVisible(false); + } + + public static void getFile(String filepath) + { + // copies the file from user specified location to + // the buffer tempinput + try + { + // Open the file that is the first + FileInputStream fstream = new FileInputStream(filepath); + + DataInputStream in = new DataInputStream(fstream); + tempmol=""; + while (in.available() !=0) + { + // Print file line to screen + tempmol+=in.readLine(); + tempmol+="\n"; + } + + + in.close(); + + if(InputFile.inputfetched==1) + { + inputfileOverWrite=JOptionPane.showConfirmDialog(null,"You already have an imported input file." + + " Do you want to over write the existing input file?","Do you want to Continue?",JOptionPane.YES_NO_OPTION); + if(inputfileOverWrite==0) + { + //YES + InputFile.inputfetched=0; + G03MenuTree.nanocadNotice.setText("Molecular Specification Imported from External File"); + } + + + } + else + { + G03MenuTree.nanocadNotice.setText("Molecular Specification Imported from External File"); + } + + + + + } + + catch (Exception e) + { + JOptionPane.showMessageDialog(null,"File input error","Error",JOptionPane.ERROR_MESSAGE); + } + + + } + + public void doFetchInputFile() + { + // Open a FileChooser with *.com Filter + + inputChooser = new JFileChooser(); + + int state = inputChooser.showOpenDialog(null); + File file = inputChooser.getSelectedFile(); + + if(file != null && + state == JFileChooser.APPROVE_OPTION) { + // JOptionPane.showMessageDialog( + // null, file.getPath()); + getFile(file.getPath()); + + } + else if(state == JFileChooser.CANCEL_OPTION) { + JOptionPane.showMessageDialog( + null, "Input File Selection Canceled"); + } + + + } + + void replaceInputFile() + { + BufferedReader br= new BufferedReader(new StringReader(InputFile.tempinput)); + boolean matchedcharge=false,matchedmol=false; + StringBuffer inputString=new StringBuffer(); + String temp="$"; + + //Reads the input file until the charge and multiplicity are obtained + while(matchedcharge==false) + { + try { + temp=br.readLine(); + + if(temp==null) //EOF no luck + break; + + matchedmol=Pattern.matches("[A-Z][a-z]?[\\s]+[\\+|\\-]?[0-9]+\\.?[0-9]+[\\s]+[\\+|\\-]?[0-9]+\\.?[0-9]+[\\s]+[\\+|\\-]?[0-9]+\\.?[0-9]+[\\s]*",temp); + + if(matchedmol==true) // Charge & multiplicity not yet entered Mol. Specification exists + break; + + inputString.append(temp+"\n"); + matchedcharge= Pattern.matches("[\\s]*[\\+|\\-]?[0-9]+\\.?[0-9]*[\\s]*[\\+|\\-]?[0-9]+\\.?[0-9]*[\\s]*",temp); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + inputString.append(tempmol); + InputFile.tempinput=inputString.toString(); + //InputFile.tempinput.replaceAll(); + + + } + public void actionPerformed(ActionEvent e) + { + + // Molecular editor stuff... calling nanocad... + if(e.getSource()==openmol || e.getSource()== G03MenuTree.nanoItem) + { + // need to show the nano cad copied from editingStuff.java + nanoFlag=1; + doCallNanocad(); + molFrame.dispose(); + } + + /* + if(e.getSource()==validate) + atomCoordinateParser.getCoordinates(); + * Commented to integrate both the buttons */ + if(e.getSource()==cut) + molText.cut(); + if(e.getSource()==copy) + molText.copy(); + if(e.getSource()==paste) + molText.paste(); + if(e.getSource()==selectall) + molText.selectAll(); + if(e.getSource()==save) + { + if(InputFile.inputfetched==1) + { + int save = JOptionPane.showConfirmDialog(this,"Do you want to save the changes on the imported molecular coordinates","Warning",JOptionPane.YES_NO_OPTION); + if(save==0) + { + InputfileReader.geom = molText.getText(); + tempmol = InputfileReader.geom; + replaceInputFile(); + G03MenuTree.nanocadNotice.setText("Molecular Structure Updated"); + + + + } + else{ + //tempmol = molText.getText(); + } + + } + + + tempmol=molText.getText(); + System.out.println(" tempmol: "+tempmol); + new GeometryEditor(tempmol); + G03MenuTree.nanocadNotice.setText("Molecular Structure Updated"); + saved=1; + atomCoordinateParser.getCoordinates(); + } + if(e.getSource()==open) + { + molFrame.dispose(); + doFetchInputFile(); + new showMolEditor(); + molFrame.setVisible(true); + } + + + + + + if(e.getSource()==close) + { + if(molText.getText().length()==0 || (molText.getText().length()==tempmol.length()) ) + saved=1; + if(InputFile.inputfetched==1 && (molText.getText().length()==tempmol.length())) + saved=1; + + if(saved==0) // not saved + choiceclose= JOptionPane.showConfirmDialog(null,"The Changes you made will not be saved.Do you want to continue?","Do you want to Continue?",JOptionPane.YES_NO_OPTION); + if(choiceclose==0||saved==1) + molFrame.dispose(); + saved=0; + } + + + } + + public void windowOpened(WindowEvent e) {} + + public void windowClosing(WindowEvent e) + { + // check for temp file and if it exists, load into text box + System.err.println("load temp file here!"); + + + + + //File f = new File(defaultDirStr + + File f = new File(newNanocad.applicationDataDir + + fileSeparator + "tmp.txt"); + if ((f.exists()) )//&& !(f.isEmpty())) + { + try + { + BufferedReader inStream = new BufferedReader(new FileReader(f)); + String text = ""; + String line; + while ((line = inStream.readLine()) != null) + { + int n = line.length(); + if (n > 0) + { + text = text + line + "\n"; + System.err.println(line); + } + } + inStream.close(); + changeInputText(text); + } + + + + catch (IOException ioe) + { + System.err.println("IOException in editJobPanel"); + } + } + + + + nanWin.dispose(); + if (nanWin.nano.t != null) + nanWin.nano.t.setVisible(false); + + + //setVisible(false); + } + + public void windowClosed(WindowEvent e) + { + } + + public void windowIconified(WindowEvent e) {} + + public void windowDeiconified(WindowEvent e) {} + + public void windowActivated(WindowEvent e) {} + + public void windowDeactivated(WindowEvent e) {} + + public void componentMoved(ComponentEvent e) {} + public void componentResized(ComponentEvent e) {} + public void componentShown(ComponentEvent e) {} + public void componentHidden(ComponentEvent e) + { + System.err.println("load temp file here!"); + + + //File f = new File(legacy.editors.commons.Settings.defaultDirStr + + File f = new File(newNanocad.applicationDataDir + + Settings.fileSeparator + "tmp.txt"); + if ((f.exists()) )//&& !(f.isEmpty())) + { + try + { + BufferedReader inStream = new BufferedReader(new FileReader(f)); + String text = ""; + String line; + while ((line = inStream.readLine()) != null) + { + int n = line.length(); + if (n > 0) + { + text = text + line + "\n"; + System.err.println(line); + } + } + inStream.close(); + changeInputText(text); + } + catch (IOException ioe) + { + System.err.println("IOException in showMolEditor"); + } + } + try { + nanWin.dispose(); + //if (nanWin.nano.t.isActive()) + //if (nanWin.nano.t.isVisible()) + if (nanWin.nano.t !=null) + nanWin.nano.t.setVisible(false); + +// FIXME-SEAGrid +// if (stuffInside.selectedGUI == 0){ +// System.out.println(" G03 GUI is not selected. Printing Input Template Warning"+stuffInside.selectedGUI); +//F +// JOptionPane.showMessageDialog(null, "WARNING: The input" + +// " appearing here is taken from a template.\n" + +// "The molecule information is correct, but" + +// " make sure to edit \n the other parts of the" + +// " text.", +// "GridChem: Job Editor", +// JOptionPane.WARNING_MESSAGE); +// }else +// { +// JOptionPane.showMessageDialog(null, "WARNING: Molecule information" + +// " has been exported correctly. Make sure\n" + +// "to edit other sections of GUI.", +// "GridChem: Gaussian GUI", +// JOptionPane.WARNING_MESSAGE); +// } + } catch (HeadlessException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + +// displaying molecule on GUI panel after it has been exported to GUI from Nanocad + /* + tempmol=molText.getText(); + System.out.println("Printing: tempmol"+tempmol); + new GeometryEditor(tempmol); + G03MenuTree.nanocadNotice.setText("Molecular Structure Updated"); + saved=1; + atomCoordinateParser.getCoordinates(); + */ + + } + public void changeInputText(String i) + { + try { + // this.inputText = new JTextArea(i, 20,40); +//inputText.selectAll(); +//inputText.replaceSelection(i); +// inputText.append(i); +// String coordString=i; +// String chargMul=new String(G03MenuTree.molCharge.getText())+" "+G03MenuTree.molMultiplicity.getText(); +/* tempmol=new String(G03MenuTree.molCharge.getText()); + tempmol+=" "+G03MenuTree.molMultiplicity.getText();*/ + + //exportedMol=i; + tempmol=i; + //Set the Label in G03MenuTree + G03MenuTree.nanocadNotice.setText("Molecular Specification Imported from Nanocad"); + + + //tempmol+="\n"+i; + } catch (RuntimeException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + public void doCallNanocad() + { + + + + System.out.println(" Calling Nanocad"); + String setsfile = ".settings"; + boolean append = false; + File sets = new File(Settings.defaultDirStr + Settings.fileSeparator + + setsfile); + try + { + FileWriter fw = new FileWriter(sets, append); + fw.write("Username= " + Settings.username + "\n"); + fw.write("CGI= " + Settings.httpsGateway + "\n"); + fw.close(); + FileWriter fw2 = new FileWriter(Settings.defaultDirStr + Settings.fileSeparator + + "loadthis", append); + fw2.write(Settings.defaultDirStr + Settings.fileSeparator + + "common" + Settings.fileSeparator + "Molecule" + Settings.fileSeparator + + "Inorganic" + Settings.fileSeparator + + "water.pdb\n"); + fw2.close(); + } + catch (IOException ioe) {} + String tmpfile = "tmp.txt"; + + //File fa = new File(legacy.editors.commons.Settings.defaultDirStr+legacy.editors.commons.Settings.fileSeparator+tmpfile); + File fa = new File(newNanocad.applicationDataDir+ Settings.fileSeparator+tmpfile); + if ( fa.exists()) + { + fa.delete(); +// new File(legacy.editors.commons.Settings.defaultDirStr + legacy.editors.commons.Settings.fileSeparator + tmpfile).delete(); + } + // launch nanocad + System.out.println("Calling nanocadMain"); + nanWin = new nanocadFrame2(); + // WindowListener wl = new WindowListener(); + nanWin.addWindowListener(this); + nanWin.nano.addComponentListener(this); + + System.out.println(" Done with Nanocad"); +// System.err.println("Now put yer data from the file into the text thing"); + + + + } +} diff --git a/src/main/java/gamess/.DS_Store b/src/main/java/gamess/.DS_Store new file mode 100644 index 0000000..f00f9f1 Binary files /dev/null and b/src/main/java/gamess/.DS_Store differ diff --git a/src/main/java/gamess/._.DS_Store b/src/main/java/gamess/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/gamess/._.DS_Store differ diff --git a/src/main/java/gamess/ContentAssist.java b/src/main/java/gamess/ContentAssist.java new file mode 100644 index 0000000..93b81ba --- /dev/null +++ b/src/main/java/gamess/ContentAssist.java @@ -0,0 +1,675 @@ +package gamess; + +import java.awt.Component; +import java.awt.Cursor; +import java.awt.Rectangle; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Hashtable; + +import javax.swing.DefaultListModel; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JScrollPane; +import javax.swing.JTextPane; +import javax.swing.ListCellRenderer; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultStyledDocument; +import javax.swing.text.StyledDocument; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import gamess.Storage.Repository; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class ContentAssist{ + + private static ContentAssist instance = null; + public static void CreateInstance() + { + if(instance == null) + { + instance = new ContentAssist(); + } + } + + private JTextPane inputPane = GamessGUI.inputFilePane; + private StyledDocument inputStyles = GamessGUI.inputFilePane.getStyledDocument(); + private JScrollPane listScrollPane = null; + private JList list = null; + private DefaultListModel model = null; + + /** + * This is holds the complete list of the items currently displaying + */ + private ArrayList currentDisplayingList = new ArrayList(); + /** + * This is holds the complete list of the items currently displaying + */ + private ArrayList currentFilteredDisplayingList = new ArrayList(); + /** + * This is holds the complete list of the tooltips for all the items currently displaying + */ + private ArrayList currentToolTipList = new ArrayList(); + /** + * This is holds the complete list of the tooltips for the items currently displayed + */ + private ArrayList currentDisplayToolTipList = new ArrayList(); + private inputPaneListeners inputListeners = new inputPaneListeners(); + private listKeyAdapter listKeyListeners = new listKeyAdapter(); + private listMouseAdapter listMouseListeners = new listMouseAdapter(); + private XPath tooltipXpath = XPathFactory.newInstance().newXPath(); + boolean isControlKeyPressed = false; + int currentDisplayedOffset = 0; + String context = ""; + + private ContentAssist() + { + //Create the model and add the items to it + model = new DefaultListModel(); + for(int i=0;i < currentDisplayingList.size();i++) + { + model.addElement(currentDisplayingList.get(i)); + } + //Add the model to the JList + list = new JList(model); + list.setCellRenderer(new AssistRenderer()); + list.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); + list.addMouseListener(listMouseListeners); + list.addKeyListener(listKeyListeners); + list.setForeground(new java.awt.Color(0, 102, 0)); + + //Create the scroll pane over the list displayed + listScrollPane = new JScrollPane(list); + listScrollPane.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); + listScrollPane.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(102, 102, 102), 3, true)); + listScrollPane.setVisible(false); + listScrollPane.setSize(92, 100); + + //add the scrollpabe to the inputFilePane + GamessGUI.inputFilePane.add(listScrollPane); + GamessGUI.inputFilePane.addKeyListener(inputListeners); + GamessGUI.inputFilePane.addMouseListener(new inputPaneAdapter()); + + } + + + //This is used to show the assist in a new context or if it is not displayed + private void fire(boolean isForced) + { + if(getParagraphLine(getCaretPostion()).trim().length() > 0 && inputStyles.getParagraphElement(getCaretPostion()).getAttributes().containsAttributes(Cosmetics.COMMENTS_ATTRIBUTE)) + return; + setCurrentDisplayOffset(); + loadDisplayItems(isForced); + //Check if the event is consumed + if(inputListeners.currentEvent != null && inputListeners.currentEvent.isConsumed()) + return; + //if everything is proper show the intellisance + loadToolTipForDisplayItem(); + filter(); + showDropDownAtLocation(); + } + + private void filter() + { + String filterString = getCurrentPassedText(); + model.removeAllElements(); + currentFilteredDisplayingList = new ArrayList(); + currentDisplayToolTipList = new ArrayList(); + for (int i = 0; i < currentDisplayingList.size(); i++) { + if(currentDisplayingList.get(i).toUpperCase().startsWith(filterString.toUpperCase()) && currentDisplayingList.get(i).length() > filterString.length()) + { + currentFilteredDisplayingList.add(currentDisplayingList.get(i)); + currentDisplayToolTipList.add(currentToolTipList.get(i)); + } + } + for (int i = 0; i < currentFilteredDisplayingList.size(); i++) { + model.addElement(currentFilteredDisplayingList.get(i)); + } + if(currentFilteredDisplayingList.size() > 0) + list.setSelectedIndex(0); + } + + private void showDropDownAtLocation() + { + try + { + //Set the location of the dropdown to be showed + Rectangle cursor = inputPane.modelToView(currentDisplayedOffset); + // + setDownVisibleLocations(cursor); + if((cursor.y + cursor.height + listScrollPane.getHeight()) > inputPane.getHeight()) + { + //Setting visible down is not possible + //Try setting visible upside + if((cursor.y - listScrollPane.getHeight()) < 0) + { + //Setting visible upside is not possible + //Show it downwards + setDownVisibleLocations(cursor); + } + else + { + //You can show the list upside + //Show the list upside + setUpVisibleLocations(cursor); + } + } + + //Show the dropdown + listScrollPane.setVisible(true); + } + catch (BadLocationException e){ e.printStackTrace(); } + } + + private void setUpVisibleLocations(Rectangle rect) + { + listScrollPane.setLocation(rect.x, rect.y - listScrollPane.getHeight()); + } + + private void setDownVisibleLocations(Rectangle rect) + { + listScrollPane.setLocation(rect.x, rect.y + rect.height); + } + + private int getCaretPostion() + { + return inputPane.getCaretPosition(); + } + + private void setCurrentDisplayOffset() + { + int caretPostition = getCaretPostion(); + + int paragraphStartingIndex = inputStyles.getParagraphElement(caretPostition).getStartOffset(); + + currentDisplayedOffset = paragraphStartingIndex; + + String currentLine = getParagraphLine(caretPostition).substring(0, caretPostition - paragraphStartingIndex); + + //Get the last seperator + //Check for = + int equalIndex = paragraphStartingIndex + currentLine.lastIndexOf("=") + 1 ; + //if = later than currentDisplayedOffset update it + if(equalIndex > currentDisplayedOffset) + currentDisplayedOffset = equalIndex; + + //Check for ' ' + int spaceIndex = paragraphStartingIndex + currentLine.lastIndexOf(" ") + 1; + + //if ' ' later than currentDisplayedOffset update it + if(spaceIndex > currentDisplayedOffset) + currentDisplayedOffset = spaceIndex; + } + + private String getCurrentPassedText() + { + try + { + setCurrentDisplayOffset(); + return inputStyles.getText(currentDisplayedOffset, getCaretPostion() - currentDisplayedOffset); + } + catch(BadLocationException e){ e.printStackTrace(); } + return ""; + } + + + private void loadDisplayItems(boolean isForced) + { + //Get the contextinfo and load the details as needed + context = getContextInfo(currentDisplayedOffset); + //if context has nothing load groups + if(context.length() == 0) + { + loadGroups(); + return; + } + + context = context.toUpperCase(); + String[] splitString = context.split(" "); + + if(isForced) + { + Hashtable dialogs = Dictionary.dialogs; + if(splitString.length == 1 && dialogs.containsKey( Dictionary.getFormattedKeyword(splitString[0].substring(1))) ) + { + if(inputListeners.currentEvent != null) inputListeners.currentEvent.consume(); + dialogs.get( Dictionary.getFormattedKeyword(splitString[0].substring(1)) ).setVisible(true); + return; + } + else if(splitString.length == 2 && dialogs.containsKey( Dictionary.getFormattedKeyword(splitString[0].substring(1) + " " + splitString[1])) ) + { + if(inputListeners.currentEvent != null) inputListeners.currentEvent.consume(); + dialogs.get( Dictionary.getFormattedKeyword(splitString[0].substring(1) + " " + splitString[1]) ).setVisible(true); + return; + } + } + + //if there is no group ending then include $END + //if context has group load keywords + if(splitString.length == 1) + loadKeywords(splitString[0].substring(1)); + //if context has group and keywords load values + else loadValues(splitString[0].substring(1), splitString[1]); + } + + private String getContextInfo(int location) + { + //Search back for the $ sign + //if there is no $ word or the word is $END then return "" + String stringBefore = null; + try { + stringBefore = inputStyles.getText(0, location); + } catch (BadLocationException e) {e.printStackTrace();} + + int groupStartingIndex = stringBefore.lastIndexOf("$"); + //if there is no $ symbol then send "" as group should be displayed + if(groupStartingIndex == -1) + return ""; + + String Group = getWordAfter(groupStartingIndex); + //if the group is $END then send "" as group should be displayed + if(Group.equalsIgnoreCase("$END")) + return ""; + + //if the word is other than $END load the group and keywords + //if the word just before this is = load values + int paraStartOffset = inputStyles.getParagraphElement(location).getStartOffset(); + String wordLine = getParagraphLine(location); + int lineOffset = location - paraStartOffset; + wordLine = wordLine.substring(0, lineOffset); + + if(wordLine.trim().endsWith("=")) + { + //to load the values + //Get the keyword + int equalIndex = wordLine.lastIndexOf("="); + wordLine = wordLine.substring(0, equalIndex).trim(); + int keywordStarting = wordLine.lastIndexOf(" "); + keywordStarting++; + //return the group and the keyword + return Group + " " + wordLine.substring(keywordStarting); + } + else + { + //to load the keywords + //return the group + return Group; + } + } + + + private void loadGroups() + { + Repository db = Repository.getInstance(); + currentDisplayingList = new ArrayList(); + //Get all the groups + Element groupRoot = Dictionary.get(); + if(groupRoot == null) return; + + NodeList groups = groupRoot.getChildNodes(); + //Load the groups + for (int i = 0; i < groups.getLength(); i++) { + //Remove the group that is already available here + String GroupName = groups.item(i).getNodeName(); + //Add if the group is not available + if( ! db.isAvailable(GroupName)) + currentDisplayingList.add("$" + groups.item(i).getNodeName()); + } + Collections.sort(currentDisplayingList); + } + + + private void loadKeywords(String group) + { + Repository db = Repository.getInstance(); + currentDisplayingList = new ArrayList(); + //Check if the group has an $END else add it + String stringAfter = getText(getCaretPostion(), inputStyles.getLength()); + int groupStartPosition = stringAfter.indexOf("$"); + if(groupStartPosition == -1) + currentDisplayingList.add("$END"); + else + { + groupStartPosition += getCaretPostion(); + //if the group at groupStartPosition is not $END then add it + if(!getWordAfter(groupStartPosition).equalsIgnoreCase("$END")) + currentDisplayingList.add("$END"); + } + + //Get all the keywords for the groups + Element groupRoot = Dictionary.get(group); + if(groupRoot == null) return; + + NodeList groups = groupRoot.getChildNodes(); + //Load the groups + for (int i = 0; i < groups.getLength(); i++) { + String loadingKeyword = groups.item(i).getNodeName(); + //Remove the group that is already available here + //load if the keyword is not a textvalue or a text dialog or a grid dialog + //And if keyword is not available + if( !(loadingKeyword.equals(Dictionary.TEXTBOX_VALUE) || loadingKeyword.equals(Dictionary.TEXT_DIALOG) || loadingKeyword.equals(Dictionary.GRID_DIALOG) || loadingKeyword.equals(Dictionary.CUSTOM_DIALOG)) ) + if(!db.isAvailable(group, loadingKeyword)) + currentDisplayingList.add(loadingKeyword.replace("__", "(").replace("_", ")")); + } + Collections.sort(currentDisplayingList); + } + + + private void loadValues(String group, String keyword) + { + currentDisplayingList = new ArrayList(); + //Check if the group has an $END else add it + String stringAfter = getText(getCaretPostion(), inputStyles.getLength()); + int groupStartPosition = stringAfter.indexOf("$"); + if(groupStartPosition == -1) + currentDisplayingList.add("$END"); + else + { + groupStartPosition += getCaretPostion(); + //if the group at groupStartPosition does not start with $E then add it + if(!getWordAfter(groupStartPosition).equalsIgnoreCase("$END")) + currentDisplayingList.add("$END"); + } + + //Get all the values for the keyword in the groups + Element groupRoot = Dictionary.get(group,keyword); + if(groupRoot == null) return; + + NodeList groups = groupRoot.getChildNodes(); + //Load all the values + for (int i = 0; i < groups.getLength(); i++) { + String loadingValue = groups.item(i).getAttributes().getNamedItem("value").getNodeValue(); + //load if the value is not a textvalue or a text dialog or a grid dialog + if( !(loadingValue.equals(Dictionary.TEXTBOX_VALUE) || loadingValue.equals(Dictionary.TEXT_DIALOG) || loadingValue.equals(Dictionary.GRID_DIALOG) || loadingValue.equals(Dictionary.CUSTOM_DIALOG)) ) + currentDisplayingList.add(loadingValue); + } + Collections.sort(currentDisplayingList); + } + + private String getWordAfter(int location) + { + String wordLine = getParagraphLine(location); + + location -= inputStyles.getParagraphElement(location).getStartOffset(); + + int wordEnding = wordLine.indexOf(" ", location); + wordEnding = (wordEnding == -1)? wordLine.length() - 1: wordEnding; + + return wordLine.substring(location, wordEnding); + } + + @SuppressWarnings("unused") + private String getWordBefore(int location) + { + String wordLine = getParagraphLine(location); + + int wordStarting = wordLine.lastIndexOf(" ", location); + wordStarting++; + + return wordLine.substring(wordStarting, location); + } + + private String getParagraphLine(int location) + { + try { + javax.swing.text.Element paraElement = inputStyles.getParagraphElement(location); + String paraLine = inputStyles.getText(paraElement.getStartOffset(), paraElement.getEndOffset() - paraElement.getStartOffset()); + return paraLine; + } catch (BadLocationException e) {e.printStackTrace();} + return ""; + } + + private String getText(int startLoc , int EndLoc) + { + try { + return inputStyles.getText(startLoc, EndLoc - startLoc); + } catch (BadLocationException e) {e.printStackTrace();} + return ""; + } + + private void loadToolTipForDisplayItem() + { + currentToolTipList = new ArrayList(); + + String Group = null ,Keyword = null; + String[] splitString = context.split(" "); + + if(context.length() != 0 && splitString.length > 0) + { + Group = splitString[0].substring(1); + } + if(splitString.length > 1) + { + Keyword = splitString[1]; + } + + for (int i = 0; i < currentDisplayingList.size(); i++) { + String currentItem = currentDisplayingList.get(i); + if(currentItem.equalsIgnoreCase("$END")) + { + currentToolTipList.add("Group ending"); + continue; + } + + String xpathCondExpr = "/root/ToolTips/ToolTip["; + + if(Group == null) + { + //The item is a group + xpathCondExpr += "@Group='" + currentItem.substring(1) + "' and not(@Keyword) and not(@Value)"; + } + else if(Keyword == null) + { + //The item is a keyword + xpathCondExpr += "@Group='" + Group + "' and @Keyword='" + Dictionary.getFormattedKeyword(currentItem) + "' and not(@Value)"; + } + else + { + //The item is a value + xpathCondExpr += "@Group='" + Group + "' and @Keyword='" + Dictionary.getFormattedKeyword(Keyword) + "' and @Value='" + currentItem + "'"; + } + + xpathCondExpr += "]"; + + try + { + Node tooltipNode = (Node)tooltipXpath.evaluate( xpathCondExpr ,GlobalParameters.userNotesAndToolTip, XPathConstants.NODE); + if(tooltipNode == null) + currentToolTipList.add(null); + else + currentToolTipList.add( Cosmetics.getInputFileToolTip(tooltipNode.getTextContent().trim())); + } + catch (XPathExpressionException e) + { + currentToolTipList.add(null); + } + } + } + + private class inputPaneListeners extends KeyAdapter + { + KeyEvent currentEvent = null; + public void keyPressed(KeyEvent evt) { + currentEvent = evt; + //if ENTER is pressed and the list is visible then get the + //value selected in the list and insert it into the textpane + //if ESC is pressed and the list is visible then close the list + //if UP or DOWN is pressed and the list is visible then move the selection + if(!isControlKeyPressed && + (evt.getKeyCode() == KeyEvent.VK_ENTER + || evt.getKeyCode() == KeyEvent.VK_TAB + || evt.getKeyCode() == KeyEvent.VK_ESCAPE + || evt.getKeyCode() == KeyEvent.VK_UP + || evt.getKeyCode() == KeyEvent.VK_DOWN + ) + ) + listKeyListeners.keyPressed(evt); + + //if CTRL + ' ' is pressed force the ContentAssist to show + if(isControlKeyPressed && evt.getKeyCode() == KeyEvent.VK_SPACE) + fire(true); + + if(evt.getKeyCode() == KeyEvent.VK_CONTROL) + isControlKeyPressed = true; + else + isControlKeyPressed = false; + currentEvent = null; + } + + public void keyReleased(KeyEvent evt) { + currentEvent = evt; + //if the space or equalTo or an enter is pressed then + //display either Group or Keyword or Value based on the context + if(!isControlKeyPressed && + (evt.getKeyCode() == KeyEvent.VK_SPACE // ' ' + || evt.getKeyCode() == KeyEvent.VK_EQUALS // = + ) + ) + { + try { + if(evt.getKeyCode() == KeyEvent.VK_SPACE && getCaretPostion() != inputStyles.getLength() && !inputStyles.getText(getCaretPostion(), 1).equals(" ")) + return; + } catch (BadLocationException e) {} + fire(false); + } + + if(!(evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_DOWN)) + listKeyListeners.keyPressed(evt); + + currentEvent = null; + } + } + + private class inputPaneAdapter extends MouseAdapter + { + public void mouseClicked(java.awt.event.MouseEvent evt) { + listScrollPane.setVisible(false); + } + } + + private class listKeyAdapter extends KeyAdapter + { + public void keyPressed(KeyEvent evt) { + if(!listScrollPane.isVisible()) + return; + + if(evt.getKeyCode() == KeyEvent.VK_ENTER || evt.getKeyCode() == KeyEvent.VK_TAB) + { + if(list.getSelectedValue() != null) + { + try + { + String stringToInsert = list.getSelectedValue().toString(); + String filterString = getCurrentPassedText(); + if(stringToInsert.toUpperCase().startsWith(filterString.toUpperCase())) + stringToInsert = stringToInsert.substring(filterString.length()); + ((DefaultStyledDocument)inputStyles).replace(getCaretPostion(), 0 , stringToInsert, null); + + /*//This is to replace the remaining part of the keywords with the current keyword completely + * + int paragraphEndPosition = inputStyles.getParagraphElement(getCaretPostion()).getEndOffset(); + if(inputStyles.getLength() == 0) paragraphEndPosition = 0; + int endPosition = inputStyles.getText(getCaretPostion(), paragraphEndPosition - getCaretPostion()).indexOf(" "); + if(endPosition == -1) endPosition = paragraphEndPosition - 1 ; + else endPosition += getCaretPostion(); + + ((DefaultStyledDocument)inputStyles).replace(getCaretPostion(), endPosition - getCaretPostion(), stringToInsert, null); + */ + } + catch(Exception e){ e.printStackTrace(); } + UndoRedoHandler.toggleGroupClassifier(); + } + listScrollPane.setVisible(false); + inputPane.requestFocus(); + evt.consume(); + return; + } + if(evt.getKeyCode() == KeyEvent.VK_ESCAPE) + { + listScrollPane.setVisible(false); + inputPane.requestFocus(); + evt.consume(); + return; + } + if(evt.getKeyCode() == KeyEvent.VK_DOWN) + { + int selectedIndex = (list.getSelectedIndex() < list.getModel().getSize() - 1)?list.getSelectedIndex() + 1:0; + list.setSelectedIndex(selectedIndex); + list.ensureIndexIsVisible(selectedIndex); + evt.consume(); + return; + } + if(evt.getKeyCode() == KeyEvent.VK_UP) + { + list.setSelectedIndex((list.getSelectedIndex() > 0)?list.getSelectedIndex() - 1:list.getModel().getSize() - 1); + list.ensureIndexIsVisible(list.getSelectedIndex()); + evt.consume(); + return; + } + if(evt.getKeyCode() == KeyEvent.VK_BACK_SPACE) + { + if(getCaretPostion() < currentDisplayedOffset) + { + listScrollPane.setVisible(false); + evt.consume(); + } + else + filter(); + return; + } + //if the list is visible and if it is not any of the actions above then filter the text + filter(); + } + + + } + + private class listMouseAdapter extends MouseAdapter + { + public void mouseClicked(java.awt.event.MouseEvent evt) { + if(evt.getClickCount() == 2) + listKeyListeners.keyPressed(new KeyEvent(list,0,0L,0,KeyEvent.VK_ENTER,'\n')); + } + } + + private class AssistRenderer extends JLabel implements ListCellRenderer + { + private static final long serialVersionUID = -5243578200443821114L; + + public AssistRenderer() + { + setOpaque(true); + } + + public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) + { + if(isSelected) + { + setBackground(list.getSelectionBackground()); + setForeground(list.getSelectionForeground()); + } + else + { + setBackground(list.getBackground()); + if(value != null && value.toString().startsWith("$")) + setForeground(Cosmetics.GROUP_ATTRIBUTE_COLOR); + else + setForeground(list.getForeground()); + } + //Set Text + setText(value.toString()); + //Set the tool tips if present + setToolTipText(currentDisplayToolTipList.get(index)); + return this; + } + } +} diff --git a/src/main/java/gamess/Cosmetics.java b/src/main/java/gamess/Cosmetics.java new file mode 100644 index 0000000..82fa385 --- /dev/null +++ b/src/main/java/gamess/Cosmetics.java @@ -0,0 +1,126 @@ +package gamess; + +import java.awt.Color; + +import javax.swing.text.AttributeSet; +import javax.swing.text.Element; +import javax.swing.text.SimpleAttributeSet; +import javax.swing.text.StyleConstants; +import javax.swing.text.StyledDocument; +import javax.swing.text.Highlighter.HighlightPainter; + +public class Cosmetics +{ + //Underliners + private static final WavedUnderlinePen ERROR_UNDERLINE_PEN = new WavedUnderlinePen(Color.RED); + private static final WavedUnderlinePen WARNING_UNDERLINE_PEN = new WavedUnderlinePen(Color.YELLOW); + + //Attributes + public static final SimpleAttributeSet NORMAL_ATTRIBUTE = new SimpleAttributeSet(); + public static final SimpleAttributeSet GROUP_ATTRIBUTE = new SimpleAttributeSet(); + public static final SimpleAttributeSet COMMENTS_ATTRIBUTE = new SimpleAttributeSet(); + public static final SimpleAttributeSet KEYWORD_ATTRIBUTE = new SimpleAttributeSet(); + public static final SimpleAttributeSet ERROR_UNDERLINE = new SimpleAttributeSet(); + public static final SimpleAttributeSet WARNING_UNDERLINE = new SimpleAttributeSet(); + + //Colors + public static final Color NORMAL_ATTRIBUTE_COLOR = Color.BLACK; + public static final Color GROUP_ATTRIBUTE_COLOR = Color.RED; + public static final Color KEYWORD_ATTRIBUTE_COLOR = Color.BLUE; + + static + { + //Normal AttributeSet + StyleConstants.setForeground(NORMAL_ATTRIBUTE, NORMAL_ATTRIBUTE_COLOR); + StyleConstants.setBold(NORMAL_ATTRIBUTE, false); + + + //Group AttributeSet + //StyleConstants.setForeground(GROUP_ATTRIBUTE, Color.getHSBColor(4.83456203f,.67f,.44f)); + StyleConstants.setForeground(GROUP_ATTRIBUTE, GROUP_ATTRIBUTE_COLOR); + StyleConstants.setBold(GROUP_ATTRIBUTE, true); + + //Comment AttributeSet + StyleConstants.setForeground(COMMENTS_ATTRIBUTE, Color.getHSBColor(1.35f, .63f, .71f)); + StyleConstants.setBold(COMMENTS_ATTRIBUTE, false); + + //Keyword attribute + StyleConstants.setForeground(KEYWORD_ATTRIBUTE, KEYWORD_ATTRIBUTE_COLOR); + StyleConstants.setBold(KEYWORD_ATTRIBUTE, false); + + //Error Underline + ERROR_UNDERLINE.addAttribute("UNDERLINEPEN", ERROR_UNDERLINE_PEN); + + //Warning Underline + WARNING_UNDERLINE.addAttribute("UNDERLINEPEN", WARNING_UNDERLINE_PEN); + } + + public static final SimpleAttributeSet getCustomAttribute(String key, Object value) + { + SimpleAttributeSet toolTipAttribute = new SimpleAttributeSet(); + toolTipAttribute.addAttribute(key, value); + return toolTipAttribute; + } + + public static final SimpleAttributeSet getCustomAttribute(String key, Object value, AttributeSet existingAttribute) + { + SimpleAttributeSet toolTipAttribute = getCustomAttribute(key, value); + if(existingAttribute != null) + { + toolTipAttribute.setResolveParent(existingAttribute); + } + return toolTipAttribute; + } + + public static final void setCharacterAttributes(int startOffset , int length , AttributeSet attribute, boolean replace) + { + StyledDocument styledDocument = GamessGUI.inputFilePane.getStyledDocument(); + Element element = null; + element = styledDocument.getCharacterElement(startOffset); + + //Do not do anything if the element already contains the same attribute + if(element.getAttributes().containsAttributes(attribute) && replace == false) + return; + styledDocument.setCharacterAttributes(startOffset, length, attribute, replace); + } + + public static final void setParagraphAttributes(int startOffset , int length , AttributeSet attribute) + { + StyledDocument styledDocument = GamessGUI.inputFilePane.getStyledDocument(); + Element element = null; + element = styledDocument.getParagraphElement(startOffset); + //Do not do anything if the element already contains the same attribute + if(element.getAttributes().containsAttributes(attribute)) + return; + styledDocument.setParagraphAttributes(startOffset, length, attribute, true); + setCharacterAttributes(startOffset, length, attribute, true); + } + + public static final void setUnderline(int startOffset , int length , AttributeSet attribute) + { + StyledDocument styledDocument = GamessGUI.inputFilePane.getStyledDocument(); + styledDocument.setCharacterAttributes(startOffset, length, getCustomAttribute("UNDERLINE", (HighlightPainter)attribute.getAttribute("UNDERLINEPEN")), false); + } + + public static final void setTooltip(int startOffset , int length , String tooltip) + { + StyledDocument styledDocument = GamessGUI.inputFilePane.getStyledDocument(); + styledDocument.setCharacterAttributes(startOffset, length, getCustomAttribute("TOOLTIP", tooltip), false); + } + + public static final String getFormattedToolTip(String tooltip) + { + //previous value was #E6BE8A + return "" + tooltip.replace("\n", "
") + ""; + } + + public static final String getInputFileToolTip(String tooltip) + { + return "" + tooltip.replace("\n", "
") + ""; + } + + public static final String getMenuToolTip(String tooltip) + { + return "" + tooltip.replace("\n", "
") + ""; + } +} diff --git a/src/main/java/gamess/Dialogs/FormatParser.java b/src/main/java/gamess/Dialogs/FormatParser.java new file mode 100644 index 0000000..dd0827c --- /dev/null +++ b/src/main/java/gamess/Dialogs/FormatParser.java @@ -0,0 +1,530 @@ +package gamess.Dialogs; + +import java.util.Hashtable; + +import gamess.GlobalParameters; +import gamess.InputFileHandlers.InputFileReader; +import gamess.Storage.Repository; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + + +public class FormatParser +{ + private static Hashtable formatLookup = new Hashtable(); + + public static FormatParser getFormat(String Group, String Keyword, Node currentNode) + { + //Check if the format is already available + FormatParser formatParser = formatLookup.get(Group + " " + Keyword); + if(formatParser == null) + { + //the format is not available + //create a new format + formatParser = new FormatParser(Group,Keyword,currentNode); + //add it to the lookup + formatLookup.put(Group + " " + Keyword, formatParser); + } + return formatParser; + } + + ///////////////////////////////////////////////////////////// + + private enum inputType {String,Int,Float,Double}; + private boolean isInfinity = false; + inputType type = inputType.Int; + String Count = null; + String Minimum = null; + String Maximum = null; + String Default = null; + String Group = null; + String Keyword = null; + String Reason = null; + + private FormatParser(String _Group, String _Keyword, Node currentNode) + { + Group = _Group; + Keyword = _Keyword; + //Type + if(currentNode == null ) + { + type = inputType.String; + return; + } + NamedNodeMap attributes = currentNode.getAttributes(); + if(attributes.getNamedItem("Type") != null) + { + String valueType = attributes.getNamedItem("Type").getNodeValue(); + if(valueType.equalsIgnoreCase("String")) + { + type = inputType.String; + } + else if(valueType.equalsIgnoreCase("Int")) + { + type = inputType.Int; + } + else if(valueType.equalsIgnoreCase("Float")) + { + type = inputType.Float; + } + else if(valueType.equalsIgnoreCase("Double")) + { + type = inputType.Double; + } + } + //Count + if(attributes.getNamedItem("Count") != null) + Count = attributes.getNamedItem("Count").getNodeValue(); + if(Count != null && Count.equals("...")) + isInfinity = true; + //Min + if(attributes.getNamedItem("Min") != null) + Minimum = attributes.getNamedItem("Min").getNodeValue(); + //Max + if(attributes.getNamedItem("Max") != null) + Maximum = attributes.getNamedItem("Max").getNodeValue(); + //Default + Default = currentNode.getTextContent().trim(); + } + + public boolean isConsistent(String Value) + { + if(Value == null || Value.length() == 0) + return true; + + //if it is a string return true + if(type == inputType.String) + return true; + //otherwise it should be either Integer/Float/Double + String[] values = Value.split(","); + int count = getCount(); + //Check if it is infinity + if(isInfinity) + count = values.length; + + //Check if the count is matching with the no of values available + //if not return false + if(count != values.length) + { + //Not a proper format. Missing some values. Format is [count] + Reason = "The must be " + count + " values seperated by comma."; + return false; + } + + //Test the values one by one and evaluate + for (int i = 0; i < count; i++) { + Number numberValue = null; + try + { + numberValue = getValue(values[i].trim()); + } + catch (NumberFormatException e) { + //Not a proper format. Invalid value. Format is [count] + Reason = "Please type a valid number format"; + return false; + } + if(!testRange(numberValue)) + return false; + } + + return true; + } + + public boolean isDefault(String Value) + { + //if the user is completely removing the value then it is set to default + if(Value == null || Value.length() == 0) + return true; + //Check if it is string + if(type == inputType.String) + { + if( Value.equalsIgnoreCase(Default)) + return true; + return false; + } + //otherwise it should be either Integer/Float/Double + String[] values = Value.split(","); + String[] defaults = null; + if(Default != null) + defaults = getDefault(values.length).split(","); + + if(defaults.length == 0 || values.length != defaults.length) + return false; + + int count = getCount(); + //Check if it is infinity + if(isInfinity) + count = values.length; + + //compare the values and the defaults + for (int i = 0; i < count; i++) { + Number inputValues = null , defaultValue = null; + try + { + inputValues = getValue(values[i]); + defaultValue = getValue(defaults[i]); + switch (type) { + case Int: + if(inputValues.intValue() != defaultValue.intValue()) + return false; + break; + case Float: + if(inputValues.floatValue() != defaultValue.floatValue()) + return false; + break; + case Double: + if(inputValues.doubleValue() != defaultValue.doubleValue()) + return false; + break; + } + } + catch (NumberFormatException e) { + //Default values are not in proper format + return false; + } + } + + return true; + } + + public String getDefault(int valueCount) + { + //Build the dynamic default value + if(Default.endsWith("...")) + { + if(valueCount == -1) + return Default; + + StringBuilder dynamicDefault = new StringBuilder(); + + String CurrentDefault = Default; + int recursionIndex = -1; + int count = isInfinity?valueCount:getCount(); + + //Check if there is a sub structure like 1,{0... + if( (recursionIndex = Default.indexOf(",{")) != -1) + { + CurrentDefault = Default.substring(recursionIndex + 2); + String InitialValues = Default.substring(0, recursionIndex); + dynamicDefault.append(InitialValues); + count -= InitialValues.split(",").length; + } + // + String[] defaultValues = CurrentDefault.replace("...", "").split(","); + + for (int i = 0, currentDefaultValuePosition = 0; i < count; i++, + currentDefaultValuePosition = (currentDefaultValuePosition == defaultValues.length-1)?0:(currentDefaultValuePosition + 1)) + { + if(dynamicDefault.length() != 0) + dynamicDefault.append(","); + dynamicDefault.append(defaultValues[currentDefaultValuePosition]); + } + return dynamicDefault.toString(); + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // // + + //TODO HARDCODE VALUES HERE + ValueReader reader = new ValueReader(); + //NRAD0 , NTHE0 , NPHI0 + if(Group.equalsIgnoreCase("DFT") && (Keyword.equalsIgnoreCase("NRAD0") || Keyword.equalsIgnoreCase("NTHE0") || Keyword.equalsIgnoreCase("NPHI0"))) + { + String NRAD = reader.Read("DFT", "NRAD") , NTHE = reader.Read("DFT", "NTHE") , NPHI = reader.Read("DFT", "NPHI"); + int nNRAD = (NRAD == null)?96:Integer.parseInt(NRAD) , nNTHE = (NTHE == null)?12:Integer.parseInt(NTHE) , nNPHI = (NPHI == null)?24:Integer.parseInt(NPHI); + if(Keyword.equalsIgnoreCase("NRAD0")) + { + if(nNRAD== 96 && nNTHE == 12 && nNPHI == 24) + return "24"; + return Float.toString(Math.max(nNRAD/4, 24)); + } + if(Keyword.equalsIgnoreCase("NTHE0")) + { + if(nNRAD== 96 && nNTHE == 12 && nNPHI == 24) + return "8"; + return Float.toString(Math.max(nNTHE/3, 8)); + } + if(Keyword.equalsIgnoreCase("NPHI0")) + { + if(nNRAD== 96 && nNTHE == 12 && nNPHI == 24) + return "16"; + return Float.toString(Math.max(nNPHI/3, 16)); + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + if(Group.equalsIgnoreCase("RELWFN") && Keyword.equalsIgnoreCase("QRTOL")) + { + if(reader.isAvailable("CONTRL", "RELWFN=RESC")) + { + String QMTTOL = reader.Read("RELWFN", "QMTTOL"); + float nQMTTOL = (QMTTOL == null)?0:getValue(QMTTOL).floatValue(); + return Float.toString((float)Math.min(1.0E-8, nQMTTOL)); + } + else if(reader.isAvailable("CONTRL", "RELWFN=DK")) + { + return "1.0E-2"; + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + if(Group.equalsIgnoreCase("STATPT") && Keyword.equalsIgnoreCase("TRMAX")) + { + if(reader.isAvailable("CONTRL","RUNTYP=OPTIMIZE")) + return "0.5"; + if(reader.isAvailable("CONTRL","RUNTYP=SADPOINT")) + return "0.3"; + } + + if(Group.equalsIgnoreCase("STATPT") && Keyword.equalsIgnoreCase("NNEG")) + { + if(reader.isAvailable("CONTRL","RUNTYP=OPTIMIZE")) + return "0"; + if(reader.isAvailable("CONTRL","RUNTYP=SADPOINT")) + return "1"; + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + if(Group.equalsIgnoreCase("TRANST") && Keyword.equalsIgnoreCase("NSTATE")) + { + if(reader.isAvailable("TRANST","IROOTS")) + return reader.Read("TRANST","IROOTS"); + else + return "1"; + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + if(Group.equalsIgnoreCase("CIDET") || Group.equalsIgnoreCase("CIGEN") || Group.equalsIgnoreCase("DET") || Group.equalsIgnoreCase("GEN")) + { + if(Keyword.equalsIgnoreCase("NSTGSS")) + { + if(reader.isAvailable(Group.toUpperCase(),"NSTATE")) + return reader.Read(Group.toUpperCase(),"NSTATE"); + else + return "1"; + } + + if(Keyword.equalsIgnoreCase("MXXPAN")) + { + if(reader.isAvailable(Group.toUpperCase(),"NSTATE")) + { + String NSTGSS = reader.Read(Group.toUpperCase(),"NSTGSS"); + int iNSTGSS = 0; + if( (iNSTGSS = Integer.parseInt(NSTGSS) * 2) > 10) + return String.valueOf(iNSTGSS); + else + return "10"; + } + else + return "10"; + } + } + + // // + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + //Return the normal default + return Default; + } + + private int getCount() + { + //Check if this is referres some other key + if(Count != null && Count.startsWith("$")) + { + String[] dataSplit = Count.split(" "); + if(dataSplit.length >= 2 ) + { + //Get the referred value + String referredValue = new ValueReader().Read(dataSplit[0].substring(1), dataSplit[1]); + int returnValue = 0; + if(referredValue == null) + { + referredValue = "0"; + } + else + { + returnValue = Integer.parseInt(referredValue); + } + + + + ////////////////////////////////////////////////////////////////////////////// + // // + + //TODO HARDCODED VALUES + if(Group.equalsIgnoreCase("SCF") && Keyword.equalsIgnoreCase("CICOEF")) + returnValue *= 2; + + ////////////////////////////////////////////////////////////////////////////// + + if(Group.equalsIgnoreCase("EOMNIP") && Keyword.equalsIgnoreCase("MOACT")) + { + referredValue = new ValueReader().Read("EOMNIP", "NUACT"); + if(referredValue == null) + referredValue = "0"; + + returnValue += Integer.parseInt(referredValue); + } + + ////////////////////////////////////////////////////////////////////////////// + + if(Group.equalsIgnoreCase("TDHF") && Keyword.equalsIgnoreCase("FREQ")) + returnValue = (new ValueReader().Read(dataSplit[0].substring(1), dataSplit[1]) == null)?1:returnValue; + + ////////////////////////////////////////////////////////////////////////////// + + if(Group.equalsIgnoreCase("ORMAS") && dataSplit[1].equalsIgnoreCase("NSPACE")) + returnValue = (referredValue == null)?1:returnValue; + + // // + ////////////////////////////////////////////////////////////////////////////// + + //Return the integer version of the referred value + return returnValue; + } + else { + return 0; + } + } + //Check if the count is not null + if(Count != null && !Count.equals("...")) + { + //Write the Hardcoded expressions here + return Integer.parseInt(Count); + } + //if count is null return 1 + return 1; + } + private Number getValue(String value) throws NumberFormatException + { + switch (type) + { + case Int: + return Integer.parseInt(value); + case Float: + return Float.parseFloat(value); + case Double: + return Double.parseDouble(value); + default: + break; + } + return null; + } + + private boolean testRange(Number value) + { + try + { + if(testMin(value) == false) + { + //Number is not within range + Reason = "The number should be >= (greaterthan or equal to) " + Minimum + "."; + return false; + } + } + catch (NumberFormatException e) { + //Minimum cannot be parsed + return false; + } + try + { + if(testMax(value)== false) + { + //Number is not within range + Reason = "The number should be <= (lessthan or equal to) " + Minimum + "."; + return false; + } + } + catch (NumberFormatException e) { + //Maximum cannot be parsed + return false; + } + + return true; + } + + private boolean testMin(Number Value) throws NumberFormatException + { + if(Minimum != null) + { + //TODO Hardcode values here. change the maximum here + switch (type) + { + case Int: + //if the value is less than the minimum then return false + if(Value.intValue() < getValue(Minimum).intValue()) + return false; + return true; + case Float: + //if the value is less than the minimum then return false + if(Value.floatValue() < getValue(Minimum).floatValue()) + return false; + return true; + case Double: + //if the value is less than the minimum then return false + if(Value.doubleValue() < getValue(Minimum).doubleValue()) + return false; + return true; + } + } + return true; + } + + private boolean testMax(Number Value) throws NumberFormatException + { + if(Maximum != null) + { + //TODO Hardcode values here. change the maximum here + switch (type) + { + case Int: + //if the value is greater than the maximum then return false + if(Value.intValue() > getValue(Maximum).intValue()) + return false; + return true; + case Float: + //if the value is greater than the maximum then return false + if(Value.floatValue() > getValue(Maximum).floatValue()) + return false; + return true; + case Double: + //if the value is greater than the maximum then return false + if(Value.doubleValue() > getValue(Maximum).doubleValue()) + return false; + return true; + } + } + return true; + } + + private class ValueReader + { + Repository DB = Repository.getInstance(); + InputFileReader reader = InputFileReader.getInstance(); + + public boolean isAvailable(String Group, String Keyword) + { + //Check if the dialog is opened or is called from update file + //if the dialog is opeaned then the application will be in provisional mode + if(GlobalParameters.isProvisionalMode) + return DB.isAvailable(Group, Keyword); + else + return reader.isAvailable(Group, Keyword); + } + + public String Read(String Group, String Keyword) + { + //Check if the dialog is opened or is called from update file + //if the dialog is opeaned then the application will be in provisional mode + if(GlobalParameters.isProvisionalMode) + return DB.Retrieve(Group, Keyword); + else + return reader.Read(Group, Keyword); + } + } +} \ No newline at end of file diff --git a/src/main/java/gamess/Dialogs/HelpDisplayer.java b/src/main/java/gamess/Dialogs/HelpDisplayer.java new file mode 100644 index 0000000..7c17bf5 --- /dev/null +++ b/src/main/java/gamess/Dialogs/HelpDisplayer.java @@ -0,0 +1,84 @@ +/*Copyright (c) 2007, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ +/** + * @author Michael Sheetz + * @author Shreeram Sridharan + */ + +package gamess.Dialogs; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import javax.swing.JDialog; +import javax.swing.JEditorPane; +import javax.swing.JFrame; +import javax.swing.JScrollPane; + +public class HelpDisplayer extends JDialog { + + private static final long serialVersionUID = -2305486391181499543L; + private JEditorPane hlpedt = null; + private JScrollPane scrlPane = null; + public HelpDisplayer(JFrame parentFrame , String url) + { + super(parentFrame); + setTitle("GAMESS Input GUI Help"); + this.setLayout(new BorderLayout()); + hlpedt = new JEditorPane(); + scrlPane = new JScrollPane(); + scrlPane.setViewportView(hlpedt); + hlpedt.setEditable(false); + this.setSize(new Dimension(500,600)); + getContentPane().add(scrlPane , BorderLayout.CENTER); + try { + String text = "", temp; + BufferedReader reader = new BufferedReader(new FileReader(new File(url))); + temp = reader.readLine(); + while(temp != null && !temp.isEmpty()){ + text += temp; + temp = reader.readLine(); + } + hlpedt.setText(text); + } catch (IOException e) { + e.printStackTrace(); + } + hlpedt.setAutoscrolls(true); + } +} diff --git a/src/main/java/gamess/Dialogs/IMenuTableCellTester.java b/src/main/java/gamess/Dialogs/IMenuTableCellTester.java new file mode 100644 index 0000000..4c2fc22 --- /dev/null +++ b/src/main/java/gamess/Dialogs/IMenuTableCellTester.java @@ -0,0 +1,14 @@ +package gamess.Dialogs; + +public interface IMenuTableCellTester +{ + void recomputeConsistency(); + boolean isConsistent(); + boolean isDefault(); + String getGroup(); + String getKeyword(); + String getValue(); + void setGroup(String Group); + void setKeyword(String Keyword); + void resetValues(); +} diff --git a/src/main/java/gamess/Dialogs/MatrixDialog.java b/src/main/java/gamess/Dialogs/MatrixDialog.java new file mode 100644 index 0000000..5b9d84f --- /dev/null +++ b/src/main/java/gamess/Dialogs/MatrixDialog.java @@ -0,0 +1,690 @@ +/*Copyright (c) 2007, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ +/** + * @author Shreeram + * @author Michael Sheetz + */ + +package gamess.Dialogs; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.util.ArrayList; +import java.util.Vector; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.event.TableModelEvent; +import javax.swing.event.TableModelListener; +import javax.swing.table.DefaultTableModel; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import gamess.Storage.Repository; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import gamess.Dictionary; +import gamess.UndoRedoHandler; +import gamess.InputFileHandlers.InputFileWriter; + + +public class MatrixDialog extends JDialog +{ + /** + * serialVersionUID + */ + private static final long serialVersionUID = 1L; + // + private JDialog thisDialog = null; + private JFrame frame = new JFrame(); + private JPanel headingPanel = null; + private JLabel headingLabel = null; + private JPanel btnPanel = new JPanel(); + private JButton doneBtn = new JButton("Done"); + private JButton clearBtn = new JButton("Clear"); + private JButton exitBtn = new JButton("Exit"); + private JScrollPane tableScrollPane = new JScrollPane(); + private String DefaultGroup = ""; + private int GridRowCount = 5; + private JTable table = null; + private DefaultTableModel model = null; + private Class[] ColumnClasses = null; + private String[] ColumnNames = null; + private ActionListener buttonAction = null; + private GridGroupRW GroupRW = null; + + public MatrixDialog( Frame parentFrame , Node referenceNode , String _DefaultGroup ) + { + super(parentFrame); + thisDialog = this; + DefaultGroup = _DefaultGroup; + if(referenceNode == null) + { + //Error:No referenceNode assigned + } + + /* + * add the basic layouts and the basic frame contents + */ + this.setLayout(new BorderLayout()); + frame.setLayout(new BorderLayout()); + this.getContentPane().add(frame.getContentPane()); + //add button panel + btnPanel.setLayout(new FlowLayout()); + btnPanel.add(doneBtn); + btnPanel.add(clearBtn); + btnPanel.add(exitBtn); + //Add button listeners + buttonAction = new ButtonListener(); + doneBtn.addActionListener(buttonAction); + clearBtn.addActionListener(buttonAction); + exitBtn.addActionListener(buttonAction); + // + frame.getContentPane().add(btnPanel,BorderLayout.SOUTH); + this.setSize(400,300); + this.setLocationRelativeTo(parentFrame); + // + + NamedNodeMap mainAttributes = referenceNode.getAttributes(); + if(mainAttributes.getNamedItem("Title") != null) + { + setTitle(mainAttributes.getNamedItem("Title").getNodeValue()); + } + if(mainAttributes.getNamedItem("Heading") != null) + { + headingPanel = new JPanel(); + headingLabel = new JLabel(); + headingLabel.setText(mainAttributes.getNamedItem("Heading").getNodeValue()); + headingPanel.add(headingLabel); + frame.getContentPane().add(headingPanel,BorderLayout.NORTH); + } + if(mainAttributes.getNamedItem("RowCount") != null) + { + GridRowCount = Integer.parseInt( mainAttributes.getNamedItem("RowCount").getNodeValue()); + } + + /* + * Form the table model here + */ + int GridColumnCount = 0; + XPath xpathcolumnList; + xpathcolumnList = XPathFactory.newInstance().newXPath(); + NodeList ColumnList = null; + try { + ColumnList = (NodeList)xpathcolumnList.evaluate("GridModel/column", referenceNode, XPathConstants.NODESET); + } catch (XPathExpressionException e) { + e.printStackTrace(); + } + + //Get the number of columns + GridColumnCount = ColumnList.getLength(); + + //Initialize the column variables + ColumnClasses = new Class[GridColumnCount]; + ColumnNames = new String[GridColumnCount]; + + //Get the information about the particular Column + for (int i = 0; i ColArrayList = new ArrayList(); + private String RowSeperator = ""; + private String ColumnSeperator = ""; + private boolean isDynamic = false; + + public GroupFormat(Node GroupTag) + { + CurrentGroup = DefaultGroup; + if(GroupTag == null) + { + //Error:No group information found + } + NamedNodeMap GroupAttributes = GroupTag.getAttributes(); + if(GroupAttributes.getNamedItem("GroupName")!=null) + { + CurrentGroup = GroupAttributes.getNamedItem("GroupName").getNodeValue(); + } + if(GroupAttributes.getNamedItem("Keyword")==null) + { + //Error:No Keyword attribute found + } + Keyword = GroupAttributes.getNamedItem("Keyword").getNodeValue(); + if(GroupAttributes.getNamedItem("RowSeperator")==null) + { + //Error:No row Seperator found + } + RowSeperator = GroupAttributes.getNamedItem("RowSeperator").getNodeValue(); + if(GroupAttributes.getNamedItem("ColumnSeperator")==null) + { + //Error:No Column Seperator found + } + ColumnSeperator = GroupAttributes.getNamedItem("ColumnSeperator").getNodeValue(); + + /* + * Set the column list value + */ + XPath ColumnList; + ColumnList = XPathFactory.newInstance().newXPath(); + Node columnListValue = null; + try { + columnListValue = (Node)ColumnList.evaluate("ColumnList", GroupTag , XPathConstants.NODE); + } catch (XPathExpressionException e) { + e.printStackTrace(); + } + if(columnListValue==null) + { + //Error:No Keyword attribute found + } + columnListValue= columnListValue.getFirstChild(); + while(columnListValue != null && columnListValue.getNodeValue().trim().equals("")) + { + columnListValue = columnListValue.getNextSibling(); + } + if(columnListValue == null) + { + //Error:No list found + } + SetColumnList(columnListValue.getNodeValue()); + + ////////////////////////////////////////////////////////////////////// + // Register the entity with the Organized document // + // This is used for the ContentAssist + Dictionary.Register(CurrentGroup,Keyword,Dictionary.GRID_DIALOG); + Dictionary.registerDialog(CurrentGroup + " " + Keyword, thisDialog); + // // + ////////////////////////////////////////////////////////////////////// + + } + + private void SetColumnList(String _colList) + { + String[] ColNos = _colList.split(","); + for(int i = 0 ; i < ColNos.length ; i++) + { + try + { + //Check if there is a range in the string + if(ColNos[i].indexOf("..") != -1) + { + String[] ColRange = ColNos[i].split("\\.\\."); + //the first string should be a number + //get the starting range + int StartRange = Integer.parseInt(ColRange[0]); + int EndRange = 0; + //Check if the second value starts with COL: + //if it is then it is dynamic + if(ColRange[1].startsWith("COL:")) + isDynamic = true; + //get the ending range + //if it is dynamic then COL represents the Column from where we + //get the number of columns to search for the specific row. + if(isDynamic) + EndRange = Integer.parseInt(ColRange[1].substring("COL:".length())); + else + EndRange = Integer.parseInt(ColRange[1]); + + //Add the list of the column to the array + for (int j = 0; j < (EndRange - StartRange + 1); j++) { + ColArrayList.add(StartRange++); + } + continue; + } + ColArrayList.add(Integer.parseInt(ColNos[i])); + } + catch (NumberFormatException e) { + throw new NumberFormatException("Improper number format at position " + i); + } + } + } + + private ArrayList GetColumnList() + { + return ColArrayList; + } + + private ArrayList GetDynamicColumnList(int row) + { + //check if the column list is dynamic + if(isDynamic) + { + //if the column list is dynamic then it comes here + if(ColArrayList.size() == 0) + return ColArrayList; + //Start with the empty array list + ArrayList dynamicList = new ArrayList(); + //Get the column no of the dynamic column + int dynamicColNo = ColArrayList.get(ColArrayList.size() - 1); + //Check if the column contains some value + //if not return an emptylist + if(table.getValueAt(row , dynamicColNo - 1) == null) + return dynamicList; + //The dynamic column contains the no of columns more on that row + int noOfColumnsToAdd = Integer.parseInt(table.getValueAt(row , dynamicColNo - 1).toString()); + + //HARDCODED value for IZMAT, IXZMAT, IRZMAT, IFZMAT + if(Keyword.startsWith("I") && Keyword.contains("ZMAT")) + { + if(noOfColumnsToAdd == 1 || noOfColumnsToAdd == 2 || noOfColumnsToAdd == 3) + noOfColumnsToAdd++; + if(noOfColumnsToAdd == 5) + noOfColumnsToAdd = 3; + if(noOfColumnsToAdd == 6 || noOfColumnsToAdd == 7) + noOfColumnsToAdd--; + } + + //prepare the list of column numbers for that row + for (int i = 0; i < noOfColumnsToAdd; i++) { + dynamicList.add(++dynamicColNo); + } + return dynamicList; + } + //if the column list is not dynamic then it is going to be the same for all rows + //so return the static array list + return ColArrayList; + } + + public void Write() + { + ArrayList ColList = null; + StringBuilder ValueBuilder = new StringBuilder(); + for(int row = 0 ; row < table.getRowCount() ; row++) + { + boolean isValueSet = false; + boolean isColumnValueChanged = false; + ColList = GetColumnList(); + //Check if it is dynamic + if(isDynamic) + { + //if it is then get the appropriate column list + ColList = new ArrayList(ColList); + ColList.addAll(GetDynamicColumnList(row)); + } + + for(int colIndex = 0 ; colIndex < ColList.size() ; colIndex++) + { + int col = ColList.get(colIndex) - 1; + if(table.getValueAt(row, col) != null && ! table.getValueAt(row, col).toString().trim().equals("")) + { + if(isColumnValueChanged) + ValueBuilder.append(ColumnSeperator); + ValueBuilder.append(table.getValueAt(row, col).toString()); + isColumnValueChanged = true; + isValueSet = true; + } + } + if(isValueSet) + { + ValueBuilder.append(RowSeperator); + } + } + if(ValueBuilder.length() > 0) + { + Value = ValueBuilder.substring(0 , ValueBuilder.length() - RowSeperator.length()); + } + //System.out.println("$" + CurrentGroup.toUpperCase() + " " + Keyword + "=" + Value + " $END"); + UndoRedoHandler.toggleGroupClassifier(); + UndoRedoHandler.setLock(); + + Repository.getInstance().Store(CurrentGroup, Keyword + "=" + Value); + InputFileWriter.getInstance().Write(CurrentGroup, Keyword + "=" + Value); + + UndoRedoHandler.releaseLock(); + } + + public void Read() + { + //String matrixInput = "1,1,2 ,2,1,2,3 ,1,2,3"; + //String matrixInput = "1,1,2,2"; + String matrixInput = Repository.getInstance().Retrieve(CurrentGroup, Keyword); + ReadInput(matrixInput); + } + + public boolean testValue(String group, String keyword, String value) + { + if(!CurrentGroup.equalsIgnoreCase(group) || !Keyword.equalsIgnoreCase(keyword)) + return true; + else + return ReadInput(value); + } + + private boolean ReadInput(String matrixInput) + { + if(matrixInput == null) + return false; + //split the complete list based on the seperator + String[] matrixSplit = matrixInput.split(RowSeperator + "|" + ColumnSeperator); + //Check if the split is empty or not + if(matrixSplit.length == 0) + return false; + int splitLocation = 0; + //Check if the table has sufficient rows + if(table.getRowCount() == 0) + model.addRow(new Vector()); + + try + { + for (int row = 0; row < table.getRowCount() && splitLocation < matrixSplit.length; row++) + { + //get the number of columns for that row. + ArrayList ColList = GetColumnList(); + for (int colIndex = 0; colIndex < ColList.size(); colIndex++) + { + int col = ColList.get(colIndex) - 1; + //if setValueOnGrid is true then set value to the table else test value + //place the items on that row. + table.setValueAt( getParsedValue( matrixSplit[splitLocation++].trim(), col) , row, col); + } + //see if the row is dynamic. + if(isDynamic) + { + //if it is get dynamic column list again + ArrayList dynamicColList = GetDynamicColumnList(row); + if(dynamicColList.size() != 0) + { + //start from the next column. and read the values + for (int colIndex = 0; colIndex < dynamicColList.size(); colIndex++) + { + int col = dynamicColList.get(colIndex) - 1; + //if setValueOnGrid is true then set value to the table else test value + //place the items on that row. + table.setValueAt( getParsedValue(matrixSplit[splitLocation++].trim(), col) , row, col); + } + } + } + //if it is then check if there are rows for it. + //else add more rows + if(row == (table.getRowCount() - 1)) + model.addRow(new Vector()); + } + } + catch(Exception ex) + { + //ex.printStackTrace(); + return false; + } + return true; + } + + private Object getParsedValue(String value, int col) throws Exception + { + Class currentColumnClass = table.getColumnClass(col); + + if(currentColumnClass == Integer.class) + { + return Integer.parseInt(value); + } + else if(currentColumnClass == Boolean.class) + { + return Boolean.parseBoolean(value); + } + else if(currentColumnClass == Float.class) + { + return Float.parseFloat(value); + } + else if(currentColumnClass == Double.class) + { + return Double.parseDouble(value); + } + else if(currentColumnClass == String.class) + { + return value; + } + else + return value; + } + } + + class GridGroupRW + { + GroupFormat[] GroupList = null; + public GridGroupRW(NodeList GroupListTags) { + if(GroupListTags == null) + { + //Error:No Group info tag found + return; + } + GroupList = new GroupFormat[GroupListTags.getLength()]; + for(int i = 0 ; i < GroupListTags.getLength() ; i++) + { + GroupList[i] = new GroupFormat(GroupListTags.item(i)); + } + } + + public void Write() + { + for(int i = 0 ; i < GroupList.length ; i++) + { + GroupList[i].Write(); + } + } + + public void Read() + { + for(int i = 0 ; i < GroupList.length ; i++) + { + GroupList[i].Read(); + } + } + + public boolean testValue(String group, String keyword, String value) + { + if(group == null || keyword == null || value == null) + return false; + for (int i = 0; i < GroupList.length; i++) + { + if(GroupList[i].testValue(group, keyword, value) == false) + return false; + } + return true; + } + } + + private class DialogOpenClose extends ComponentAdapter + { + @Override + public void componentShown(ComponentEvent arg0) { + SetNewModalForTable(); + table.setModel(model); + GroupRW.Read(); + } + } +} diff --git a/src/main/java/gamess/Dialogs/MenuTableComboBox.java b/src/main/java/gamess/Dialogs/MenuTableComboBox.java new file mode 100644 index 0000000..db77aa5 --- /dev/null +++ b/src/main/java/gamess/Dialogs/MenuTableComboBox.java @@ -0,0 +1,411 @@ +package gamess.Dialogs; + +import java.awt.Color; +import java.awt.Component; +import java.util.ArrayList; +import java.util.EventObject; + +import javax.swing.BorderFactory; +import javax.swing.JComboBox; +import javax.swing.JTable; +import javax.swing.border.Border; +import javax.swing.event.CellEditorListener; +import javax.swing.event.ChangeEvent; +import javax.swing.table.TableCellEditor; +import javax.swing.table.TableCellRenderer; + +import gamess.Cosmetics; +import gamess.IncompatibilityPackage.ExcludeIncompatibility; +import gamess.IncompatibilityPackage.RequiresIncompatibility; +import gamess.Storage.Repository; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import gamess.Dictionary; + +public class MenuTableComboBox extends JComboBox implements TableCellRenderer,TableCellEditor,IMenuTableCellTester +{ + private static final long serialVersionUID = 1L; + private String Group = null; + private String Keyword = null; + private ArrayList OriginalValues = new ArrayList(); + private String DEFAULT = ""; + private String DefaultValue = null; + private String DefaultToolTip = "DefaultValue : "; + private ArrayList cellListeners = new ArrayList(); + private boolean isConsistent = true; + private boolean isRecomputingConsistency = false; + private Border consistentBorder = getBorder(); + private Border inConsistentBorder = BorderFactory.createLineBorder(Color.RED); + ArrayList cellListenerList = null; + private JComboBox rendererInstance = new JComboBox(); + + //default constructor + public MenuTableComboBox() + { + super(); + } + + //default constructor + public MenuTableComboBox(Object[] items) + { + super(items); + } + + //Constructor + public MenuTableComboBox(String Group, Node currentNode, ArrayList cellListenerList) + { + super(); + + NamedNodeMap currentAttributes = currentNode.getAttributes(); + + //Check if it is combobox node + if(currentAttributes.getNamedItem("MenuType") == null || !currentAttributes.getNamedItem("MenuType").getNodeValue().equalsIgnoreCase("COMBO")) + { + //Error : Not a combobox node + return; + } + + this.cellListenerList = cellListenerList; + + if(currentAttributes.getNamedItem("Group") != null) + Group = currentAttributes.getNamedItem("Group").getNodeValue(); + + //Group + this.Group = Group; + + //Keyword + if(currentAttributes.getNamedItem("DisplayName") != null) + Keyword = currentAttributes.getNamedItem("DisplayName").getNodeValue(); + + String userToolTip = ""; + //ToolTip + if(currentAttributes.getNamedItem("ToolTip") != null) + userToolTip = currentAttributes.getNamedItem("ToolTip").getNodeValue(); + + + //Values + NodeList valueList = currentNode.getChildNodes(); + for(int i = 0 ; valueList.getLength() > i ; i++) + { + Node valueNode; + //if it is a text node skipit; + if((valueNode = valueList.item(i)).getNodeType() == Node.TEXT_NODE) + continue; + String _Value = valueNode.getTextContent().trim(); + currentAttributes = valueNode.getAttributes(); + //Check if this value is the default value + if(currentAttributes.getNamedItem("isDefault") != null && currentAttributes.getNamedItem("isDefault").getNodeValue().equalsIgnoreCase("True")) + DefaultValue = _Value; + //Add the value to the list + OriginalValues.add(_Value); + + ////////////////////////////////////////////////////////////////////// + // Register the entity with the Organized document // + // This is used for the ContentAssist + Dictionary.Register(Group, Keyword, _Value); + // // + ////////////////////////////////////////////////////////////////////// + + } + //Add items + addItem(DEFAULT); + for (int i = 0; i < OriginalValues.size(); i++) + addItem(OriginalValues.get(i)); + if(DefaultValue != null) + { + setSelectedItem(DEFAULT); + DefaultToolTip += DefaultValue; + } + else + { + setSelectedIndex(-1); + DefaultToolTip += "There is no default value set"; + } + + if(userToolTip.length() != 0) + DefaultToolTip = userToolTip + "
" + DefaultToolTip; + + setToolTip(DefaultToolTip); + } + + public void resetValues() + { + isRecomputingConsistency = true; + String valueInDB = Repository.getInstance().Retrieve(Group , Keyword); + //if valueInDB is null then there is no value in the document. + if(valueInDB == null) + { + //reset it to the default value + if(DefaultValue == null) + setSelectedIndex(-1); + else + setSelectedItem(DefaultValue); + isRecomputingConsistency = false; + return; + } + //else set the value in the DB to be the current selected + setSelectedItem(valueInDB); + isRecomputingConsistency = false; + } + + public Component getTableCellRendererComponent(JTable arg0, Object arg1, boolean arg2, boolean arg3, int arg4, int arg5) { + rendererInstance.removeAllItems(); + rendererInstance.addItem((getSelectedItem() == null)?null:getSelectedItem()); + //if(isConsistent == false) + //rendererInstance.setBorder(inConsistentBorder); + //else + //rendererInstance.setBorder(consistentBorder); + //rendererInstance.setEnabled(super.isEnabled()); + return rendererInstance; + //return new MenuTableComboBox(new String[]{(this.getSelectedItem() == null)?null:this.getSelectedItem().toString()}); + } + + public Component getTableCellEditorComponent(JTable arg0, Object arg1, boolean arg2, int arg3, int arg4) { + return this; + } + + public void addCellEditorListener(CellEditorListener listener) + { + cellListeners.add(listener); + } + + public void cancelCellEditing() { + for (int i = 0; i < cellListeners.size(); i++) + { + cellListeners.get(i).editingCanceled(new ChangeEvent(this)); + } + } + + public Object getCellEditorValue() + { + if(getSelectedItem() == null) + return null; + + String CellValue = null; + //if the selected value is "" return the default value + if(DEFAULT.equalsIgnoreCase(getSelectedItem().toString())) + CellValue = DefaultValue; + else + CellValue = getSelectedItem().toString(); + + Repository.getInstance().Store(Group, Keyword + "=" + CellValue); + + return CellValue; + } + + public boolean isCellEditable(EventObject arg0) + { + //if the combobox is empty then this is not editable + if(super.getItemCount() == 0) + return false; + return true; + } + + public void removeCellEditorListener(CellEditorListener listener) + { + cellListeners.remove(listener); + } + + public boolean shouldSelectCell(EventObject arg0) + { + return true; + } + + public boolean stopCellEditing() + { + for (int i = 0; i < cellListeners.size(); i++) + { + cellListeners.get(i).editingStopped(new ChangeEvent(this)); + } + return true; + } + + public void recomputeConsistency() { + isRecomputingConsistency = true; + //Check if this group/keyword is excluded + if(ExcludeIncompatibility.getInstance().isLikelyToBecomeIncompatible(Group) || ExcludeIncompatibility.getInstance().isLikelyToBecomeIncompatible(Group + " " + Keyword)) + { + setComboBoxEnabled(false); + setToolTip("This is disabled because it is likely to be excluded if selected."); + isRecomputingConsistency = false; + return; + } + setComboBoxEnabled(true); + setToolTip(DefaultToolTip); + + String currentValue = (String)getSelectedItem(); + if(DEFAULT.equalsIgnoreCase(currentValue)) + currentValue = DefaultValue; + //Remove all the items + removeAllItems(); + addItem(DEFAULT); + //check all the values in the original list + for (int i = 0; i < OriginalValues.size(); i++) + { + String Value = OriginalValues.get(i); + //Check if this value is required + //if required and if is not the current selected value then set the inconsistency to true + if(RequiresIncompatibility.getInstance().isLikelyToBecomeIncompatible(Group + " " + Keyword + " " + Value) && !Value.equals(currentValue)) + { + setConsistency(false); + setToolTip(Value + " is currently required. Please select it"); + } + //Check if this value is excluded + //if excluded then remove it from the combobox else add it + //This makes the the combobox consistent + boolean isIncompatible = ExcludeIncompatibility.getInstance().isLikelyToBecomeIncompatible(Group + " " + Keyword + " " + Value); + //the value is incompatible + //check if the item is the current selected value + if(isIncompatible == true && Value.equals(currentValue)) + { + //The item is inconsistent + addItem(Value); + setConsistency(false); + setToolTip("Current selected value is inconsistent. Please select another value"); + } + if(!isIncompatible) + addItem(Value); + /*if(isIncompatible) + { + if(Value.equals(currentValue)) + { + //it is the current selected value + isConsistent = false; + continue; + } + for (int j = 0; j < getItemCount(); j++) + { + if(getItemAt(j).equals(Value)) + { + removeItemAt(j); + j--; + } + } + } + else + { + //This value is not incompatible. + //Check if it is available in the list. if not add it. + boolean isItemAvail = false; + for (int j = 0; j < getItemCount(); j++) + { + if(getItemAt(j).equals(Value)) + isItemAvail = true; + } + // find the position to insert + if(!isItemAvail) + addItem(Value); + }*/ + } + if(currentValue == null) + setSelectedIndex(-1); + else + { + if(currentValue.equalsIgnoreCase(DefaultValue)) + setSelectedItem(DEFAULT); + else + setSelectedItem(currentValue); + } + isRecomputingConsistency = false; + } + + public boolean isConsistent() { + return isConsistent; + } + + public boolean isDefault() { + //if nothing is selected or if it is the default value or if the value is "" then it is default + if(getSelectedItem() == null || getSelectedItem().toString().equalsIgnoreCase(DefaultValue) || getSelectedItem().toString().equalsIgnoreCase(DEFAULT)) + return true; + return false; + } + + public String getGroup() { + return Group; + } + + public String getKeyword() { + return Keyword; + } + + public String getValue() + { + return (String)getSelectedItem(); + } + + public void setGroup(String Group) { + this.Group = Group; + } + + public void setKeyword(String Keyword) { + this.Keyword = Keyword; + } + + private void setConsistency(boolean Consistent) + { + isConsistent = Consistent; + if(Consistent == false) + { + setBorder(inConsistentBorder); + rendererInstance.setBorder(inConsistentBorder); + } + else + { + setBorder(consistentBorder); + rendererInstance.setBorder(consistentBorder); + } + } + + @Override + protected void selectedItemChanged() { + if(isRecomputingConsistency == false) + { + //Propogate the values and retest all the incompatibility + String value = null; + //Get the previous item from the combobox + if(getSelectedItem() != null) + value = getSelectedItem().toString(); + if(DEFAULT.equalsIgnoreCase(value)) + value = DefaultValue; + //delete the previous item from the repository + if(value != null) + { + Repository.getInstance().Remove(Group, Keyword); + } + + //set the new item + super.selectedItemChanged(); + //some value is changed. Place it in the DB + //Get the changed value + if(getSelectedItem() != null) + value = getSelectedItem().toString(); + if(DEFAULT.equalsIgnoreCase(value)) + value = DefaultValue; + //Add it to the repository + if(value != null && !value.equalsIgnoreCase(DefaultValue)) + { + String seperator = Repository.getInstance().getKeywordValueSeperator(Group); + Repository.getInstance().Store(Group, Keyword + seperator + value); + } + //fire test in all the peer component in this dialog + for (int i = 0; i < cellListenerList.size(); i++) { + cellListenerList.get(i).recomputeConsistency(); + } + } + } + + private void setToolTip(String tooltip) + { + tooltip = Cosmetics.getFormattedToolTip(tooltip); + setToolTipText(tooltip); + rendererInstance.setToolTipText(tooltip); + } + + private void setComboBoxEnabled(boolean enabled) + { + setEnabled(enabled); + rendererInstance.setEnabled(enabled); + } +} diff --git a/src/main/java/gamess/Dialogs/MenuTableDialog.java b/src/main/java/gamess/Dialogs/MenuTableDialog.java new file mode 100644 index 0000000..f4db7af --- /dev/null +++ b/src/main/java/gamess/Dialogs/MenuTableDialog.java @@ -0,0 +1,311 @@ +package gamess.Dialogs; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.ArrayList; + +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableCellEditor; +import javax.swing.table.TableCellRenderer; +import javax.swing.table.TableModel; + +import gamess.GlobalParameters; +import gamess.InputFileHandlers.InputFileWriter; +import gamess.Storage.Repository; +import gamess.UndoRedoHandler; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class MenuTableDialog extends JDialog +{ + private static final long serialVersionUID = -4769273198912927330L; + ArrayList cellListenerList = new ArrayList(); + ArrayList cellRendererList = new ArrayList(); + ArrayList cellEditorList = new ArrayList(); + JDialog thisDialog = null; + public MenuTable table = null; + JButton doneButton = null, exitButton = null; + + public MenuTableDialog(String Group, String title, Node currentNode, Frame parentFrame) + { + super(parentFrame, true); + + thisDialog = this; + + super.setTitle(title); + + //Set the layout + this.setLayout(new BorderLayout()); + + //Check if the current node is a groupframe node + if(!currentNode.getNodeName().equalsIgnoreCase("GroupFrame")) + return; + + NamedNodeMap currentAttributes = currentNode.getAttributes(); + + //Set the title + if(currentAttributes.getNamedItem("DisplayName") != null) + setTitle(currentAttributes.getNamedItem("DisplayName").getNodeValue()); + + //Group + if(currentAttributes.getNamedItem("Group") != null) + Group = currentAttributes.getNamedItem("Group").getNodeValue(); + + //Create the table model for the table + DefaultTableModel tableModel = new DefaultTableModel(new Object[]{"Keyword" , "Value"}, 0); + table = new MenuTable(tableModel); + + //Keywords + //Get all the keywordlist and create the menu table + NodeList keywords = currentNode.getChildNodes(); + for (int i = 0; i < keywords.getLength() ; i++) { + Node keyword = keywords.item(i); + if(keyword == null || keyword.getNodeType() == Node.TEXT_NODE) + continue; + + currentAttributes = keyword.getAttributes(); + String keywordText = null, valueType = null; + + if(currentAttributes.getNamedItem("DisplayName") != null) + keywordText = currentAttributes.getNamedItem("DisplayName").getNodeValue(); + + if(currentAttributes.getNamedItem("MenuType") != null) + valueType = currentAttributes.getNamedItem("MenuType").getNodeValue(); + + if(keywordText == null || valueType == null) + continue; + + tableModel.addRow(new Object[]{keywordText , null}); + + //add the value item here + if(valueType.equalsIgnoreCase("COMBO")) + { + //add a combobox + MenuTableComboBox menuCombo = new MenuTableComboBox(Group , keyword , cellListenerList); + cellListenerList.add(menuCombo); + cellRendererList.add(menuCombo); + cellEditorList.add(menuCombo); + } + else if(valueType.equalsIgnoreCase("TEXTBOX")) + { + //add a textbox + MenuTableTextBox menuText = new MenuTableTextBox(Group , keyword , cellListenerList, thisDialog); + cellListenerList.add(menuText); + cellRendererList.add(menuText); + cellEditorList.add(menuText); + } + } + + //add buttons + JPanel buttonPanel = new JPanel(); + doneButton = new JButton("Done"); + exitButton = new JButton("Exit"); + + doneButton.setPreferredSize(new Dimension(75,25)); + exitButton.setPreferredSize(new Dimension(75,25)); + + ActionListener buttonListener = new ButtonListener(); + + doneButton.addActionListener(buttonListener); + exitButton.addActionListener(buttonListener); + + buttonPanel.add(doneButton); + buttonPanel.add(exitButton); + + //add listeners + addComponentListener(new DialogOpenClose()); + addWindowListener(new WindowAdapter(){ + @Override + public void windowClosed(WindowEvent arg0) { + super.windowClosed(arg0); + //Switch to normal mode when closing + GlobalParameters.switchToNormalMode(); + } + }); + + //add table properties + table.setRowHeight(25); + + //add all the items to the dialogs contentPane + getContentPane().add(new JScrollPane(table), BorderLayout.CENTER); + getContentPane().add(buttonPanel, BorderLayout.SOUTH); + + //Set size + int titleBarHeight = 37; + int tableHeaderHeight = table.getTableHeader().getPreferredSize().height; + int tableRowsHeight = table.getRowHeight() * (table.getRowCount()); + int buttonPanelHeight = buttonPanel.getPreferredSize().height; + + int Height = titleBarHeight + tableHeaderHeight + tableRowsHeight + buttonPanelHeight; + Height = (Height > 450)?450:Height; + + int Width = 160 + 160; + super.setSize(new Dimension(Width, Height)); + setLocationRelativeTo(parentFrame); + } + + public class MenuTable extends JTable + { + private static final long serialVersionUID = 4279227050469207134L; + + public MenuTable(TableModel tableModel) { + super(tableModel); + } + + @Override + public TableCellRenderer getCellRenderer(int row, int column) { + if(convertColumnIndexToModel(column) == 1)// && cellRendererList.get(row) instanceof MenuTableComboBox) + { + //return TableCellRenderer.class.cast(cellListenerList.get(row)); + return cellRendererList.get(row); + } + return super.getCellRenderer(row, column); + } + + @Override + public TableCellEditor getCellEditor(int row, int column) { + if(convertColumnIndexToModel(column) == 1) + { + //return TableCellEditor.class.cast(cellListenerList.get(row)); + return cellEditorList.get(row); + } + return super.getCellEditor(row, column); + } + + @Override + public boolean isCellEditable(int row, int column) { + if(column == 1) + return true; + return false; + } + } + + private class ButtonListener implements ActionListener + { + public void actionPerformed(ActionEvent evt) + { + if(evt.getSource().equals(doneButton)) + { + //Try to stop the editing of the cells + if(table.isEditing()) + cellEditorList.get(table.getEditingRow()).stopCellEditing(); + //Check if there is some editor still editing + if(table.isEditing()) + { + JOptionPane.showMessageDialog(thisDialog, "Table cannot stop editing because of some inconsistency in the editing cell."); + ((JComponent)cellEditorList.get(table.getEditingRow())).requestFocus(); + return; + } + for (int i = 0; i < cellListenerList.size(); i++) { + IMenuTableCellTester cellValues = cellListenerList.get(i); + if(!cellValues.isConsistent()) + { + //some value is inconsistent. + //Ask the user if he needs to proceed or not + int response = JOptionPane.showConfirmDialog(thisDialog, "Value to the keyword \"" + cellValues.getKeyword() + "\" is inconsistent in the table.\nDo you wany to proceed anyway?", "Inconsistency", JOptionPane.YES_NO_OPTION , JOptionPane.WARNING_MESSAGE); + //if the user does not need to proceed + if(response == JOptionPane.NO_OPTION) + { + table.editCellAt(i, 1); + ((JComponent)cellValues).requestFocus(); + return; + } + } + } + + GlobalParameters.switchToNormalMode(); + + UndoRedoHandler.toggleGroupClassifier(); + UndoRedoHandler.setLock(); + + for (int i = 0; i < cellListenerList.size(); i++) { + IMenuTableCellTester cellValues = cellListenerList.get(i); + if(!cellValues.isDefault()) + { + //The value is not default. So add to the repository and write it to the input file + String seperator = Repository.getInstance().getKeywordValueSeperator(cellValues.getGroup()); + Repository.getInstance().Store(cellValues.getGroup(), cellValues.getKeyword() + seperator + cellValues.getValue()); + InputFileWriter.getInstance().Write(cellValues.getGroup(), cellValues.getKeyword() + seperator + cellValues.getValue()); + } + //The value is default. Remove the value if it is available + else if(Repository.getInstance().isAvailable(cellValues.getGroup(), cellValues.getKeyword()) ) + { + Repository.getInstance().Remove(cellValues.getGroup(), cellValues.getKeyword()); + InputFileWriter.getInstance().Remove(cellValues.getGroup(), cellValues.getKeyword()); + } + } + + UndoRedoHandler.releaseLock(); + + thisDialog.dispose(); + } + else if(evt.getSource().equals(exitButton)) + { + //drop the provisional instance + Repository.getInstance().DropDB(); + //switch to normal mode + GlobalParameters.switchToNormalMode(); + //close this + thisDialog.dispose(); + } + } + } + + private class DialogOpenClose extends ComponentAdapter + { + @Override + public void componentShown(ComponentEvent arg0) { + //This is called when Dialog is opened + //Reset all the values + super.componentShown(arg0); + ArrayList dataToPushProvisionalDB = new ArrayList(); + //Load the data from the main DB + for (int i = 0; i < cellListenerList.size(); i++) { + IMenuTableCellTester currentCellListenerList = cellListenerList.get(i); + + currentCellListenerList.resetValues(); + + //if the cell value is not default add the list to the provisional DB + if(!currentCellListenerList.isDefault()) + dataToPushProvisionalDB.add(currentCellListenerList.getGroup() + " " + currentCellListenerList.getKeyword() + Repository.getInstance().getKeywordValueSeperator(currentCellListenerList.getGroup()) + currentCellListenerList.getValue()); + + currentCellListenerList.recomputeConsistency(); + } + //Switch to provisional mode + GlobalParameters.switchToProvisionalMode(); + Repository.getInstance().DropDB(); + for (int i = 0; i < dataToPushProvisionalDB.size(); i++) + { + String FullData = dataToPushProvisionalDB.get(i); + int splitIndex = FullData.indexOf(" "); + Repository.getInstance().Store(FullData.substring(0, splitIndex), FullData.substring(splitIndex + 1)); + } + + //Repaint this dialog for updating it + thisDialog.repaint(); + } + + @Override + public void componentHidden(ComponentEvent arg0) { + //This is called when the Dialog is closed + super.componentHidden(arg0); + //Switch to normal mode when closing + GlobalParameters.switchToNormalMode(); + } + } +} diff --git a/src/main/java/gamess/Dialogs/MenuTableTextBox.java b/src/main/java/gamess/Dialogs/MenuTableTextBox.java new file mode 100644 index 0000000..0357746 --- /dev/null +++ b/src/main/java/gamess/Dialogs/MenuTableTextBox.java @@ -0,0 +1,302 @@ +package gamess.Dialogs; + +import java.awt.Color; +import java.awt.Component; +import java.util.ArrayList; +import java.util.EventObject; + +import javax.swing.BorderFactory; +import javax.swing.JDialog; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.border.Border; +import javax.swing.event.CellEditorListener; +import javax.swing.event.ChangeEvent; +import javax.swing.table.TableCellEditor; +import javax.swing.table.TableCellRenderer; + +import gamess.Cosmetics; +import gamess.Dictionary; +import gamess.IncompatibilityPackage.ExcludeIncompatibility; +import gamess.IncompatibilityPackage.RequiresIncompatibility; +import gamess.Storage.Repository; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + +public class MenuTableTextBox extends JTextField implements + TableCellRenderer, TableCellEditor, IMenuTableCellTester{ + + private static final long serialVersionUID = 1L; + private ArrayList cellEditorListener = new ArrayList(); + private String Group = null; + private String Keyword = null; + private String DEFAULT = ""; + private String DefaultToolTip = "Default value : "; + private boolean isConsistent = true; + private boolean isCellEditable = true; + private boolean isDefault = false; + private boolean isValueChanged = true; + private FormatParser format = null; + private Border consistentBorder = getBorder(); + private Border inConsistentBorder = BorderFactory.createLineBorder(Color.RED); + ArrayList cellListenerList = null; + private JTextField rendererInstance = new JTextField(); + + public MenuTableTextBox() + { + super(); + } + + public MenuTableTextBox(String Group , Node currentNode , ArrayList _cellListenerList, JDialog parentDialog) { + super(); + + NamedNodeMap currentAttributes = currentNode.getAttributes(); + + //Check if it is combobox node + if(currentAttributes.getNamedItem("MenuType") == null || !currentAttributes.getNamedItem("MenuType").getNodeValue().equalsIgnoreCase("TEXTBOX")) + { + //Error : Not a combobox node + return; + } + + cellListenerList = _cellListenerList; + + if(currentAttributes.getNamedItem("Group") != null) + Group = currentAttributes.getNamedItem("Group").getNodeValue(); + + //Group + this.Group = Group; + + //Keyword + if(currentAttributes.getNamedItem("DisplayName") != null) + Keyword = currentAttributes.getNamedItem("DisplayName").getNodeValue(); + + //Format + Node optionNode = null; + for(optionNode = currentNode.getFirstChild(); optionNode != null && optionNode.getNodeType() == Node.TEXT_NODE ; optionNode = optionNode.getNextSibling()); + format = FormatParser.getFormat(this.Group, Keyword, optionNode); + + //ToolTip + if(currentAttributes.getNamedItem("ToolTip") != null) + DefaultToolTip = currentAttributes.getNamedItem("ToolTip").getNodeValue() + "
" + DefaultToolTip; + DefaultToolTip += ((format.getDefault(-1) == null || format.getDefault(-1).trim().length() == 0)?"There is no default value for this":format.getDefault(-1) ); + + setToolTip(DefaultToolTip); + + ////////////////////////////////////////////////////////////////////// + // Register the entity with the Organized document // + // This is used for the ContentAssist + Dictionary.Register(Group, Keyword, Dictionary.TEXTBOX_VALUE); + Dictionary.registerDialog(Group + " " + Keyword, parentDialog); + // // + ////////////////////////////////////////////////////////////////////// + } + + public void resetValues() + { + String valueInDB = Repository.getInstance().Retrieve(Group , Keyword); + + //if the value in the textbox and the DB are different then set isValueChanged to true + if(!getText().equalsIgnoreCase(valueInDB)) + isValueChanged = true; + + //if valueInDB is null then there is no value in the document. + if(valueInDB == null) + { + //reset it to the default value + setText(DEFAULT); + setToolTip(DefaultToolTip); + } + //else set the value in the DB to be the current selected + setText(valueInDB); + } + + public Component getTableCellRendererComponent(JTable arg0, Object arg1,boolean arg2, boolean arg3, int arg4, int arg5) { + //Check if the value is changed since last call to this function + //if it is then check if the current value is default + if(isValueChanged) + isDefault = format.isDefault(getText()); + //change the flag to false + isValueChanged = false; + //if the current value is default then set the text as default + if(isDefault) + rendererInstance.setText(DEFAULT); + //else set the current text value + else + rendererInstance.setText(getText()); + //if(isConsistent == false) + //rendererInstance.setBorder(inConsistentBorder); + //else + //rendererInstance.setBorder(consistentBorder); + return rendererInstance; + } + + public Component getTableCellEditorComponent(JTable arg0, Object arg1,boolean arg2, int arg3, int arg4) { + return this; + } + + public void addCellEditorListener(CellEditorListener listener) { + cellEditorListener.add(listener); + } + + public void cancelCellEditing() { + String previousText = rendererInstance.getText(); + if(DEFAULT.equals(previousText)) + setText(format.getDefault(-1)); + setText(previousText); + for (int i = 0; i < cellEditorListener.size(); i++) { + cellEditorListener.get(i).editingCanceled(new ChangeEvent(this)); + } + } + + public Object getCellEditorValue() { + String CellValue = null; + if(format.isDefault(getText())) + { + CellValue = format.getDefault(-1); + } + else + CellValue = super.getText(); + + if(CellValue != null) + Repository.getInstance().Store(Group, Keyword + "=" + CellValue); + + return CellValue; + } + + public boolean isCellEditable(EventObject arg0) { + return this.isCellEditable; + } + + public void removeCellEditorListener(CellEditorListener listener) { + cellEditorListener.remove(listener); + } + + public boolean shouldSelectCell(EventObject arg0) { + return true; + } + + public boolean stopCellEditing() + { + //parse the string + setConsistency(format.isConsistent(getText())); + if(isConsistent) + { + setToolTip(DefaultToolTip); + isValueChanged = true; + for (int i = 0; i < cellEditorListener.size(); i++) + cellEditorListener.get(i).editingStopped(new ChangeEvent(this)); + valueChanged(); + return true; + } + + setToolTip("There is an error in this field.
Reason : " + format.Reason); + //else set the inconsistency border + return false; + } + + public String getGroup() { + return Group; + } + + public String getKeyword() { + return Keyword; + } + + public String getValue() + { + return getText(); + } + + public boolean isConsistent() { + return isConsistent; + } + + public boolean isDefault() + { + return format.isDefault(getText()); + } + + public void recomputeConsistency() + { + //Test if the value is excluded + ExcludeIncompatibility excludes = ExcludeIncompatibility.getInstance(); + setTextboxEnabled(!( excludes.isLikelyToBecomeIncompatible(Group) || excludes.isLikelyToBecomeIncompatible(Group + " " + Keyword) || excludes.isLikelyToBecomeIncompatible(Group + " " + Keyword + " " + getText()))); + if(isEnabled()) + { + //Set the consistency if the textbox + setConsistency(format.isConsistent(getText())); + if(isConsistent) + setToolTip(DefaultToolTip); + else + setToolTip("There is an error in this field.
Reason : " + format.Reason); + + + //Test if it is partially incompatible. test the Required Incompatibility + String partialIncompatibilities = RequiresIncompatibility.getInstance().getPartialIncompatibility(Group + " " + Keyword); + if(isConsistent && partialIncompatibilities != null && partialIncompatibilities.trim().length() != 0) + { + //This item is incompatible. + //But this is Required. + //So this should be enabled + //Set an in consistency border and set the tooltip as required + setConsistency(false); + setToolTip("$" + Group + " " + Keyword + " = " + partialIncompatibilities + " is required"); + } + } + } + + private void setTextboxEnabled(boolean enabled) { + setEnabled(enabled); + rendererInstance.setEnabled(enabled); + if(enabled) + setToolTip(DefaultToolTip); + else + setToolTip("This is disabled because it is likely to be excluded if selected."); + } + + public void setGroup(String Group) { + this.Group = Group; + + } + + public void setKeyword(String Keyword) { + this.Keyword = Keyword; + } + + public void valueChanged() + { + ///Check if the value is consistent. + if(isConsistent) + { + //if it is then recompute the consistency on all cells + for (int i = 0; i < cellListenerList.size(); i++) + { + cellListenerList.get(i).recomputeConsistency(); + } + } + + } + + private void setConsistency(boolean Consistent) + { + isConsistent = Consistent; + if(Consistent == false) + { + setBorder(inConsistentBorder); + rendererInstance.setBorder(inConsistentBorder); + } + else + { + setBorder(consistentBorder); + rendererInstance.setBorder(consistentBorder); + } + } + + private void setToolTip(String tooltip) + { + tooltip = Cosmetics.getFormattedToolTip(tooltip); + setToolTipText(tooltip); + rendererInstance.setToolTipText(tooltip); + } +} diff --git a/src/main/java/gamess/Dialogs/MolecularSpecification.java b/src/main/java/gamess/Dialogs/MolecularSpecification.java new file mode 100644 index 0000000..bf86980 --- /dev/null +++ b/src/main/java/gamess/Dialogs/MolecularSpecification.java @@ -0,0 +1,655 @@ +/*Copyright (c) 2007, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ +/** + * @author Michael Sheetz + * @author Pavithra Koka + * @author Shreeram + */ + +package gamess.Dialogs; + + +import gamess.*; +import gamess.InputFileHandlers.InputFileReader; +import gamess.InputFileHandlers.InputFileWriter; +import gamess.Storage.Repository; +import legacy.editor.commons.Settings; +import nanocad.nanocadFrame2; +import nanocad.newNanocad; + +import javax.swing.*; +import javax.swing.event.MenuListener; +import javax.swing.event.UndoableEditEvent; +import javax.swing.event.UndoableEditListener; +import javax.swing.undo.UndoManager; +import java.awt.*; +import java.awt.event.*; +import java.io.*; + +public class MolecularSpecification extends JDialog implements ItemListener{ + + private static final long serialVersionUID = 1L; + static JDialog ThisDialog= null; + + JPanel northPanel,titlePanel,textPanel, basePanel,buttonPanel; + + JMenuBar menuBar=new JMenuBar(); + + static JMenu fileMenu=new JMenu("File"); + static JMenu editMenu=new JMenu("Edit"); + + JMenuItem openMenu,saveMenu,saveAsMenu,closeMenu,undoMenu,redoMenu,cutMenu,copyMenu,pasteMenu; + + public static JTextArea titleBox; + public static JTextArea dataFileDisplayArea; + public static JTextArea chargeBox,multiplicityBox; + + public static JComboBox symmetryBox,nBox; + + public static JButton doneBtn; + JButton clearBtn,exitBtn; + + String dataFile; + String symmetryBoxValue=null,nBoxValue=null; + StringBuffer dataFileDisplay = new StringBuffer(); + + UndoManager undoManager = new UndoManager(); + + public NanocadHandler nanoCadHandler; + + MenuListener listener; + MolDisplay geom; + + public MolecularSpecification(MolDisplay geom1 , Frame parentFrame){ + super(parentFrame,true); + + ThisDialog = this; + this.setSize(600,500); + this.setLocationRelativeTo(parentFrame); + this.setTitle("Molecular Specification"); + + geom=geom1; + + createNorthPanel(); + createTitlePanel(); + createTextAreaPanel(); + createBasePanel(); + + createFileMenu(); + createEditMenu(); + + System.out.println("Molecular Specification"); + menuBar.add(fileMenu); + menuBar.add(editMenu); + + this.setJMenuBar(menuBar); + + //UndoRedoHandler is not used here because the extra datastructure used for + //grouping the edits is not necessary here. + dataFileDisplayArea.getDocument().addUndoableEditListener + ( + new UndoableEditListener() + { + public void undoableEditHappened(UndoableEditEvent e) + { + undoManager.addEdit(e.getEdit()); + } + } + ); + + // + setChargeAndMult(); + + ////////////////////////////////////////////////////////////////////// + // Register the entity with the Organized document // + // This is used for the ContentAssist + Dictionary.Register("DATA",Dictionary.CUSTOM_DIALOG); + Dictionary.Register("CONTRL", "ICHARG", Dictionary.CUSTOM_DIALOG); + Dictionary.Register("CONTRL", "MULT", Dictionary.CUSTOM_DIALOG); + + Dictionary.registerDialog( "DATA", ThisDialog); + Dictionary.registerDialog("CONTRL ICHARG", ThisDialog); + Dictionary.registerDialog("CONTRL MULT", ThisDialog); + // // + ////////////////////////////////////////////////////////////////////// + } + + public void setChargeAndMult() + { + //Check if CONTRL group contains charge and multiplicity values + //If it is not available then set them to default. + InputFileReader reader = InputFileReader.getInstance(); + + //Charge + String charge = reader.Read("CONTRL" , "ICHARG"); + chargeBox.setText( (charge == null || charge.trim().length() == 0) ? "0" : charge); + + //Multiplicity + String multiplicity = reader.Read("CONTRL" , "MULT"); + multiplicityBox.setText( (multiplicity == null || multiplicity.trim().length() == 0) ? "1" : multiplicity); + + } + + public String ReadUpdate() + { + boolean isModified = false; + + String chargeBoxText = chargeBox.getText(); + String multBoxText = multiplicityBox.getText(); + + setChargeAndMult(); + + if( chargeBoxText.equalsIgnoreCase(chargeBox.getText()) == false || multBoxText.equalsIgnoreCase(multiplicityBox.getText()) == false ) + isModified = true; + + String DataContent = InputFileReader.getInstance().Read("$DATA"); + if(DataContent == null) + return "Invalid group content"; + else + { + DataContent = DataContent.trim(); + + //Get the job title + int jobTitleEnding = DataContent.indexOf("\n"); + if(jobTitleEnding == -1) + return "No JobTitle Found"; + String jobTitle = DataContent.substring(0, jobTitleEnding).trim(); + if(jobTitle.split(" ").length >1) + return "Invalid Title"; + + //Set the job title + titleBox.setText(jobTitle); + + DataContent = DataContent.substring(jobTitleEnding + 1); + + //Get the Symmetry and N + int Symmetry_N_Ending = DataContent.indexOf("\n"); + if(Symmetry_N_Ending == -1) + return "No JobTitle Found"; + String symmetry_N = DataContent.substring(0, Symmetry_N_Ending).trim(); + String[] Symmetry_N_Vals = symmetry_N.split(" "); + //Set the nbox value first + if(Symmetry_N_Vals.length > 1) + nBox.setSelectedItem(Symmetry_N_Vals[1]); + symmetryBox.setSelectedItem(Symmetry_N_Vals[0]); + + DataContent = DataContent.substring(Symmetry_N_Ending + 1).trim(); + System.out.println("Molecular DataContent: " + DataContent); + + if(dataFileDisplayArea.getText().trim().equalsIgnoreCase(DataContent) == false) + isModified = true; + //Set the Data file content + dataFileDisplayArea.setText(DataContent); + + if(isModified) + doneBtn.doClick(); + } + return null; + } + + public void createNorthPanel() + { + //Charge + JLabel chargeLbl=new JLabel("Charge:"); + chargeBox=new JTextArea(); + chargeBox.setPreferredSize(new Dimension(50,30)); + chargeBox.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY,1)); + + //Multiplicity + JLabel multiplicityLbl=new JLabel(" Multiplicity:"); + multiplicityBox=new JTextArea(); + multiplicityBox.setPreferredSize(new Dimension(50,30)); + multiplicityBox.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY,1)); + + //N : set nBox values + JLabel nLbl=new JLabel(" n:"); + String nBoxValues[]={"1","2","3","4","5","6","7","8","9"}; + nBox=new JComboBox(nBoxValues); + nBox.setPreferredSize(new Dimension(50,30)); + nBox.addItemListener(this); + + //Symmetry : set symmetryBox values + JLabel symmetryLbl=new JLabel(" Symmetry:"); + String symmetryValues[]={"C1","Cs","Ci","Cn","S2n","Cnh","Cnv","Dn","Dnh","Dnd","T","Th","Td","O","Oh"}; + symmetryBox=new JComboBox(symmetryValues); + symmetryBox.setPreferredSize(new Dimension(70,30)); + symmetryBox.addItemListener(this); + symmetryBoxValue=symmetryBox.getItemAt(0).toString(); + + //Add all the above components to the north panel + northPanel=new JPanel(); + northPanel.add(chargeLbl); + northPanel.add(chargeBox); + northPanel.add(multiplicityLbl); + northPanel.add(multiplicityBox); + northPanel.add(symmetryLbl); + northPanel.add(symmetryBox); + northPanel.add(nLbl); + northPanel.add(nBox); + } + + public void createTitlePanel(){ + titlePanel=new JPanel(); + + titleBox=new JTextArea(); + titleBox.setText("default_Job"); + titleBox.setPreferredSize(new Dimension(300,30)); + titleBox.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY,1)); + titleBox.setRows(2); + titleBox.setLineWrap(true); + + JLabel titleLbl =new JLabel("Title: "); + titlePanel.add(titleLbl); + titlePanel.add(titleBox); + } + + public void createTextAreaPanel(){ + //Add the text area + textPanel=new JPanel(); + textPanel.setLayout(new BorderLayout()); + + dataFileDisplayArea=new JTextArea(); + JScrollPane scrollPane = new JScrollPane(); + scrollPane.setPreferredSize(new Dimension(250,320)); + scrollPane.setViewportView(dataFileDisplayArea); + textPanel.add(scrollPane); + + // Adding Buttons + buttonPanel=new JPanel(); + buttonPanel.setLayout(new FlowLayout()); + doneBtn=new JButton("Done"); + clearBtn=new JButton("Clear"); + exitBtn=new JButton("Exit"); + + doneBtn.addActionListener(new buttonListener()); + clearBtn.addActionListener(new buttonListener()); + exitBtn.addActionListener(new buttonListener()); + + buttonPanel.add(doneBtn); + buttonPanel.add(clearBtn); + buttonPanel.add(exitBtn); + + textPanel.add(buttonPanel,BorderLayout.SOUTH); + } + + public void createBasePanel(){ + basePanel=new JPanel(new BorderLayout()); + basePanel.add(northPanel,BorderLayout.NORTH); + basePanel.add(titlePanel,BorderLayout.CENTER); + basePanel.add(textPanel,BorderLayout.SOUTH); + this.getContentPane().add(basePanel,BorderLayout.CENTER); + } + + public void itemStateChanged(ItemEvent e) { + if(e.getSource()==symmetryBox){ + Object item=e.getItem(); + if(e.getStateChange()==ItemEvent.SELECTED){ + symmetryBoxValue=item.toString(); + if(item.toString().equals("Cn")||item.toString().equals("S2n")||item.toString().equals("Cnh")|| + item.toString().equals("Cnv")||item.toString().equals("Dn")||item.toString().equals("Dnh")|| + item.toString().equals("Dnd")){ + nBox.setEnabled(true); + nBoxValue=nBox.getItemAt(0).toString(); + } + else{ + nBox.setEnabled(false); + nBoxValue=null; + } + } + } + if(e.getSource()==nBox){ + Object item=e.getItem(); + nBoxValue=item.toString(); + } + } + + public class buttonListener implements ActionListener{ + // pass it to the buildInputFile1 + + public void actionPerformed(ActionEvent e) { + //Done button + if((JButton)e.getSource()==doneBtn){ + dataFileDisplay.delete(0, dataFileDisplay.length()); + dataFile = ""; + // get text from the textArea and put it into a string + //pass it to the build file and readGeomerty() + //String dataFile is used to pass the value to ReadGeometry + + dataFile=dataFileDisplayArea.getText(); + + boolean consistent = false; + try + { + boolean invokeSymmetry = false; + if(JOptionPane.showConfirmDialog(ThisDialog, "Use point group symmetry to display molecule?","Invoke Symmetry", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) + { + invokeSymmetry = true; + } + System.out.println("Data File: \n" + dataFile); + System.out.println("Charge: " + chargeBox.getText()); + System.out.println("Multiplicity: " + multiplicityBox.getText()); + consistent=geom.setStrGeom(dataFile,chargeBox.getText().trim(),multiplicityBox.getText().trim(), invokeSymmetry, symmetryBoxValue, Integer.parseInt(nBox.getSelectedItem().toString())); + } + catch(Exception ex ) + { + JOptionPane.showMessageDialog(ThisDialog, "Improper molecular specification format\n" + + "Please enter specification either in Z-matrix or Cartesian coordinates format\n" + + "Please refer Help for further clarification","ERROR", JOptionPane.ERROR_MESSAGE); + geom.setStrGeom("", chargeBox.getText(), multiplicityBox.getText(), false, symmetryBoxValue, Integer.parseInt(nBox.getSelectedItem().toString())); + return; + } + + // ICHARG and MULT belong to $CONTRL group. + String charge=chargeBox.getText().trim(); + String multiplicity=multiplicityBox.getText().trim(); + consistent = true; + if(consistent==true){ + //CONTRL Group values + UndoRedoHandler.toggleGroupClassifier(); + UndoRedoHandler.setLock(); + + Repository db = Repository.getInstance(); + InputFileWriter writer = InputFileWriter.getInstance(); + + db.Store("CONTRL", "ICHARG=" + charge); + writer.Write("CONTRL", "ICHARG=" + charge); + db.Store("CONTRL", "MULT=" + multiplicity); + writer.Write("CONTRL", "MULT=" + multiplicity); + + /* TO DISPLAY IN THE INPUT FILE TEXT AREA OF THE MAIN GUI*/ + if(!dataFile.equals("")){ + if(titleBox.getText().trim()=="") + dataFileDisplay.append("default_Job"+"\n"); + else + dataFileDisplay.append(titleBox.getText().trim()+"\n"); // add title + + //get the symmetry and n values + // symmetryBoxValues and nBoxValues have the values + dataFileDisplay.append(symmetryBoxValue); + // If nBoxValue is not 'null' append it to the 'dataFileDisplay' + if(nBoxValue!=null) + dataFileDisplay.append(" "+nBoxValue+"\n"); + + //INPUT.DOC: For C1 group, there is no card -3- or -4-. + if(symmetryBoxValue=="C1") + dataFileDisplay.append("\n"); + dataFileDisplay.append("\n"+dataFile); + + //dataFileDisplay.append("\n"+dataFile); + + //dataFileDisplay contains the data under the $DATA group + db.Store("DATA", dataFileDisplay.toString() ); + writer.Write("DATA", dataFileDisplay.toString() ); + } + UndoRedoHandler.releaseLock(); + + MolDisplay.glcanvas.repaint(); + ThisDialog.dispose(); + } + else + { + //Display error message. + String message = "ERROR ! A spin multiplicity of " + multiplicity + " is inconsistent with the net charge of " + charge + " on this molecule"; + JOptionPane.showMessageDialog(ThisDialog, message,"ERROR", JOptionPane.ERROR_MESSAGE); + + } + } + //Clear button + else if((JButton)e.getSource()==clearBtn){ + dataFileDisplayArea.setText(""); + dataFileDisplay.delete(0, dataFileDisplay.length()); + + } + //Exit button + else if((JButton)e.getSource()==exitBtn){ + ThisDialog.dispose(); + } + } + + } + + public void createFileMenu(){ + fileMenu=new JMenu("File"); + menuBar.add(fileMenu); + + ActionListener molSpecListener = new FileMenuListener(ThisDialog, dataFileDisplayArea , null , undoManager , false); + + //Open + openMenu=new JMenuItem("Open"); + openMenu.addActionListener(molSpecListener); + fileMenu.add(openMenu); + + //Save + saveMenu=new JMenuItem("Save"); + saveMenu.addActionListener(molSpecListener); + fileMenu.add(saveMenu); + + //SaveAs + saveAsMenu=new JMenuItem("Save As"); + saveAsMenu.addActionListener(molSpecListener); + fileMenu.add(saveAsMenu); + + fileMenu.addSeparator(); + + //Import : JMolEditor/Nanocad + JMenu importMenu = new JMenu("Import"); + fileMenu.add(importMenu); +// Import SubMenu + { + JMenuItem jMolEditor = new JMenuItem("JMolEditor"); + importMenu.add(jMolEditor); + jMolEditor.setEnabled(false); + JMenuItem nanoCad = new JMenuItem("Nanocad "); + importMenu.add(nanoCad); + nanoCad.addActionListener(nanoCadHandler = new NanocadHandler()); + } + + fileMenu.addSeparator(); + + //Close + closeMenu=new JMenuItem("Close"); + closeMenu.addActionListener(molSpecListener); + fileMenu.add(closeMenu); + } + + public void createEditMenu(){ + editMenu=new JMenu("Edit"); + menuBar.add(editMenu); + + ActionListener editMenuListener = new EditMenuListener(dataFileDisplayArea , undoManager); + + //Undo + undoMenu= new JMenuItem("Undo"); + undoMenu.addActionListener(editMenuListener); + editMenu.add(undoMenu); + + //Redo + redoMenu= new JMenuItem("Redo"); + redoMenu.addActionListener(editMenuListener); + editMenu.add(redoMenu); + + // + editMenu.addSeparator(); + + //Cut + cutMenu= new JMenuItem("Cut"); + cutMenu.addActionListener(editMenuListener); + editMenu.add(cutMenu); + + //Copy + copyMenu= new JMenuItem("Copy"); + copyMenu.addActionListener(editMenuListener); + editMenu.add(copyMenu); + + //Paste + pasteMenu= new JMenuItem("Paste"); + pasteMenu.addActionListener(editMenuListener); + editMenu.add(pasteMenu); + } + + public class NanocadHandler implements ActionListener , ComponentListener , WindowListener + { + public nanocadFrame2 nanWin = null; + + public void actionPerformed(ActionEvent arg0) + { + System.out.println(" Calling Nanocad"); + String setsfile = ".settings"; + boolean append = false; + File sets = new File(Settings.defaultDirStr + Settings.fileSeparator + + setsfile); + try + { + FileWriter fw = new FileWriter(sets, append); + fw.write("Username= " + Settings.username + "\n"); + fw.write("CGI= " + Settings.httpsGateway + "\n"); + fw.close(); + FileWriter fw2 = new FileWriter(Settings.defaultDirStr + Settings.fileSeparator + + "loadthis", append); + fw2.write(Settings.defaultDirStr + Settings.fileSeparator + + "common" + Settings.fileSeparator + "Molecule" + Settings.fileSeparator + + "Inorganic" + Settings.fileSeparator + + "water.pdb\n"); + fw2.close(); + } + catch (IOException ioe) {} + + // if the output file is present then delete it + String tmpfile = "tmp.txt"; + File fa = new File(newNanocad.applicationDataDir+ Settings.fileSeparator+tmpfile); + if ( fa.exists()) + { + fa.delete(); + } + + // launch nanocad + System.out.println("Calling nanocadMain"); + nanWin = new nanocadFrame2(); + nanWin.addWindowListener(this); + nanWin.nano.addComponentListener(this); + ThisDialog.setVisible(false); + nanWin.setVisible(true); + nanWin.toFront(); + + System.out.println(" Done with Nanocad"); + } + + public void componentHidden(ComponentEvent arg0) + { + if(nanWin.nano.exportedApplication.equals(Settings.APP_NAME_GAMESS)) + { + System.err.println("load temp file here!"); + File f = new File(newNanocad.applicationDataDir + + Settings.fileSeparator + "coord.txt"); + //legacy.editors.commons.Settings.fileSeparator + "tmp.txt"); + if ((f.exists()) ) + { + try + { + BufferedReader inStream = new BufferedReader(new FileReader(f)); + String text = ""; + String line; + while ((line = inStream.readLine()) != null) + { + int n = line.length(); + if (n > 0) + { + text = text + line + "\n"; + } + } + inStream.close(); + dataFileDisplayArea.setText(text); + } + catch (IOException ioe) + { + System.err.println("IOException in showMolEditor"); + } + } + + try + { + nanWin.setVisible(false); + nanWin.dispose(); + if (nanWin.nano.t !=null) + nanWin.nano.t.setVisible(false); + } + catch (HeadlessException e1) + { + e1.printStackTrace(); + } + } + else + nanWin.setVisible(false); + + if(!ThisDialog.isVisible()) + { + ThisDialog.setVisible(true); + } + } + + public void componentMoved(ComponentEvent arg0) { + } + + public void componentResized(ComponentEvent arg0) { + } + + public void componentShown(ComponentEvent arg0) { + } + + public void windowActivated(WindowEvent arg0) { + } + + public void windowClosed(WindowEvent arg0) { + } + + public void windowClosing(WindowEvent arg0) { + } + + public void windowDeactivated(WindowEvent arg0) { + } + + public void windowDeiconified(WindowEvent arg0) { + } + + public void windowIconified(WindowEvent arg0) { + } + + public void windowOpened(WindowEvent arg0) { + } + + } +}// end of class + + \ No newline at end of file diff --git a/src/main/java/gamess/Dialogs/TextDialog.java b/src/main/java/gamess/Dialogs/TextDialog.java new file mode 100644 index 0000000..633b801 --- /dev/null +++ b/src/main/java/gamess/Dialogs/TextDialog.java @@ -0,0 +1,321 @@ +/*Copyright (c) 2007, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ +/** + * @author Shreeram + * @author Michael Sheetz + */ + +package gamess.Dialogs; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.event.UndoableEditEvent; +import javax.swing.event.UndoableEditListener; +import javax.swing.undo.UndoManager; + +import gamess.Dictionary; +import gamess.Storage.Repository; +import org.w3c.dom.*; + +import gamess.UndoRedoHandler; +import gamess.InputFileHandlers.InputFileWriter; + +public class TextDialog extends JDialog { + + /** + * private variables declaration + */ + private static final long serialVersionUID = 1L; + private JDialog ThisDialog = null; + private JFrame frame = new JFrame(); + private JMenuBar menuBar = new JMenuBar(); + private JTextArea textArea = new JTextArea(); + private JScrollPane txtscrl = new JScrollPane(); + private JPanel buttonPanel = new JPanel(); + private JButton doneBtn = new JButton("Done"); + private JButton clearBtn = new JButton("Clear"); + private JButton exitBtn = new JButton("Exit"); + private ActionListener buttonListener = null; + private ActionListener menuListener = null; + private UndoManager editManager = new UndoManager(); + private JFileChooser fc = null; + private String CurrentGroup = ""; + + public TextDialog(Frame parentFrame, String DefaultGroup , Node refNode) { + super(parentFrame); + + ThisDialog = this; + + CurrentGroup = DefaultGroup; + if(refNode != null && refNode.getAttributes().getNamedItem("Group") != null) + { + CurrentGroup = refNode.getAttributes().getNamedItem("Group").getNodeValue(); + } + + setTitle(CurrentGroup); + this.setSize(500, 400); + this.setLayout(new BorderLayout()); + frame.setLayout(new BorderLayout()); + this.getContentPane().add(frame.getContentPane()); + this.setLocationRelativeTo(parentFrame); + + //Add the Menubar in the top for basic operation + setJMenuBar(menuBar); + //frame.setJMenuBar(menuBar); + //Add menuitems + BuildMenu(); + + //Add the TextArea to type or paste the content + txtscrl.setViewportView(textArea); + frame.getContentPane().add(txtscrl,BorderLayout.CENTER); + textArea.getDocument().addUndoableEditListener(new UndoRedoListener()); + + //Add the Button panal + buttonPanel.setLayout(new FlowLayout()); + frame.getContentPane().add(buttonPanel , BorderLayout.SOUTH); + + //Add the buttons here + buttonPanel.add(doneBtn); + buttonPanel.add(clearBtn); + buttonPanel.add(exitBtn); + + buttonListener = new ButtonListener(); + doneBtn.addActionListener(buttonListener); + clearBtn.addActionListener(buttonListener); + exitBtn.addActionListener(buttonListener); + + ////////////////////////////////////////////////////////////////////// + // Register the entity with the Organized document // + // This is used for the ContentAssist + Dictionary.Register(CurrentGroup, Dictionary.TEXT_DIALOG); + Dictionary.registerDialog(CurrentGroup, ThisDialog); + // // + ////////////////////////////////////////////////////////////////////// + } + + private void BuildMenu() + { + menuListener = new MenuListener(); + JMenuItem menuItem = null; + + // + JMenu fileMenu = new JMenu("File"); + + menuItem = new JMenuItem("Open"); + menuItem.addActionListener(menuListener); + fileMenu.add(menuItem); + + menuItem = new JMenuItem("Save"); + menuItem.addActionListener(menuListener); + fileMenu.add(menuItem); + + menuItem = new JMenuItem("Close"); + menuItem.addActionListener(menuListener); + fileMenu.add(menuItem); + + // + JMenu editMenu = new JMenu("Edit"); + + menuItem = new JMenuItem("Undo"); + menuItem.addActionListener(menuListener); + editMenu.add(menuItem); + + menuItem = new JMenuItem("Redo"); + menuItem.addActionListener(menuListener); + editMenu.add(menuItem); + + editMenu.addSeparator(); + + menuItem = new JMenuItem("Cut"); + menuItem.addActionListener(menuListener); + editMenu.add(menuItem); + + menuItem = new JMenuItem("Copy"); + menuItem.addActionListener(menuListener); + editMenu.add(menuItem); + + menuItem = new JMenuItem("Paste"); + menuItem.addActionListener(menuListener); + editMenu.add(menuItem); + + // + menuBar.add(fileMenu); + menuBar.add(editMenu); + } + + class ButtonListener implements ActionListener + { + public void actionPerformed(ActionEvent e) { + if(e.getSource() == doneBtn) + { + UndoRedoHandler.toggleGroupClassifier(); + UndoRedoHandler.setLock(); + + InputFileWriter.getInstance().Write(CurrentGroup, textArea.getText()); + Repository.getInstance().Store(CurrentGroup, textArea.getText()); + + UndoRedoHandler.releaseLock(); + ThisDialog.dispose(); + } + else if(e.getSource() == clearBtn) + { + textArea.setText(""); + } + else if(e.getSource() == exitBtn) + { + ThisDialog.dispose(); + } + } + } + + class UndoRedoListener implements UndoableEditListener + { + public void undoableEditHappened(UndoableEditEvent e) { + editManager.addEdit(e.getEdit()); + } + } + + class MenuListener implements ActionListener + { + public void actionPerformed(ActionEvent e) { + if(e.getActionCommand().equals("Open")) + { + if(fc == null) + { + fc = new JFileChooser(); + } + fc.setDialogTitle("Open file"); + int fcResult = fc.showOpenDialog(ThisDialog); + if(fcResult == JFileChooser.APPROVE_OPTION) + { + //read the content of the file into the text area + try + { + textArea.setText(""); + FileReader in = new FileReader(fc.getSelectedFile()); + BufferedReader bin = new BufferedReader(in); + String line = ""; + while( ( line = bin.readLine()) != null) + textArea.append(line); + bin.close(); + in.close(); + } + catch (IOException ex) + { + ex.printStackTrace(); + } + } + } + else if(e.getActionCommand().equals("Save")) + { + if(fc == null) + { + fc = new JFileChooser(); + } + fc.setDialogTitle("Save file"); + int fcResult = fc.showSaveDialog(ThisDialog); + if(fcResult == JFileChooser.APPROVE_OPTION) + { + try + { + if(fc.getSelectedFile().exists()) + { + int response = JOptionPane.showConfirmDialog(ThisDialog , "Overwrite existing file?" , "Confirm Overwrite", + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE); + if(response == JOptionPane.CANCEL_OPTION || response == JOptionPane.CLOSED_OPTION) + return; + } + PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter(fc.getSelectedFile()))); + out.print(textArea.getText()); + out.flush(); + out.close(); + } + catch(IOException ex) + { + ex.printStackTrace(); + } + } + } + else if(e.getActionCommand().equals("Close")) + { + ThisDialog.dispose(); + } + else if(e.getActionCommand().equals("Undo")) + { + if(editManager.canUndo()) + editManager.undo(); + } + else if(e.getActionCommand().equals("Redo")) + { + if(editManager.canRedo()) + editManager.redo(); + } + else if(e.getActionCommand().equals("Cut")) + { + textArea.cut(); + } + else if(e.getActionCommand().equals("Copy")) + { + textArea.copy(); + } + else if(e.getActionCommand().equals("Paste")) + { + textArea.paste(); + } + } + } +} diff --git a/src/main/java/gamess/Dictionary.java b/src/main/java/gamess/Dictionary.java new file mode 100644 index 0000000..14aa217 --- /dev/null +++ b/src/main/java/gamess/Dictionary.java @@ -0,0 +1,175 @@ +package gamess; + +import java.util.Hashtable; + +import javax.swing.JDialog; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.DOMImplementation; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +public class Dictionary +{ + public static Document organizedDoc = null; + public static final String GRID_DIALOG = "GRID_DIALOG"; + public static final String TEXT_DIALOG = "TEXT_DIALOG"; + public static final String CUSTOM_DIALOG = "CUSTOM_DIALOG"; + public static final String TEXTBOX_VALUE = "TEXTBOX_VALUE"; + + public static final Hashtable dialogs = new Hashtable(); + public static void registerDialog(String key, JDialog dialog) + { + + //if not found create it and add it to the table + //TODO change this to proper way + key = getFormattedKeyword(key); + + dialogs.put(key, dialog); + } + + private static Element root = null; + public static Hashtable groupsStartingNodes = new Hashtable(); + private static Hashtable groupKeywordNodes = new Hashtable(); + private static Hashtable keywordValueNodes = new Hashtable(); + static + { + try + { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + DOMImplementation di = db.getDOMImplementation(); + + organizedDoc = di.createDocument(null, "root", null); + root = organizedDoc.getDocumentElement(); + } + catch(ParserConfigurationException e){} + } + + + public static Element Register(String group) { + group = group.toUpperCase(); + + //Try to find the element of group in the groupStartingNode table. + if(groupsStartingNodes.containsKey(group)) + { + return groupsStartingNodes.get(group); + } + //if not found create it and add it to the table + Element groupElement = organizedDoc.createElement(group); + root.appendChild(groupElement); + groupsStartingNodes.put(group, groupElement); + return groupElement; + } + + public static Element Register(String group, String keyword) { + group = group.toUpperCase(); + keyword = keyword.toUpperCase(); + + //if not found create it and add it to the table + keyword = getFormattedKeyword(keyword); + + //Try to find the element of keyword in the groupKeywordNodes table. + if(groupKeywordNodes.containsKey(group + " " + keyword)) + { + return groupKeywordNodes.get(group + " " + keyword); + } + + Element keywordElement = organizedDoc.createElement(keyword); + Register(group).appendChild(keywordElement); + groupKeywordNodes.put(group + " " + keyword, keywordElement); + return keywordElement; + } + + public static Element Register(String group, String keyword, String value) { + group = group.toUpperCase(); + keyword = keyword.toUpperCase(); + value = value.toUpperCase(); + + keyword = getFormattedKeyword(keyword); + + //Try to find the element of keyword in the groupKeywordNodes table. + if(keywordValueNodes.containsKey(group + " " + keyword + " " + value)) + { + return keywordValueNodes.get(group + " " + keyword + " " + value); + } + //if not found create it and add it to the table + Element valueElement = organizedDoc.createElement("Value"); + //The reason for setting the value as attribute is because the value can have + //some special characters like "(" and numbers which are not valid names + valueElement.setAttribute("value", value); + Register(group, keyword).appendChild(valueElement); + keywordValueNodes.put(group + " " + keyword + " " + value, valueElement); + return valueElement; + } + + public static Element get() + { + return root; + } + + public static Element get(String group) + { + group = group.toUpperCase(); + if(groupsStartingNodes.containsKey(group)) + { + return groupsStartingNodes.get(group); + } + return null; + } + + public static Element get(String group, String keyword) + { + group = group.toUpperCase(); + keyword = keyword.toUpperCase(); + + keyword = getFormattedKeyword(keyword); + + if(groupKeywordNodes.containsKey(group + " " + keyword)) + { + return groupKeywordNodes.get(group + " " + keyword); + } + return null; + } + + public static Element get(String group, String keyword , String value) + { + group = group.toUpperCase(); + keyword = keyword.toUpperCase(); + value = value.toUpperCase(); + + keyword = getFormattedKeyword(keyword); + + if(keywordValueNodes.containsKey(group + " " + keyword + " " + value)) + { + return keywordValueNodes.get(group + " " + keyword + " " + value); + } + return null; + } + + public static String getFormattedKeyword(String keyword) + { + int arrayIndexStarting = -1; + + //Check if the keyword contains an array index that starts with '(' and ends with ')' + if( (arrayIndexStarting = keyword.indexOf("(")) != -1 && keyword.endsWith(")")) + { + try + { + String IndexValue = keyword.substring(arrayIndexStarting + 1, keyword.length() - 1); + Integer.parseInt(IndexValue); + } + catch (NumberFormatException e) { + //if the array index is not an integer then return keyword as it is + return keyword; + } + //replace ( and ) with _ + //keyword = keyword.replace("(", "__").replace(")", "_"); + keyword = keyword.substring(0, arrayIndexStarting); + } + + return keyword; + } +} diff --git a/src/main/java/gamess/EditMenuListener.java b/src/main/java/gamess/EditMenuListener.java new file mode 100644 index 0000000..aa6b782 --- /dev/null +++ b/src/main/java/gamess/EditMenuListener.java @@ -0,0 +1,85 @@ +/*Copyright (c) 2007, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ +/** + * @author Michael Sheetz + * @author Pavithra Koka + */ + +package gamess; + +import java.awt.event.*; + +import javax.swing.text.JTextComponent; +import javax.swing.undo.UndoManager; + +public class EditMenuListener implements ActionListener +{ + private UndoManager undoManager = null; + private JTextComponent textComponent = null; + + public EditMenuListener(JTextComponent _textComponent , UndoManager _undoManager) + { + undoManager = _undoManager; + textComponent = _textComponent; + } + + public void actionPerformed(ActionEvent e) + { + String menuName = e.getActionCommand (); + + if(menuName.equals ("Undo")) + { + if(undoManager != null && undoManager.canUndo()) + undoManager.undo(); + } + else if(menuName.equals("Redo")) + { + if(undoManager != null && undoManager.canRedo()) + undoManager.redo(); + } + else if(menuName.equals("Cut")) + { + textComponent.cut(); + } + if(menuName.equals("Copy")) + { + textComponent.copy(); + } + if(menuName.equals("Paste")) + { + textComponent.paste(); + } + } +} diff --git a/src/main/java/gamess/FileMenuListener.java b/src/main/java/gamess/FileMenuListener.java new file mode 100644 index 0000000..4ea97a3 --- /dev/null +++ b/src/main/java/gamess/FileMenuListener.java @@ -0,0 +1,269 @@ +/*Copyright (c) 2007, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ +/** + * @author Michael Sheetz + * @author Pavithra Koka + */ + +package gamess; + +import javax.swing.*; +import javax.swing.border.TitledBorder; +import javax.swing.text.JTextComponent; +import javax.swing.undo.UndoManager; + +import gamess.Storage.Repository; + +import java.awt.Window; +import java.awt.event.*; +import java.io.*; + +public class FileMenuListener implements ActionListener +{ + private File currentFile = null; + private JFileChooser fileChooser = new JFileChooser (); + private Window parentWindow = null; + private JTextComponent textEditor = null; + private TitledBorder border = null; + private boolean updateDatabase = false; + private UndoManager undoManager = null; + + /** + * This is the constructor of the FileMenuListener + * @param _parentWindow The parent window of the save and open dialog. Value cannot be null + * @param _textEditor The textEditor present in the window. Value cannot be null + * @param _border The border sourrounding the textEditor. Can be null + * @param _undoManager The undo/redo manager that is associated with the textEditor. Can be null + * @param _updateDatabase Value specifying whether to update the Database when a new file is opeaned. + */ + public FileMenuListener(Window _parentWindow , JTextComponent _textEditor ,TitledBorder _border , UndoManager _undoManager , boolean _updateDatabase) + { + parentWindow = _parentWindow; + textEditor = _textEditor; + updateDatabase = _updateDatabase; + undoManager = _undoManager; + border = _border; + } + + public void actionPerformed(ActionEvent e) + { + String menuName = e.getActionCommand (); + + if(menuName.equals ("New")) + { + //Reset the current text + textEditor.setText(""); + //Reset current file + currentFile = null; + //Reset the title + ResetInputFileWindowTitle("untitled"); + //Since a new file has been opeaned clear all the undo and redo events + if(undoManager != null) + undoManager.discardAllEdits(); + //Drop the DB if updateDatabase == true + if(updateDatabase) + Repository.getInstance().DropDB(); + } + else if (menuName.equals ("Open")) + { + // Open a file + openFile (); + //Since a new file has been opeaned clear all the undo and redo events + if(undoManager != null) + undoManager.discardAllEdits(); + //Drop the DB if updateDatabase == true + if(updateDatabase) + Repository.getInstance().DropDB(); + } + else if (menuName.equals ("Save")) + { + // Save a file + if(currentFile == null) + saveFile ("Save"); + else + { + //Saving on the same file name + //Check if the writing is success(true) + writeFile (currentFile, textEditor.getText ()); + } + } + else if (menuName.equals ("Save As")) + { + // Save the current input as a file with different name + saveFile("Save As"); + } + else if (menuName.equals ("Close") ) + parentWindow.dispose (); + + } // end of actionPerformed() + + /** + * Use a JFileChooser in Open mode to select files + * to open. Use a filter for FileFilter subclass to select + * for *.java files. If a file is selected then read the + * file and place the string into the textarea. + **/ + private void openFile () + { + fileChooser.setDialogTitle ("Open File"); + + // Now open chooser + int result = fileChooser.showOpenDialog (parentWindow); + + if (result == JFileChooser.APPROVE_OPTION) + { + currentFile = fileChooser.getSelectedFile (); + + //Reset the title in the main window + ResetInputFileWindowTitle(currentFile.getName().substring(0 , currentFile.getName().indexOf(".")) ); + + // Invoke the readFile method in this class + String file_string = readFile (currentFile); + + if (file_string != null) + { + textEditor.setText (file_string); + if(updateDatabase) + { + //TODO update the Database + } + } + return; + } + } // openFile + + + /** + * Use a JFileChooser in Save mode to select files + * to open. Use a filter for FileFilter subclass to select + * for "*.java" files. If a file is selected, then write the + * the string from the textarea into it. + **/ + private void saveFile (String title) + { + File oldFile = currentFile; + + // Set to a default name for save. + fileChooser.setSelectedFile (currentFile); + fileChooser.setDialogTitle(title); + + // Open chooser dialog + int result = fileChooser.showSaveDialog (parentWindow); + + if (result == JFileChooser.APPROVE_OPTION) + { + currentFile = fileChooser.getSelectedFile (); + if (currentFile.exists ()) + { + int response = JOptionPane.showConfirmDialog (null,"Overwrite existing file?","Confirm Overwrite", + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE); + if (response == JOptionPane.CANCEL_OPTION) + { + //reset currentFile to the old file + currentFile = oldFile; + return; + } + } + //Reset the title in the main window + ResetInputFileWindowTitle(currentFile.getName().substring(0 , currentFile.getName().indexOf(".") )); + writeFile (currentFile, textEditor.getText ()); + } + } // saveFile + + + /** Use a BufferedReader wrapped around a FileReader to read + * the text data from the given file. + **/ + public static String readFile (File file) + { + StringBuffer fileBuffer; + String fileString=null; + String line; + + try + { + FileReader in = new FileReader (file); + BufferedReader dis = new BufferedReader (in); + fileBuffer = new StringBuffer () ; + + while ((line = dis.readLine ()) != null) + fileBuffer.append (line + "\n"); + + in.close (); + fileString = fileBuffer.toString (); + } + catch (IOException e ) { + return null; + } + return fileString; + } // readFile + + + /** + * Use a PrintWriter wrapped around a BufferedWriter, which in turn + * is wrapped around a FileWriter, to write the string data to the + * given file. + **/ + public static void writeFile (File file, String dataString) + { + try + { + PrintWriter out = new PrintWriter (new BufferedWriter (new FileWriter (file))); + out.print (dataString); + out.flush (); + out.close (); + } + catch (IOException e) + { + JOptionPane.showMessageDialog (null,"IO error in saving file!!", "File Save Error", JOptionPane.ERROR_MESSAGE); + } + } // writeFile + + /** + * @author Shreeram + * This is common function that is used to set the title on the + * window that is above the input file textarea in the main window. + * + */ + private void ResetInputFileWindowTitle(String title) + { + if(border != null) + { + border.setTitle("INPUT FILE"+" - "+ title); + GamessGUI.textPanel.repaint(); + } + } +}//end of class diff --git a/src/main/java/gamess/GamessGUI.java b/src/main/java/gamess/GamessGUI.java new file mode 100644 index 0000000..81127ee --- /dev/null +++ b/src/main/java/gamess/GamessGUI.java @@ -0,0 +1,628 @@ +/*Copyright (c) 2007, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ +/** + * @author Michael Sheetz + * @author Pavithra Koka + * @author Shreeram Sridharan + */ + +package gamess; + +import gamess.Dialogs.HelpDisplayer; +import gamess.Dialogs.MolecularSpecification; +import gamess.IncompatibilityPackage.ExcludeIncompatibility; +import gamess.IncompatibilityPackage.RequiresIncompatibility; +import gamess.Storage.Repository; +import legacy.editor.commons.Settings; + +import javax.swing.*; +import javax.swing.border.TitledBorder; +import javax.swing.text.AbstractDocument; +import javax.swing.text.Element; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import java.awt.*; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseMotionListener; +import java.io.File; +import java.util.Hashtable; + +/*import ExcludeIncompatibility; +import IncompatibilityGetter; +import RequiresIncompatibility; +import And; +import Condition; +import ConditionBuilder; +import Not; +import Or; +import AvailableOnlyIfRestriction; +import ExcludeRestriction; +import ExcludedIfRestriction; +import RequiredIfRestriction; +import RequiresRestriction; +import RestrictionsHolder; +import InputFileReader; +import InputFileWriter; +import RWGetter; +import IDBChangeListener; +import Repository; +*/ + + +public class GamessGUI extends JFrame{ + + private static final long serialVersionUID = -2311360325546782256L; + //GUI COMPONENTS + public static JFrame frame; + private static JMenuBar menuBar ; + + public static JMenuItem newMenu,openMenu,saveMenu,saveAsMenu, importMenu,exportMenu,closeMenu; + public static JMenuItem undoMenu,redoMenu,cutMenu,copyMenu,pasteMenu; + + public static JTextArea msgDisplayArea; + public static JTextPane inputFilePane; + + public static JPanel menuPanel,textPanel,mainPanel,msgDisplayPanel,basePanel,submitButtonPanel,molDisplayPanel; + + public static JButton submitInputFile; + public static JButton saveInputFile; + public static JButton updateInputFile; + + ActionListener fileMenuListener , editMenuListener; + + /* VARIBLES FOR OTHER CLASSES */ + public static MolecularSpecification molSpec; + public MolDisplay molDisp; + + TitledBorder textPanelBorder = null; + + + public static void showGamesGUI(){ + if(frame == null){ + frame = new GamessGUI("GAMESS Input GUI"); + frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + screenSize.height -= 100; + screenSize.width -= 100; + frame.setSize(screenSize); + frame.setResizable(true); + frame.setVisible(true); + } + frame.setVisible(true); + frame.toFront(); + frame.requestFocus(); + } + + private GamessGUI(String title) + { + this(); + setTitle(title); + } + + /* CONSTRUCTOR */ + private GamessGUI() + { + menuBar = new JMenuBar(); + setJMenuBar(menuBar); + + //Change the menu from lightweight to heavyweight + JPopupMenu.setDefaultLightWeightPopupEnabled(false); + + createInputFileDisplayPanel(); + createMolDisplayPanel(); + createSubmitButtonPanel(); + createBasePanel(); + + fileMenuListener = new FileMenuListener(this, inputFilePane , textPanelBorder , GlobalParameters.undoRedoHandle ,true); + editMenuListener = new EditMenuListener(inputFilePane , GlobalParameters.undoRedoHandle); + + createFileMenu(); + createEditMenu(); + + +// Creating Global Document + try + { + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + dbFactory.setIgnoringComments(true); + dbFactory.setValidating(false); + dbFactory.setIgnoringElementContentWhitespace(true); + DocumentBuilder builder = dbFactory.newDocumentBuilder(); + + GlobalParameters.doc = builder.parse(new File( Settings.getApplicationDataDir() + File.separator + "gamess" + + File.separator + "Incompatibility.xml")); + GlobalParameters.userNotesAndToolTip = builder.parse(new File( Settings.getApplicationDataDir() + + File.separator + "gamess" + File.separator + "UserNotesAndToolTips.xml")); + } + catch(Exception ex) + { + + } + + ContentAssist.CreateInstance(); + + Hashtable CustomDialogs = new Hashtable(); + CustomDialogs.put("Data", molSpec = new MolecularSpecification(molDisp , frame)); + CustomDialogs.put("Help", new HelpDisplayer(frame , GlobalParameters.HelpFile)); + /* functions to populate the different menus in the Main menu bar*/ + MenuBuilder mb = new MenuBuilder(menuBar , this , GlobalParameters.GamessMenuNew , CustomDialogs); + mb.BuildMenu(); + + + /*try + { + DOMSource ds = new DOMSource(Dictionary.organizedDoc); + StreamResult sr = new StreamResult(new File("OrganizedInput.xml")); + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer trans = tf.newTransformer(); + trans.transform(ds, sr); + } + catch(TransformerException e){e.printStackTrace();}*/ + + inputFilePane.setFont(new Font("Courier" , Font.PLAIN , 12)); + inputFilePane.getDocument().addUndoableEditListener(GlobalParameters.undoRedoHandle); + ((AbstractDocument)inputFilePane.getStyledDocument()).setDocumentFilter(new InputFileFilter(inputFilePane)); +//*/ + /* + RWGetter.loadHandleDetails(); + /*InputFileWriter ifw = InputFileWriter.getInstance(); + ifw.Write("SYSTEM", "PARALLEL=.True."); + ifw.Write("SYSTEM", "TILIM=RHF"); + ifw.Write("CONTROL", "PARALLEL=.True."); + ifw.Write("SYSTEM", "PARALLEL=.FALSE."); + ifw.Remove("SYSTEM", "PARALLEL=.FALSE."); + + ifw.Write("LIBE", "APTS(1)=1,3 ,1,2"); + ifw.Write("LIBE", "APTS(1)=1,2 ,1,2,3"); + ifw.Remove("LIBE", "APTS(1)"); + + ifw.Write("DATA", "C1 1\nC\nH 1"); + ifw.Write("DATA", "C1 1\nC\nH 1 1.09"); + ifw.Remove("DATA", " dhdghds "); + + ifw.Write("TDHFX", "USE_Q"); + ifw.Write("TDHFX", "FREQ"); + ifw.Write("TDHFX", "FREE 0.02"); + ifw.Write("TDHFX", "ALLDIRS"); + ifw.Write("TDHFX", "HRAMAN 0.02"); + ifw.Write("TDHFX", "FREE 0.02 0.03"); + ifw.Write("TDHFX", "FREE 0.02 0.03 0.04"); + ifw.Write("TDHFX", "FREE 0.01 0.02"); + ifw.Write("TDHFX", "USE_C"); + ifw.Remove("TDHFX", "USE_Q"); + //ifw.Remove("TDHFX", "HRAMAN"); + + InputFileReader ifr = InputFileReader.getInstance(); + System.out.println(ifr.Read("SYSTEM" , "PARALLEL" ));*/ + + //Storage Testing + Repository db = Repository.getInstance(); + db.registerDBChangeListener(ExcludeIncompatibility.getInstance()); + db.registerDBChangeListener(RequiresIncompatibility.getInstance()); + db.registerDBChangeListener(MessageBox.notes); + + GlobalParameters.switchToProvisionalMode(); + db = Repository.getInstance(); + db.registerDBChangeListener(ExcludeIncompatibility.getInstance()); + db.registerDBChangeListener(RequiresIncompatibility.getInstance()); + db.registerDBChangeListener(MessageBox.notes); + + GlobalParameters.switchToNormalMode(); + /*db = Repository.getInstance(); + // + + db.Store("SYSTEM", "PARALLEL=.FALSE."); + db.Store("SYSTEM", "TILIM=RHF"); + GlobalParameters.switchToProvisionalMode(); + db = Repository.getInstance(); + System.out.println(db.equal("SYSTEM" , "PARALLEL=.FALSE.")); + db.Store("CONTROL", "PARALLEL=.FALSE."); + db.Overwrite("SYSTEM", "SCFTYP=RHF PARALLEL=.TRUE. MPLEVEL=2"); + GlobalParameters.switchToNormalMode(); + db = Repository.getInstance(); + System.out.println(db.Retrieve("SYSTEM")); + System.out.println(db.Retrieve("SYSTEM","PARALLEL")); + + db.Store("TDHFX", "ITERMAX 100"); + db.Store("TDHFX", "USE_Q"); + db.Store("TDHFX", "ALLDIRS"); + db.Remove("TDHFX","USEQ"); + db.Overwrite("TDHFX", "USE_C \n USE_Q \n ITERMAX 110"); + System.out.println(db.equal("TDHFX", "USE_Q")); + System.out.println(db.isAvailable("TDHFX" , "USE_Q")); + System.out.println(db.Retrieve("TDHFX")); + System.out.println(db.Retrieve("TDHFX","ITERMAX")); + + db.Store("DATA", "C\nH 1 1.09"); + db.Remove("DATA", " "); + db.Overwrite("DATA", "C\nH 1 1.01"); + System.out.println(db.equal("DATA","\nC\nH 1 1.09\n")); + System.out.println(db.isAvailable("DATA","adfa")); + System.out.println(db.isAvailable("DATA")); + System.out.println(db.Retrieve("DATA" , "vsfs")); + + db.Store("ZMAT", "IZMAT=1,2 ,1,2,3"); + db.Store("ZMAT", "IRZMAT = 1,4,3"); + //db.Remove("ZMAT"); + db.Remove("ZMAT", "ICZMAT"); + System.out.println(db.equal("ZMAT" , "IRZMAT=1,4,3")); + db.Store("LIBE", "PARALLEL=.FALSE."); + db.Overwrite("ZMAT", "IZMAT=1,2 ,1,2,3 IXZMAT = 1,4 ,421"); + System.out.println(db.Retrieve("ZMAT")); + System.out.println(db.Retrieve("ZMAT","IXZMAT")); + /*/ + /*/Condition Testing + Condition cond1 = new And("SYSTEM MPLEVEL 3"); + //Condition cond1 = ConditionBuilder.buildCondition("SYSTEM MPLEVEL 3"); + cond1.add("LIBE PARALLEL .FALSE."); + System.out.println(cond1.test()); + + Condition cond2 = new Or("SYSTEM MPLEVEL 2"); + //Condition cond2 = ConditionBuilder.buildCondition("SYSTEM MPLEVEL 3"); + cond2.add("LIBE PARALLEL .TRUE."); + cond2.add(cond1); + System.out.println(cond2.test()); + + Condition cond3 = new Not(); + cond3.add(cond1); + System.out.println(cond3.test()); + + XPath xpath = XPathFactory.newInstance().newXPath(); + InputSource inputSource = null; + try { + inputSource=new InputSource(new FileInputStream("Incompatibility.xml")); + Node node = (Node)xpath.evaluate("/root/Not[Entity[@Group and @Keyword and not(@Value)]]", inputSource , XPathConstants.NODE); + Condition andCond = ConditionBuilder.buildCondition(node); + andCond = ConditionBuilder.buildCondition(node); + System.out.println(andCond.test()); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + // + ExcludeRestriction er = new ExcludeRestriction(); + er.buildList("SYSTEM MPLEVEL"); + //er.getExcludeList(); + RequiresRestriction er1 = new RequiresRestriction(); + er1.buildList("SYSTEM MPLEVEL 2"); + ExcludedIfRestriction er2 = new ExcludedIfRestriction(); + er2.buildList("LIBE PARALLEL"); + //er.buildList("*"); + RequiredIfRestriction er3 = new RequiredIfRestriction(); + er3.buildList("LIBE PARALLEL"); + //er.buildList("*"); + AvailableOnlyIfRestriction er4 = new AvailableOnlyIfRestriction(); + er4.buildList("LIBE PARALLEL"); + //er.buildList("*"); + RestrictionsHolder rh = IncompatibilityGetter.getIncompatibility("LIBE PARALLEL"); + IDBChangeListener incomp = ExcludeIncompatibility.getInstance(); + incomp.DataAdded("SYSTEM MPLEVEL 2"); + incomp.DataRemoved("SYSTEM MPLEVEL 2"); + + incomp = RequiresIncompatibility.getInstance(); + incomp.DataAdded("SYSTEM MPLEVEL 2"); + incomp.DataRemoved("SYSTEM MPLEVEL 2"); + /*/ + + /*/ + //Testing MenuTable + XPath xpath = XPathFactory.newInstance().newXPath(); + InputSource inputSource = null; + Node node = null; + try { + inputSource=new InputSource(new FileInputStream("GamessMenuNew.xml")); + node = (Node)xpath.evaluate("//MenuItem[@DisplayName='Geometry']/GroupFrame[@DisplayName='Geometry']", inputSource , XPathConstants.NODE); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + MenuTableDialog menuTable = new MenuTableDialog("SYSTEM" , "SYSTEM" ,node , frame); + /*/ + //frame.setVisible(true); + setVisible(true); + //ToolTipManager.sharedInstance().setDismissDelay(10000); + //menuTable.setVisible(true); + inputFilePane.addMouseMotionListener(new ToolTipDisplayer()); + try + { + molDisp.setSelected(true); + } + catch(Exception exp) + {} + + //Initial values set + UndoRedoHandler.setLock(); + + /*InputFileWriter.getInstance().Write("SYSTEM", "PARALL=.TRUE."); + Repository.getInstance().Store("SYSTEM", "PARALL=.TRUE."); + + InputFileWriter.getInstance().Write("SYSTEM", "TIMLIM=1"); + Repository.getInstance().Store("SYSTEM", "TIMLIM=1"); + + InputFileWriter.getInstance().Write("SYSTEM", "MEMDDI=1"); + Repository.getInstance().Store("SYSTEM", "MEMDDI=1"); + */ + UndoRedoHandler.releaseLock(); + + //MessageBox.notes.write("The above values are used for running the computation parallelly"); + /*MessageBox.notes.write("message1"); + MessageBox.notes.write("message2"); + MessageBox.notes.write("message3"); + MessageBox.notes.write("message4");*/ + + MessageBox.excludes.UpdateList(); + MessageBox.requires.UpdateList(); + + ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false); + } + + public void createFileMenu(){ + + JMenu fileMenu = new JMenu("File"); + menuBar.add(fileMenu); + + newMenu=new JMenuItem("New"); + newMenu.addActionListener(fileMenuListener); + fileMenu.add(newMenu); + + openMenu=new JMenuItem("Open"); + openMenu.addActionListener(fileMenuListener); + fileMenu.add(openMenu); + + saveMenu=new JMenuItem("Save"); + saveMenu.addActionListener(fileMenuListener); + fileMenu.add(saveMenu); + + saveAsMenu=new JMenuItem("Save As"); + saveAsMenu.addActionListener(fileMenuListener); + fileMenu.add(saveAsMenu); + + fileMenu.addSeparator(); + + importMenu=new JMenuItem("Import"); + importMenu.addActionListener(fileMenuListener); + fileMenu.add(importMenu); + importMenu.setEnabled(false); + + exportMenu=new JMenuItem("Export"); + exportMenu.addActionListener(fileMenuListener); + fileMenu.add(exportMenu); + exportMenu.setEnabled(false); + + fileMenu.addSeparator(); + + closeMenu=new JMenuItem("Close"); + closeMenu.addActionListener(fileMenuListener); + fileMenu.add(closeMenu); + + } + + public void createEditMenu(){ + JMenu editMenu =new JMenu("Edit"); + menuBar.add(editMenu); + + undoMenu= new JMenuItem("Undo"); + undoMenu.addActionListener(editMenuListener); + editMenu.add(undoMenu); + + redoMenu= new JMenuItem("Redo"); + redoMenu.addActionListener(editMenuListener); + editMenu.add(redoMenu); + + editMenu.addSeparator(); + + cutMenu= new JMenuItem("Cut"); + cutMenu.addActionListener(editMenuListener); + editMenu.add(cutMenu); + + copyMenu= new JMenuItem("Copy"); + copyMenu.addActionListener(editMenuListener); + editMenu.add(copyMenu); + + pasteMenu= new JMenuItem("Paste"); + pasteMenu.addActionListener(editMenuListener); + editMenu.add(pasteMenu); + + + JMenuItem updateAll = new JMenuItem("Update All"); + updateAll.setActionCommand("Update All"); + updateAll.addActionListener(UpdateInputFile.getInstance()); + editMenu.add(updateAll); + } + + //FUNCTION TO CREATE TEXTPANE TO DISPLAY THE INPUT FILE + + void createInputFileDisplayPanel() + { + textPanel =new JPanel(); + textPanel.setLayout(new BorderLayout()); + + inputFilePane =new JTextPane(); + inputFilePane.setEditable(true); + + textPanelBorder = new TitledBorder("INPUT FILE"+" - untitled"); + textPanelBorder.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY,1)); + + JScrollPane scrpane=new JScrollPane(inputFilePane); + scrpane.setPreferredSize(new Dimension(getCurrentResolutionWidth(624), getCurrentResolutionHeight(470))); + scrpane.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY,2)); + scrpane.setAutoscrolls(true); + + textPanel.add(scrpane); + textPanel.setBorder(textPanelBorder); + + } + + void createMolDisplayPanel() + { + molDisp = new MolDisplay(); + } + + + + void createSubmitButtonPanel() + { + submitButtonPanel= new JPanel(new FlowLayout()); + + submitInputFile = new JButton("EXPORT"); + updateInputFile = new JButton("UPDATE"); + saveInputFile = new JButton("SAVE"); + + submitInputFile.addActionListener(new checkInputFile()); + updateInputFile.addActionListener(UpdateInputFile.getInstance()); + saveInputFile.addActionListener(fileMenuListener); + + saveInputFile.setActionCommand("Save"); + + submitButtonPanel.add(updateInputFile); + submitButtonPanel.add(submitInputFile); + submitButtonPanel.add(saveInputFile); + + updateInputFile.setEnabled(false); + } + + void createBasePanel() + { + SpringLayout centralLayout = new SpringLayout(); + JPanel centerPanel= new JPanel( centralLayout ); + centerPanel.add(textPanel); + centerPanel.add(molDisp); + + //Row constraints + centralLayout.putConstraint(SpringLayout.WEST , textPanel , 2 , SpringLayout.WEST , centerPanel); + centralLayout.putConstraint(SpringLayout.WEST , molDisp , 2 , SpringLayout.EAST , textPanel); + centralLayout.putConstraint(SpringLayout.EAST , centerPanel , 2 , SpringLayout.EAST , molDisp); + + //Column constraints + centralLayout.putConstraint(SpringLayout.NORTH , textPanel , 2 , SpringLayout.NORTH , centerPanel); + centralLayout.putConstraint(SpringLayout.SOUTH , centerPanel , 2 , SpringLayout.SOUTH , textPanel); + centralLayout.putConstraint(SpringLayout.NORTH , molDisp , 10 , SpringLayout.NORTH , centerPanel); + centralLayout.putConstraint(SpringLayout.SOUTH , molDisp , -4 , SpringLayout.SOUTH , centerPanel); + + basePanel=new JPanel(new BorderLayout()); + + basePanel.add(centerPanel, BorderLayout.CENTER); + + JPanel southPanel = new JPanel(); + southPanel.setLayout(new BorderLayout()); + southPanel.add(new MessageBox(), BorderLayout.CENTER); + southPanel.add(submitButtonPanel,BorderLayout.SOUTH); + southPanel.setPreferredSize(new Dimension( getCurrentResolutionWidth(990) , getCurrentResolutionHeight(195))); + + basePanel.add(southPanel,BorderLayout.SOUTH); + + getContentPane().add(basePanel,BorderLayout.CENTER); + + } + + public static void main(String s[ ]) + { + frame = new GamessGUI("GAMESS Input GUI"); + frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + screenSize.height -= 100; + screenSize.width -= 100; + frame.setSize(screenSize); + frame.setResizable(true); + frame.setVisible(true); + } + + public static int getCurrentResolutionHeight(int _1024X768_Resolution) + { + return ((Double)(Toolkit.getDefaultToolkit().getScreenSize().getHeight() * ((double)_1024X768_Resolution/768))).intValue() ; + } + + public static int getCurrentResolutionWidth(int _1024X768_Resolution) + { + return ((Double)(Toolkit.getDefaultToolkit().getScreenSize().getWidth() * ((double)_1024X768_Resolution/1024))).intValue() ; + } + + private class ToolTipDisplayer implements MouseMotionListener + { + + public void mouseDragged(MouseEvent arg0) {} + + public void mouseMoved(MouseEvent e) + { + //Get offset of the text under the mouse pointer + Point mousePosition = new Point(e.getX(),e.getY()); + int postionOfMouse = inputFilePane.viewToModel(mousePosition); + //Get the element at that offset + Element elementAtMousePosition = inputFilePane.getStyledDocument().getCharacterElement(postionOfMouse); + + //form the rectangle of mouse + /*try + { + //System.out.println(inputFilePane.getText(elementAtMousePosition.getStartOffset(), elementAtMousePosition.getEndOffset() - elementAtMousePosition.getStartOffset())); + System.out.println(elementAtMousePosition.getAttributes().getAttribute("TOOLTIP")); + Rectangle elementBound = new Rectangle(inputFilePane.modelToView(elementAtMousePosition.getStartOffset())); + if(inputFilePane.getText().length() > elementAtMousePosition.getEndOffset()) + elementBound = elementBound.union(inputFilePane.modelToView(elementAtMousePosition.getEndOffset())); + if(!elementBound.contains(mousePosition)) + inputFilePane.setToolTipText(null); + return; + } + catch(BadLocationException ex){ + ex.printStackTrace(); + }*/ + + //Check if the element has any tooltip to be displayed. + //if it is then display it + String toolTip = null; + if( (toolTip = (String)elementAtMousePosition.getAttributes().getAttribute("TOOLTIP") ) != null) + inputFilePane.setToolTipText(toolTip); + else + inputFilePane.setToolTipText(null); + } + } + + public static void setUpdateMode(boolean UpdateMode) + { + boolean updateStatus = !UpdateMode; + updateInputFile.setEnabled(UpdateMode); + for (int i = 0; i < menuBar.getMenuCount() ; i++) + { + JMenu currentMenu = menuBar.getMenu(i); + if(currentMenu != null && (currentMenu.getText().equalsIgnoreCase("File") || currentMenu.getText().equalsIgnoreCase("Edit") + || currentMenu.getText().equalsIgnoreCase("Help"))) + continue; + if(currentMenu != null) + currentMenu.setEnabled(updateStatus); + } + } +} // end of main class diff --git a/src/main/java/gamess/GlobalParameters.java b/src/main/java/gamess/GlobalParameters.java new file mode 100644 index 0000000..39cb4e0 --- /dev/null +++ b/src/main/java/gamess/GlobalParameters.java @@ -0,0 +1,102 @@ +/*Copyright (c) 2007, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ +/** + * @author Michael Sheetz + * @author Pavithra Koka + * @author Shreeram Sridharan + */ + +package gamess; + +import legacy.editor.commons.Settings; +import org.w3c.dom.Document; + +import java.util.ArrayList; + +public class GlobalParameters { + + static String inputDocumentName= Settings.getApplicationDataDir() + "/gamess/GamessMenu.xml"; + static String inputDocumentName1= Settings.getApplicationDataDir() + "/gamess/GamessIncompatibilities.xml"; + static String GamessMenuNew= Settings.getApplicationDataDir() + "/gamess/GamessMenuNew.xml"; + static String HelpFile = Settings.getApplicationDataDir() + "/gamess/GamessHelp.html"; + static public Document doc = null; + static public Document userNotesAndToolTip = null; + static public boolean isProvisionalMode = false; + + public static void switchToProvisionalMode() + { + isProvisionalMode = true; + } + + public static void switchToNormalMode() + { + isProvisionalMode = false; + } + + static public UndoRedoHandler undoRedoHandle = new UndoRedoHandler(); + + static private StringBuilder listOfGroups = new StringBuilder("|$END|$CONTRL|$SYSTEM|$BASIS|$DATA|$ZMAT|$LIBE|$SCF|$SCFMI|$DFT|" + + "$MP2|$CIS|$CISVEC|$CCINP|$EOMINP|$MOPAC|$GUESS|$VEC|$MOFRZ|$STATPT|$TRUDGE|$TRURST|$FORCE|$CPHF|$MASS|$HESS|$GRAD|" + + "$DIPDR|$VIB|$VIB2|$VSCF|$VIBSCF|$IRC|$DRC|$MEX|$MD|$GLOBOP|$GRADEX|$SURF|$LOCAL|$TWOEI|$TRUNCN|$ELMOM|$ELPOT|$ELDENS|" + + "$ELFLDG|$POINTS|$GRID|$PDC|$MOLGRF|$STONE|$RAMAN|$ALPDR|$NMR|$MOROKM|$FFCALC|$TDHF|$TDHFX|$EFRAG|$FRAGNAME|$FRGRPL|" + + "$PRTEFP|$DAMP|$DAMPGS|$PCM|$PCMGRD|$PCMCAV|$TESCAV|$NEWCAV|$IEFPCM|$PCMITR|$DISBS|$DISREP|$SVP|$SVPIRF|$COSGMS|$SCRF|" + + "$ECP|$MCP|$RELWFN|$EFIELD|$INTGRL|$FMM|$TRANS|$FMO|$FMOPRP|$FMOXYZ|$OPTFMO|$FMOLMO|$FMOBND|$FMOENM|$FMOEND|$OPTRST|" + + "$GDDI|$CIINP|$DET|$CIDET|$GEN|$CIGEN|$ORMAS|$GCILST|$SODET|$DRT|$CIDRT|$MCSCF|$MRMP|$DEMRPT|$MCQDPT|$CISORT|$GUGEM|" + + "$GUGDIA|$GUGDM|$GUGDM2|$LAGRAN|$TRFDM2|$TRANST|"); + + public static boolean isGroupAvailable(String group) + { + if(listOfGroups.indexOf("|" + group.toUpperCase() + "|") == -1) + return false; + else + return true; + } + + + public static ArrayList plainDataGroup = new ArrayList(); + public static ArrayList gridGroup = new ArrayList(); + static + { + // Loading plain data group + plainDataGroup.add("DATA"); + plainDataGroup.add("VEC"); + plainDataGroup.add("VIBSCF"); + plainDataGroup.add("CISVEC"); + + //Loading + gridGroup.add("ZMAT"); + gridGroup.add("LIBE"); + } +} diff --git a/src/main/java/gamess/IncompatibilityPackage/.DS_Store b/src/main/java/gamess/IncompatibilityPackage/.DS_Store new file mode 100644 index 0000000..2cf77c6 Binary files /dev/null and b/src/main/java/gamess/IncompatibilityPackage/.DS_Store differ diff --git a/src/main/java/gamess/IncompatibilityPackage/._.DS_Store b/src/main/java/gamess/IncompatibilityPackage/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/gamess/IncompatibilityPackage/._.DS_Store differ diff --git a/src/main/java/gamess/IncompatibilityPackage/ConditionLogic/And.java b/src/main/java/gamess/IncompatibilityPackage/ConditionLogic/And.java new file mode 100644 index 0000000..a0c4307 --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/ConditionLogic/And.java @@ -0,0 +1,122 @@ +package gamess.IncompatibilityPackage.ConditionLogic; + +import java.util.ArrayList; + +import org.w3c.dom.Node; + +public class And implements Condition { + + ArrayList conditionList = new ArrayList(); + + public And() + { + } + + public And(Condition cond) + { + add(cond); + } + + public And(Node condNode) + { + add(condNode); + } + + public And(String Data) + { + add(Data); + } + + public void add(Condition cond) + { + if(!conditionList.contains(cond)) + conditionList.add(cond); + } + + public void add(Node condNode) + { + //if the current node is And the start from the first child + if(condNode.getNodeName().equalsIgnoreCase("And")) + { + condNode = condNode.getFirstChild(); + } + + Node currentNode = condNode; + while( currentNode != null) + { + if(currentNode.getNodeType() != Node.TEXT_NODE) + { + //Check if the current node is an And node + if(currentNode.getNodeName().equalsIgnoreCase("And")) + { + conditionList.add(new And(currentNode)); + } + //Check if the current node is an Or node + else if(currentNode.getNodeName().equalsIgnoreCase("Or")) + { + conditionList.add(new Or(currentNode)); + } + //Check if the current node is an Not node + else if(currentNode.getNodeName().equalsIgnoreCase("Not")) + { + conditionList.add(new Not(currentNode)); + } + //If the above three did not happen then the node is an Entity node + else + { + conditionList.add(new Entity(currentNode)); + } + } + //move to the next node + currentNode = currentNode.getNextSibling(); + } + } + + public void add(String Data) + { + //Add a new entity to the list of conditions + conditionList.add(new Entity(Data)); + } + + public boolean test() { + if(conditionList.size() == 0) + return false; + //Evaluate the And logic + //This returns true only if all the values returns true + for (int i = 0; i < conditionList.size(); i++) + { + if(conditionList.get(i).test() == false) + { + //one of the condition evaluated to false so return false + //a && B && c + return false; + } + } + return true; + } + + public void trim() { + conditionList.trimToSize(); + for (int i = 0; i < conditionList.size(); i++) { + conditionList.get(i).trim(); + } + } + + @Override + public String toString() { + StringBuilder returnString = new StringBuilder(); + for (int i = 0; i < conditionList.size(); i++) { + Condition currentCondition = conditionList.get(i); + //if(currentCondition.test()) + { + if(i != 0) + returnString.append(" and "); + if(!(currentCondition instanceof Entity)) + returnString.append(" ( " + currentCondition.toString() + " ) "); + else + returnString.append(currentCondition.toString()); + } + } + return returnString.toString(); + } +} diff --git a/src/main/java/gamess/IncompatibilityPackage/ConditionLogic/Condition.java b/src/main/java/gamess/IncompatibilityPackage/ConditionLogic/Condition.java new file mode 100644 index 0000000..22d8613 --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/ConditionLogic/Condition.java @@ -0,0 +1,14 @@ +package gamess.IncompatibilityPackage.ConditionLogic; + +import org.w3c.dom.Node; + + +public interface Condition +{ + void add(Condition cond); + void add(Node condNode); + void add(String Data); + boolean test(); + void trim(); + String toString(); +} diff --git a/src/main/java/gamess/IncompatibilityPackage/ConditionLogic/ConditionBuilder.java b/src/main/java/gamess/IncompatibilityPackage/ConditionLogic/ConditionBuilder.java new file mode 100644 index 0000000..4224b9b --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/ConditionLogic/ConditionBuilder.java @@ -0,0 +1,63 @@ +package gamess.IncompatibilityPackage.ConditionLogic; + +import java.util.Hashtable; + +import org.w3c.dom.Node; + +public class ConditionBuilder +{ + private static Hashtable ConditionCache = new Hashtable(); + + public static Condition buildCondition(String Data) + { + //if there is a hit then return the value + if(hit(Data)) + return ConditionCache.get(Data); + + //Create a new And Condition and return it + Condition cond = new And(Data); + cond.trim(); + //Add the condition to the Cache + ConditionCache.put(Data, cond); + return cond; + } + + public static Condition buildCondition(Node condNode) + { + if(condNode == null) + return null; + //if there is a hit then return the value + if(hit(condNode)) + return ConditionCache.get(condNode); + + Condition cond = null; + + //Check if the current node has any siblings. + //if it has then create a new And logic and return it + Node nextSibNode = null; + for(nextSibNode = condNode.getNextSibling(); nextSibNode != null && nextSibNode.getNodeType() == Node.TEXT_NODE; nextSibNode = nextSibNode.getNextSibling()); + if(nextSibNode != null) + cond = new And(condNode); + + //Else check if the current node belongs to And/Or/Not/Entity. + //Create a new logic based on that and return it. + if(cond == null && condNode.getNodeName().equalsIgnoreCase("And")) + cond = new And(condNode); + else if(cond == null && condNode.getNodeName().equalsIgnoreCase("Or")) + cond = new Or(condNode); + else if(cond == null && condNode.getNodeName().equalsIgnoreCase("Not")) + cond = new Not(condNode); + else + cond = new And(condNode); + + cond.trim(); + //Add the condition to the Cache + ConditionCache.put(condNode, cond); + return cond; + } + + private static boolean hit(Object obj) + { + return ConditionCache.containsKey(obj); + } +} diff --git a/src/main/java/gamess/IncompatibilityPackage/ConditionLogic/Entity.java b/src/main/java/gamess/IncompatibilityPackage/ConditionLogic/Entity.java new file mode 100644 index 0000000..738700b --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/ConditionLogic/Entity.java @@ -0,0 +1,100 @@ +package gamess.IncompatibilityPackage.ConditionLogic; + +import gamess.Storage.Repository; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + +public class Entity implements Condition { + + Repository database = null; + String Group = ""; + String Keyword = ""; + String Value = ""; + String Seperator = ""; + + public Entity() + { + } + + public Entity(Condition cond) + { + add(cond); + } + + public Entity(Node condNode) + { + add(condNode); + } + + public Entity(String Data) + { + add(Data); + } + + public void add(Condition cond) + { + return; + } + + public void add(Node condNode) + { + NamedNodeMap nodeMap = condNode.getAttributes(); + Node entityNode = nodeMap.getNamedItem("Group"); + if(entityNode != null) + Group = entityNode.getNodeValue().trim(); + + entityNode = nodeMap.getNamedItem("Keyword"); + if(entityNode != null) + Keyword = entityNode.getNodeValue().trim(); + + entityNode = nodeMap.getNamedItem("Value"); + if(entityNode != null) + Value = entityNode.getNodeValue().trim(); + + Seperator = Repository.getInstance().getKeywordValueSeperator(Group); + } + + public void add(String Data) + { + String[] splitData = Data.split(" "); + Group = splitData[0].trim(); + if(Group.length() == 0) + return; + if(splitData.length > 1) + Keyword = splitData[1].trim(); + if(splitData.length > 2) + Value = splitData[2].trim(); + + Seperator = Repository.getInstance().getKeywordValueSeperator(Group); + } + + public boolean test() { + database = Repository.getInstance(); + //if group is not available return false + if(!database.isAvailable(Group)) + return false; + + //if only group is specified return true; + if(Keyword.length() == 0 && Value.length() == 0) + return true; + + //if Group and keyword are only specified return true if keyword is available + if(Value.length() == 0) + return database.isAvailable(Group, Keyword); + + //if control comes here then it means that all the three are specified + return database.equal(Group, Keyword + Seperator + Value); + } + + public void trim() + { + //No implementation needed + } + + @Override + public String toString() { + if(Value.length() != 0) + return "$" + Group + " " + Keyword + Seperator + Value; + return "$" + Group + " " + Keyword; + } +} diff --git a/src/main/java/gamess/IncompatibilityPackage/ConditionLogic/Not.java b/src/main/java/gamess/IncompatibilityPackage/ConditionLogic/Not.java new file mode 100644 index 0000000..859656e --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/ConditionLogic/Not.java @@ -0,0 +1,103 @@ +package gamess.IncompatibilityPackage.ConditionLogic; + +import org.w3c.dom.Node; + +public class Not implements Condition { + + Condition condition = null; + + public Not() + { + } + + public Not(Condition cond) + { + add(cond); + } + + public Not(Node condNode) + { + add(condNode); + } + + public Not(String Data) + { + add(Data); + } + + public void add(Condition cond) + { + condition = cond; + } + + public void add(Node condNode) + { + //Check if the current node is Not. If it is then start from the first child + if(condNode.getNodeName().equalsIgnoreCase("Not")) + { + condNode = condNode.getFirstChild(); + while(condNode != null && condNode.getNodeType() == Node.TEXT_NODE) + condNode = condNode.getNextSibling(); + } + + if(condNode == null) + return; + + //Check if the current node has any siblings. + //if it is then add the nodes to And logic and add the And to this Not. + Node nextSibNode = null; + for(nextSibNode = condNode.getNextSibling(); nextSibNode != null && nextSibNode.getNodeType() == Node.TEXT_NODE; nextSibNode = nextSibNode.getNextSibling()); + if(nextSibNode != null) + { + condition = new And(condNode); + return; + } + + //Check if the current node is an And node + if(condNode.getNodeName().equalsIgnoreCase("And")) + { + condition = new And(condNode); + } + //Check if the current node is an Or node + else if(condNode.getNodeName().equalsIgnoreCase("Or")) + { + condition = new Or(condNode); + } + //Check if the current node is an Not node + else if(condNode.getNodeName().equalsIgnoreCase("Not")) + { + condition = new Not(condNode); + } + //If the above three did not happen then the node is an Entity node + else + { + condition = new Entity(condNode); + } + } + + public void add(String Data) + { + condition = new Entity(Data); + } + + public boolean test() { + if(condition == null) + return false; + + //Not always returns the opposite of the boolean value received + return (!condition.test()); + } + + public void trim() { + condition.trim(); + } + + @Override + public String toString() { + StringBuilder returnString = new StringBuilder(); + Condition currentCondition = condition; + //if(!currentCondition.test()) + returnString.append(" not( " + currentCondition.toString() + " ) "); + return returnString.toString(); + } +} diff --git a/src/main/java/gamess/IncompatibilityPackage/ConditionLogic/Or.java b/src/main/java/gamess/IncompatibilityPackage/ConditionLogic/Or.java new file mode 100644 index 0000000..e1f0995 --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/ConditionLogic/Or.java @@ -0,0 +1,118 @@ +package gamess.IncompatibilityPackage.ConditionLogic; + +import java.util.ArrayList; + +import org.w3c.dom.Node; + +public class Or implements Condition { + + ArrayList conditionList = new ArrayList(); + + public Or() + { + } + + public Or(Condition cond) + { + add(cond); + } + + public Or(Node condNode) + { + add(condNode); + } + + public Or(String Data) + { + add(Data); + } + + public void add(Condition cond) + { + if(!conditionList.contains(cond)) + conditionList.add(cond); + + } + + public void add(Node condNode) + { + //if the current node is Or the start from the first child + if(condNode.getNodeName().equalsIgnoreCase("Or")) + { + condNode = condNode.getFirstChild(); + } + + Node currentNode = condNode; + while( currentNode != null) + { + if(currentNode.getNodeType() != Node.TEXT_NODE) + { + //Check if the current node is an And node + if(currentNode.getNodeName().equalsIgnoreCase("And")) + { + conditionList.add(new And(currentNode)); + } + //Check if the current node is an Or node + else if(currentNode.getNodeName().equalsIgnoreCase("Or")) + { + conditionList.add(new Or(currentNode)); + } + //Check if the current node is an Not node + else if(currentNode.getNodeName().equalsIgnoreCase("Not")) + { + conditionList.add(new Not(currentNode)); + } + //If the above three did not happen then the node is an Entity node + else + { + conditionList.add(new Entity(currentNode)); + } + } + + //Move to the next node + currentNode = currentNode.getNextSibling(); + } + } + + public void add(String Data) + { + conditionList.add(new Entity(Data)); + } + + public boolean test() { + //Evaluate the Or condition. + //Or condition returns true if any one of the conditions return true + for (int i = 0; i < conditionList.size(); i++) + { + //a || b || C + if(conditionList.get(i).test() == true) + return true; + } + return false; + } + + public void trim() { + conditionList.trimToSize(); + for (int i = 0; i < conditionList.size(); i++) { + conditionList.get(i).trim(); + } + } + + @Override + public String toString() { + StringBuilder returnString = new StringBuilder(); + for (int i = 0; i < conditionList.size(); i++) { + Condition currentCondition = conditionList.get(i); + //if(currentCondition.test()) + { + if(i != 0) + returnString.append(" or "); + if(!(currentCondition instanceof Entity)) + returnString.append(" ( " + currentCondition.toString() + " ) "); + else + returnString.append(currentCondition.toString()); + } + } + return returnString.toString(); + } +} diff --git a/src/main/java/gamess/IncompatibilityPackage/ExcludeIncompatibility.java b/src/main/java/gamess/IncompatibilityPackage/ExcludeIncompatibility.java new file mode 100644 index 0000000..4561732 --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/ExcludeIncompatibility.java @@ -0,0 +1,72 @@ +package gamess.IncompatibilityPackage; + +import gamess.GlobalParameters; +import gamess.IncompatibilityPackage.Restriction.AvailableOnlyIfRestriction; +import gamess.IncompatibilityPackage.Restriction.ExcludedIfRestriction; +import gamess.IncompatibilityPackage.Restriction.IbuildList; +import gamess.IncompatibilityPackage.Restriction.RestrictionsHolder; + +public class ExcludeIncompatibility extends IncompatibilityBase +{ + private static ExcludeIncompatibility instance = new ExcludeIncompatibility(true); + private static ExcludeIncompatibility provisionalInstance = new ExcludeIncompatibility(false); + + public static ExcludeIncompatibility getInstance() + { + if(GlobalParameters.isProvisionalMode) + return provisionalInstance; + return instance; + } + + private ExcludeIncompatibility(boolean isMainObject) + { + //Check if it is the main object. + //If it is then initialize it + if(isMainObject) + Initialize(); + } + + private void Initialize() + { + //test all the conditions first and remove all that is not satisfied + //test all the availableOnlyIf condition + AvailableOnlyIfRestriction availOnlyIfList = new AvailableOnlyIfRestriction(); + ((IbuildList)availOnlyIfList).buildList("*"); + addIncompatibilityList(availOnlyIfList); + + //test all the excludedIf condition + ExcludedIfRestriction excludedIfList = new ExcludedIfRestriction(); + ((IbuildList)excludedIfList).buildList("*"); + addIncompatibilityList(excludedIfList); + } + + @Override + void callAddIncompatibilityList(RestrictionsHolder restrictions) + { + //exclude + addIncompatibilityList(restrictions.getExcludeRestriction()); + //excludedIf + addIncompatibilityList(restrictions.getExcludedIfRestriction()); + //availableOnlyIf + addIncompatibilityList(restrictions.getAvailableOnlyIfRestriction()); + } + + @Override + void callRemoveIncompatibilityList(RestrictionsHolder restrictions) + { + //exclude + removeIncompatibilityList(restrictions.getExcludeRestriction()); + //excludedIf + removeIncompatibilityList(restrictions.getExcludedIfRestriction()); + //availableOnlyIf + removeIncompatibilityList(restrictions.getAvailableOnlyIfRestriction()); + } + + @Override + boolean isIncompatible(Incompatible incompatible) { + //this is incompatible if the item is excluded and it is available + if(incompatible != null) + return incompatible.isAvailable(); + return false; + } +} diff --git a/src/main/java/gamess/IncompatibilityPackage/IncompatibilityBase.java b/src/main/java/gamess/IncompatibilityPackage/IncompatibilityBase.java new file mode 100644 index 0000000..9b3a77f --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/IncompatibilityBase.java @@ -0,0 +1,212 @@ +package gamess.IncompatibilityPackage; + +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.Iterator; + +import gamess.IncompatibilityPackage.Restriction.IIncompatibilityList; +import gamess.IncompatibilityPackage.Restriction.RestrictionType; +import gamess.IncompatibilityPackage.Restriction.RestrictionsHolder; +import gamess.Storage.IDBChangeListener; +import gamess.Storage.Repository; + +public abstract class IncompatibilityBase implements IDBChangeListener +{ + protected Hashtable incompatibilityTable = new Hashtable(); + + public void DataAdded(String Data) + { + //A new data is added. So build the incompatibility + //Get the Incompatibility for the Data from the IncompatibilityGetter + //The RestrictionHolder is returned + RestrictionsHolder restrictions = IncompatibilityGetter.getIncompatibility(Data); + //Get the Restrictions one by one. + //Test each restriction and add it to the Table + //Call the subclass implementation for adding the items to the incompatibilityList + callAddIncompatibilityList(restrictions); + //Add the availability of the current added item if available + Incompatible incompatible = incompatibilityTable.get(Data); + if(incompatible != null) + setIsAvailable(Data, incompatible); + } + + public void DataRemoved(String Data) + { + //The Data is removed from the storage. + //Get the List of Incompatibilities from the IncompatibilityGetter + RestrictionsHolder restrictions = IncompatibilityGetter.getIncompatibility(Data); + //Test each Incompatibility and remove those from the Table + //Call the subclass implementation for adding the items to the incompatibilityList + callRemoveIncompatibilityList(restrictions); + //Add the availability of the current added item if available + Incompatible incompatible = incompatibilityTable.get(Data); + if(incompatible != null) + setIsAvailable(Data, incompatible); + } + + public void DropDB() + { + ArrayList incompatibleList = new ArrayList(); + //Remove all the incompatible objects + for (Iterator incompatibleItem = incompatibilityTable.values().iterator(); incompatibleItem.hasNext();) + incompatibleList.add(incompatibleItem.next()); + + for (int i = 0; i < incompatibleList.size(); i++) + removeIncompatibility(incompatibleList.get(i)); + } + + protected void addIncompatibilityList(IIncompatibilityList incompatibilities) + { + //Get the list of required's/excluded's + ArrayList incompatibilityList = incompatibilities.getIncompatibilityList(); + for (int i = 0; i < incompatibilityList.size(); i++) + { + //get the requireds/excludeds one by one and test it + RestrictionType restriction = incompatibilityList.get(i); + + //Test the condition + if(restriction.testCondition()) + { + //if the condition is true then add it to the list + addIncompatibility(restriction); + } + //Control comes here if the testcondition is false + //Check if the input is already available. + else + { + //if the control comes here then the testcondition failed. + //So the restriction does not exist. Remove it from the table if it completely fails + removeIncompatibility(restriction); + } + + } + } + + protected void addIncompatibility(RestrictionType restriction) + { + String Input = restriction.getInput().trim(); + + //if incompatibilityTable does not contain the restriction + if(!incompatibilityTable.containsKey(Input)) + { + //create a new incompatible object with the new restriction + Incompatible incompatible= new Incompatible(restriction); + //test if the Input is available. Set the isAvailable variable + setIsAvailable(Input, incompatible); + //add a new incompatible object to the table + incompatibilityTable.put(restriction.getInput(), incompatible); + return; + } + //else get the incompatible object + Incompatible incompatible = incompatibilityTable.get(Input); + //Add the condition to the Or condition inside it + incompatible.addCondition(restriction.getCondition()); + //test if the Input is available. Set the isAvailable variable + setIsAvailable(Input, incompatible); + } + + protected void removeIncompatibilityList(IIncompatibilityList incompatibilities) + { + //Get the list of required/excluded + ArrayList incompatibilityList = incompatibilities.getIncompatibilityList(); + for (int i = 0; i < incompatibilityList.size(); i++) + { + //Get the incompatibilities one by one + RestrictionType restriction = incompatibilityList.get(i); + //Check and see if the restriction is false. + if(restriction.testCondition() == false) + { + //if it is false then try removing it from the table + //test it and remove it + removeIncompatibility(restriction); + } + else + { + //Control comes here is the restriction condition is true + //So this is a restriction. add this restriction to the table + addIncompatibility(restriction); + } + } + } + + protected void removeIncompatibility(RestrictionType restriction) + { + //if incompatibilityTable does contain the restriction + if(incompatibilityTable.containsKey(restriction.getInput())) + { + //get the incompatibility retriction and test it. + Incompatible incompatible = incompatibilityTable.get(restriction.getInput()); + //if the test condition is false then remove it + if(!incompatible.testCondition()) + incompatibilityTable.remove(restriction.getInput()); + else + setIsAvailable(restriction.getInput(), incompatible); + } + } + + protected void setIsAvailable(String Input , Incompatible incompatible) + { + String Group = "" , Keyword = "" , Value = ""; + //get the group and the Data + int splitIndex = Input.indexOf(" "); + if(splitIndex == -1) + { + Group = Input; + incompatible.setAvailable(Repository.getInstance().isAvailable(Group)); + } + else + { + Group = Input.substring(0,splitIndex).trim(); + //The format here is "GROUP KEYWORD VALUE" + //Convert it to "GROUP KEYWORD=VALUE" + String[] Data = Input.substring(splitIndex).trim().split(" "); + Keyword = Data[0]; + if(Data.length > 1) + Value = Data[1]; + + Repository DB = Repository.getInstance(); + + //Check if the group is available + if(!DB.isAvailable(Group)) + //Group is not available. so this incompatible object is not available + incompatible.setAvailable(false); + //Group is available. Check if the Keyword in that Group is available + else if(Keyword.length() > 0 && !DB.isAvailable(Group, Keyword)) + //Keyword in this Group is not available. So this incompatible object is not available + incompatible.setAvailable(false); + //Group and Keyword are available. Check if the Value to that Keyword is available + else if(Value.length() != 0) + incompatible.setAvailable(DB.equal(Group, Keyword + DB.getKeywordValueSeperator(Group) + Value)); + else + incompatible.setAvailable(true); + } + + + } + + public boolean isLikelyToBecomeIncompatible(String Data) + { + //Check if there is an entry for the incompatibility + Incompatible incompatible = incompatibilityTable.get(Data); + if(incompatible == null) + return false; + //if there is an entry check if it is incompatible + //return isIncompatible(incompatible); + return true; + } + + + public ArrayList getIncompatibilityList() { + ArrayList incompatibles = new ArrayList(); + for (Iterator iter = incompatibilityTable.values().iterator(); iter.hasNext();) { + Incompatible element = (Incompatible) iter.next(); + if(isIncompatible(element)) + incompatibles.add(element); + } + return incompatibles; + } + + abstract void callAddIncompatibilityList(RestrictionsHolder restrictions); + abstract void callRemoveIncompatibilityList(RestrictionsHolder restrictions); + abstract boolean isIncompatible(Incompatible incompatible); +} diff --git a/src/main/java/gamess/IncompatibilityPackage/IncompatibilityGetter.java b/src/main/java/gamess/IncompatibilityPackage/IncompatibilityGetter.java new file mode 100644 index 0000000..52129da --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/IncompatibilityGetter.java @@ -0,0 +1,46 @@ +package gamess.IncompatibilityPackage; + +import java.util.Hashtable; + +import gamess.IncompatibilityPackage.Restriction.RestrictionsHolder; + +public class IncompatibilityGetter +{ + private static Hashtable incompatibilityCache = new Hashtable(); + + private static boolean hit(String Data) + { + if(incompatibilityCache.containsKey(Data)) + return true; + return false; + } + + public static RestrictionsHolder getIncompatibility(String Data) + { + //if the data is present in the cache then return it + if(hit(Data)) + return retrieve(Data); + + //It is a miss. + //Build a new set of restriction and add it to the cache for later use. + RestrictionsHolder restriction = new RestrictionsHolder(); + restriction.buildRestriction(Data); + + addToCache(Data, restriction); + + //Return the restriction + return restriction; + } + + private static RestrictionsHolder retrieve(String Data) + { + if(!hit(Data)) + return null; + return incompatibilityCache.get(Data); + } + + private static void addToCache(String Data, RestrictionsHolder restriction) + { + incompatibilityCache.put(Data, restriction); + } +} diff --git a/src/main/java/gamess/IncompatibilityPackage/Incompatible.java b/src/main/java/gamess/IncompatibilityPackage/Incompatible.java new file mode 100644 index 0000000..33d7725 --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/Incompatible.java @@ -0,0 +1,38 @@ +package gamess.IncompatibilityPackage; + +import gamess.IncompatibilityPackage.ConditionLogic.Condition; +import gamess.IncompatibilityPackage.ConditionLogic.Or; +import gamess.IncompatibilityPackage.Restriction.RestrictionType; + +public class Incompatible extends RestrictionType +{ + private boolean isAvailable = false; + + public Incompatible() + { + condition = new Or(); + } + + public Incompatible(RestrictionType copyRestr) + { + condition = new Or(); + this.Input = copyRestr.getInput(); + this.condition.add(copyRestr.getCondition()); + } + + @Override + public void addCondition(Condition cond) + { + condition.add(cond); + } + + public boolean isAvailable() + { + return isAvailable; + } + + public void setAvailable(boolean isAvail) + { + isAvailable = isAvail; + } +} diff --git a/src/main/java/gamess/IncompatibilityPackage/RequiresIncompatibility.java b/src/main/java/gamess/IncompatibilityPackage/RequiresIncompatibility.java new file mode 100644 index 0000000..eb0feb9 --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/RequiresIncompatibility.java @@ -0,0 +1,83 @@ +package gamess.IncompatibilityPackage; + +import java.util.Enumeration; + +import gamess.GlobalParameters; +import gamess.IncompatibilityPackage.Restriction.IbuildList; +import gamess.IncompatibilityPackage.Restriction.RequiredIfRestriction; +import gamess.IncompatibilityPackage.Restriction.RequiresRestriction; +import gamess.IncompatibilityPackage.Restriction.RestrictionsHolder; + +public class RequiresIncompatibility extends IncompatibilityBase +{ + private static RequiresIncompatibility instance = new RequiresIncompatibility(true); + private static RequiresIncompatibility provisionalInstance = new RequiresIncompatibility(false); + + public static RequiresIncompatibility getInstance() + { + if(GlobalParameters.isProvisionalMode) + return provisionalInstance; + return instance; + } + + private RequiresIncompatibility(boolean isMainObject) + { + if(isMainObject) + initiallize(); + } + + private void initiallize() + { + //requires + RequiresRestriction requires = new RequiresRestriction(); + ((IbuildList)requires).buildList("*"); + addIncompatibilityList(requires); + + //requiredIf + RequiredIfRestriction required = new RequiredIfRestriction(); + ((IbuildList)required).buildList("*"); + addIncompatibilityList(required); + } + + @Override + void callAddIncompatibilityList(RestrictionsHolder restrictions) + { + //requires + addIncompatibilityList(restrictions.getRequiresRestriction()); + //requiredIf + addIncompatibilityList(restrictions.getRequiredIfRestriction()); + } + + @Override + void callRemoveIncompatibilityList(RestrictionsHolder restrictions) + { + //requires + removeIncompatibilityList(restrictions.getRequiresRestriction()); + //requiredIf + removeIncompatibilityList(restrictions.getRequiredIfRestriction()); + } + + @Override + boolean isIncompatible(Incompatible incompatible) { + //this is incompatible if the item is required and it is not available + if(incompatible != null) + return !incompatible.isAvailable(); + return false; + } + + public String getPartialIncompatibility(String Data) + { + StringBuilder requiredList = new StringBuilder(); + for (Enumeration keys = incompatibilityTable.keys(); keys.hasMoreElements() ;) { + String currentKey = keys.nextElement(); + if(currentKey.startsWith(Data)) + { + currentKey = currentKey.substring(Data.length()).trim(); + if(requiredList.length() != 0) + requiredList.append("|"); + requiredList.append(currentKey); + } + } + return requiredList.toString(); + } +} diff --git a/src/main/java/gamess/IncompatibilityPackage/Restriction/AvailableOnlyIfRestriction.java b/src/main/java/gamess/IncompatibilityPackage/Restriction/AvailableOnlyIfRestriction.java new file mode 100644 index 0000000..ede8a10 --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/Restriction/AvailableOnlyIfRestriction.java @@ -0,0 +1,17 @@ +package gamess.IncompatibilityPackage.Restriction; + +import gamess.IncompatibilityPackage.ConditionLogic.Condition; +import gamess.IncompatibilityPackage.ConditionLogic.Not; + +public class AvailableOnlyIfRestriction extends ExcludedIfRestriction +{ + public AvailableOnlyIfRestriction() + { + xpathPreExpr = "/root/input/availableonlyif[descendant::Entity"; + } + + @Override + protected void addRestrictionCondition(RestrictionType restriction, Condition condition) { + restriction.addCondition(new Not(condition)); + } +} diff --git a/src/main/java/gamess/IncompatibilityPackage/Restriction/ExcludeRestriction.java b/src/main/java/gamess/IncompatibilityPackage/Restriction/ExcludeRestriction.java new file mode 100644 index 0000000..6821a68 --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/Restriction/ExcludeRestriction.java @@ -0,0 +1,84 @@ +package gamess.IncompatibilityPackage.Restriction; + +import java.util.ArrayList; + +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + +import gamess.GlobalParameters; +import gamess.IncompatibilityPackage.ConditionLogic.ConditionBuilder; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import gamess.IncompatibilityPackage.ConditionLogic.Condition; + +public class ExcludeRestriction implements IbuildList, IIncompatibilityList +{ + private ArrayList excludeList = new ArrayList(); + + String xpathPreExpr = "/root/input"; + String xpathCondExpr = ""; + String xpathPostExpr = "/exclude/Entity"; + private static XPath xpath = XPathFactory.newInstance().newXPath(); + + public void buildList(String Data) + { + try + { + //InputSource inputSource = new InputSource(new FileInputStream("Incompatibility.xml"));; + + //build the condition matching given input + String Group,Keyword,Value; + String[] splitData = Data.split(" "); + + Group = (splitData.length > 0) ? "@Group='" + splitData[0] + "' and " : "not(@Group) and " ; + Keyword = (splitData.length > 1) ? "@Keyword='" + splitData[1] + "' and " : "not(@Keyword) and "; + Value = (splitData.length > 2) ? "@Value='" + splitData[2] + "'" : "not(@Value)"; + + xpathCondExpr = "[" + Group + Keyword + Value + "]"; + + //get the xml node list matching the given condition + NodeList excludeNodes = (NodeList)xpath.evaluate(xpathPreExpr + xpathCondExpr + xpathPostExpr , GlobalParameters.doc , XPathConstants.NODESET); + + //The condition which excludes the nodes is the condition which is searched for i.e. Data + //XYZ is excluded because of ABC + Condition excludeCondition = ConditionBuilder.buildCondition(Data.trim()); + //Get the list of exclude nodes + for (int i = 0; i < excludeNodes.getLength(); i++) + { + //For each exclude entity get the condition and add it to the restriction list + Node currentExcludeEntity = excludeNodes.item(i); + + RestrictionType restriction = new RestrictionType(); + excludeList.add(restriction); + + restriction.addCondition(excludeCondition); + + NamedNodeMap inputAttributes = currentExcludeEntity.getAttributes(); + + Node AttributeNode = inputAttributes.getNamedItem("Group"); + String Input = (AttributeNode != null) ? AttributeNode.getNodeValue() + " " : ""; + + AttributeNode = inputAttributes.getNamedItem("Keyword"); + Input += (AttributeNode != null) ? AttributeNode.getNodeValue() + " " : ""; + + AttributeNode = inputAttributes.getNamedItem("Value"); + Input += (AttributeNode != null) ? AttributeNode.getNodeValue() + " " : ""; + + restriction.setInput(Input.trim()); + } + excludeList.trimToSize(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + public ArrayList getIncompatibilityList() { + return excludeList; + } + + +} diff --git a/src/main/java/gamess/IncompatibilityPackage/Restriction/ExcludedIfRestriction.java b/src/main/java/gamess/IncompatibilityPackage/Restriction/ExcludedIfRestriction.java new file mode 100644 index 0000000..2562511 --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/Restriction/ExcludedIfRestriction.java @@ -0,0 +1,94 @@ +package gamess.IncompatibilityPackage.Restriction; + +import java.util.ArrayList; + +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + +import gamess.IncompatibilityPackage.ConditionLogic.ConditionBuilder; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import gamess.GlobalParameters; +import gamess.IncompatibilityPackage.ConditionLogic.Condition; + +public class ExcludedIfRestriction implements IbuildList, IIncompatibilityList { + + private ArrayList excludeList = new ArrayList(); + + protected String xpathPreExpr = "/root/input/excludedif[descendant::Entity"; + protected String xpathCondExpr = ""; + protected String xpathPostExpr = "]"; + private static XPath xpath = XPathFactory.newInstance().newXPath(); + + public void buildList(String Data) { + try + { + //InputSource inputSource = new InputSource(new FileInputStream("Incompatibility.xml"));; + + //build the condition matching given input + if(!Data.trim().equals("*")) + { + String Group,Keyword,Value; + String[] splitData = Data.split(" "); + + Group = (splitData.length > 0) ? "@Group='" + splitData[0] + "' and " : "not(@Group) and " ; + Keyword = (splitData.length > 1) ? "@Keyword='" + splitData[1] + "' and " : "not(@Keyword) and "; + Value = (splitData.length > 2) ? "@Value='" + splitData[2] + "'" : "not(@Value)"; + + xpathCondExpr = "[" + Group + Keyword + Value + "]"; + } + else + xpathCondExpr = ""; + + //get the xml node list matching the given condition + NodeList excludeNodes = (NodeList)xpath.evaluate(xpathPreExpr + xpathCondExpr + xpathPostExpr ,GlobalParameters.doc , XPathConstants.NODESET); + + //Get the list of exclude nodes + for (int i = 0; i < excludeNodes.getLength(); i++) + { + //For each exclude entity get the condition and add it to the restriction list + Node excludedIfEntity = excludeNodes.item(i); + + RestrictionType restriction = new RestrictionType(); + excludeList.add(restriction); + + //The condition which excludes the nodes is the condition which is searched for i.e. Data + //XYZ is excluded because of ABC + Node firstchild = excludedIfEntity.getFirstChild(); + for(; firstchild != null && firstchild.getNodeType() == Node.TEXT_NODE ; firstchild = firstchild.getNextSibling()); + Condition excludeCondition = ConditionBuilder.buildCondition(firstchild); + + addRestrictionCondition(restriction, excludeCondition); + + NamedNodeMap inputAttributes = excludedIfEntity.getParentNode().getAttributes(); + + Node AttributeNode = inputAttributes.getNamedItem("Group"); + String Input = (AttributeNode != null) ? AttributeNode.getNodeValue() + " " : ""; + + AttributeNode = inputAttributes.getNamedItem("Keyword"); + Input += (AttributeNode != null) ? AttributeNode.getNodeValue() + " " : ""; + + AttributeNode = inputAttributes.getNamedItem("Value"); + Input += (AttributeNode != null) ? AttributeNode.getNodeValue() + " " : ""; + + restriction.setInput(Input.trim()); + } + excludeList.trimToSize(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + public ArrayList getIncompatibilityList() { + return excludeList; + } + + protected void addRestrictionCondition(RestrictionType restriction , Condition condition) + { + restriction.addCondition(condition); + } +} diff --git a/src/main/java/gamess/IncompatibilityPackage/Restriction/IIncompatibilityList.java b/src/main/java/gamess/IncompatibilityPackage/Restriction/IIncompatibilityList.java new file mode 100644 index 0000000..7a7cb6e --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/Restriction/IIncompatibilityList.java @@ -0,0 +1,10 @@ +package gamess.IncompatibilityPackage.Restriction; + +import java.util.ArrayList; + + + +public interface IIncompatibilityList +{ + ArrayList getIncompatibilityList(); +} diff --git a/src/main/java/gamess/IncompatibilityPackage/Restriction/IbuildList.java b/src/main/java/gamess/IncompatibilityPackage/Restriction/IbuildList.java new file mode 100644 index 0000000..fee7f0c --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/Restriction/IbuildList.java @@ -0,0 +1,6 @@ +package gamess.IncompatibilityPackage.Restriction; + +public interface IbuildList +{ + void buildList(String Data); +} diff --git a/src/main/java/gamess/IncompatibilityPackage/Restriction/RequiredIfRestriction.java b/src/main/java/gamess/IncompatibilityPackage/Restriction/RequiredIfRestriction.java new file mode 100644 index 0000000..cdf65da --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/Restriction/RequiredIfRestriction.java @@ -0,0 +1,92 @@ +package gamess.IncompatibilityPackage.Restriction; + +import java.util.ArrayList; + +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import gamess.GlobalParameters; +import gamess.IncompatibilityPackage.ConditionLogic.Condition; +import gamess.IncompatibilityPackage.ConditionLogic.ConditionBuilder; + +public class RequiredIfRestriction implements IbuildList, IIncompatibilityList { + + private ArrayList requiredList = new ArrayList(); + + String xpathPreExpr = "/root/input/requiredif[descendant::Entity"; + String xpathCondExpr = ""; + String xpathPostExpr = "]"; + private static XPath xpath = XPathFactory.newInstance().newXPath(); + + public void buildList(String Data) + { + try + { + + //InputSource inputSource = new InputSource(new FileInputStream("Incompatibility.xml"));; + + //build the condition matching given input + if(!Data.trim().equals("*")) + { + String Group,Keyword,Value; + String[] splitData = Data.split(" "); + + Group = (splitData.length > 0) ? "@Group='" + splitData[0] + "' and " : "not(@Group) and " ; + Keyword = (splitData.length > 1) ? "@Keyword='" + splitData[1] + "' and " : "not(@Keyword) and "; + Value = (splitData.length > 2) ? "@Value='" + splitData[2] + "'" : "not(@Value)"; + + xpathCondExpr = "[" + Group + Keyword + Value + "]"; + } + else + xpathCondExpr = ""; + + //get the xml node list matching the given condition + NodeList requiredNodes = (NodeList)xpath.evaluate(xpathPreExpr + xpathCondExpr + xpathPostExpr , GlobalParameters.doc , XPathConstants.NODESET); + + //Get the list of Required nodes + for (int i = 0; i < requiredNodes.getLength(); i++) + { + //For each required entity get the condition and add it to the restriction list + Node requiredIfEntity = requiredNodes.item(i); + + RestrictionType restriction = new RestrictionType(); + requiredList.add(restriction); + + //The condition which includes the nodes is the condition which is searched for i.e. Data + //XYZ is included because of ABC + Node firstchild = requiredIfEntity.getFirstChild(); + for(; firstchild != null && firstchild.getNodeType() == Node.TEXT_NODE ; firstchild = firstchild.getNextSibling()); + Condition requiredCondition = ConditionBuilder.buildCondition(firstchild); + + restriction.addCondition(requiredCondition); + + NamedNodeMap inputAttributes = requiredIfEntity.getParentNode().getAttributes(); + + Node AttributeNode = inputAttributes.getNamedItem("Group"); + String Input = (AttributeNode != null) ? AttributeNode.getNodeValue() + " " : ""; + + AttributeNode = inputAttributes.getNamedItem("Keyword"); + Input += (AttributeNode != null) ? AttributeNode.getNodeValue() + " " : ""; + + AttributeNode = inputAttributes.getNamedItem("Value"); + Input += (AttributeNode != null) ? AttributeNode.getNodeValue() + " " : ""; + + restriction.setInput(Input.trim()); + } + requiredList.trimToSize(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + public ArrayList getIncompatibilityList() { + return requiredList; + } + +} diff --git a/src/main/java/gamess/IncompatibilityPackage/Restriction/RequiresRestriction.java b/src/main/java/gamess/IncompatibilityPackage/Restriction/RequiresRestriction.java new file mode 100644 index 0000000..43de147 --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/Restriction/RequiresRestriction.java @@ -0,0 +1,82 @@ +package gamess.IncompatibilityPackage.Restriction; + +import java.util.ArrayList; + +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + +import gamess.GlobalParameters; +import gamess.IncompatibilityPackage.ConditionLogic.Condition; +import gamess.IncompatibilityPackage.ConditionLogic.ConditionBuilder; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class RequiresRestriction implements IbuildList, IIncompatibilityList { + + private ArrayList requiredList = new ArrayList(); + + String xpathPreExpr = "/root/input"; + String xpathCondExpr = ""; + String xpathPostExpr = "/requires/Entity"; + private static XPath xpath = XPathFactory.newInstance().newXPath(); + + public void buildList(String Data) { + try + { + + //InputSource inputSource = new InputSource(new FileInputStream("Incompatibility.xml"));; + + //build the condition matching given input + String Group,Keyword,Value; + String[] splitData = Data.split(" "); + + Group = (splitData.length > 0) ? "@Group='" + splitData[0] + "' and " : "not(@Group) and " ; + Keyword = (splitData.length > 1) ? "@Keyword='" + splitData[1] + "' and " : "not(@Keyword) and "; + Value = (splitData.length > 2) ? "@Value='" + splitData[2] + "'" : "not(@Value)"; + + xpathCondExpr = "[" + Group + Keyword + Value + "]"; + + //get the xml node list matching the given condition + NodeList requiredNodes = (NodeList)xpath.evaluate(xpathPreExpr + xpathCondExpr + xpathPostExpr , GlobalParameters.doc , XPathConstants.NODESET); + + //The condition which includes the nodes is the condition which is searched for i.e. Data + //XYZ is included because of ABC + Condition requiredCondition = ConditionBuilder.buildCondition(Data.trim()); + //Get the list of required nodes + for (int i = 0; i < requiredNodes.getLength(); i++) + { + //For each required entity get the condition and add it to the restriction list + Node currentRequiredEntity = requiredNodes.item(i); + + RestrictionType restriction = new RestrictionType(); + requiredList.add(restriction); + + restriction.addCondition(requiredCondition); + + NamedNodeMap inputAttributes = currentRequiredEntity.getAttributes(); + + Node AttributeNode = inputAttributes.getNamedItem("Group"); + String Input = (AttributeNode != null) ? AttributeNode.getNodeValue() + " " : ""; + + AttributeNode = inputAttributes.getNamedItem("Keyword"); + Input += (AttributeNode != null) ? AttributeNode.getNodeValue() + " " : ""; + + AttributeNode = inputAttributes.getNamedItem("Value"); + Input += (AttributeNode != null) ? AttributeNode.getNodeValue() + " " : ""; + + restriction.setInput(Input.trim()); + } + requiredList.trimToSize(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + public ArrayList getIncompatibilityList() { + return requiredList; + } + +} diff --git a/src/main/java/gamess/IncompatibilityPackage/Restriction/RestrictionType.java b/src/main/java/gamess/IncompatibilityPackage/Restriction/RestrictionType.java new file mode 100644 index 0000000..f666dfe --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/Restriction/RestrictionType.java @@ -0,0 +1,35 @@ +package gamess.IncompatibilityPackage.Restriction; + +import gamess.IncompatibilityPackage.ConditionLogic.Condition; + +public class RestrictionType +{ + protected String Input = ""; + protected Condition condition = null; + + public String getInput() + { + return Input; + } + + public void setInput(String _Input) + { + Input = _Input; + } + + + public void addCondition(Condition cond) + { + condition = cond; + } + + public Condition getCondition() + { + return condition; + } + + public boolean testCondition() + { + return condition.test(); + } +} diff --git a/src/main/java/gamess/IncompatibilityPackage/Restriction/RestrictionsHolder.java b/src/main/java/gamess/IncompatibilityPackage/Restriction/RestrictionsHolder.java new file mode 100644 index 0000000..b7ac149 --- /dev/null +++ b/src/main/java/gamess/IncompatibilityPackage/Restriction/RestrictionsHolder.java @@ -0,0 +1,46 @@ +package gamess.IncompatibilityPackage.Restriction; + + + +public class RestrictionsHolder +{ + private ExcludeRestriction exclude = new ExcludeRestriction(); + private RequiresRestriction requires = new RequiresRestriction(); + private ExcludedIfRestriction excludedif = new ExcludedIfRestriction(); + private RequiredIfRestriction requiredif = new RequiredIfRestriction(); + private AvailableOnlyIfRestriction availableonlyif = new AvailableOnlyIfRestriction(); + + public void buildRestriction(String Data) + { + ((IbuildList)exclude).buildList(Data); + ((IbuildList)requires).buildList(Data); + ((IbuildList)excludedif).buildList(Data); + ((IbuildList)requiredif).buildList(Data); + ((IbuildList)availableonlyif).buildList(Data); + } + + public IIncompatibilityList getExcludeRestriction() + { + return exclude; + } + + public IIncompatibilityList getExcludedIfRestriction() + { + return excludedif; + } + + public IIncompatibilityList getAvailableOnlyIfRestriction() + { + return availableonlyif; + } + + public IIncompatibilityList getRequiresRestriction() + { + return requires; + } + + public IIncompatibilityList getRequiredIfRestriction() + { + return requiredif; + } +} diff --git a/src/main/java/gamess/InputFileFilter.java b/src/main/java/gamess/InputFileFilter.java new file mode 100644 index 0000000..067f52c --- /dev/null +++ b/src/main/java/gamess/InputFileFilter.java @@ -0,0 +1,241 @@ +package gamess; + + +import javax.swing.JTextPane; +import javax.swing.text.AttributeSet; +import javax.swing.text.BadLocationException; +import javax.swing.text.DocumentFilter; +import javax.swing.text.Element; +import javax.swing.text.StyledDocument; + +public class InputFileFilter extends DocumentFilter +{ + StyledDocument styledDocument = null; + JTextPane textPane = null; + + public InputFileFilter(JTextPane _textPane) + { + textPane = _textPane; + styledDocument = textPane.getStyledDocument(); + textPane.setHighlighter(new WavedUnderline()); + } + + @Override + public void insertString(FilterBypass fb, int offset, String str, AttributeSet a) throws BadLocationException + { + //Insert is normally called by the MenuBuilder or by the Dialogs + if(UndoRedoHandler.isLocked() == false) + { + UndoRedoHandler.toggleGroupClassifier(); + UpdateInputFile.startUpdate(); + } + + //Highlight the keyword with color + if(UndoRedoHandler.isLocked() && str.contains("=")) + { + //This happens form the menubuilder + int splitIndex = str.indexOf("="); + String keyword = str.substring(0,splitIndex); + if(keyword.trim().indexOf(" ") != -1) + { + splitIndex = 0; + keyword = ""; + } + if(keyword.startsWith(" ")) + { + super.insertString(fb, offset, " " , Cosmetics.NORMAL_ATTRIBUTE); + keyword = keyword.substring(1); + offset++; + } + super.insertString(fb, offset, keyword, Cosmetics.KEYWORD_ATTRIBUTE); + super.insertString(fb, offset + keyword.length(), str.substring(splitIndex), Cosmetics.NORMAL_ATTRIBUTE); + return; + } + //First insert the text and parse the text + super.insertString(fb, offset, str, Cosmetics.NORMAL_ATTRIBUTE); + + //Check if the string inserted is having a group + //if it is then colour the group + setAttributes(offset,offset + str.length() + str.split("\n").length); + } + + @Override + public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { + //Remove can be called from (MenuBuilder|Dialogs) or Filemenu or by Handtyping + //Do nothing if it is called by (MenuBuilder|Dialogs) + //If the undoredohandler is locked then it is done by MenuBuilder/some Dialogs + if(UndoRedoHandler.isLocked() == false) + { + UndoRedoHandler.toggleGroupClassifier(); + UpdateInputFile.startUpdate(); + } + super.remove(fb, offset, length); + Element elem = styledDocument.getParagraphElement(offset); + + setAttributes(elem); + } + + private int previousInsertOffset = -2; + + @Override + public void replace(FilterBypass fb, int offset, int length, String str, AttributeSet a) throws BadLocationException { + //Replace is called from mainly from Handtyping + //Filter the single character typing + UpdateInputFile.startUpdate(); + + //if typed a character or a number or a ',' and if it is typed in a sequence + //then classify it as a same group otherwise change the group + if(!(str.length() == 1 && (Character.isLetterOrDigit(str.toCharArray()[0]) || str.equals(",")) && previousInsertOffset == offset-1)) + UndoRedoHandler.toggleGroupClassifier(); + previousInsertOffset = offset; + + super.replace(fb, offset, length, str, Cosmetics.NORMAL_ATTRIBUTE); + + setAttributes(offset, offset + str.length()); + } + + /*static final String tooltip = "ToolTip"; + public void setGroupAttributes(String str, int offset) + { + int strOffset = 0; + while(str.indexOf("$" , strOffset) != -1) + { + //get the starting position of the $ sign + int startOffset = str.indexOf("$",strOffset); + + //get the ending position of the $ sign + int endOffset = str.indexOf(" ", startOffset); + if(endOffset == -1) + endOffset = str.length(); + + Element currentGroupElement = styledDocument.getCharacterElement(offset + startOffset); + + //Check if the group is valid group contained in the list of group + if(GlobalParameters.listOfGroups.indexOf("|" + str.substring(startOffset, endOffset).toUpperCase().trim() + "|") == -1) + { + try + { + //Group is not available. Set normal attributes + //Set the tooltip + SimpleAttributeSet normalErrorAttributes = Cosmetics.getCustomAttribute(tooltip ,"Invalid group identifier",Cosmetics.NORMAL_ATTRIBUTE); + + //Add the highlight and add its tag + //Remove the underline if present + + Object HighlightTagAttribute = null; + if( (HighlightTagAttribute = currentGroupElement.getAttributes().getAttribute("HighlightTag")) != null) + { + textPane.getHighlighter().changeHighlight(HighlightTagAttribute, offset + startOffset , offset + endOffset); + normalErrorAttributes = Cosmetics.getCustomAttribute("HighlightTag", HighlightTagAttribute, normalErrorAttributes); + } + else + normalErrorAttributes = Cosmetics.getCustomAttribute("HighlightTag", textPane.getHighlighter().addHighlight(offset + startOffset , offset + endOffset, Cosmetics.ERROR_UNDERLINE) , normalErrorAttributes); + + //Set the character attributes + styledDocument.setCharacterAttributes(offset + startOffset ,endOffset - startOffset + 1, normalErrorAttributes , true); + } + catch (BadLocationException e){} + + strOffset = endOffset; + continue; + } + + Object HighlightTagAttribute = null; + if( (HighlightTagAttribute = currentGroupElement.getAttributes().getAttribute("HighlightTag")) != null) + textPane.getHighlighter().removeHighlight(HighlightTagAttribute); + + //Also remove highlight + + //Set the Group attribute to the String + styledDocument.setCharacterAttributes(offset + startOffset ,endOffset - startOffset + 1, Cosmetics.GROUP_ATTRIBUTE , true); + strOffset = endOffset; + } + }*/ + + private void setAttributes(int StartOffset, int EndOffset) + { + do + { + //Check if the end offset is greater than the actual end + if(EndOffset > styledDocument.getLength()) + EndOffset = styledDocument.getLength(); + // + Element paragraph = styledDocument.getParagraphElement(StartOffset); + setAttributes(paragraph); + StartOffset = paragraph.getEndOffset() + 1; + } + while(EndOffset > StartOffset); + } + + ///This is used to set the comment attribute and group attributes + private void setAttributes(Element paragraphElement) + { + String line = null; + try { + line = styledDocument.getText(paragraphElement.getStartOffset() , paragraphElement.getEndOffset() - paragraphElement.getStartOffset()); + } catch (BadLocationException e1) {} + + String trimmedLine = line.trim(); + + //Skip blankline + if(trimmedLine.length() == 0) + return; + + //Check if the line is a comment + if(trimmedLine.startsWith("!")) + { + //set the comments attribute on all the characters + Cosmetics.setCharacterAttributes(paragraphElement.getStartOffset() , paragraphElement.getEndOffset() - paragraphElement.getStartOffset(), Cosmetics.COMMENTS_ATTRIBUTE, true); + //set the comments attribute on the paragraph element for identifying that this paragraph is compeately a comment line. + //setting this attribute will help in other places to identify that this paragraphElement is a commented line. + Cosmetics.setParagraphAttributes(paragraphElement.getStartOffset() , paragraphElement.getEndOffset() - paragraphElement.getStartOffset(), Cosmetics.COMMENTS_ATTRIBUTE); + return; + } + + //if the line is changed from comment to normal group reset the group to normal + if(paragraphElement.getAttributes().containsAttributes(Cosmetics.COMMENTS_ATTRIBUTE)) + { + Cosmetics.setParagraphAttributes(paragraphElement.getStartOffset() , paragraphElement.getEndOffset() - paragraphElement.getStartOffset(), Cosmetics.NORMAL_ATTRIBUTE); + Cosmetics.setCharacterAttributes(paragraphElement.getStartOffset() , paragraphElement.getEndOffset() - paragraphElement.getStartOffset(), Cosmetics.NORMAL_ATTRIBUTE,true); + } + + //Set the attributes of the group in the line + for(int startOffset = 0, endOffset = -1, lineCurrentOffset = 0; (startOffset = line.indexOf("$" , lineCurrentOffset)) != -1; lineCurrentOffset = endOffset) + { + //get the ending position of the $ sign + endOffset = line.indexOf(" ", startOffset); + if(endOffset == -1) + endOffset = line.length()-1; + + //Check if the group is valid and group contained in the list of group + if(GlobalParameters.isGroupAvailable(line.substring(startOffset, endOffset))) + { + //Set the Group attribute to the String + styledDocument.setCharacterAttributes(paragraphElement.getStartOffset() + startOffset , endOffset - startOffset , Cosmetics.GROUP_ATTRIBUTE, true); + } + } + + //Reset all the invalid group elements + for (int i = 0; i < paragraphElement.getElementCount(); i++) { + Element currentElement = paragraphElement.getElement(i); + if(currentElement.getAttributes().containsAttributes(Cosmetics.GROUP_ATTRIBUTE)) + { + //find the group starting + int startOffset = currentElement.getStartOffset() - paragraphElement.getStartOffset(); + //find the end of the group + int endOffset = line.indexOf(" ", startOffset); + if(endOffset == -1) + endOffset = line.length() - 1; + //Get the group value + String group = line.substring(startOffset , endOffset); + //See if the group is valid + if(!GlobalParameters.isGroupAvailable(group)) + Cosmetics.setCharacterAttributes(startOffset + paragraphElement.getStartOffset(), endOffset - startOffset, Cosmetics.NORMAL_ATTRIBUTE, true); + + //Reset the counter if the endOffset has crossed the current element boundary + if(paragraphElement.getStartOffset() + endOffset > currentElement.getEndOffset()) + i = paragraphElement.getElementIndex(paragraphElement.getStartOffset() + endOffset); + } + } + } +} diff --git a/src/main/java/gamess/InputFileHandlers/DefaultKeywordRW.java b/src/main/java/gamess/InputFileHandlers/DefaultKeywordRW.java new file mode 100644 index 0000000..c3f1586 --- /dev/null +++ b/src/main/java/gamess/InputFileHandlers/DefaultKeywordRW.java @@ -0,0 +1,182 @@ +package gamess.InputFileHandlers; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.swing.JTextPane; + +public class DefaultKeywordRW extends KeywordRW { + + private static DefaultKeywordRW instance = null; + protected String CurrentKeyword = ""; + protected String KeywordValueDelimiter = "="; + + protected DefaultKeywordRW(JTextPane inputFilePane) + { + super(inputFilePane); + } + + public static DefaultKeywordRW getInstance(JTextPane inputFilePane ) + { + if(instance == null) + { + instance = new DefaultKeywordRW(inputFilePane); + } + return instance; + } + + ////////////////////////////////////////////////////////////// + + protected boolean CheckDataFormat(String Data) + { + if(Data.indexOf(KeywordValueDelimiter) == -1) + return false; + else + return true; + } + + protected int findKeyword(String keyword) + { + Pattern keywordPattern = Pattern.compile("\\s+" + + keyword.replace("(", "\\(").replace(")", "\\)") + + "\\s*" + KeywordValueDelimiter + "\\s*" , Pattern.CASE_INSENSITIVE); + Matcher keywordMatches = keywordPattern.matcher(CurrentGroupconText); + if(keywordMatches.find()) + { + return keywordMatches.end(); + } + return -1; + } + + protected void writeNewKeyword(String Data) + { + insertTextAt(groupOffset + CurrentGroupconText.length() , DefaultKeywordSeperator + Data); + } + + protected String getValueAt(int valueLocation) + { + //get the value end location + int valueEndLoc = CurrentGroupconText.indexOf(DefaultKeywordSeperator , valueLocation); + if(valueEndLoc == -1) + { + valueEndLoc = CurrentGroupconText.length(); + } + //get the value + return getTextAt(groupOffset + valueLocation, valueEndLoc - valueLocation); + } + + protected void writeValue(int valueLocation , String newValue ) + { + //Get the current value to the keyword + String currentValue = getValueAt(valueLocation); + //Check if the value is same. + if(!currentValue.equalsIgnoreCase(newValue)) + { + //The current value and the new Value are different. + //Replace the current value with the new value + replaceTextAt( + groupOffset + valueLocation, + currentValue.length(), + newValue); + } + } + + /** + * Get the offset from where the keyword starts + * This gives the offset in the local Group String + * @param keyword The keyword that has to be searched + * @return The location of the keyword in current group string + */ + protected int getKeywordStarting(String keyword) + { + return CurrentGroupconText.indexOf(keyword); + } + + protected String[] getKeywordValueSplit(String Data) + { + return Data.split(KeywordValueDelimiter); + } + + ////////////////////////////////////////////////////////////// + + @Override + public void write(String Group, String Data , int grpStart , int grpEnd ) { + //load the Group in the context + loadText(Group, grpStart , grpEnd - grpStart); + if(!CheckDataFormat(Data)) + { + //Error: Not correct format + return; + } + String[] datapart = getKeywordValueSplit(Data); + String keyword = datapart[0].trim(); + CurrentKeyword = keyword; + String value = datapart[1].trim(); + + //Check if the keyword is already present there + //yes = replace value ; no = insert value + int valueLocation = findKeyword(keyword); + if(valueLocation == -1) + { + //Keyword not found. So write the keyword at the end of the list + writeNewKeyword(Data); + return; + } + + //keyword is found. So replace the value + writeValue(valueLocation, value); + } + + @Override + void remove(String Group, String Data, int grpStart, int grpEnd) { + //load the Group in the context + loadText(Group, grpStart , grpEnd - grpStart); + + String keyword = Data; + if(CheckDataFormat(Data)) + { + //Error: KeywordValueDelimiter is present. You can only remove keyword + //return; + String[] datapart = getKeywordValueSplit(Data); + keyword = datapart[0].trim(); + } + CurrentKeyword = keyword; + int keywordEnding = findKeyword(keyword); + if(keywordEnding == -1) return; + int keywordStarting = getKeywordStarting(keyword); + keywordStarting--; //for space + + //Remove the value + writeValue(keywordEnding, ""); + + //Remove the keyword + replaceTextAt( + groupOffset + keywordStarting, + keywordEnding - keywordStarting, + ""); + } + + @Override + String read(String Group, int grpStart, int grpEnd) { + //load the Group in the context + loadText(Group, grpStart , grpEnd - grpStart); + return CurrentGroupconText; + } + + @Override + String read(String Group, String Keyword, int grpStart, int grpEnd) { + //load the Group in the context + loadText(Group, grpStart , grpEnd - grpStart); + if(CheckDataFormat(Keyword)) + { + //Error: KeywordValueDelimiter is present. You can only remove keyword + //return; + String[] datapart = getKeywordValueSplit(Keyword); + Keyword = datapart[0].trim(); + } + int keywordLocation = findKeyword(Keyword); + if(keywordLocation == -1) + return null; + return getValueAt(keywordLocation); + } +} diff --git a/src/main/java/gamess/InputFileHandlers/GridKeywordRW.java b/src/main/java/gamess/InputFileHandlers/GridKeywordRW.java new file mode 100644 index 0000000..6ee795b --- /dev/null +++ b/src/main/java/gamess/InputFileHandlers/GridKeywordRW.java @@ -0,0 +1,41 @@ +package gamess.InputFileHandlers; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.swing.JTextPane; + +public class GridKeywordRW extends DefaultKeywordRW { + + private static GridKeywordRW instance = null; + + protected GridKeywordRW(JTextPane inputFilePane) { + super(inputFilePane); + } + + public static GridKeywordRW getInstance(JTextPane inputFilePane ) + { + if(instance == null) + { + instance = new GridKeywordRW(inputFilePane); + } + return instance; + } + + + @Override + protected String getValueAt(int valueLocation) { + //if the Group is ZMAT and Keyword is either DLC or AUTO, Call the base function + if(CurrentGroup.equalsIgnoreCase("ZMAT") && (CurrentKeyword.equalsIgnoreCase("DLC") || CurrentKeyword.equalsIgnoreCase("AUTO"))) + return super.getValueAt(valueLocation); + + //else match the Grid format + Pattern keywordPattern = Pattern.compile("\\d+(\\s*,\\s*\\d+)*" , Pattern.CASE_INSENSITIVE); + Matcher keywordMatches = keywordPattern.matcher(CurrentGroupconText.substring(valueLocation)); + if(keywordMatches.find()) + { + return keywordMatches.group(); + } + return ""; + } +} diff --git a/src/main/java/gamess/InputFileHandlers/InputFileReader.java b/src/main/java/gamess/InputFileHandlers/InputFileReader.java new file mode 100644 index 0000000..923dc39 --- /dev/null +++ b/src/main/java/gamess/InputFileHandlers/InputFileReader.java @@ -0,0 +1,116 @@ +package gamess.InputFileHandlers; + +import javax.swing.JTextPane; +import javax.swing.text.BadLocationException; +import javax.swing.text.StyledDocument; + +import gamess.GamessGUI; + +public class InputFileReader { + private static InputFileReader instance = new InputFileReader(); + private JTextPane inputFilePane = null; + private StyledDocument inputFile = null; + + private InputFileReader() + { + if(GamessGUI.inputFilePane != null) + { + inputFilePane = GamessGUI.inputFilePane; + inputFile = GamessGUI.inputFilePane.getStyledDocument(); + } + } + + public static InputFileReader getInstance() + { + return instance; + } + + public String Read(String Group) + { + //Read the full Group + int groupStartPosition = -1; + if((groupStartPosition = getGroupStartPosition(Group)) == -1) + { + return null; + } + groupStartPosition += Group.length() + 1; + + int groupEndPosition = getFullInputText().indexOf("$END", groupStartPosition); + groupEndPosition--; + + KeywordRW KeywordReader = RWGetter.getReadWriteHandle(Group, inputFilePane); + return KeywordReader.read(Group, groupStartPosition, groupEndPosition); + } + + public String Read(String Group, String Keyword) + { + //Read the value of the keyword + int groupStartPosition = -1; + if((groupStartPosition = getGroupStartPosition(Group)) == -1) + { + return null; + } + groupStartPosition += Group.length() + 1; + + int groupEndPosition = getFullInputText().indexOf("$END", groupStartPosition); + groupEndPosition--; + + KeywordRW KeywordReader = RWGetter.getReadWriteHandle(Group, inputFilePane); + return KeywordReader.read(Group, Keyword, groupStartPosition, groupEndPosition); + } + + public boolean isAvailable(String Group) + { + if(Read(Group) == null) + return false; + return true; + } + + public boolean isAvailable(String Group, String Keyword) + { + int valueIndex = -1; + if( (valueIndex = Keyword.indexOf("=")) == -1) + { + if(Read(Group,Keyword) == null) + return false; + } + else + { + String value = Read(Group,Keyword.substring(0, valueIndex)); + if(value == null || !value.equalsIgnoreCase(Keyword.substring(valueIndex + 1))) + return false; + } + return true; + } + + private int getGroupStartPosition(String Group) + { + String fullText = getFullInputText(); + //Get the start index + for(int startIndex, possibleStartIndex = fullText.indexOf("$" + Group); possibleStartIndex != -1 ; possibleStartIndex = fullText.indexOf("$" + Group,startIndex + 1)) + { + startIndex = possibleStartIndex; + + //Try to hit the line starting backwards with empty spaces + while(--possibleStartIndex >= 0 && fullText.charAt(possibleStartIndex) == ' '); + + //Check if it is the starting of the text + if(possibleStartIndex == -1) + return startIndex; + //Check if there are some other characters in between + if(fullText.charAt(possibleStartIndex) != '\n') + continue; + + return startIndex; + } + return -1; + } + + private String getFullInputText() + { + try { + return inputFile.getText(0, inputFile.getLength()); + } catch (BadLocationException e) {} + return ""; + } +} diff --git a/src/main/java/gamess/InputFileHandlers/InputFileWriter.java b/src/main/java/gamess/InputFileHandlers/InputFileWriter.java new file mode 100644 index 0000000..2dd4b0d --- /dev/null +++ b/src/main/java/gamess/InputFileHandlers/InputFileWriter.java @@ -0,0 +1,232 @@ +package gamess.InputFileHandlers; + +import javax.swing.JTextPane; +import javax.swing.text.BadLocationException; +import javax.swing.text.StyledDocument; + +import gamess.GamessGUI; + + +public class InputFileWriter { + + private static InputFileWriter instance = new InputFileWriter(); + private JTextPane inputFilePane = null; + private StyledDocument inputFile = null; + private String GroupOrder = "CONTRL,BASIS"; + + private InputFileWriter() + { + if(GamessGUI.inputFilePane != null) + { + inputFilePane = GamessGUI.inputFilePane; + inputFile = GamessGUI.inputFilePane.getStyledDocument(); + } + } + + public static InputFileWriter getInstance() + { + return instance; + } + + public void Write(String Group, String Data) + { + //Get the group position where the keyword has to be written + int groupStartPos = getKeywordGroupPosition(Group); + groupStartPos += Group.length() + 1; + + //Get the end position of the text + int groupEndPos = getFullInputText().toUpperCase().indexOf("$END", groupStartPos); + groupEndPos--; + + //if the group does not have an ending then add it + if(groupEndPos < 0) + { + int caretPosition = inputFilePane.getCaretPosition(); + insertTextAt(inputFile.getLength() , " $END"); + groupEndPos = getFullInputText().toUpperCase().indexOf("$END", groupStartPos); + groupEndPos--; + inputFilePane.setCaretPosition(caretPosition); + } + if(groupEndPos < 0) + return; + + //Get the keyword writer and write the data + KeywordRW KeywordWriter= RWGetter.getReadWriteHandle(Group, inputFilePane); + KeywordWriter.write(Group, Data, groupStartPos, groupEndPos); + } + + public void Remove(String Group, String Data) + { + //Check if the Group is present + int groupStartPos = getGroupPosition(Group); + if(groupStartPos == -1) + { + //Error: group not found + return; + } + groupStartPos += Group.length() + 1; + + //Get the end position of the text + int groupEndPos = getFullInputText().toUpperCase().indexOf("$END", groupStartPos); + groupEndPos--; + + //Get the keyword writer and write the data + KeywordRW KeywordWriter= RWGetter.getReadWriteHandle(Group, inputFilePane); + KeywordWriter.remove(Group, Data, groupStartPos, groupEndPos); + } + + ////////////////////////////////////////////////////////////////// + // Get the position where group is // + // If group is not found write it // + ////////////////////////////////////////////////////////////////// + private int getKeywordGroupPosition(String Group) + { + int groupPos = -1; + //check if the group is present + //if yes return the group position + //if no create the group position and return it + if( (groupPos = getGroupPosition(Group)) == -1) + { + //Group is not present so create it + + //First check the rule for the order in which the + //Group has to appear + + //Check if this group is there in the order + if(GroupOrder.indexOf(Group) == -1) + { + //Group is not there in the order. So append the group + groupPos = inputFile.getLength(); + if(groupPos != 0) + { + if(!getFullInputText().endsWith("\n")) + { + insertTextAt(inputFile.getLength(), "\n"); + groupPos += "\n".length(); + } + } + } + else + { + //Group is there in some order. + //Resolve the order + String[] OrderSplit = GroupOrder.split(","); + int GroupLocation = -1; + for (int i = 0; i < OrderSplit.length; i++) { + if(OrderSplit[i].equals(Group)) + { + GroupLocation = i; + break; + } + } + + //Check if you can insert this group after the previous group + groupPos = insertGroupBefore(OrderSplit, GroupLocation); + + //else check if you can insert this group before next available group + if(groupPos == -1) + { + groupPos = insertGroupAfter(OrderSplit, GroupLocation); + } + } + + //Create the group and write the text start and end + insertTextAt(groupPos, " $" + Group.toUpperCase() + " $END"); + groupPos++; //for the space before the group starting.(see above line) + } + + return groupPos; + } + + private int insertGroupBefore(String[] GroupsBefore , int currGrpPos) + { + //Find the last group in the set that is available and insert after that + //reverse direction + for (int i = currGrpPos - 1 , insPos; i >= 0 ; i--) { + if(GroupsBefore[i].equals("...")) + return -1; + if((insPos = getGroupPosition(GroupsBefore[i])) != -1) + { + //Last group that is available is found + //find the end of the group + insPos = getFullInputText().toUpperCase().indexOf("$END", insPos); + insPos += "$END".length(); + insPos = insertTextAt(insPos, "\n"); + return insPos; + } + } + + //No group is found before this. So write the group in the first + if(inputFile.getLength() != 0) + insertTextAt(0, "\n"); + return 0; + } + + private int insertGroupAfter(String[] GroupsAfter , int currGrpPos) + { + //Control comes here only if there is ... before the current group + + //Find the first group in the set that is available and insert before that + //forward direction + for (int i = currGrpPos + 1 , insPos; i < GroupsAfter.length; i++) { + if(GroupsAfter[i].equals("...")) + continue; + if((insPos = getGroupPosition(GroupsAfter[i])) != -1) + { + insertTextAt(insPos, "\n"); + return insPos; + } + } + + //No group is found after this group. So append this at the end + if(inputFile.getLength() != 0) + { + if(!getFullInputText().endsWith("\n")) + insertTextAt(inputFile.getLength(), "\n"); + } + return inputFile.getLength(); + } + + private int insertTextAt(int pos , String text) + { + try + { + inputFile.insertString(pos, text , null); + } + catch (BadLocationException e) {} + return pos + text.length(); + } + + private int getGroupPosition(String Group) + { + String fullText = getFullInputText().toUpperCase(); + //Get the start index + for(int startIndex, possibleStartIndex = fullText.indexOf("$" + Group.toUpperCase()); possibleStartIndex != -1 ; possibleStartIndex = fullText.indexOf("$" + Group,startIndex + 1)) + { + startIndex = possibleStartIndex; + + //Try to hit the line starting backwards with empty spaces + while(--possibleStartIndex >= 0 && fullText.charAt(possibleStartIndex) == ' '); + + //Check if it is the starting of the text + if(possibleStartIndex == -1) + return startIndex; + //Check if there are some other characters in between + if(fullText.charAt(possibleStartIndex) != '\n') + continue; + + return startIndex; + } + return -1; + } + + ////////////////////////////////////////////////////////////////// + + private String getFullInputText() + { + try { + return inputFile.getText(0, inputFile.getLength()); + } catch (BadLocationException e) {} + return ""; + } +} diff --git a/src/main/java/gamess/InputFileHandlers/KeywordRW.java b/src/main/java/gamess/InputFileHandlers/KeywordRW.java new file mode 100644 index 0000000..3272456 --- /dev/null +++ b/src/main/java/gamess/InputFileHandlers/KeywordRW.java @@ -0,0 +1,76 @@ +package gamess.InputFileHandlers; + +import javax.swing.JTextPane; +import javax.swing.text.BadLocationException; +import javax.swing.text.StyledDocument; + +public abstract class KeywordRW { + + private StyledDocument inputFile = null; + protected int groupOffset = -1; + protected String DefaultKeywordSeperator = " "; + protected String CurrentGroupconText = null; + protected String CurrentGroup = null; + + public KeywordRW(JTextPane _inputFilePane) { + if(_inputFilePane != null) + inputFile = _inputFilePane.getStyledDocument(); + } + + protected final void loadText(String _Group, int _offset , int length) + { + CurrentGroupconText = null; + CurrentGroup = _Group; + groupOffset = _offset; + try + { + CurrentGroupconText = inputFile.getText(groupOffset, length); + } catch (BadLocationException e) {} + } + + protected final String getTextAt(int offset , int length) + { + String requestedText = null; + try + { + requestedText = inputFile.getText(offset, length); + } catch (BadLocationException e) {} + + return requestedText; + } + + + protected final int insertTextAt(int pos , String text) + { + try + { + inputFile.insertString(pos, text , null); + } + catch (BadLocationException e) {} + return pos + text.length(); + } + + protected final void replaceTextAt(int offset , int length , String replaceText) + { + try + { + inputFile.remove(offset, length); + inputFile.insertString(offset, replaceText , null); + } + catch (BadLocationException e) {} + } + + protected final void removeTextAt(int offset , int length) + { + try + { + inputFile.remove(offset, length); + } + catch (BadLocationException e) {} + } + + abstract void write(String Group, String Data , int grpStart , int grpEnd); + abstract void remove(String Group, String Data , int grpStart , int grpEnd); + abstract String read(String Group, int grpStart , int grpEnd);; + abstract String read(String Group, String Keyword , int grpStart , int grpEnd); +} diff --git a/src/main/java/gamess/InputFileHandlers/PlainDataRW.java b/src/main/java/gamess/InputFileHandlers/PlainDataRW.java new file mode 100644 index 0000000..ca1b5a0 --- /dev/null +++ b/src/main/java/gamess/InputFileHandlers/PlainDataRW.java @@ -0,0 +1,57 @@ +package gamess.InputFileHandlers; + +import javax.swing.JTextPane; + +public class PlainDataRW extends KeywordRW { + + private static PlainDataRW instance= null; + + protected PlainDataRW(JTextPane _inputFilePane) { + super(_inputFilePane); + } + + public static PlainDataRW getInstance(JTextPane inputFilePane) { + if(instance == null) + { + instance = new PlainDataRW(inputFilePane); + } + return instance; + } + + @Override + void remove(String Group, String Data, int grpStart, int grpEnd) { + removeTextAt(grpStart, grpEnd - grpStart); + insertTextAt(grpStart, " "); + } + + @Override + void write(String Group, String Data, int grpStart, int grpEnd) { + //Remove the complete text and rewrite the text completely + removeTextAt(grpStart, grpEnd - grpStart); + + //Rewrite the text with the newline at start and end + StringBuilder sb = new StringBuilder(Data); + if(!Data.startsWith("\n")) + { + sb.insert( 0 , "\n"); + } + if(!Data.endsWith("\n")) + { + sb.append("\n"); + } + + insertTextAt(grpStart, sb.toString()); + } + + @Override + String read(String Group, int grpStart, int grpEnd) { + loadText(Group, grpStart, grpEnd - grpStart); + return CurrentGroupconText; + } + + @Override + String read(String Group, String Keyword, int grpStart, int grpEnd) { + return read(Group, grpStart, grpEnd); + } + +} diff --git a/src/main/java/gamess/InputFileHandlers/RWGetter.java b/src/main/java/gamess/InputFileHandlers/RWGetter.java new file mode 100644 index 0000000..8a99b43 --- /dev/null +++ b/src/main/java/gamess/InputFileHandlers/RWGetter.java @@ -0,0 +1,50 @@ +package gamess.InputFileHandlers; + +import java.util.ArrayList; + +import javax.swing.JTextPane; + +import gamess.GlobalParameters; + +public class RWGetter { + private static ArrayList plainDataGroup = new ArrayList(); + private static ArrayList gridGroup = new ArrayList(); + + //public static void loadHandleDetails() + static + { + //Loading plain data group + plainDataGroup = GlobalParameters.plainDataGroup; + + //Loading grid group + gridGroup = GlobalParameters.gridGroup; + } + + public static KeywordRW getReadWriteHandle(String Group , JTextPane inputFilePane) + { + if(plainDataGroup.contains(Group.toUpperCase())) + { + //The group is a plain Data Group + //return the plainDataGroup handler instance + return PlainDataRW.getInstance(inputFilePane); + } + else if(gridGroup.contains(Group.toUpperCase())) + { + //The group is a grid group + //return the grid group handler instance + return GridKeywordRW.getInstance(inputFilePane); + } + else if(Group.toUpperCase().equals("TDHFX")) + { + //The group is a TDHFX group + //return the TDHFX group handler instance + return TDHFXKeywordRW.getInstance(inputFilePane); + } + else + { + //The group does not belong to any above group. This should be a default group + //return the default group handler instance + return DefaultKeywordRW.getInstance(inputFilePane); + } + } +} diff --git a/src/main/java/gamess/InputFileHandlers/TDHFXKeywordRW.java b/src/main/java/gamess/InputFileHandlers/TDHFXKeywordRW.java new file mode 100644 index 0000000..1052c0f --- /dev/null +++ b/src/main/java/gamess/InputFileHandlers/TDHFXKeywordRW.java @@ -0,0 +1,223 @@ +package gamess.InputFileHandlers; + +import java.util.ArrayList; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.swing.JTextPane; + +public class TDHFXKeywordRW extends DefaultKeywordRW { + + private static TDHFXKeywordRW instance = null; + private ArrayList set1 = new ArrayList(); + private ArrayList set2 = new ArrayList(); + private String Keyword = ""; + private String Value = ""; + private String emptySpaces = "\n "; + + protected TDHFXKeywordRW(JTextPane inputFilePane) { + super(inputFilePane); + DefaultKeywordSeperator = "\n"; + KeywordValueDelimiter = " "; + + //Load set1 values + set1.add("ALLDIRS"); + set1.add("DIR"); + set1.add("USE_C"); + set1.add("USE_Q"); + + //Load set2 values + set2.add("FREQ"); + set2.add("FREQ2"); + } + + public static TDHFXKeywordRW getInstance(JTextPane inputFilePane) + { + if(instance == null) + { + instance = new TDHFXKeywordRW(inputFilePane); + } + return instance; + } + + @Override + protected boolean CheckDataFormat(String Data) { + String[] split = getKeywordValueSplit(Data); + Keyword = split[0]; + Value = split[1]; + + //Check if the format is normal + //if this group dose not end with a newline add a newline at the end + if(!getTextAt(groupOffset + CurrentGroupconText.length(), 1).equals("\n")) + { + replaceTextAt(groupOffset + CurrentGroupconText.length(), 1 , "\n"); + } + return true; + } + + @Override + protected int findKeyword(String keyword) { + //Check if the keyword is FREE + if(!keyword.equalsIgnoreCase("FREE")) + { + //Get the normal pattern matching to get the keyword + Pattern keywordPattern = Pattern.compile("\\s*" + + keyword.replace("(", "\\(").replace(")", "\\)") + + "[ \t]*", Pattern.CASE_INSENSITIVE); + Matcher keywordMatches = keywordPattern.matcher(CurrentGroupconText); + if(keywordMatches.find()) + { + return keywordMatches.end(); + } + } + else + { + //Get the FREE keyword: based on the value + //Check to which pattern the value belongs + String matchedPattern = ""; + String freePattern1 = "\\d+\\.?\\d*+\\s*"; + String freePattern2 = "\\d+\\.?\\d*+\\s+\\d+\\.?\\d*+\\s*"; + String freePattern3 = "\\d+\\.?\\d*+\\s+\\d+\\.?\\d*+\\s+\\d+\\.?\\d*+\\s*"; + + //Test for pattern1 + Pattern keywordPattern = Pattern.compile(freePattern1 , Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); + Matcher keywordMatches = keywordPattern.matcher(Value); + if(keywordMatches.find()) + { + matchedPattern = freePattern1; + } + + //Test for pattern2 + keywordPattern = Pattern.compile(freePattern2 , Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); + keywordMatches = keywordPattern.matcher(Value); + if(keywordMatches.find()) + { + matchedPattern = freePattern2; + } + + //Test for pattern3 + keywordPattern = Pattern.compile(freePattern3 , Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); + keywordMatches = keywordPattern.matcher(Value); + if(keywordMatches.find()) + { + matchedPattern = freePattern3; + } + + if(matchedPattern.length() == 0) + return -1; + + //Test for the matching keyword in the input file + keywordPattern = Pattern.compile("^(\\s*" + + keyword.replace("(", "\\(").replace(")", "\\)") + + "\\s+)" + matchedPattern + "$", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); + keywordMatches = keywordPattern.matcher(CurrentGroupconText); + if(keywordMatches.find()) + { + keywordMatches.find(1); + return keywordMatches.end(1); + } + } + return -1; + } + + @Override + protected void writeNewKeyword(String Data) { + //Check if keyword is in set1 + if(set1.contains(Keyword)) + { + //The keyword belongs to set 1. + //Find the last set 1 item and write the keyword after that + insertTextAt( groupOffset + findLastSet1Keyword() , emptySpaces + Data); + } + //else check if the keyword is in set 2 + else if(set2.contains(Keyword)) + { + //The keyword belongs to set 1. + insertTextAt( groupOffset + findLastSet2Keyword() , emptySpaces + Data); + } + //else the keyword is in set 3. So append the data + else + { + //append the keyword to the last + insertTextAt( groupOffset + CurrentGroupconText.length() , emptySpaces + Data); + } + } + + @Override + protected int getKeywordStarting(String keyword) { + int keywordStart = CurrentGroupconText.substring(0 , findKeyword(keyword)).lastIndexOf("\n"); + keywordStart++; + return keywordStart; + } + + @Override + protected String[] getKeywordValueSplit(String Data) { + String[] splitValue = Data.split(KeywordValueDelimiter); + if(splitValue.length == 2) + return splitValue; + if(splitValue.length > 2) + { + String[] returnValue = new String[2]; + returnValue[0] = splitValue[0]; + returnValue[1] = ""; + for (int i = 1; i < splitValue.length; i++) { + returnValue[1] += splitValue[i] + " "; + } + returnValue[1] = returnValue[1].trim(); + return returnValue; + } + String[] returnValue = new String[2]; + returnValue[0] = splitValue[0]; + returnValue[1] = ""; + return returnValue; + } + + private int findLastSet1Keyword() + { + int lastLocation = 0; + for (int i = 0; i < set1.size(); i++) + { + int keywordLoc = CurrentGroupconText.indexOf(set1.get(i)); + if(keywordLoc > lastLocation) + lastLocation = keywordLoc; + } + if(lastLocation != 0) + { + int endLocation = CurrentGroupconText.indexOf("\n" , lastLocation); + if(endLocation != -1) + { + lastLocation = endLocation; + } + else + { + lastLocation += CurrentGroupconText.substring(lastLocation).length(); + } + } + return lastLocation; + } + + private int findLastSet2Keyword() + { + int lastSet1Location = findLastSet1Keyword(); + int lastLocation = lastSet1Location; + for (int i = 0; i < set2.size(); i++) + { + int keywordLoc = CurrentGroupconText.indexOf(set2.get(i) , lastLocation); + if(keywordLoc > lastLocation) + lastLocation = keywordLoc; + } + if(lastLocation != lastSet1Location) + { + int endLocation = CurrentGroupconText.indexOf("\n" , lastLocation); + if(endLocation != -1) + { + lastLocation = endLocation; + } + else + { + lastLocation += CurrentGroupconText.substring(lastLocation).length(); + } + } + return lastLocation; + } +} diff --git a/src/main/java/gamess/MenuBuilder.java b/src/main/java/gamess/MenuBuilder.java new file mode 100644 index 0000000..85bccba --- /dev/null +++ b/src/main/java/gamess/MenuBuilder.java @@ -0,0 +1,856 @@ +/*Copyright (c) 2007, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ +/** + * @author Shreeram + * @author Michael Sheetz + */ +package gamess; + +import java.awt.Component; +import java.awt.Frame; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.io.File; +import java.util.Hashtable; +import java.util.Stack; + +import javax.swing.JDialog; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.WindowConstants; +import javax.swing.event.MenuListener; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import gamess.Storage.Repository; +import org.w3c.dom.*; + +import gamess.Dialogs.MatrixDialog; +import gamess.Dialogs.MenuTableDialog; +import gamess.Dialogs.TextDialog; +import gamess.IncompatibilityPackage.ExcludeIncompatibility; +import gamess.InputFileHandlers.InputFileWriter; + +public class MenuBuilder { + + private JMenuBar menuBar; + private String menuFileLocation; + private Node relativeNode; + private Document doc = null; + private Hashtable MenuValueMapper = new Hashtable(); + private MenuListener standardMenuListener = null; + private ActionListener standardMenuItemListener = null; + private Stack menuPath = new Stack() , menuPathImage = new Stack(); + private Frame parentFrame; + private Hashtable CustomDialogs; + private XPath toolTipXPath = XPathFactory.newInstance().newXPath(); + + public MenuBuilder(JMenuBar _menuBar, Frame _parentFrame, String _menuFileLocation, Hashtable _CustomDialogs) + { + menuBar = _menuBar; + menuFileLocation = _menuFileLocation; + parentFrame = _parentFrame; + CustomDialogs = _CustomDialogs; + } + + public MenuBuilder(JMenuBar _menuBar, Frame _parentFrame, Node _relativeNode, Hashtable _CustomDialogs) + { + menuBar = _menuBar; + relativeNode = _relativeNode; + parentFrame = _parentFrame; + CustomDialogs = _CustomDialogs; + } + + public void BuildMenu() + { + /** + * The nodes that has to be parsed + */ + NodeList nodesToParse = null; + + /* + * if relativeNode is null the object has been called with filename + * In that case open file and get the root node + */ + if(relativeNode == null) + { + try { + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + dbFactory.setIgnoringComments(true); + dbFactory.setValidating(false); + dbFactory.setIgnoringElementContentWhitespace(true); + DocumentBuilder builder = dbFactory.newDocumentBuilder(); + doc = builder.parse(new File(menuFileLocation)); + Node root = doc.getFirstChild(); + + //Check if this is the correct Document + if(root.getNodeName().equals("gamessInput")) + { + nodesToParse = root.getChildNodes(); + } + else + { +// Error:Throw exception malformed xml + } + } catch (Exception e) { + e.printStackTrace(); + } + } + else + { + nodesToParse = relativeNode.getChildNodes(); + } + + //Check if the standard menu Listener is Null + if(standardMenuItemListener == null) + { + standardMenuItemListener = new StandardMenuItemListener(); + } + if(standardMenuListener == null) + { + standardMenuListener = new StandardMenuListener(); + } + + /* + * Pass each root node and build the menu + */ + for(int i = 0 ; i < nodesToParse.getLength() ; i++) + { + if(nodesToParse.item(i).getNodeType() != Node.TEXT_NODE) + InsertMenu(nodesToParse.item(i) , null , ""); + } + } + + /** + * Insert Menu + * @param currNode Current Node + * @param parentMenu + * @param parentGroup + */ + private void InsertMenu(Node currNode , JMenu parentMenu, String parentGroup) + { + NamedNodeMap CurrAttributes; + Node LocalAttribute; + String CurrentGroupName = parentGroup; + + //Get all the attributes of current node + CurrAttributes = currNode.getAttributes(); + + //if the current node has a group tag (Overriding) + if((LocalAttribute = CurrAttributes.getNamedItem("Group")) != null) + { + CurrentGroupName = LocalAttribute.getNodeValue(); + } + + /* + * If the current tag is the new group tag + * (all the items below it will be of this group unless overriden) + */ + if(currNode.getNodeName().trim().equals("Group")) + { + Node LocalNode = null; + if((LocalNode = CurrAttributes.getNamedItem("Name")) == null) + { + //Error:Throw name attribute not available + } + CurrentGroupName = LocalNode.getNodeValue(); + //Get all the node list under it and pass it with the new group + NodeList ChildNodes = currNode.getChildNodes(); + for(int i = 0 ; i < ChildNodes.getLength() ; i++) + { + if(ChildNodes.item(i).getNodeType() != Node.TEXT_NODE) + InsertMenu(ChildNodes.item(i), parentMenu, CurrentGroupName); + } + return; + } + + + /* + * Check if Current tag is either Menu or MenuItem or Seperator + * if neither then throw error + * The tags that occur in this recursion should be either menu or menuitem + */ + if(currNode.getNodeName().equals("Menu")) + { + if(CurrentGroupName == null || CurrentGroupName.trim().length() == 0) + { + //Error:throw error malformed menu xml + } + + //This node is of type menu and is a submenu to the parent menu + //add a jmenu to the parentMenu + JMenu CurrentMenu = new JMenu(); + if(parentMenu == null) + { + //add the new menu to the menubar + menuBar.add(CurrentMenu); + } + else + { + parentMenu.add(CurrentMenu); + } + + /* + * Set the properties of the new menu created + */ + + //Basic properties + CurrentMenu.setText(CurrAttributes.getNamedItem("DisplayName").getNodeValue()); + if(CurrAttributes.getNamedItem("ActionName") == null) + { + CurrentMenu.setActionCommand(CurrAttributes.getNamedItem("DisplayName").getNodeValue()); + } + else + { + CurrentMenu.setActionCommand(CurrAttributes.getNamedItem("ActionName").getNodeValue()); + } + if(CurrAttributes.getNamedItem("ToolTip") != null) + { + String toolTip = CurrAttributes.getNamedItem("ToolTip").getNodeValue(); + CurrentMenu.setToolTipText(getParsedToolTipForMenu(toolTip)); + } + + String MenuType = null; + if(CurrAttributes.getNamedItem("MenuType") == null) + { + //Error:No MenuType attribute found in + } + MenuType = CurrAttributes.getNamedItem("MenuType").getNodeValue(); + + if(MenuType.equals("Dummy")) + CurrentMenu.addMenuListener(new DummyMenuListener()); + + //Additional properties + if(MenuType.equals("Keyword") || MenuType.equals("Value") || MenuType.equals("Both") || MenuType.equals("Group")) + { + //Create the Entity Type + MenuEntity Entity = new MenuEntity(); + Entity.Group = CurrentGroupName; + Entity.MenuType = EntityType.GROUP; + if(MenuType.equals("Keyword")) + { + Entity.Keyword = CurrentMenu.getActionCommand(); + Entity.MenuType = EntityType.KEYWORD; + } + if(MenuType.equals("Value")) + { + Entity.Value = CurrentMenu.getActionCommand(); + Entity.Keyword = CurrAttributes.getNamedItem("Keyword").getNodeValue(); + Entity.MenuType = EntityType.VALUE; + } + if(MenuType.equals("Both")) + { + String[] KW_V_item = CurrentMenu.getActionCommand().split("="); + Entity.Keyword = KW_V_item[0]; + Entity.Value = KW_V_item[1]; + Entity.MenuType = EntityType.BOTH; + } + //Add the entity to the HashTable + MenuValueMapper.put(CurrentMenu, Entity); + + ////////////////////////////////////////////////////////////////////// + // Register the entity with the Organized document // + // This is used for the ContentAssist + if(Entity.MenuType == EntityType.GROUP) + Dictionary.Register(Entity.Group); + else if(Entity.MenuType == EntityType.KEYWORD) + Dictionary.Register(Entity.Group, Entity.Keyword); + else + Dictionary.Register(Entity.Group, Entity.Keyword, Entity.Value); + // // + ////////////////////////////////////////////////////////////////////// + + //Set the listener to the menu + CurrentMenu.addMenuListener(standardMenuListener); + + } + if(MenuType.equals("GroupFrame") || MenuType.equals("Grid") || MenuType.equals("Custom") || MenuType.equals("Textbox")) + { + ItemLauncher LaunchListener = new ItemLauncher(); + LaunchListener.setGroup(CurrentGroupName); + LaunchListener.setReferenceNode(currNode); + if(MenuType.equals("GroupFrame")) + LaunchListener.setLaunchType(LaunchType.GROUPFRAME); + if(MenuType.equals("Grid")) + LaunchListener.setLaunchType(LaunchType.GRID); + if(MenuType.equals("Textbox")) + LaunchListener.setLaunchType(LaunchType.TEXTBOX); + if(MenuType.equals("Custom")) + { + LaunchListener.setLaunchType(LaunchType.CUSTOM); + //Add the JDialog passed in + LaunchListener.setCustomDialog(CustomDialogs.get(CurrentMenu.getActionCommand()), true); + } + CurrentMenu.addMouseListener(LaunchListener); + + //This is used for creating objects that are required for content assist + LaunchListener.createObject(); + + //These kind of menus are of Launch type so any menu having this will not be built further + return; + } + //Call the same function recursively to all the child nodes of the current node + NodeList ChildNodeList = currNode.getChildNodes(); + for(int i = 0; i < ChildNodeList.getLength() ; i++) + { + if(ChildNodeList.item(i).getNodeType() != Node.TEXT_NODE) + InsertMenu(ChildNodeList.item(i), CurrentMenu, CurrentGroupName); + } + + return; + } + else if(currNode.getNodeName().equals("MenuItem")) + { + if(parentMenu == null || CurrentGroupName == null || CurrentGroupName.trim().length() == 0) + { + //Error:throw error malformed menu xml + } + + //create add a new menuitem + JMenuItem CurrentMenuItem = new JMenuItem(); + parentMenu.add(CurrentMenuItem); + + /* + * Set the properties of the new menuitem created + */ + + //Basic properties + CurrentMenuItem.setText(CurrAttributes.getNamedItem("DisplayName").getNodeValue()); + if(CurrAttributes.getNamedItem("ActionName") == null) + { + CurrentMenuItem.setActionCommand(CurrAttributes.getNamedItem("DisplayName").getNodeValue()); + } + else + { + CurrentMenuItem.setActionCommand(CurrAttributes.getNamedItem("ActionName").getNodeValue()); + } + + if(CurrAttributes.getNamedItem("ToolTip") != null) + { + String toolTip = CurrAttributes.getNamedItem("ToolTip").getNodeValue(); + CurrentMenuItem.setToolTipText(getParsedToolTipForMenu(toolTip)); + } + + String MenuType = null; + if(CurrAttributes.getNamedItem("MenuType") == null) + { + //Error:No MenuType attribute found in + } + MenuType = CurrAttributes.getNamedItem("MenuType").getNodeValue(); + + //Additional Properties + + if(MenuType.equals("Keyword") || MenuType.equals("Value") || MenuType.equals("Both") || MenuType.equals("Group")) + { + //Create the Entity Type + MenuEntity Entity = new MenuEntity(); + Entity.Group = CurrentGroupName; + Entity.MenuType = EntityType.GROUP; + if(MenuType.equals("Keyword")) + { + Entity.Keyword = CurrentMenuItem.getActionCommand(); + Entity.MenuType = EntityType.KEYWORD; + } + if(MenuType.equals("Value")) + { + Entity.Value = CurrentMenuItem.getActionCommand(); + Entity.Keyword = CurrAttributes.getNamedItem("Keyword").getNodeValue(); + Entity.MenuType = EntityType.VALUE; + } + if(MenuType.equals("Both")) + { + String[] KW_V_item = CurrentMenuItem.getActionCommand().split("="); + Entity.Keyword = KW_V_item[0]; + Entity.Value = (KW_V_item.length != 2)?"":KW_V_item[1]; + Entity.MenuType = EntityType.BOTH; + } + //Add the entity to the HashTable + MenuValueMapper.put(CurrentMenuItem, Entity); + + ////////////////////////////////////////////////////////////////////// + // Register the entity with the Organized document // + /**/ if(Entity.MenuType == EntityType.GROUP) + /**/ Dictionary.Register(Entity.Group); + /**/ else if(Entity.MenuType == EntityType.KEYWORD) + /**/ Dictionary.Register(Entity.Group, Entity.Keyword); + /**/ else + /**/ Dictionary.Register(Entity.Group, Entity.Keyword, Entity.Value); + // // + ////////////////////////////////////////////////////////////////////// + + //Set the action listener to the menu + CurrentMenuItem.addActionListener(standardMenuItemListener); + } + if(MenuType.equals("GroupFrame") || MenuType.equals("Grid") || MenuType.equals("Custom") || MenuType.equals("Textbox")) + { + ItemLauncher LaunchListener = new ItemLauncher(); + LaunchListener.setGroup(CurrentGroupName); + LaunchListener.setReferenceNode(currNode); + if(MenuType.equals("GroupFrame")) + LaunchListener.setLaunchType(LaunchType.GROUPFRAME); + if(MenuType.equals("Grid")) + LaunchListener.setLaunchType(LaunchType.GRID); + if(MenuType.equals("Textbox")) + LaunchListener.setLaunchType(LaunchType.TEXTBOX); + if(MenuType.equals("Custom")) + { + LaunchListener.setLaunchType(LaunchType.CUSTOM); + //Add the JDialog passed in + LaunchListener.setCustomDialog(CustomDialogs.get(CurrentMenuItem.getActionCommand()), true); + } + CurrentMenuItem.addActionListener(LaunchListener); + + //This is used for creating objects that are required for content assist + LaunchListener.createObject(); + + //These kind of menus are of Launch type so any menu having this will not be built further + return; + } + + return; + } + else if(currNode.getNodeName().equals("Seperator")) + { + if(parentMenu == null) + { + //Error:throw error malformed menu xml + } + parentMenu.addSeparator(); + + return; + } + else if(currNode.getNodeName().equals("CallLink")) + { + //Call the linking node to continue building + if( CurrAttributes.getNamedItem("id") == null) + { + //Error:Throw Error malformed xml + } + //Get the link id to get the linking document + String LinkID = CurrAttributes.getNamedItem("id").getNodeValue(); + + //Get the linking node to continue + XPath xpath = XPathFactory.newInstance().newXPath(); + Node Linker = null; + try { + Linker = (Node)xpath.evaluate("/gamessInput/Link[@id='" + LinkID + "']", doc , XPathConstants.NODE); + } catch (XPathExpressionException e) { + e.printStackTrace(); + } + if( Linker == null) + { + //Error:Throw Linking tag not found + } + NodeList linkerNodeList = Linker.getChildNodes(); + for(int i = 0 ; i < linkerNodeList.getLength() ; i++) + { + if(linkerNodeList.item(i).getNodeType() != Node.TEXT_NODE) + InsertMenu(linkerNodeList.item(i), parentMenu, CurrentGroupName); + } + + //check if there are some items removed + if(currNode.hasChildNodes()) + { + //Then there are some items to disable + NodeList localNodeList = currNode.getChildNodes(); + for(int i = 0 ; i < localNodeList.getLength() ; i++) + { + if(localNodeList.item(i).getNodeType() == Node.TEXT_NODE) + continue; + if(localNodeList.item(i).getNodeName().equals("Disable")) + { + NodeList disableMenuItems = localNodeList.item(i).getChildNodes(); + for(int j = 0 ; j < disableMenuItems.getLength() ; j++) + { + if(disableMenuItems.item(j).getNodeType() == Node.TEXT_NODE) + continue; + if(disableMenuItems.item(j).getNodeName().equals("item")) + { + NamedNodeMap localAttribute = disableMenuItems.item(j).getAttributes(); + if(localAttribute.getNamedItem("Name") != null) + { + String DisablePath = localAttribute.getNamedItem("Name").getNodeValue(); + String[] itemLocation = DisablePath.split("\\."); + JMenu CurrentSearchMenu = parentMenu; + for(int k = 0 ; k < itemLocation.length ; k++) + { + for( int l = 0 ; l < CurrentSearchMenu.getItemCount() ; l++) + { + Component TestComponent = CurrentSearchMenu.getMenuComponent(l); + //Check if the item is either a menu or menuitem + if(TestComponent.getClass().getName().endsWith("JMenu")) + { + JMenu TestItem = (JMenu)TestComponent; + if( TestItem.getText().equals(itemLocation[k])) + { + CurrentSearchMenu = TestItem; + if((k+1) == itemLocation.length) + { + TestItem.setEnabled(false); + MenuValueMapper.get(TestItem).isExcluded = true; + break; + } + } + + } + else if(TestComponent.getClass().getName().endsWith("JMenuItem")) + { + JMenuItem TestItem = (JMenuItem)TestComponent; + if(TestItem.getText().equals(itemLocation[k])) + { + TestItem.setEnabled(false); + MenuValueMapper.get(TestItem).isExcluded = true; + break; + } + } + } + } + } + else + { +// Error:Throw malformed xml + } + } + else + { + //Error:Throw malformed xml + } + } + } + else + { + //Error:Throw malformed xml + } + } + } + + return; + } + else if(currNode.getNodeName().equals("Link")) + { + //Do Nothing + } + else + { + //Error::Throw error as malformed xml + } + } + + private String getParsedToolTipForMenu(String toolTip) + { + if(toolTip.startsWith("#$")) + { + try + { + String Group,Keyword,Value; + String[] splitData = toolTip.substring(2).split(" "); + + Group = (splitData.length > 0) ? "@Group='" + splitData[0] + "' and " : "not(@Group) and " ; + Keyword = (splitData.length > 1) ? "@Keyword='" + splitData[1] + "' and " : "not(@Keyword) and "; + Value = (splitData.length > 2) ? "@Value='" + splitData[2] + "'" : "not(@Value)"; + + String xpathCondExpr = "/root/ToolTips/ToolTip[" + Group + Keyword + Value + "]"; + + Node tooltipNode = (Node)toolTipXPath.evaluate( xpathCondExpr, GlobalParameters.userNotesAndToolTip, XPathConstants.NODE); + if(tooltipNode != null) + { + return Cosmetics.getMenuToolTip(tooltipNode.getTextContent().trim()); + } + } + catch (XPathExpressionException e) {e.printStackTrace();} + } + return Cosmetics.getMenuToolTip(toolTip); + } + + /** + * Write all the classes that are used in this object + */ + public enum EntityType { GROUP,KEYWORD,VALUE,BOTH }; + public enum LaunchType { GRID,GROUPFRAME,TEXTBOX,CUSTOM}; + private class MenuEntity + { + public String Group = null, Keyword = null, Value = null; + EntityType MenuType; + boolean isExcluded = false; + } + + private class DummyMenuListener implements MenuListener + { + public void menuCanceled(javax.swing.event.MenuEvent evt) { + } + public void menuDeselected(javax.swing.event.MenuEvent evt) { + } + public void menuSelected(javax.swing.event.MenuEvent evt) { + //Test enabling or disabling the submenus here + JMenu parentMenu = (JMenu)evt.getSource(); + ExcludeIncompatibility excludes = ExcludeIncompatibility.getInstance(); + for (int i = 0; i < parentMenu.getItemCount(); i++) + { + JMenuItem childMenuItem = parentMenu.getItem(i); + if(childMenuItem == null) continue; + MenuEntity childEntity = MenuValueMapper.get(childMenuItem); + if(childEntity != null && childEntity.isExcluded) continue; + + //check if this is excluded + if(childEntity != null && (excludes.isLikelyToBecomeIncompatible(childEntity.Group) || excludes.isLikelyToBecomeIncompatible(childEntity.Group + " " + childEntity.Keyword ) || excludes.isLikelyToBecomeIncompatible(childEntity.Group + " " + childEntity.Keyword + " " + childEntity.Value))) + { + childMenuItem.setEnabled(false); + } + else + childMenuItem.setEnabled(true); + + /*/check if this is required + if(childEntity != null && RequiresIncompatibility.getInstance().testIncompatibility(childEntity.Group + " " + childEntity.Keyword + " " + childEntity.Value)) + { + // + //childMenuItem.setFont(childMenuItem.getFont().deriveFont(Font.BOLD)); + } + else + childMenuItem.setFont(childMenuItem.getFont().deriveFont(Font.PLAIN)); + */ + } + } + } + + private class StandardMenuListener implements MenuListener + { + public void menuCanceled(javax.swing.event.MenuEvent evt) { + } + public void menuDeselected(javax.swing.event.MenuEvent evt) { + menuPath.pop(); + } + @SuppressWarnings("unchecked") + public void menuSelected(javax.swing.event.MenuEvent evt) { + MenuEntity CurrentSelectedMenu = MenuValueMapper.get(evt.getSource()); + + //Test enabling or disabling the submenus here + JMenu parentMenu = (JMenu)evt.getSource(); + ExcludeIncompatibility excludes = ExcludeIncompatibility.getInstance(); + for (int i = 0; i < parentMenu.getItemCount(); i++) + { + JMenuItem childMenuItem = parentMenu.getItem(i); + if(childMenuItem == null) continue; + MenuEntity childEntity = MenuValueMapper.get(childMenuItem); + if(childEntity != null && childEntity.isExcluded) continue; + + //check if this is excluded + if(childEntity != null && (excludes.isLikelyToBecomeIncompatible(childEntity.Group) || excludes.isLikelyToBecomeIncompatible(childEntity.Group + " " + childEntity.Keyword ) || excludes.isLikelyToBecomeIncompatible(childEntity.Group + " " + childEntity.Keyword + " " + childEntity.Value))) + { + childMenuItem.setEnabled(false); + } + else + childMenuItem.setEnabled(true); + + /*/check if this is required + if(childEntity != null && RequiresIncompatibility.getInstance().testIncompatibility(childEntity.Group + " " + childEntity.Keyword + " " + childEntity.Value)) + { + // + //childMenuItem.setFont(childMenuItem.getFont().deriveFont(Font.BOLD)); + } + else + childMenuItem.setFont(childMenuItem.getFont().deriveFont(Font.PLAIN)); + */ + } + menuPath.push(CurrentSelectedMenu); + menuPathImage = (Stack)menuPath.clone();; + } + } + + private class StandardMenuItemListener implements ActionListener + { + public void actionPerformed(java.awt.event.ActionEvent evt) { + MenuEntity CurrentSelectedMenu = MenuValueMapper.get(evt.getSource()); + menuPathImage.push(CurrentSelectedMenu); + // + //Set the parent lock and classify all the items added now under the same group. + UndoRedoHandler.toggleGroupClassifier(); + UndoRedoHandler.setLock(); + //from starting to the ending of the menupath + for(int i = 0 , j ; i < menuPathImage.size() ; i++) + { + //Get each item + MenuEntity MenuItemInPath = menuPathImage.elementAt(i); + //if the menu is of type keyword or both then it to have a matching value + if(MenuItemInPath.MenuType == EntityType.KEYWORD || MenuItemInPath.MenuType == EntityType.BOTH) + { + //Find the menu entity containing values for the corresponding keywords + for(j = i ; j < menuPathImage.size() ; j++) + { + //Check for the value type and both type + MenuEntity MenuToCompare = menuPathImage.elementAt(j); + if((MenuToCompare.MenuType == EntityType.VALUE || MenuToCompare.MenuType == EntityType.BOTH) && MenuToCompare.Keyword.equals(MenuItemInPath.Keyword)) + { + InputFileWriter KeywordValueWriter = InputFileWriter.getInstance(); + String seperator = Repository.getInstance().getKeywordValueSeperator(MenuToCompare.Group); + KeywordValueWriter.Write(MenuToCompare.Group, MenuToCompare.Keyword + seperator + MenuToCompare.Value); + Repository.getInstance().Store(MenuToCompare.Group, MenuToCompare.Keyword + seperator + MenuToCompare.Value); + break; + } + } + if(j == menuPathImage.size()) + { + //Error:No matching value found for the keyword MenuItemInPath.Keyword + } + } + } + + UndoRedoHandler.releaseLock(); + } + } + + private class ItemLauncher extends MouseAdapter implements ActionListener + { + private LaunchType LauncherType = null; + private Node referenceNode = null; + private JDialog LaunchingItem = null; + private String Group = null; + + public ItemLauncher(){} + + public ItemLauncher(LaunchType LaunchTyp , Node refNode) + { + LauncherType = LaunchTyp; + referenceNode = refNode.cloneNode(true); + } + + public void setGroup(String _Group) + { + Group = _Group; + } + + public void setLaunchType(LaunchType launchType) + { + LauncherType = launchType; + } + + public void setReferenceNode(Node refNode) + { + if(refNode.hasChildNodes()) + { + Node childNode = refNode.getFirstChild(); + while(childNode != null && childNode.getNodeType() == Node.TEXT_NODE) + { + childNode = childNode.getNextSibling(); + } + if(childNode == null){ + //Error:No child type listed + } + referenceNode = childNode.cloneNode(true); + } + } + + public void setCustomDialog(JDialog dialog , boolean isModalDialog) + { + if(LauncherType != null && LauncherType == LaunchType.CUSTOM) + { + LaunchingItem = dialog; + if(isModalDialog && dialog != null) + LaunchingItem.setModal(true); + } + } + + /* + * This is mainly used to create the objects of the launching types + * Eager instantiation is used to as there is a code to support the + * ContentAssist in the objects created + */ + public void createObject() + { + if(LauncherType != LaunchType.CUSTOM) + LoadDialog(); + } + + public void mouseClicked(java.awt.event.MouseEvent evt) + { + LaunchItem(); + } + + public void actionPerformed(java.awt.event.ActionEvent evt) + { + LaunchItem(); + } + + private void LaunchItem() + { + if(LaunchingItem == null) + { + //Load the Dialogue based on the launcher type and node information + LoadDialog(); + } + LaunchingItem.setVisible(true); + } + + private void LoadDialog() + { + if(LauncherType == null) + { + //Error:No launching type specified + } + if(LauncherType != LaunchType.CUSTOM && referenceNode == null) + { + //Error:No information found for launching the item + } + + //Create the jdialog object object here + if(LauncherType == LaunchType.GRID) + { + LaunchingItem = new MatrixDialog(parentFrame , referenceNode , Group); + } + else if(LauncherType == LaunchType.GROUPFRAME) + { + NamedNodeMap GroupframeAttributes = referenceNode.getAttributes(); + LaunchingItem = new MenuTableDialog(Group,GroupframeAttributes.getNamedItem("DisplayName").getNodeValue(),referenceNode,parentFrame); + } + else if(LauncherType == LaunchType.TEXTBOX) + { + LaunchingItem = new TextDialog(parentFrame , Group , referenceNode); + } + else + { + //Error:Trying to launch a custom dialog which is not available + } + + LaunchingItem.setModal(true); + LaunchingItem.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + } + } + + +} diff --git a/src/main/java/gamess/MessageBox.java b/src/main/java/gamess/MessageBox.java new file mode 100644 index 0000000..61a6dbe --- /dev/null +++ b/src/main/java/gamess/MessageBox.java @@ -0,0 +1,249 @@ +package gamess; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ArrayList; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTabbedPane; +import javax.swing.JTextArea; +import javax.swing.JTextPane; +import javax.swing.border.TitledBorder; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import gamess.IncompatibilityPackage.RequiresIncompatibility; +import org.w3c.dom.Node; + +import gamess.IncompatibilityPackage.ExcludeIncompatibility; +import gamess.IncompatibilityPackage.Incompatible; +import gamess.Storage.IDBChangeListener; + +public class MessageBox extends JTabbedPane { + + private static final long serialVersionUID = 4069514782057521435L; + + public static UserNotes notes = null; + public static ExcludeMessages excludes = null; + public static RequiredMessages requires = null; + private static JTabbedPane ThisPane = null; + private final String NOTE_TITLE = "Note"; + private final String EXCLUDE_TITLE = "Incompatible Inputs"; + private final String REQUIRE_TITLE = "Required Inputs"; + //private final String ExcludeInformationFormat = "Exclude $%s because %s is selected"; + private final String ExcludeInformationFormat = "Exclude $%s"; + private final String RequiredInformationFormat = "Requires $%s"; + public MessageBox() + { + ThisPane = this; + + notes = new UserNotes(); + excludes = new ExcludeMessages(); + requires = new RequiredMessages(); + + addTab(NOTE_TITLE , notes); + addTab(EXCLUDE_TITLE, excludes); + addTab(REQUIRE_TITLE , requires); + + } + + public class UserNotes extends JPanel implements IDBChangeListener + { + private static final long serialVersionUID = 1L; + private int messageCount = 0; + private JTextArea msgDisplayArea= new JTextArea(); + private XPath xpath = XPathFactory.newInstance().newXPath(); + public UserNotes() + { + setLayout(new BorderLayout()); + + msgDisplayArea.setAutoscrolls(true); + msgDisplayArea.setEditable(false); + msgDisplayArea.setFont( msgDisplayArea.getFont().deriveFont(Font.BOLD) ); + + TitledBorder msgDisplayPanelTitle = new TitledBorder("Message Display"); + msgDisplayPanelTitle.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY,1)); + msgDisplayArea.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY,2)); + + JScrollPane scrpane=new JScrollPane(msgDisplayArea); + scrpane.setAutoscrolls(true); + + super.add(scrpane,BorderLayout.CENTER); + super.setBorder(msgDisplayPanelTitle); + } + + public void write(String note) + { + msgDisplayArea.insert(" ------------------------------------------------------------------------------\n", 0); + msgDisplayArea.insert(note + "\n", 0); + msgDisplayArea.setCaretPosition(0); + ThisPane.setTitleAt( 0 , NOTE_TITLE + " (" + ++messageCount + ")"); + } + + public void DataAdded(String Data) { + try + { + String Group,Keyword,Value; + String[] splitData = Data.split(" "); + + Group = (splitData.length > 0) ? "@Group='" + splitData[0] + "' and " : "not(@Group) and " ; + Keyword = (splitData.length > 1) ? "@Keyword='" + splitData[1] + "' and " : "not(@Keyword) and "; + Value = (splitData.length > 2) ? "@Value='" + splitData[2] + "'" : "not(@Value)"; + + String xpathCondExpr = "/root/UserNotes/UserNote[" + Group + Keyword + Value + "]"; + + Node note = (Node)xpath.evaluate( xpathCondExpr ,GlobalParameters.userNotesAndToolTip, XPathConstants.NODE); + if(note != null) + write("Note:\n When you select : $" + Data + "\n" + note.getTextContent()); + } + catch(XPathExpressionException e){e.printStackTrace();} + } + + public void DataRemoved(String Data) { + if(Data.equalsIgnoreCase("SYSTEM PARALL")) + { + write("Note:\n $SYSTEM PARALL=.TRUE. as is needed for distributed data parallel\nMP2 program to execute the parallel algorithm,\n even if you are running on only one node"); + } + } + public void DropDB() {} + } + + public abstract class IncompatibilityMessages extends JPanel implements ActionListener + { + private static final long serialVersionUID = 1L; + private JTextPane incompDisplay = new JTextPane(); + public ArrayList incompList = null; + private int currentSelectedIndex = 0; + JButton next , previous; + + public IncompatibilityMessages() + { + incompDisplay.setFont( incompDisplay.getFont().deriveFont(Font.BOLD)); + + setLayout(new BorderLayout()); + //Add the next and previous button + next = new JButton(">>"); + next.addActionListener(this); + next.setActionCommand("next"); + //next.setPreferredSize(new Dimension(25,25)); + + previous = new JButton("<<"); + previous.addActionListener(this); + previous.setActionCommand("previous"); + //previous.setPreferredSize(new Dimension(25,25)); + + JPanel buttonPannel = new JPanel(); + buttonPannel.add(previous, BorderLayout.CENTER); + buttonPannel.add(next, BorderLayout.CENTER); + + add(buttonPannel , BorderLayout.NORTH); + + //Add the TextArea to the center + JScrollPane scrollPane = new JScrollPane(incompDisplay); + scrollPane.setBorder(BorderFactory.createLineBorder(Color.BLACK)); + add(scrollPane, BorderLayout.CENTER); + + resetList(new ArrayList()); + } + + public void actionPerformed(ActionEvent evt) + { + if(evt.getActionCommand().equalsIgnoreCase("NEXT")) + { + currentSelectedIndex++; + incompDisplay.setText(incompList.get(currentSelectedIndex)); + updateNextAndPrevious(); + } + else + { + currentSelectedIndex--; + incompDisplay.setText(incompList.get(currentSelectedIndex)); + updateNextAndPrevious(); + } + } + + private void updateNextAndPrevious() + { + if(currentSelectedIndex < incompList.size() - 1) + next.setEnabled(true); + else + next.setEnabled(false); + + if(currentSelectedIndex > 0) + previous.setEnabled(true); + else + previous.setEnabled(false); + } + + protected void resetList(ArrayList newList) + { + incompList = newList; + if(incompList.size() == 0) + { + currentSelectedIndex = 0; + incompDisplay.setText("No incompatibilities currently identified"); + updateNextAndPrevious(); + } + else + { + currentSelectedIndex = 0; + incompDisplay.setText(incompList.get(currentSelectedIndex)); + updateNextAndPrevious(); + } + } + + protected void UpdateTitle(String title, int TabLocation) + { + if(incompList.size() == 0) + { + ThisPane.setTitleAt(TabLocation, title); + } + else + { + ThisPane.setTitleAt(TabLocation, title + " (" + incompList.size() + ")"); + } + } + } + + public class ExcludeMessages extends IncompatibilityMessages + { + private static final long serialVersionUID = 1L; + + public void UpdateList() + { + ArrayList excludeList = new ArrayList(); + ArrayList list = ExcludeIncompatibility.getInstance().getIncompatibilityList(); + for (int i = 0; i < list.size(); i++) { + //excludeList.add("Exclude $" + list.get(i).getInput() + " because " + list.get(i).getCondition().toString() + " is selected"); + excludeList.add( String.format(ExcludeInformationFormat, list.get(i).getInput()) ) ; + } + resetList(excludeList); + UpdateTitle(EXCLUDE_TITLE, 1); + } + } + + public class RequiredMessages extends IncompatibilityMessages + { + private static final long serialVersionUID = 1L; + + public void UpdateList() + { + ArrayList requireList = new ArrayList(); + ArrayList list = RequiresIncompatibility.getInstance().getIncompatibilityList(); + for (int i = 0; i < list.size(); i++) { + //requireList.add("Require $" + list.get(i).getInput() + " because " + list.get(i).getCondition().toString() + " is selected"); + requireList.add( String.format(RequiredInformationFormat, list.get(i).getInput()) ) ; + } + resetList(requireList); + UpdateTitle(REQUIRE_TITLE, 2); + } + } +} diff --git a/src/main/java/gamess/MolDisplay.java b/src/main/java/gamess/MolDisplay.java new file mode 100644 index 0000000..0ff5e73 --- /dev/null +++ b/src/main/java/gamess/MolDisplay.java @@ -0,0 +1,5122 @@ +/*Copyright (c) 2007, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ +/** + * @author Michael Sheetz + * @author Pavithra Koka + * @author Shreeram Sridharan + */ + +package gamess; + +// Molecular Display - R. Michael Sheetz (Oct 2006) + +import com.jogamp.opengl.*; +import com.jogamp.opengl.awt.GLCanvas; +import com.jogamp.opengl.fixedfunc.GLLightingFunc; +import com.jogamp.opengl.fixedfunc.GLMatrixFunc; +import com.jogamp.opengl.glu.GLU; +import com.jogamp.opengl.glu.GLUquadric; +import com.jogamp.opengl.util.gl2.GLUT; + +import javax.swing.*; +import javax.swing.border.TitledBorder; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import java.awt.*; +import java.awt.event.*; +import java.util.ArrayList; +import java.util.StringTokenizer; + +public class MolDisplay extends JInternalFrame +{ + static public GLCanvas glcanvas = null; + + GL4bc gl; // commented by Narendra Kumar for adding "GL4bc" + //GL4bc gl; // added by Narendra Kumar + + GLU glu; + GLUT glut = new GLUT(); + + MolecularDisplay mdisplay; + + int j, k, index, indx, ndx, atomIndex; + int canvasWidth, canvasHeight; + int cnvsWidth, cnvsHeight; + int nmenus, npopupmenus, nsubmenus, natoms; + int mbHeight, mbWidth, mbx, mby; + int scaleRadius; + int defaultConnSliderValue; + int nsymm, naxis; + + int[] atomicNumber; + + double x, y, z; + double x1, y1, x2, y2; + double theta, phi, zloc; + double x0, y0, z0; // origin of Cartesian reference frame + double delx, dely, delz; + double axisSelectionDimen; + double canvas2frameRatio, maxDisplayDimen, molScalingFactor; + double max_x, max_y, max_z, min_x, min_y, min_z; + double displayWidth, displayHeight, maxMolecularDimen; + double defaultAtomRadius, unscaledAtomRadius, bondRadius, scaleFactor, bondParam; + + double dx, dy, dz, r, bl; + double ar1, ar2, cr1, cr2; + + double atomRadius; + + double[] atomCoords; + double[] radius; + double[] radiusScalingFactor; + double[] scaledAtomRadius; + double[] molDimen; + double[] x_axisLen; + double[] y_axisLen; + double[] z_axisLen; + + double[][] zmatBondLength; + double[][] bondLength; + + float bkg_red, bkg_green, bkg_blue, red, green, blue; + float color_alphaValue, material_alphaValue; + float[] atomColors; + float[] bondMat1; + float[] bondMat2; + float[] material; + + boolean x_rot, y_rot, z_rot, coincidence; + boolean displayGeom, retrievedGeom, displayMolecule, recomputeConnectivity; + boolean bondsVisible, bondsColored; + boolean initDisplay = true; //initialize initDisplay + boolean invokeSymm; + + String symm = new String(); + String coordFormat; + String[] atomID; + + ArrayList alGeom; + + Dimension screenSize, frameSize; + + JMenuBar menuBar; + JMenu menu, fileMenu, editMenu, viewMenu, helpMenu; + JMenu displayOptionsSubmenu, showBondsSubmenu, displayMOSubmenu, animationSubmenu, outputdataSubmenu; + //JPopupMenu filePopupMenu, editPopupMenu, viewPopupMenu, helpPopupMenu; + JMenuItem openItem, saveItem, saveAsItem, importItem, exportItem, printItem, closeItem; + JMenuItem openPopupItem, savePopupItem, saveAsPopupItem, importPopupItem, exportPopupItem, printPopupItem, closePopupItem; + JMenuItem undoItem, redoItem, cutItem, copyItem, pasteItem, clearItem; + JMenuItem showBondsItem, hideBondsItem, colorBondsItem, uncolorBondsItem, adjustBondCriteriaItem; + JMenuItem displayItem, displayOption1, displayOption2, displayOption3, displayOption4, displayOption5, displayOption6, displayOption7, displayOption8; + JMenuItem chargeDensityItem, homoItem, lumoItem, electrostaticPotenialItem; + + //JPopupMenu displayOptionsPopupSubmenu, showBondsPopupSubmenu, displayMOPopupSubmenu, animationPopupSubmenu, outputdataPopupSubmenu; + + JDialog connectivityAdjustmentFrame , radiusScalingFrame; + Container container; + JSlider connSlider, radiusSlider; + JPanel connPanel, radiusPanel; + JButton connDoneButton, radiusDoneButton; + TitledBorder border; + + static JDesktopPane dp; + String strGeom=new String(); + + // Required for checking consistency of charge and mulitiplicity + int nuclearCharge, nelectrons; + String chargeStr, multiplicityStr; + boolean CM_consistency; + + + public MolDisplay() + { + super("Molecular Display"); + + dp=new JDesktopPane(); + dp.setLayout(new BorderLayout()); + setPreferredSize(new Dimension(370,500)); + + // Create molecular display + mdisplay = new MolecularDisplay(); + + // Step1: choose a GLProfile + GLProfile glp = GLProfile.getDefault(); // added by Narendra Kumar + + // Step2: Configure GLCapabilities + GLCapabilities glcaps = new GLCapabilities(glp) ; // javax.media.opengl package needs an arugment - commented by Narendra Kumar + //GLCapabilities glcaps = new GLCapabilities(glp) ; // parameter added to constructor method of GLCapabilities - added by Narendra Kumar + glcaps.setDoubleBuffered(true); + + // Step 3: create a GLCanvas +// glcanvas = GLDrawableFactory.getFactory().createGLCanvas(glcaps); // commented by Narendra Kumar + glcanvas = new GLCanvas(glcaps); // GLCanvas can be instantiated using GLCapablities object - added by Narendra Kumare + + glcanvas.addGLEventListener(mdisplay); + glcanvas.addMouseMotionListener(mdisplay); + glcanvas.addMouseListener(new CanvasMouseListener()); + glcanvas.addKeyListener(new CanvasKeyListener()); + getContentPane().add(glcanvas, BorderLayout.CENTER); + // Set initial canvas dimension + canvasHeight = 500; canvasWidth = 500; + + setSize(canvasWidth, canvasHeight); + + centerWindow(this); + + // Create menus + menuBar = new JMenuBar(); + + setJMenuBar(menuBar); + + // Create menus on main menu bar + fileMenu = new JMenu("File"); + fileMenu.setEnabled(false); + //fileMenu.addMouseListener(new menuMouseListener()); + editMenu = new JMenu("Edit"); + editMenu.setEnabled(false); + //editMenu.addMouseListener(new menuMouseListener()); + viewMenu = new JMenu("View"); + //viewMenu.addMouseListener(new menuMouseListener()); + helpMenu = new JMenu("Help"); + //helpMenu.addMouseListener(new menuMouseListener()); + helpMenu.setEnabled(false); + + // Create file popup menu associated with file menu + //filePopupMenu = new JPopupMenu(); + + openItem = new JMenuItem("Open"); + //filePopupMenu.add(openItem); + //filePopupMenu.addSeparator(); + fileMenu.add(openItem); + fileMenu.addSeparator(); + saveItem = new JMenuItem("Save"); + //filePopupMenu.add(saveItem); + fileMenu.add(saveItem); + saveAsItem = new JMenuItem("SaveAs"); + //filePopupMenu.add(saveAsItem); + //filePopupMenu.addSeparator(); + fileMenu.add(saveAsItem); + fileMenu.addSeparator(); + importItem = new JMenuItem("Import"); + //filePopupMenu.add(importItem); + fileMenu.add(importItem); + exportItem = new JMenuItem("Export"); + //filePopupMenu.add(exportItem); + //filePopupMenu.addSeparator(); + fileMenu.add(exportItem); + fileMenu.addSeparator(); + printItem = new JMenuItem("Print"); + //filePopupMenu.add(printItem); + //filePopupMenu.addSeparator(); + fileMenu.add(printItem); + fileMenu.addSeparator(); + closeItem = new JMenuItem("Close"); + //filePopupMenu.add(closeItem); + fileMenu.add(closeItem); + //filePopupMenu.setLightWeightPopupEnabled(false); + //filePopupMenu.setVisible(false); + + menuBar.add(fileMenu); + + // Create edit popup menu associated with edit menu + //editPopupMenu = new JPopupMenu(); + + undoItem = new JMenuItem("Undo"); + //editPopupMenu.add(undoItem); + editMenu.add(undoItem); + redoItem = new JMenuItem("Redo"); + //editPopupMenu.add(redoItem); + //editPopupMenu.addSeparator(); + editMenu.add(redoItem); + editMenu.addSeparator(); + cutItem = new JMenuItem("Cut"); + //editPopupMenu.add(cutItem); + editMenu.add(cutItem); + copyItem = new JMenuItem("Copy"); + //editPopupMenu.add(copyItem); + editMenu.add(copyItem); + pasteItem = new JMenuItem("Paste"); + //editPopupMenu.add(pasteItem); + //editPopupMenu.addSeparator(); + editMenu.add(pasteItem); + editMenu.addSeparator(); + clearItem = new JMenuItem("Clear"); + //editPopupMenu.add(clearItem); + editMenu.add(clearItem); + //editPopupMenu.setLightWeightPopupEnabled(false); + //editPopupMenu.setVisible(false); + + menuBar.add(editMenu); + + // Create view popup menu associated with edit menu + //viewPopupMenu = new JPopupMenu(); + + //displayItem = new JMenuItem("Display Molecule"); + //viewMenu.add(displayItem); + + displayOptionsSubmenu = new JMenu("Display Options"); + //displayOptionsSubmenu.addMouseListener(new displayOptionsSubmenuMouseListener()); + //displayOptionsPopupSubmenu = new JPopupMenu(); + //displayOptionsPopupSubmenu.addMouseListener(new displayOptionsSubmenuMouseListener()); + + displayOption1 = new JMenuItem("Ball & Stick:"); + //displayOptionsPopupSubmenu.add(displayOption1); + displayOptionsSubmenu.add(displayOption1); + + displayOption2 = new JMenuItem(" Scaled Radii"); + //displayOption2.addMouseListener(new displayOptionMouseListener()); + displayOption2.addActionListener(new displayOptionMouseListener()); + //displayOptionsPopupSubmenu.add(displayOption2); + displayOptionsSubmenu.add(displayOption2); + + displayOption3 = new JMenuItem(" Unscaled Radii"); + //displayOption3.addMouseListener(new displayOptionMouseListener()); + displayOption3.addActionListener(new displayOptionMouseListener()); + //displayOptionsPopupSubmenu.add(displayOption3); + displayOptionsSubmenu.add(displayOption3); + + //displayOptionsPopupSubmenu.addSeparator(); + displayOptionsSubmenu.addSeparator(); + + displayOption4 = new JMenuItem("Wireframe"); + //displayOption4.addMouseListener(new displayOptionMouseListener()); + displayOption4.addActionListener(new displayOptionMouseListener()); + //displayOptionsPopupSubmenu.add(displayOption4); + displayOptionsSubmenu.add(displayOption4); + + displayOption5 = new JMenuItem("Space Filling"); + //displayOption5.addMouseListener(new displayOptionMouseListener()); + displayOption5.addActionListener(new displayOptionMouseListener()); + //displayOptionsPopupSubmenu.add(displayOption5); + displayOptionsSubmenu.add(displayOption5); + + //displayOptionsPopupSubmenu.addSeparator(); + displayOptionsSubmenu.addSeparator(); + + displayOption6 = new JMenuItem("Modify Atom Radius"); + //displayOption6.addMouseListener(new displayOptionMouseListener()); + displayOption6.addActionListener(new displayOptionMouseListener()); + //displayOptionsPopupSubmenu.add(displayOption6); + displayOptionsSubmenu.add(displayOption6); + + //displayOptionsPopupSubmenu.addSeparator(); + displayOptionsSubmenu.addSeparator(); + + displayOption7 = new JMenuItem("Modify Connectivity"); + //displayOption7.addMouseListener(new displayOptionMouseListener()); + displayOption7.addActionListener(new displayOptionMouseListener()); + //displayOptionsPopupSubmenu.add(displayOption7); + displayOptionsSubmenu.add(displayOption7); + + //displayOptionsPopupSubmenu.addSeparator(); + displayOptionsSubmenu.addSeparator(); + + displayOption8 = new JMenuItem("Label Atoms"); + //displayOption8.addMouseListener(new displayOptionMouseListener()); + displayOption8.addActionListener(new displayOptionMouseListener()); + //displayOptionsPopupSubmenu.add(displayOption8); + displayOptionsSubmenu.add(displayOption8); + + //displayOptionsPopupSubmenu.setLightWeightPopupEnabled(false); + //displayOptionsPopupSubmenu.setVisible(false); + //viewPopupMenu.add(displayOptionsSubmenu); + //viewPopupMenu.addSeparator(); + viewMenu.add(displayOptionsSubmenu); + viewMenu.addSeparator(); + showBondsSubmenu = new JMenu("Show Bonds"); + //showBondsSubmenu.addMouseListener(new showBondsSubmenuMouseListener()); + showBondsSubmenu.addActionListener(new showBondsSubmenuMouseListener()); + //showBondsPopupSubmenu = new JPopupMenu(); + //showBondsPopupSubmenu.addMouseListener(new showBondsSubmenuMouseListener()); + + colorBondsItem = new JMenuItem("Color Bonds"); + //colorBondsItem.addMouseListener(new colorBondsMouseListener()); + colorBondsItem.addActionListener(new showBondsSubmenuMouseListener()); + colorBondsItem.addActionListener(new colorBondsMouseListener()); + //showBondsPopupSubmenu.add(colorBondsItem); + //showBondsPopupSubmenu.addSeparator(); + showBondsSubmenu.add(colorBondsItem); + showBondsSubmenu.addSeparator(); + uncolorBondsItem = new JMenuItem("Uncolor Bonds"); + //uncolorBondsItem.addMouseListener(new uncolorBondsMouseListener()); + uncolorBondsItem.addActionListener(new showBondsSubmenuMouseListener()); + uncolorBondsItem.addActionListener(new uncolorBondsMouseListener()); + //showBondsPopupSubmenu.add(uncolorBondsItem); + showBondsSubmenu.add(uncolorBondsItem); + + //showBondsPopupSubmenu.setLightWeightPopupEnabled(false); + //showBondsPopupSubmenu.setVisible(false); + + //viewPopupMenu.add(showBondsSubmenu); + viewMenu.add(showBondsSubmenu); + + hideBondsItem = new JMenuItem("Hide Bonds"); + //hideBondsItem.addMouseListener(new hideBondsMouseListener()); + hideBondsItem.addActionListener(new hideBondsMouseListener()); + //viewPopupMenu.add(hideBondsItem); + //viewPopupMenu.addSeparator(); + viewMenu.add(hideBondsItem); + viewMenu.addSeparator(); + + chargeDensityItem = new JMenuItem("Charge Density"); + //viewPopupMenu.add(chargeDensityItem); + viewMenu.add(chargeDensityItem); + electrostaticPotenialItem = new JMenuItem("Electrostatic Potenial"); + //viewPopupMenu.add(electrostaticPotenialItem); + //viewPopupMenu.addSeparator(); + viewMenu.add(electrostaticPotenialItem); + viewMenu.addSeparator(); + + displayMOSubmenu = new JMenu("Display MOs"); + //displayMOSubmenu.addMouseListener(new displayMOSubmenuMouseListener()); + //displayMOPopupSubmenu = new JPopupMenu(); + //displayMOPopupSubmenu.addMouseListener(new displayMOSubmenuMouseListener()); + + homoItem = new JMenuItem("HOMO"); + //displayMOPopupSubmenu.add(homoItem); + displayMOSubmenu.add(homoItem); + lumoItem = new JMenuItem("LUMO"); + //displayMOPopupSubmenu.add(lumoItem); + displayMOSubmenu.add(lumoItem); + + //displayMOPopupSubmenu.setLightWeightPopupEnabled(false); + //displayMOPopupSubmenu.setVisible(false); + //viewPopupMenu.add(displayMOSubmenu); + //viewPopupMenu.addSeparator(); + viewMenu.add(displayMOSubmenu); + viewMenu.addSeparator(); + animationSubmenu = new JMenu("Animation"); + animationSubmenu.addActionListener(new animationSubmenuMouseListener()); + //viewPopupMenu.add(animationSubmenu); + viewMenu.add(animationSubmenu); + outputdataSubmenu = new JMenu("Output Data"); + outputdataSubmenu.addActionListener(new outputdataSubmenuMouseListener()); + //viewPopupMenu.add(outputdataSubmenu); + viewMenu.add(outputdataSubmenu); + + //viewPopupMenu.setLightWeightPopupEnabled(false); + //viewPopupMenu.setVisible(false); + + menuBar.add(viewMenu); + + // Create help popup menu associated with edit menu + //helpPopupMenu = new JPopupMenu(); + + menuBar.add(helpMenu); + + // Construct JFrame to be used for scaling atom radii + int fwidth, fheight; + fwidth = 250; + fheight = 140; + + radiusScalingFrame = new JDialog(GamessGUI.frame,"Modify Atom Radius",true); + radiusScalingFrame.setSize(fwidth, fheight); + radiusScalingFrame.setBackground(Color.white); + radiusScalingFrame.setVisible(false); + + container = radiusScalingFrame.getContentPane(); + + radiusSlider = new JSlider(JSlider.HORIZONTAL, 0, 300, 100); + radiusSlider.setPaintTicks(true); + radiusSlider.setMajorTickSpacing(50); + radiusSlider.setMinorTickSpacing(10); + radiusSlider.setPaintLabels(true); + radiusSlider.addChangeListener(new SliderListener()); + + radiusDoneButton = new JButton("Done"); + radiusDoneButton.addActionListener(new DoneButtonListener()); + + border = new TitledBorder(" "); + + radiusPanel= new JPanel(); + radiusPanel.add(radiusSlider, BorderLayout.CENTER); + radiusPanel.add(radiusDoneButton, BorderLayout.SOUTH); + radiusPanel.setBorder(border); + + container.add(radiusPanel); + + // Construct JFrame to be used for adjusting bonding criteria + connectivityAdjustmentFrame = new JDialog(GamessGUI.frame,"Modify Connectivity",true); + connectivityAdjustmentFrame.setSize(fwidth, fheight); + connectivityAdjustmentFrame.setBackground(Color.white); + + container = connectivityAdjustmentFrame.getContentPane(); + + defaultConnSliderValue = 40; + connSlider = new JSlider(JSlider.HORIZONTAL, 0, 100, defaultConnSliderValue); + connSlider.setPaintTicks(true); + connSlider.setMajorTickSpacing(20); + connSlider.setMinorTickSpacing(5); + connSlider.setPaintLabels(true); + connSlider.addChangeListener(new SliderListener()); + + connDoneButton = new JButton("Done"); + connDoneButton.addActionListener(new DoneButtonListener()); + + border = new TitledBorder(" "); + + connPanel= new JPanel(); + connPanel.add(connSlider, BorderLayout.CENTER); + connPanel.add(connDoneButton, BorderLayout.SOUTH); + connPanel.setBorder(border); + + container.add(connPanel); + + dp.add(this); + setVisible(true); + } + + public boolean setStrGeom(String data,String _charge, String _multiplicity, boolean _invokeSymmetry, String _symm, int _naxis ) + { + strGeom=data; + chargeStr=_charge; + multiplicityStr=_multiplicity; + invokeSymm = _invokeSymmetry; + symm = _symm; + naxis = _naxis; + //parse datafile for molecular data with gemoetry before senidng to draw + + boolean consistent = mdisplay.drawMolecule(data); + + // System.out.println(CM_consistency); + return consistent; + } + + public void callDrawMolecule(){ + mdisplay.drawMolecule(""); + glcanvas.repaint(); + } + + public void centerWindow(Component frame) + { + screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + frameSize = frame.getSize(); + + if (frameSize.width > screenSize.width) + { + frameSize.width = screenSize.width; + } + if (frameSize.height > screenSize.height) + { + frameSize.height = screenSize.height; + } + + frame.setLocation(0, (screenSize.height - frameSize.height)/2); + } + + public void parseDataFile(){ + + String geomToken, var, value; + + ArrayList alGeomElements, alElement, alElem3, alElem4; + + alGeom = new ArrayList(); + + StringTokenizer stok1, stok2; + + stok1 = new StringTokenizer(strGeom, "\n"); + + while(stok1.hasMoreTokens()) + { + geomToken = stok1.nextToken(); + + if (geomToken.indexOf("=") == -1) + { + alGeomElements = new ArrayList(); + + stok2 = new StringTokenizer(geomToken); + + while(stok2.hasMoreTokens()) + { + alGeomElements.add(stok2.nextToken()); + } + + alGeom.add(alGeomElements); + } + else + { + stok2 = new StringTokenizer(geomToken, "="); + + var = stok2.nextToken(); + value = stok2.nextToken(); + + for (index = 0; index < alGeom.size(); index++) + { + alElement = new ArrayList(); + + alElement = (ArrayList)(alGeom.get(index)); + + if (alElement.contains(var)) + { + for (int ndx = 0; ndx < alElement.size(); ndx++) + { + k = alElement.indexOf(var); + + if (k != -1) + { + alElement.set(k, value); + } + else + { + break; + } + } + + alGeom.set(index, alElement); + } + } + } + } + + } + public class MolecularDisplay implements MouseMotionListener, GLEventListener { + public void init(GLAutoDrawable gldraw) + { + //parseDataFile(); + drawMolecule(""); + } + + @Override + public void dispose(GLAutoDrawable glAutoDrawable) { + + } + + public boolean drawMolecule(String data) + { + bkg_red = 0.0f; + bkg_green = 0.0f; + bkg_blue = 0.0f; + color_alphaValue = 1.0f; + + canvas2frameRatio = 0.8; + + CM_consistency=true; + + // Parse geometry specification string, convert each line separate of geometry input to an Array List + // (alGeomInputLine), and place each Array List not containing an "=" into a second Array List (alGeom) + + //Samples + StringBuffer sbGeom = new StringBuffer(); + /* + * + // formamide + sbGeom.append("C" + "\n" + "O 1 rCO" + "\n" + "N 1 rCN 2 aNCO" + "\n" + "H 3 rNHa 1 aCNHa 2 0.0" + "\n"); + sbGeom.append("H 3 rNHb 1 aCNHb 2 180.0" + "\n" + "H 1 rCH 2 aHCO 4 180.0" + "\n"); + sbGeom.append("\n"); + sbGeom.append("rCO=1.1962565" + "\n" + "rCN=1.3534065" + "\n" + "rNHa=0.9948420" + "\n"); + sbGeom.append("rNHb=0.9921367" + "\n" + "rCH=1.0918368" + "\n" + "aNCO=124.93384" + "\n"); + sbGeom.append("aCNHa=119.16000" + "\n" + "aCNHb=121.22477" + "\n" + "aHCO=122.30822" + "\n"); + + + + // formamide + sbGeom.append("C 6 0.0 0.0 0.0" + "\n"); + sbGeom.append("O 8 0.0 0.0 1.1962565" + "\n"); + sbGeom.append("N 7 0.0 -1.109541342468682 -0.775001395866514" + "\n"); + sbGeom.append("H 1 0.0 -2.004412477898668 -0.3403564189735936" + "\n"); + sbGeom.append("H 1 -1.0390099432170336E-16 -1.0453597426919177 -1.7650599566279395" + "\n"); + sbGeom.append("H 1 -1.1301092880011223E-16 0.9228042638807764 -0.5835579563314158" + "\n"); + + + + sbGeom.append("C 6 0.0 0.0 0.0" + "\n"); + sbGeom.append("O 8 0.0 0.0 1.01962565" + "\n"); + + + + sbGeom.append("F" + "\n" + "N 1 rNF" + "\n" + "H 2 rNH 1 aFNH" + "\n" + "H 2 rNH 1 aFNH 3 aHNH" + "\n"); + sbGeom.append("O 2 rNO 3 aONH 4 aONH" + "\n" + "H 5 rOH 2 aHON 1 180.0" + "\n"); + sbGeom.append("\n"); + sbGeom.append("rNF=1.7125469" + "\n" + "rNH=0.9966981" + "\n" + "rNO=1.9359887" + "\n"); + sbGeom.append("rOH=0.9828978" + "\n" + "aFNH=90.18493" + "\n" + "aONH=79.34339" + "\n"); + sbGeom.append("aHON=100.78851" + "\n" + "aHNH=108.57000" + "\n"); + + + + // methylnitrene + sbGeom.append("N" + "\n" + "C 1 rCN" + "\n" + "H 2 rCH 1 aHCN" + "\n" + "H 2 rCH 1 aHCN 3 120.0" + "\n"); + sbGeom.append("H 2 rCH 1 aHCN 3 -120.0" + "\n"); + sbGeom.append("\n"); + sbGeom.append("rCN=1.4329216" + "\n" + "rCH=1.0876477" + "\n" + "aHCN=110.21928" + "\n"); + + + + // BiCl3 + sbGeom.append("Bi" + "\n" + "Cl 1 rBiCl" + "\n" + "Cl 1 rBiCl 2 aClBiCl" + "\n" + "Cl 1 rBiCl 2 aClBiCl 3 aClBiCl" + "\n"); + sbGeom.append("\n"); + sbGeom.append("rBiCl=2.48" + "\n" + "aClBiCl=99.0" + "\n"); + + + + sbGeom.append("N" + "\n" + "C 1 rCN" + "\n" + "H 2 rCH 1 aHCN" + "\n" + "H 2 rCH 1 aHCN 3 120.0" + "\n"); + sbGeom.append("\n"); + sbGeom.append("rCN=1.4329216" + "\n" + "rCH=1.0876477" + "\n" + "aHCN=110.21928" + "\n"); + + + + // Water-ammonia dimer + sbGeom.append("H" + "\n" + "O 1 rOH" + "\n" + "H 2 rOH 1 aHOH" + "\n" + "N 2 R 1 aHOH 3 0.0" + "\n"); + sbGeom.append("H 4 rNH 3 aNHaxis 1 180.0" + "\n" + "H 4 rNH 3 aNHaxis 5 120.0" + "\n"); + sbGeom.append("H 4 rNH 3 aNHaxis 5 -120.0" + "\n"); + sbGeom.append("\n"); + sbGeom.append("rOH=0.956" + "\n" + "aHOH=105.2" + "\n" + "rNH=1.0124" + "\n"); + sbGeom.append("aNHaxis=112.1451" + "\n" + "R=2.93" + "\n"); + + + // water trimer + + + // arbitrary molecule + sbGeom.append("O" + "\n" + "C 1 rCOa" + "\n" + "N 2 rCNa 1 aNCO" + "\n" + "C 3 rCNb 2 aCNC 1 wCNCO" + "\n"); + sbGeom.append("O 4 rCOb 3 aOCN 2 wOCNC" + "\n" + "C 2 rCC 1 aCCO 5 wCCOO" + "\n" + "H 6 rCH1 2 aHCC1 1 wHCCO1" + "\n"); + sbGeom.append("H 6 rCH2 2 aHCC2 1 wHCCO2" + "\n" + "H 6 rCH3 2 aHCC3 1 wHCCO3" + "\n" + "H 2 rCHa 1 aHCOa 5 wHCOOa" + "\n"); + sbGeom.append("H 3 rNH 2 aHNC 1 wHNCO" + "\n" + "H 4 rCHb 5 aHCOb 1 wHCOOb" + "\n" + "H 4 rCHc 5 aHCOc 1 wHCOOc" + "\n"); + sbGeom.append("\n"); + sbGeom.append("rCOa=1.43" + "\n" + "rCNa=1.47" + "\n" + "rCNb=1.47" + "\n" + "rCOb=1.43" + "\n"); + sbGeom.append("aNCO=106.0" + "\n" + "aCNC=104.0" + "\n" + "aOCN=106.0" + "\n" + "wCNCO=30.0" + "\n"); + sbGeom.append("wOCNC=-30.0" + "\n" + "rCC=1.54" + "\n" + "aCCO=110.0" + "\n" + "wCCOO=-150.0" + "\n"); + sbGeom.append("rCH1=1.09" + "\n" + "rCH2=1.09" + "\n" + "rCH3=1.09" + "\n" + "wHCC1=109.0" + "\n"); + sbGeom.append("aHCC1=109.0" + "\n" + "aHCC2=109.0" + "\n" + "aHCC3=109.0" + "\n" + "wHCCO1=60.0" + "\n" + "wHCCO2=-60.0" + "\n"); + sbGeom.append("wHCCO3=180.0" + "\n" + "rCHa=1.09" + "\n" + "aHCOa=110.0" + "\n" + "wHCOOa=100.0" + "\n"); + sbGeom.append("rNH=1.01" + "\n" + "aHNC=110.0" + "\n" + "wHNCO=170.0" + "\n" + "rCHb=1.09" + "\n"); + sbGeom.append("rCHc=1.09" + "\n" + "aHCOb=110.0" + "\n" + "aHCOc=110.0" + "\n" + "wHCOOb=150.0" + "\n"); + sbGeom.append("wHCOOc=-100.0" + "\n"); + + +// sbGeom.append("O" + "\n" + "H 1 0.965" + "\n"); + + +// sbGeom.append("O 8" + "\n"); +// sbGeom.append("H 1 0.965 1.206" + "\n"); + +// sbGeom.append("C 6 0.0 0.0 0.0" + "\n"); +// sbGeom.append("O 8 0.0 0.0 1.43" + "\n"); +// sbGeom.append("H 1 0.965 1.206 1.05" + "\n"); + +*/ + + + // Testing for symmetry + + +/* + +// point group Cs + + + // Formaldehyde + invokeSymm = true; + symm = "Cs"; + sbGeom.append("O 8.0 0.01 -0.8669736 0.0" + "\n"); + sbGeom.append("C 6.0 0.0 0.3455497 0.0" + "\n"); + sbGeom.append("H 1.0 -0.01 0.9295804 0.9376713" + "\n"); + + + + // Formaldehyde (complete molecular structure - point group symmetry not used) + sbGeom.append("C 8.0 0.0 0.0 0.0" + "\n"); + sbGeom.append("O 6.0 0.0 1.22 0.0" + "\n"); + sbGeom.append("H 1.0 0.94 -0.54 0.0" + "\n"); + sbGeom.append("H 1.0 -0.94 -0.54 0.0" + "\n"); + + +// point group Ci + + + // trans 1,2-difluoro 1,2-dichloro ethane + invokeSymm = true; + symm = "Ci"; + sbGeom.append("C 6.0 -0.0404314 0.0340784 0.7144152" + "\n"); + sbGeom.append("H 1.0 -0.5269567 0.8706125 1.0117693" + "\n"); + sbGeom.append("F 9.0 -0.6595780 -1.0335664 1.1306903" + "\n"); + sbGeom.append("Cl 17.0 1.5029963 0.0624642 1.3707514" + "\n"); + + + + // trans 1,2-difluoro 1,2-dichloro ethane (complete molecular structure - point group symmetry not used) + sbGeom.append("C 6.0 -0.0404314 0.0340784 0.7144152" + "\n"); + sbGeom.append("C 6.0 0.0404314 -0.0340784 -0.7144152" + "\n"); + sbGeom.append("H 1.0 -0.5269567 0.8706125 1.0117693" + "\n"); + sbGeom.append("H 1.0 0.5269567 -0.8706125 -1.0117693" + "\n"); + sbGeom.append("F 9.0 -0.6595780 -1.0335664 1.1306903" + "\n"); + sbGeom.append("F 9.0 0.6595780 1.0335664 -1.1306903" + "\n"); + sbGeom.append("Cl 17.0 1.5029963 0.0624642 1.3707514" + "\n"); + sbGeom.append("Cl 17.0 -1.5029963 -0.0624642 -1.3707514" + "\n"); + + +// point group Cn + + + // Hydrogen peroxide + invokeSymm = true; + symm = "Cn"; + naxis = 2; +// sbGeom.append("O 8.0 0.0 1.3723898 -0.0996337" + "\n"); +// sbGeom.append("H 1.0 1.5576983 1.6930786 0.7970698" + "\n"); + + sbGeom.append("O 8.0 0.0 0.6861949 -0.0498168" + "\n"); + sbGeom.append("H 1.0 1.5576983 0.8465393 0.3985349" + "\n"); + + + // Hydrogen peroxide (complete molecular structure - point group symmetry not used) +// sbGeom.append("O 8.0 0.0 1.3723898 -0.0996337" + "\n"); +// sbGeom.append("O 8.0 0.0 -1.3723898 -0.0996337" + "\n"); +// sbGeom.append("H 1.0 1.5576983 1.6930786 0.7970698" + "\n"); +// sbGeom.append("H 1.0 -1.5576983 -1.6930786 0.7970698" + "\n"); + + sbGeom.append("O 8.0 0.0 0.6861949 -0.0498168" + "\n"); + sbGeom.append("O 8.0 0.0 -0.6861949 -0.0498168" + "\n"); + sbGeom.append("H 1.0 1.5576983 0.8465393 0.3985349" + "\n"); + sbGeom.append("H 1.0 -1.5576983 -0.8465393 0.3985349" + "\n"); + + +// point group Cnv + + + // Water (Cartesian coordinates) + invokeSymm = true; + symm = "Cnv"; + naxis = 2; + sbGeom.append("O 8.0 0.0 0.0 0.0" + "\n"); +// sbGeom.append("H 1.0 0.0 0.7572157 0.5865358" + "\n"); + sbGeom.append("H 1.0 0.0 1.428 -1.096" + "\n"); + + + + // Water (Z-matrix) + sbGeom.append("O" + "\n" + "H 1 rOH" + "\n" + "H 1 rOH 2 aHOH" + "\n"); + sbGeom.append("\n"); + sbGeom.append("rOH=0.95" + "\n" + "aHOH=104.5" + "\n"); + + + + // Phosphine oxide + invokeSymm = true; + symm = "Cnv"; + naxis = 3; + sbGeom.append("P 15.0 0.0 0.0 0.0" + "\n"); + sbGeom.append("O 8.0 0.0 0.0 1.4701" + "\n"); + sbGeom.append("H 1.0 1.23359 0.0 -0.642102" + "\n"); + + + + // HCN + invokeSymm = true; + symm = "Cnv"; + naxis = 4; + sbGeom.append("H 1.0 0.0 0.0 -1.0589956" + "\n"); + sbGeom.append("C 6.0 0.0 0.0 0.0" + "\n"); + sbGeom.append("N 7.0 0.0 0.0 1.1327718" + "\n"); + + + + // Ammonia + invokeSymm = true; + symm = "Cnv"; + naxis = 3; + sbGeom.append("N 7.0 0.0 0.0 0.16008228" + "\n"); + sbGeom.append("H 1.0 0.0 1.81793530 -0.37352532" + "\n"); + + +// point group Cnh + + + // Boron hydroxide + invokeSymm = true; + symm = "Cnh"; + naxis = 3; + sbGeom.append("B 5.0 0.0 0.0 0.0" + "\n"); + sbGeom.append("O 8.0 0.0 1.30129442 0.0" + "\n"); + sbGeom.append("H 1.0 -0.80522102 1.72366565 0.0" + "\n"); + + +// point group Dn + + + // C(NO2)3 + invokeSymm = true; + symm = "Dn"; + naxis = 3; + sbGeom.append("C 6.0 0.0 0.0 0.0" + "\n"); + sbGeom.append("N 7.0 1.3285648 0.0 0.0" + "\n"); + sbGeom.append("O 8.0 1.8685582 0.8757526 0.4702412" + "\n"); + + + +// point group Dnd + + + // Ethane + invokeSymm = true; + symm = "Dnd"; + naxis = 3; + sbGeom.append("C 6.0 0.0 0.0 0.65" + "\n"); + sbGeom.append("H 1.0 1.81252 1.16252 1.16522" + "\n"); + + + // Test molecule for 'Dnd' point group + invokeSymm = true; + symm = "Dnd_test"; + naxis = 3; + sbGeom.append("C 6.0 0.0 0.0 0.65" + "\n"); + sbGeom.append("H 1.0 0.0 1.211 1.211" + "\n"); + + + // Ethane + sbGeom.append("C 6.0 0.0 0.0 0.65" + "\n"); + sbGeom.append("H 1.0 1.62522 1.62522 1.62522" + "\n"); + sbGeom.append("H 1.0 0.59487 -2.2201 1.62522" + "\n"); + sbGeom.append("H 1.0 -2.2201 0.59487 1.62522" + "\n"); + sbGeom.append("C 6.0 0.0 0.0 -0.65" + "\n"); + sbGeom.append("H 1.0 -1.62522 -1.62522 -1.62522" + "\n"); + sbGeom.append("H 1.0 -0.59487 2.2201 -1.62522" + "\n"); + sbGeom.append("H 1.0 2.2201 -0.59487 -1.62522" + "\n"); + + + // Ethane [ with 'z' --> ('-z') ] + sbGeom.append("C 6.0 0.0 0.0 -0.65" + "\n"); + sbGeom.append("H 1.0 1.62522 1.62522 -1.62522" + "\n"); + sbGeom.append("H 1.0 0.59487 -2.2201 -1.62522" + "\n"); + sbGeom.append("H 1.0 -2.2201 0.59487 -1.62522" + "\n"); + sbGeom.append("C 6.0 0.0 0.0 0.65" + "\n"); + sbGeom.append("H 1.0 -1.62522 -1.62522 1.62522" + "\n"); + sbGeom.append("H 1.0 -0.59487 2.2201 1.62522" + "\n"); + sbGeom.append("H 1.0 2.2201 -0.59487 1.62522" + "\n"); + + + // Sodium crown ether + invokeSymm = true; + symm = "Dnd"; + naxis = 3; + sbGeom.append("Na 23.0 0.0 0.0 0.0" + "\n"); + sbGeom.append("O 8.0 1.33848 4.99526 0.15441" + "\n"); + sbGeom.append("H 1.0 6.73421 -0.67239 2.65816" + "\n"); + sbGeom.append("C 6.0 6.75992 -0.48450 0.61366" + "\n"); + sbGeom.append("H 1.0 8.64976 0.07092 0.03454" + "\n"); + + + + // Sodium crown ether (with shorter bond lengths) + invokeSymm = true; + symm = "Dnd"; + naxis = 3; + sbGeom.append("Na 23.0 0.0 0.0 0.0" + "\n"); + sbGeom.append("O 8.0 0.44616 1.66509 0.05147" + "\n"); + sbGeom.append("H 1.0 2.24140 -0.22413 0.88605" + "\n"); + sbGeom.append("C 6.0 2.25331 -0.16150 0.20455" + "\n"); + sbGeom.append("H 1.0 2.88325 0.02364 0.01151" + "\n"); + + + // Ferrocene + invokeSymm = true; + symm = "Dnd"; + naxis = 5; + sbGeom.append("Fe 53.0 0.0 0.0 0.0" + "\n"); + sbGeom.append("C 6.0 0.0 1.194 1.789" + "\n"); + sbGeom.append("H 1.0 0.0 2.256 1.789" + "\n"); + + + // CH2CCH2 + invokeSymm = true; + symm = "Dnd"; + naxis = 2; + sbGeom.append("C 6.0 0.0 0.0 0.0" + "\n"); + sbGeom.append("C 6.0 0.0 0.0 1.300" + "\n"); + sbGeom.append("H 1.0 0.656 0.656 1.857" + "\n"); + + +// point group Dnh + + // C6H6 (benzene) + invokeSymm = true; + symm = "Dnh"; + naxis = 6; + sbGeom.append("C 6.0 2.626720 0.0 0.0" + "\n"); + sbGeom.append("C 6.0 4.686522 0.0 1.300" + "\n"); + + + +// point group S2n + + + // 1,3,5,7-tetrafluorocyclooctane ( C8H4F4 ) + invokeSymm = true; + symm = "S2n"; + naxis = 2; + sbGeom.append("C 6.0 1.12761874 1.12761874 -0.36111599" + "\n"); + sbGeom.append("C 6.0 0.02588201 1.58108002 0.32802516" + "\n"); + sbGeom.append("H 1.0 1.64192930 1.82938629 -0.87799154" + "\n"); + sbGeom.append("F 9.0 0.26098002 2.67908960 0.95452201" + "\n"); + + + + // 1,3,5,7-tetrafluorocyclooctane (complete molecular structure) + sbGeom.append("C 6.0 -1.12761874 1.12761874 0.36111599" + "\n"); + sbGeom.append("C 6.0 0.02588201 1.58108002 0.32802516" + "\n"); + sbGeom.append("C 6.0 1.12761874 1.12761874 -0.36111599" + "\n"); + sbGeom.append("C 6.0 1.58108002 -0.02588201 -0.32802516" + "\n"); + sbGeom.append("C 6.0 1.12761874 -1.12761874 0.36111599" + "\n"); + sbGeom.append("C 6.0 -0.02588201 -1.58108002 0.32802516" + "\n"); + sbGeom.append("C 6.0 -1.12761874 -1.12761874 -0.36111599" + "\n"); + sbGeom.append("C 6.0 -1.58108002 0.02588201 -0.32802516" + "\n"); + + + sbGeom.append("H 1.0 -1.82938629 1.64192930 0.87799154" + "\n"); + sbGeom.append("H 1.0 1.64192930 1.82938629 -0.87799154" + "\n"); + sbGeom.append("H 1.0 1.82938629 -1.64192930 0.87799154" + "\n"); + sbGeom.append("H 1.0 -1.64192930 -1.82938629 -0.87799154" + "\n"); + + + sbGeom.append("F 9.0 0.26098002 2.67908960 0.95452201" + "\n"); + sbGeom.append("F 9.0 2.67908960 -0.26098002 -0.95452201" + "\n"); + sbGeom.append("F 9.0 -0.26098002 -2.67908960 0.95452201" + "\n"); + sbGeom.append("F 9.0 -2.67908960 0.26098002 -0.95452201" + "\n"); + + +// point group Td + + invokeSymm = true; + symm = "Td"; + sbGeom.append("C 6.0 0.0 0.0 0.0" + "\n"); + sbGeom.append("H 1.0 0.62522 0.62522 0.62522" + "\n"); + + +// point group Th + +// point group O + +// point group Oh + + +*/ + +/////////// Display the following molecule: + + + + // C(NO2)3 +/* invokeSymm = true; + symm = "Dn"; + naxis = 3; + sbGeom.append("C 6.0 0.0 0.0 0.0" + "\n"); + sbGeom.append("N 7.0 1.3285648 0.0 0.0" + "\n"); + sbGeom.append("O 8.0 1.8685582 0.8757526 0.4702412" + "\n"); +*/ + + +/* + // Ferrocene + invokeSymm = true; + symm = "Dnd"; + naxis = 5; + sbGeom.append("Fe 53.0 0.0 0.0 0.0" + "\n"); + sbGeom.append("C 6.0 0.0 1.194 1.789" + "\n"); + sbGeom.append("H 1.0 0.0 2.256 1.789" + "\n"); +*/ + + + + // 1,3,5,7-tetrafluorocyclooctane ( C8H4F4 ) +/* invokeSymm = true; + symm = "S2n"; + naxis = 2; + sbGeom.append("C 6.0 1.12761874 1.12761874 -0.36111599" + "\n"); + sbGeom.append("C 6.0 0.02588201 1.58108002 0.32802516" + "\n"); + sbGeom.append("H 1.0 1.64192930 1.82938629 -0.87799154" + "\n"); + sbGeom.append("F 9.0 0.26098002 2.67908960 0.95452201" + "\n"); +*/ + //strGeom = sbGeom.toString(); + +/////////// + + String geomToken, var, value; + ArrayList alGeomElements, alElement, alElem3, alElem4; + + alGeom = new ArrayList(); + + StringTokenizer stok1, stok2; + + stok1 = new StringTokenizer(strGeom, "\n"); + + while(stok1.hasMoreTokens()) + { + geomToken = stok1.nextToken(); + + if (geomToken.indexOf("=") == -1) + { + alGeomElements = new ArrayList(); + + stok2 = new StringTokenizer(geomToken); + + while(stok2.hasMoreTokens()) + { + alGeomElements.add(stok2.nextToken()); + } + + alGeom.add(alGeomElements); + } + else + { + stok2 = new StringTokenizer(geomToken, "="); + + var = stok2.nextToken(); + value = stok2.nextToken(); + + for (index = 0; index < alGeom.size(); index++) + { + alElement = new ArrayList(); + + alElement = (ArrayList)(alGeom.get(index)); + + if (alElement.contains(var)) + { + for (int ndx = 0; ndx < alElement.size(); ndx++) + { + k = alElement.indexOf(var); + + if (k != -1) + { + alElement.set(k, value); + } + else + { + break; + } + } + + alGeom.set(index, alElement); + } + } + } + } + + + natoms = alGeom.size(); + System.out.println("Number of Atoms in the molecule: "+natoms); + if (natoms <= 0) { + System.out.println(" Error parsing Atoms in the input! \n Please verify the input"); + return false; + } + + coordFormat = getCoordFormat(alGeom, natoms); + + // Convert ZMatrix to Cartesian coordinate format + + atomCoords = new double[3*natoms]; + atomCoords = getAtomCoords(alGeom, natoms, coordFormat); + + // Get identity of atoms in the molecule being displayed + atomID = new String[natoms]; + atomID = getAtomID(alGeom, natoms); + +//////// // + + + if (invokeSymm == true) + { + int maxndx; + + double X0, Y0, Z0, X, Y, Z, XX, YY, ZZ, rotx, roty, rotz, symmx, symmy, symmz; + double rotangle; // rotation angle about principal axis + double del; + double rfx, rfy, rfz; + double lamx, lamy, lamz; + double lambda = 0.0001; + + double[][] symMatrx = new double[3][3]; + + String atmsymbl; + + ArrayList symmStructure; + + if (symm.equalsIgnoreCase("C1")) + { + // do nothing + } + else if (symm.equalsIgnoreCase("Cs")) + { + nsymm = 1; + } + else if (symm.equalsIgnoreCase("Ci")) + { + nsymm = 2; + } + else if (symm.equalsIgnoreCase("Cn")) + { + nsymm = 3; + } + else if (symm.equalsIgnoreCase("Cnv")) + { + nsymm = 4; + } + else if (symm.equalsIgnoreCase("Cnh")) + { + nsymm = 5; + } + else if (symm.equalsIgnoreCase("Dn")) + { + nsymm = 6; + } + else if (symm.equalsIgnoreCase("Dnd")) + { + nsymm = 7; + } + else if (symm.equalsIgnoreCase("Dnh")) + { + nsymm = 8; + } + else if (symm.equalsIgnoreCase("S2n")) + { + nsymm = 9; + } + else if (symm.equalsIgnoreCase("T")) + { + nsymm = 10; + } + else if (symm.equalsIgnoreCase("Td")) + { + nsymm = 11; + } + else if (symm.equalsIgnoreCase("Th")) + { + nsymm = 12; + } + else if (symm.equalsIgnoreCase("O")) + { + nsymm = 13; + } + else if (symm.equalsIgnoreCase("Oh")) + { + nsymm = 14; + } + else if (symm.equalsIgnoreCase("Dnd_test")) + { + nsymm = 100; + } + switch (nsymm) + { + case 1: // point group 'Cs' + + symmStructure = new ArrayList(); + + for (j = 0; j < natoms; j++) + { + symmStructure.add(atomID[j]); + + symmStructure.add(atomCoords[(3*j)]); + symmStructure.add(atomCoords[(3*j) + 1]); + symmStructure.add(atomCoords[(3*j) + 2]); + } + + maxndx = natoms; + + for (j = 0; j < natoms; j++) + { + coincidence = false; + + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = -Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(X - XX); + lamy = Math.abs(Y - YY); + lamz = Math.abs(Z - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if (coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + + maxndx += 1; + } + } + + natoms = symmStructure.size()/4; + + atomID = new String[natoms]; + atomCoords = new double[3*natoms]; + + for (j = 0; j < natoms; j++) + { + atomID[j] = (symmStructure.get(4*j)).toString(); + + atomCoords[(3*j)] = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + atomCoords[(3*j) + 1] = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + atomCoords[(3*j) + 2] = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + } + + break; + case 2: // point group 'Ci' + + symmStructure = new ArrayList(); + + for (j = 0; j < natoms; j++) + { + symmStructure.add(atomID[j]); + + symmStructure.add(atomCoords[(3*j)]); + symmStructure.add(atomCoords[(3*j) + 1]); + symmStructure.add(atomCoords[(3*j) + 2]); + } + + maxndx = natoms; + + for (j = 0; j < natoms; j++) + { + coincidence = false; + + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = -Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = -Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = -Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(X - XX); + lamy = Math.abs(Y - YY); + lamz = Math.abs(Z - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if (coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + + maxndx += 1; + } + } + + natoms = symmStructure.size()/4; + + atomID = new String[natoms]; + atomCoords = new double[3*natoms]; + + for (j = 0; j < natoms; j++) + { + atomID[j] = (symmStructure.get(4*j)).toString(); + + atomCoords[(3*j)] = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + atomCoords[(3*j) + 1] = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + atomCoords[(3*j) + 2] = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + } + + break; + case 3: // point group 'Cn' + + symmStructure = new ArrayList(); + + rotangle = 2*Math.PI/naxis; + + symMatrx[0][0] = Math.cos(rotangle); + symMatrx[0][1] = Math.sin(rotangle); + symMatrx[0][2] = 0.0; + symMatrx[1][0] = -Math.sin(rotangle); + symMatrx[1][1] = Math.cos(rotangle); + symMatrx[1][2] = 0.0; + symMatrx[2][0] = 0.0; + symMatrx[2][1] = 0.0; + symMatrx[2][2] = 1.0; + + for (j = 0; j < natoms; j++) + { + symmStructure.add(atomID[j]); + + symmStructure.add(atomCoords[(3*j)]); + symmStructure.add(atomCoords[(3*j) + 1]); + symmStructure.add(atomCoords[(3*j) + 2]); + } + + maxndx = natoms; + + for (j = 0; j < natoms; j++) + { + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + for (k = 0; k < (naxis - 1); k++) + { + coincidence = false; + + rotx = (symMatrx[0][0] * X) + (symMatrx[0][1] * Y) + (symMatrx[0][2] * Z); + roty = (symMatrx[1][0] * X) + (symMatrx[1][1] * Y) + (symMatrx[1][2] * Z); + rotz = (symMatrx[2][0] * X) + (symMatrx[2][1] * Y) + (symMatrx[2][2] * Z); + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(rotx - XX); + lamy = Math.abs(roty - YY); + lamz = Math.abs(rotz - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if (coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(rotx); + symmStructure.add(roty); + symmStructure.add(rotz); + + maxndx += 1; + } + + X = rotx; + Y = roty; + Z = rotz; + } + } + + natoms = symmStructure.size()/4; + + atomID = new String[natoms]; + atomCoords = new double[3*natoms]; + + for (j = 0; j < natoms; j++) + { + atomID[j] = (symmStructure.get(4*j)).toString(); + + atomCoords[(3*j)] = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + atomCoords[(3*j) + 1] = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + atomCoords[(3*j) + 2] = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + } + + + break; + case 4: // point group 'Cnv' + + symmStructure = new ArrayList(); + + rotangle = 2*Math.PI/naxis; + + symMatrx[0][0] = Math.cos(rotangle); + symMatrx[0][1] = Math.sin(rotangle); + symMatrx[0][2] = 0.0; + symMatrx[1][0] = -Math.sin(rotangle); + symMatrx[1][1] = Math.cos(rotangle); + symMatrx[1][2] = 0.0; + symMatrx[2][0] = 0.0; + symMatrx[2][1] = 0.0; + symMatrx[2][2] = 1.0; + + for (j = 0; j < natoms; j++) + { + symmStructure.add(atomID[j]); + + symmStructure.add(atomCoords[(3*j)]); + symmStructure.add(atomCoords[(3*j) + 1]); + symmStructure.add(atomCoords[(3*j) + 2]); + } + + maxndx = natoms; + + for (j = 0; j < natoms; j++) + { + coincidence = false; + + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(X - XX); + lamy = Math.abs(Y - YY); + lamz = Math.abs(Z - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if (coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + + maxndx += 1; + } + } + + natoms = symmStructure.size()/4; + + for (j = 0; j < natoms; j++) + { + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + for (k = 0; k < (naxis - 1); k++) + { + coincidence = false; + + rotx = (symMatrx[0][0] * X) + (symMatrx[0][1] * Y) + (symMatrx[0][2] * Z); + roty = (symMatrx[1][0] * X) + (symMatrx[1][1] * Y) + (symMatrx[1][2] * Z); + rotz = (symMatrx[2][0] * X) + (symMatrx[2][1] * Y) + (symMatrx[2][2] * Z); + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(rotx - XX); + lamy = Math.abs(roty - YY); + lamz = Math.abs(rotz - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if (coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(rotx); + symmStructure.add(roty); + symmStructure.add(rotz); + + maxndx += 1; + } + + X = rotx; + Y = roty; + Z = rotz; + } + } + + natoms = symmStructure.size()/4; + + atomID = new String[natoms]; + atomCoords = new double[3*natoms]; + + for (j = 0; j < natoms; j++) + { + atomID[j] = (symmStructure.get(4*j)).toString(); + + atomCoords[(3*j)] = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + atomCoords[(3*j) + 1] = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + atomCoords[(3*j) + 2] = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + } + + break; + case 5: // point group 'Cnh' + + symmStructure = new ArrayList(); + + rotangle = 2*Math.PI/naxis; + + symMatrx[0][0] = Math.cos(rotangle); + symMatrx[0][1] = Math.sin(rotangle); + symMatrx[0][2] = 0.0; + symMatrx[1][0] = -Math.sin(rotangle); + symMatrx[1][1] = Math.cos(rotangle); + symMatrx[1][2] = 0.0; + symMatrx[2][0] = 0.0; + symMatrx[2][1] = 0.0; + symMatrx[2][2] = 1.0; + + for (j = 0; j < natoms; j++) + { + symmStructure.add(atomID[j]); + + symmStructure.add(atomCoords[(3*j)]); + symmStructure.add(atomCoords[(3*j) + 1]); + symmStructure.add(atomCoords[(3*j) + 2]); + } + + maxndx = natoms; + + for (j = 0; j < natoms; j++) + { + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + for (k = 0; k < (naxis - 1); k++) + { + coincidence = false; + + rotx = (symMatrx[0][0] * X) + (symMatrx[0][1] * Y) + (symMatrx[0][2] * Z); + roty = (symMatrx[1][0] * X) + (symMatrx[1][1] * Y) + (symMatrx[1][2] * Z); + rotz = (symMatrx[2][0] * X) + (symMatrx[2][1] * Y) + (symMatrx[2][2] * Z); + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(rotx - XX); + lamy = Math.abs(roty - YY); + lamz = Math.abs(rotz - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if (coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(rotx); + symmStructure.add(roty); + symmStructure.add(rotz); + + maxndx += 1; + } + + X = rotx; + Y = roty; + Z = rotz; + } + } + + natoms = symmStructure.size()/4; + + // Reflect all atoms in the x,y-plane + for (j = 0; j < natoms; j++) + { + coincidence = false; + + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = -Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + for (ndx = 0; ndx < natoms; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(X - XX); + lamy = Math.abs(Y - YY); + lamz = Math.abs(Z - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) if ( (X == XX) && (Y == YY) && (X == ZZ) ) + { + coincidence = true; + } + } + + if (coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + + maxndx += 1; + } + } + + natoms = symmStructure.size()/4; + + atomID = new String[natoms]; + atomCoords = new double[3*natoms]; + + for (j = 0; j < natoms; j++) + { + atomID[j] = (symmStructure.get(4*j)).toString(); + + atomCoords[(3*j)] = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + atomCoords[(3*j) + 1] = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + atomCoords[(3*j) + 2] = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + } + + break; + case 6: // point group 'Dn' + + symmStructure = new ArrayList(); + + // Rotate all coordinates by an angle of pi about x-axis and add all new coordinates. + // Then rotate all coordinates by an angle of 2pi/naxis about z-axis (naxis - 1) times. + + rotangle = 2*Math.PI/naxis; + + symMatrx[0][0] = Math.cos(rotangle); + symMatrx[0][1] = Math.sin(rotangle); + symMatrx[0][2] = 0.0; + symMatrx[1][0] = -Math.sin(rotangle); + symMatrx[1][1] = Math.cos(rotangle); + symMatrx[1][2] = 0.0; + symMatrx[2][0] = 0.0; + symMatrx[2][1] = 0.0; + symMatrx[2][2] = 1.0; + + for (j = 0; j < natoms; j++) + { + X = atomCoords[(3*j)]; + Y = atomCoords[(3*j) + 1]; + Z = atomCoords[(3*j) + 2]; + + symmStructure.add(atomID[j]); + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + } + + // Rotate by pi about x-axis + maxndx = natoms; + + for (j = 0; j < natoms; j++) + { + coincidence = false; + + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = -Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = -Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + for (ndx = 0; ndx < natoms; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(X - XX); + lamy = Math.abs(Y - YY); + lamz = Math.abs(Z - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if (coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + + maxndx += 1; + } + } + + natoms = symmStructure.size()/4; + + // Rotate by 2pi/naxis about z-axis (naxis - 1) times + for (j = 0; j < natoms; j++) + { + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + for (k = 0; k < (naxis - 1); k++) + { + coincidence = false; + + rotx = (symMatrx[0][0] * X) + (symMatrx[0][1] * Y) + (symMatrx[0][2] * Z); + roty = (symMatrx[1][0] * X) + (symMatrx[1][1] * Y) + (symMatrx[1][2] * Z); + rotz = (symMatrx[2][0] * X) + (symMatrx[2][1] * Y) + (symMatrx[2][2] * Z); + + for (ndx = 0; ndx < natoms; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(rotx - XX); + lamy = Math.abs(roty - YY); + lamz = Math.abs(rotz - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if (coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(rotx); + symmStructure.add(roty); + symmStructure.add(rotz); + + maxndx += 1; + } + + X = rotx; + Y = roty; + Z = rotz; + } + } + + natoms = symmStructure.size()/4; + + atomID = new String[natoms]; + atomCoords = new double[3*natoms]; + + for (j = 0; j < natoms; j++) + { + atomID[j] = (symmStructure.get(4*j)).toString(); + + atomCoords[(3*j)] = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + atomCoords[(3*j) + 1] = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + atomCoords[(3*j) + 2] = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + } + + break; + case 7: // point group 'Dnd' + symmStructure = new ArrayList(); + + for (j = 0; j < natoms; j++) + { + X = atomCoords[3*j]; + Y = atomCoords[(3*j) + 1]; + Z = atomCoords[(3*j) + 2]; + + symmStructure.add(atomID[j]); + + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + } + + // Rotate each atom by pi about x-axis + maxndx = natoms; + + for (j = 0; j < natoms; j++) + { + atmsymbl = (symmStructure.get(4*j)).toString(); + + // Reflect each atom in x,z-plane + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = -Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = -Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + coincidence = false; + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(X - XX); + lamy = Math.abs(Y - YY); + lamz = Math.abs(Z - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if ( coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + + maxndx += 1; + } + } + + natoms = symmStructure.size()/4; + + // Carry out 'S2n' point group operation on each atom + + rotangle = Math.PI/naxis; + + symMatrx[0][0] = Math.cos(rotangle); + symMatrx[0][1] = Math.sin(rotangle); + symMatrx[0][2] = 0.0; + symMatrx[1][0] = -Math.sin(rotangle); + symMatrx[1][1] = Math.cos(rotangle); + symMatrx[1][2] = 0.0; + symMatrx[2][0] = 0.0; + symMatrx[2][1] = 0.0; + symMatrx[2][2] = -1.0; + + for (j = 0; j < natoms; j++) + { + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + for (k = 0; k < ( (2*naxis) - 1 ); k++) + { + rotx = (symMatrx[0][0] * X) + (symMatrx[0][1] * Y) + (symMatrx[0][2] * Z); + roty = (symMatrx[1][0] * X) + (symMatrx[1][1] * Y) + (symMatrx[1][2] * Z); + rotz = (symMatrx[2][0] * X) + (symMatrx[2][1] * Y) + (symMatrx[2][2] * Z); + + coincidence = false; + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(rotx - XX); + lamy = Math.abs(roty - YY); + lamz = Math.abs(rotz - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if ( coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(rotx); + symmStructure.add(roty); + symmStructure.add(rotz); + + maxndx += 1; + } + + X = rotx; + Y = roty; + Z = rotz; + } + } + + natoms = symmStructure.size()/4; + + atomID = new String[natoms]; + atomCoords = new double[3*natoms]; + + for (j = 0; j < natoms; j++) + { + atomID[j] = (symmStructure.get(4*j)).toString(); + + atomCoords[(3*j)] = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + atomCoords[(3*j) + 1] = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + atomCoords[(3*j) + 2] = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + } + + break; + case 8: // point group 'Dnh' + symmStructure = new ArrayList(); + + maxndx = natoms; + + for (j = 0; j < natoms; j++) + { + X = atomCoords[(3*j)]; + Y = atomCoords[(3*j) + 1]; + Z = atomCoords[(3*j) + 2]; + + symmStructure.add(atomID[j]); + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + } + + // Reflect all atoms in x,y-plane + for (j = 0; j < natoms; j++) + { + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = Double.parseDouble((symmStructure.get((4*j) + 1)).toString()); + Y = Double.parseDouble((symmStructure.get((4*j) + 2)).toString()); + Z = -Double.parseDouble((symmStructure.get((4*j) + 3)).toString()); + + coincidence = false; + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(X - XX); + lamy = Math.abs(Y - YY); + lamz = Math.abs(Z - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if ( coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + + maxndx += 1; + } + } + + natoms = symmStructure.size()/4; + + // Rotate each atom by pi about x-axis + + for (j = 0; j < natoms; j++) + { + atmsymbl = (symmStructure.get(4*j)).toString(); + + // Reflect each atom in x,z-plane + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = -Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = -Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + coincidence = false; + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(X - XX); + lamy = Math.abs(Y - YY); + lamz = Math.abs(Z - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if ( coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + + maxndx += 1; + } + } + + natoms = symmStructure.size()/4; + + // Rotate by 2pi/naxis about z-axis (naxis - 1) times + + rotangle = 2*Math.PI/naxis; + + symMatrx[0][0] = Math.cos(rotangle); + symMatrx[0][1] = Math.sin(rotangle); + symMatrx[0][2] = 0.0; + symMatrx[1][0] = -Math.sin(rotangle); + symMatrx[1][1] = Math.cos(rotangle); + symMatrx[1][2] = 0.0; + symMatrx[2][0] = 0.0; + symMatrx[2][1] = 0.0; + symMatrx[2][2] = 1.0; + + for (j = 0; j < natoms; j++) + { + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + for (k = 0; k < (naxis - 1); k++) + { + coincidence = false; + + rotx = (symMatrx[0][0] * X) + (symMatrx[0][1] * Y) + (symMatrx[0][2] * Z); + roty = (symMatrx[1][0] * X) + (symMatrx[1][1] * Y) + (symMatrx[1][2] * Z); + rotz = (symMatrx[2][0] * X) + (symMatrx[2][1] * Y) + (symMatrx[2][2] * Z); + + for (ndx = 0; ndx < natoms; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(rotx - XX); + lamy = Math.abs(roty - YY); + lamz = Math.abs(rotz - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if (coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(rotx); + symmStructure.add(roty); + symmStructure.add(rotz); + + maxndx += 1; + } + + X = rotx; + Y = roty; + Z = rotz; + } + } + + natoms = symmStructure.size()/4; + + atomID = new String[natoms]; + atomCoords = new double[3*natoms]; + + for (j = 0; j < natoms; j++) + { + atomID[j] = (symmStructure.get(4*j)).toString(); + + atomCoords[(3*j)] = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + atomCoords[(3*j) + 1] = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + atomCoords[(3*j) + 2] = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + } + + break; + case 9: // point group 'S2n' + + + symmStructure = new ArrayList(); + + for (j = 0; j < natoms; j++) + { + X = atomCoords[(3*j)]; + Y = atomCoords[(3*j) + 1]; + Z = atomCoords[(3*j) + 2]; + + symmStructure.add(atomID[j]); + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + } + + // Reflect each atom in x,y-plane and rotate by pi/naxis about z-axis + + rotangle = Math.PI/naxis; + + symMatrx[0][0] = Math.cos(rotangle); + symMatrx[0][1] = Math.sin(rotangle); + symMatrx[0][2] = 0.0; + symMatrx[1][0] = -Math.sin(rotangle); + symMatrx[1][1] = Math.cos(rotangle); + symMatrx[1][2] = 0.0; + symMatrx[2][0] = 0.0; + symMatrx[2][1] = 0.0; + symMatrx[2][2] = -1.0; + + maxndx = natoms; + + for (j = 0; j < natoms; j++) + { + coincidence = false; + + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + rotx = (symMatrx[0][0] * X) + (symMatrx[0][1] * Y) + (symMatrx[0][2] * Z); + roty = (symMatrx[1][0] * X) + (symMatrx[1][1] * Y) + (symMatrx[1][2] * Z); + rotz = (symMatrx[2][0] * X) + (symMatrx[2][1] * Y) + (symMatrx[2][2] * Z); + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(rotx - XX); + lamy = Math.abs(roty - YY); + lamz = Math.abs(rotz - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if (coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(rotx); + symmStructure.add(roty); + symmStructure.add(rotz); + + maxndx += 1; + } + } + + natoms = symmStructure.size()/4; + + // Rotate all atoms 2pi/naxis about z-axis (naxis - 1) times + + rotangle = 2*Math.PI/naxis; + + symMatrx[0][0] = Math.cos(rotangle); + symMatrx[0][1] = Math.sin(rotangle); + symMatrx[0][2] = 0.0; + symMatrx[1][0] = -Math.sin(rotangle); + symMatrx[1][1] = Math.cos(rotangle); + symMatrx[1][2] = 0.0; + symMatrx[2][0] = 0.0; + symMatrx[2][1] = 0.0; + symMatrx[2][2] = 1.0; + + for (j = 0; j < natoms; j++) + { + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + for (k = 0; k < (naxis - 1); k++) + { + rotx = (symMatrx[0][0] * X) + (symMatrx[0][1] * Y) + (symMatrx[0][2] * Z); + roty = (symMatrx[1][0] * X) + (symMatrx[1][1] * Y) + (symMatrx[1][2] * Z); + rotz = (symMatrx[2][0] * X) + (symMatrx[2][1] * Y) + (symMatrx[2][2] * Z); + + coincidence = false; + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(rotx - XX); + lamy = Math.abs(roty - YY); + lamz = Math.abs(rotz - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if ( coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(rotx); + symmStructure.add(roty); + symmStructure.add(rotz); + + maxndx += 1; + } + + X = rotx; + Y = roty; + Z = rotz; + } + } + + natoms = symmStructure.size()/4; + + atomID = new String[natoms]; + atomCoords = new double[3*natoms]; + + for (j = 0; j < natoms; j++) + { + atomID[j] = (symmStructure.get(4*j)).toString(); + + atomCoords[(3*j)] = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + atomCoords[(3*j) + 1] = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + atomCoords[(3*j) + 2] = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + } + + break; + case 10: // point group 'T' + + symmStructure = new ArrayList(); + + // Rotation matrix for S2n = S4 point group operation + naxis = 2; + + symMatrx[0][0] = 0.0; + symMatrx[0][1] = 1.0; + symMatrx[0][2] = 0.0; + symMatrx[1][0] = -1.0; + symMatrx[1][1] = 0.0; + symMatrx[1][2] = 0.0; + symMatrx[2][0] = 0.0; + symMatrx[2][1] = 0.0; + symMatrx[2][2] = -1.0; + + for (j = 0; j < natoms; j++) + { + X = atomCoords[3*j]; + Y = atomCoords[(3*j) + 1]; + Z = atomCoords[(3*j) + 2]; + + symmStructure.add(atomID[j]); + + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + } + + maxndx = natoms; + + // Apply S2n = S4 point group operation to all atoms + for (j = 0; j < natoms; j++) + { + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + for (k = 0; k < ((2*naxis) - 1); k++) + { + rotx = (symMatrx[0][0] * X) + (symMatrx[0][1] * Y) + (symMatrx[0][2] * Z); + roty = (symMatrx[1][0] * X) + (symMatrx[1][1] * Y) + (symMatrx[1][2] * Z); + rotz = (symMatrx[2][0] * X) + (symMatrx[2][1] * Y) + (symMatrx[2][2] * Z); + + coincidence = false; + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(rotx - XX); + lamy = Math.abs(roty - YY); + lamz = Math.abs(rotz - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if (coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(rotx); + symmStructure.add(roty); + symmStructure.add(rotz); + + maxndx += 1; + } + + X = rotx; + Y = roty; + Z = rotz; + } + } + + natoms = symmStructure.size()/4; + + atomID = new String[natoms]; + atomCoords = new double[3*natoms]; + + for (j = 0; j < natoms; j++) + { + atomID[j] = (symmStructure.get(4*j)).toString(); + + atomCoords[(3*j)] = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + atomCoords[(3*j) + 1] = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + atomCoords[(3*j) + 2] = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + } + + break; + case 11: // point group 'Td' + + symmStructure = new ArrayList(); + + // Rotation matrix for S2n = S4 point group operation + naxis = 2; + + symMatrx[0][0] = 0.0; + symMatrx[0][1] = 1.0; + symMatrx[0][2] = 0.0; + symMatrx[1][0] = -1.0; + symMatrx[1][1] = 0.0; + symMatrx[1][2] = 0.0; + symMatrx[2][0] = 0.0; + symMatrx[2][1] = 0.0; + symMatrx[2][2] = -1.0; + + for (j = 0; j < natoms; j++) + { + X = atomCoords[3*j]; + Y = atomCoords[(3*j) + 1]; + Z = atomCoords[(3*j) + 2]; + + symmStructure.add(atomID[j]); + + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + } + + maxndx = natoms; + + // Rotate each atom by pi about the x-axis + for (j = 0; j < natoms; j++) + { + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = -Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = -Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + coincidence = false; + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(X - XX); + lamy = Math.abs(Y - YY); + lamz = Math.abs(Z - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if (coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + + maxndx += 1; + } + } + + natoms = symmStructure.size()/4; + + for (j = 0; j < natoms; j++) + { + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + // Apply S2n = S4 point group operation to all atoms + for (k = 0; k < ((2*naxis) - 1); k++) + { + rotx = (symMatrx[0][0] * X) + (symMatrx[0][1] * Y) + (symMatrx[0][2] * Z); + roty = (symMatrx[1][0] * X) + (symMatrx[1][1] * Y) + (symMatrx[1][2] * Z); + rotz = (symMatrx[2][0] * X) + (symMatrx[2][1] * Y) + (symMatrx[2][2] * Z); + + coincidence = false; + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(rotx - XX); + lamy = Math.abs(roty - YY); + lamz = Math.abs(rotz - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if (coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(rotx); + symmStructure.add(roty); + symmStructure.add(rotz); + + maxndx += 1; + } + + X = rotx; + Y = roty; + Z = rotz; + } + } + + natoms = symmStructure.size()/4; + + atomID = new String[natoms]; + atomCoords = new double[3*natoms]; + + for (j = 0; j < natoms; j++) + { + atomID[j] = (symmStructure.get(4*j)).toString(); + + atomCoords[(3*j)] = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + atomCoords[(3*j) + 1] = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + atomCoords[(3*j) + 2] = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + } + + break; + case 12: // point group 'Th' + + symmStructure = new ArrayList(); + + // Rotation matrix for S2n = S4 point group operation + naxis = 2; + + symMatrx[0][0] = 0.0; + symMatrx[0][1] = 1.0; + symMatrx[0][2] = 0.0; + symMatrx[1][0] = -1.0; + symMatrx[1][1] = 0.0; + symMatrx[1][2] = 0.0; + symMatrx[2][0] = 0.0; + symMatrx[2][1] = 0.0; + symMatrx[2][2] = -1.0; + + for (j = 0; j < natoms; j++) + { + X = atomCoords[3*j]; + Y = atomCoords[(3*j) + 1]; + Z = atomCoords[(3*j) + 2]; + + symmStructure.add(atomID[j]); + + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + } + + maxndx = natoms; + + // Apply inversion point group operation to all atoms + + for (j = 0; j < natoms; j++) + { + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = -Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = -Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = -Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + coincidence = false; + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(X - XX); + lamy = Math.abs(Y - YY); + lamz = Math.abs(Z - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if (coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + + maxndx += 1; + } + } + + natoms = symmStructure.size()/4; + + // Apply S4 point group operation to all atoms + + for (j = 0; j < natoms; j++) + { + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + for (k = 0; k < ((2*naxis) - 1); k++) + { + rotx = (symMatrx[0][0] * X) + (symMatrx[0][1] * Y) + (symMatrx[0][2] * Z); + roty = (symMatrx[1][0] * X) + (symMatrx[1][1] * Y) + (symMatrx[1][2] * Z); + rotz = (symMatrx[2][0] * X) + (symMatrx[2][1] * Y) + (symMatrx[2][2] * Z); + + coincidence = false; + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(rotx - XX); + lamy = Math.abs(roty - YY); + lamz = Math.abs(rotz - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if (coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(rotx); + symmStructure.add(roty); + symmStructure.add(rotz); + + maxndx += 1; + } + + X = rotx; + Y = roty; + Z = rotz; + } + } + + natoms = symmStructure.size()/4; + + atomID = new String[natoms]; + atomCoords = new double[3*natoms]; + + for (j = 0; j < natoms; j++) + { + atomID[j] = (symmStructure.get(4*j)).toString(); + + atomCoords[(3*j)] = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + atomCoords[(3*j) + 1] = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + atomCoords[(3*j) + 2] = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + } + + break; + case 13: // point group 'O' + symmStructure = new ArrayList(); + + naxis = 4; + + symMatrx[0][0] = 0.0; + symMatrx[0][1] = 1.0; + symMatrx[0][2] = 0.0; + symMatrx[1][0] = -1.0; + symMatrx[1][1] = 0.0; + symMatrx[1][2] = 0.0; + symMatrx[2][0] = 0.0; + symMatrx[2][1] = 0.0; + symMatrx[2][2] = 1.0; + + for (j = 0; j < natoms; j++) + { + X = atomCoords[3*j]; + Y = atomCoords[(3*j) + 1]; + Z = atomCoords[(3*j) + 2]; + + symmStructure.add(atomID[j]); + + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + } + + maxndx = natoms; + + // Rotate all atoms by pi/2 about the z-axis (naxis - 1) times + for (j = 0; j < natoms; j++) + { + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + for (k = 0; k < (naxis - 1); k++) + { + rotx = (symMatrx[0][0] * X) + (symMatrx[0][1] * Y) + (symMatrx[0][2] * Z); + roty = (symMatrx[1][0] * X) + (symMatrx[1][1] * Y) + (symMatrx[1][2] * Z); + rotz = (symMatrx[2][0] * X) + (symMatrx[2][1] * Y) + (symMatrx[2][2] * Z); + + coincidence = false; + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(rotx - XX); + lamy = Math.abs(roty - YY); + lamz = Math.abs(rotz - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if (coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(rotx); + symmStructure.add(roty); + symmStructure.add(rotz); + + maxndx += 1; + } + + X = rotx; + Y = roty; + Z = rotz; + } + } + + natoms = symmStructure.size()/4; + + atomID = new String[natoms]; + atomCoords = new double[3*natoms]; + + for (j = 0; j < natoms; j++) + { + atomID[j] = (symmStructure.get(4*j)).toString(); + + atomCoords[(3*j)] = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + atomCoords[(3*j) + 1] = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + atomCoords[(3*j) + 2] = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + } + + break; + case 14: // point group 'Oh' + symmStructure = new ArrayList(); + + naxis = 4; + + symMatrx[0][0] = 0.0; + symMatrx[0][1] = 1.0; + symMatrx[0][2] = 0.0; + symMatrx[1][0] = -1.0; + symMatrx[1][1] = 0.0; + symMatrx[1][2] = 0.0; + symMatrx[2][0] = 0.0; + symMatrx[2][1] = 0.0; + symMatrx[2][2] = 1.0; + + for (j = 0; j < natoms; j++) + { + X = atomCoords[3*j]; + Y = atomCoords[(3*j) + 1]; + Z = atomCoords[(3*j) + 2]; + + symmStructure.add(atomID[j]); + + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + } + + maxndx = natoms; + + // Apply inversion point group operation to all atoms + + for (j = 0; j < natoms; j++) + { + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = -Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = -Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = -Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + coincidence = false; + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(X - XX); + lamy = Math.abs(Y - YY); + lamz = Math.abs(Z - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if (coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(X); + symmStructure.add(Y); + symmStructure.add(Z); + + maxndx += 1; + } + } + + natoms = symmStructure.size()/4; + + // Rotate all atoms by pi/2 about the z-axis (naxis - 1) times + for (j = 0; j < natoms; j++) + { + atmsymbl = (symmStructure.get(4*j)).toString(); + + X = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + Y = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + Z = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + + for (k = 0; k < (naxis - 1); k++) + { + rotx = (symMatrx[0][0] * X) + (symMatrx[0][1] * Y) + (symMatrx[0][2] * Z); + roty = (symMatrx[1][0] * X) + (symMatrx[1][1] * Y) + (symMatrx[1][2] * Z); + rotz = (symMatrx[2][0] * X) + (symMatrx[2][1] * Y) + (symMatrx[2][2] * Z); + + coincidence = false; + + for (ndx = 0; ndx < maxndx; ndx++) + { + XX = Double.parseDouble( (symmStructure.get((4*ndx) + 1)).toString() ); + YY = Double.parseDouble( (symmStructure.get((4*ndx) + 2)).toString() ); + ZZ = Double.parseDouble( (symmStructure.get((4*ndx) + 3)).toString() ); + + lamx = Math.abs(rotx - XX); + lamy = Math.abs(roty - YY); + lamz = Math.abs(rotz - ZZ); + + if ( (lamx < lambda) && (lamy < lambda) && (lamz < lambda) ) + { + coincidence = true; + } + } + + if (coincidence == false) + { + symmStructure.add(atmsymbl); + + symmStructure.add(rotx); + symmStructure.add(roty); + symmStructure.add(rotz); + + maxndx += 1; + } + + X = rotx; + Y = roty; + Z = rotz; + } + } + + natoms = symmStructure.size()/4; + + atomID = new String[natoms]; + atomCoords = new double[3*natoms]; + + for (j = 0; j < natoms; j++) + { + atomID[j] = (symmStructure.get(4*j)).toString(); + + atomCoords[(3*j)] = Double.parseDouble( (symmStructure.get((4*j) + 1)).toString() ); + atomCoords[(3*j) + 1] = Double.parseDouble( (symmStructure.get((4*j) + 2)).toString() ); + atomCoords[(3*j) + 2] = Double.parseDouble( (symmStructure.get((4*j) + 3)).toString() ); + } + + break; + default: // do nothing here + break; + } + } + + + // Get atomic number for each atom in the molecule being displayed + atomicNumber = new int[natoms]; + atomicNumber = getAtomicNumber(atomID, natoms); + + // Get bond lengths between bonded atoms in the molecule being displayed + // Note that this also generates an atom connectivity array + zmatBondLength = new double[natoms][natoms]; + + if (coordFormat.equals("zmat")) + { + zmatBondLength = getZMatBondLength(alGeom, natoms); + } + else + { + // Initialize zmatBondLength matrix elements to zero + for (j = 0; j < natoms; j++) + { + for (k = 0; k < natoms; k++) + { + zmatBondLength[j][k] = 0.0; + } + } + } + + // Set default bonding parameter + if(coordFormat.equals("zmat")) + bondParam = 1.0; + else + bondParam = ((double)connSlider.getValue())/10.0; + + // Set recomputeConnectivity + recomputeConnectivity = false; + + // Get complete connectivity for this molecule + + if (natoms > 1) + { + bondLength = new double[natoms][natoms]; + bondLength = getBondLength(zmatBondLength, natoms, atomCoords, atomicNumber, bondParam); + } + + // Set default radius for atom + defaultAtomRadius = 0.35; + + scaledAtomRadius = new double[natoms]; + if(natoms>0){ + if (natoms > 1) + { + unscaledAtomRadius = getUnscaledAtomRadius(bondLength, natoms); + + scaledAtomRadius = new double[natoms]; + scaledAtomRadius = getScaledAtomRadius(atomicNumber, unscaledAtomRadius, natoms); + } + else + { + unscaledAtomRadius = defaultAtomRadius; + + //scaledAtomRadius[0] = defaultAtomRadius; + } + } + // Scale atom radii by default + scaleRadius = 1; // 0 (unscaled), 1 (scaled), 2 (wireframe) + + // Set default scale factor + scaleFactor = 1.0; + + // Get color of each atom in the molecule being displayed + atomColors = new float[3*natoms]; + atomColors = getAtomColors(atomicNumber, natoms); + + // Set bonds to be visible by default (bondsVisible = true) + bondsVisible = true; + + // Set bonds to be uncolored by default (bondsColored = false) + bondsColored = false; + + // Set default bond radius + bondRadius = 0.075; + + bondMat1 = new float[(3*natoms)]; + bondMat2 = new float[(3*natoms)]; + + // Initialize angles specifying molecule's rotation + theta = 0.0; + phi = 0.0; + + // Set origin of coordinate reference frame + x0 = 0.0; + y0 = 0.0; + z0 = 0.0; + + // Set distance of coordinate frame origin from camera + zloc = 7.0; + + x1 = 0.0; + y1 = 0.0; + + x_rot = false; + y_rot = false; + z_rot = false; + + if(natoms>0){ + // check for consistency of charge and multiplicity + nuclearCharge = 0; + + + // convert charge and multiplicity to integers + Integer charge; + Integer multiplicity; + + for (j = 0; j < natoms; j++) + { + nuclearCharge += atomicNumber[j]; + } + + if ( (chargeStr != "") && (multiplicityStr != "") ) + { + + charge=Integer.parseInt(chargeStr); + multiplicity=Integer.parseInt(multiplicityStr); + + System.out.println("charge:"+chargeStr+" multiplicity:"+multiplicityStr); + System.out.println("charge:"+charge+" multiplicity:"+multiplicity); + + nelectrons = nuclearCharge-charge; + + System.out.println("nelectrons:"+nelectrons); + + if ( (nelectrons % 2 == 0) && (multiplicity % 2 == 0) ) + { + CM_consistency = false; + + + // Set corresponding boolean value in interface to false + } + else + if ( (nelectrons % 2 == 1) && (multiplicity % 2 == 1) ) + { + CM_consistency = false; + + + // Set corresponding boolean value in interface to false + } + + } + } + return CM_consistency; + } // end of draw molecule + + public String[] getAtomID(ArrayList alGeom, int natoms) + { + int indx; + + Character chr; + + ArrayList listElement; + + StringBuffer sbSymbolID; + + String indexedAtoms; + + String strSymbolID; + String[] symbolID = new String[natoms]; + + String[] atomicSymbol = {"H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd", "In", "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Ce", "Pr", "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm", "Yb", "Lu", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au", "Hg", "Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "Ac", "Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es", "Fm", "Md", "No", "Lr", "Rf", "Db", "Sg", "Bh", "Hs", "Mt", "Ds", "Rg"}; + + String[] elementName = {"Hydrogen", "Helium", "Lithium", "Beryllium", "Boron", "Carbon", "Nitrogen", "Oxygen", "Fluorine", "Neon", "Sodium", "Magnesium", "Aluminum", "Silicon", "Phosphorus", "Sulfur", "Chlorine", "Argon", "Potassium", "Calcium", "Scandium", "Titanium", "Vanadium", "Chromium", "Manganese", "Iron", "Cobalt", "Nickel", "Copper", "Zinc", "Gallium", "Germanium", "Arsenic", "Selenium", "Bromine", "Krypton", "Rubidium", "Strontium", "Yttrium", "Zirconium", "Niobium", "Molybdenum", "Technetium", "Ruthenium", "Rhodium", "Palladium", "Silver", "Cadmium", "Indium", "Tin", "Antimony", "Tellurium", "Iodine", "Xenon", "Cesium", "Barium", "Lanthanum", "Cerium", "Praseodymium", "Neodynium", "Promethium", "Samarium", "Europium","Gadolinium", "Terbium", "Dysprosium", "Holmium", "Erbium", "Thulium", "Ytterbium", "Lutetium", "Hafnium", "Tantalum", "Tungsten", "Rhenium", "Osmium", "Iridium", "Platinum", "Gold", "Mercury", "Thallium", "Lead", "Bismuth", "Polonium", "Astatine", "Radon", "Francium", "Radium", "Actinum", "Thorium", "Protactinium", "Uranium", "Neptunium", "Plutonium", "Americium", "Curium", "Berkelium", "Californium", "Einsteinium", "Fermium", "Mendelevium", "Nobelium", "Lawrencium", "Rutherfordium", "Dubnium", "Seaborgium", "Bohrium", "Hassium", "Meitnerium", "Darmstadtium", "Roentgenium"}; + + for (j = 0; j < natoms; j++) + { + listElement = new ArrayList(); + listElement = (ArrayList)(alGeom.get(j)); + + strSymbolID = (listElement.get(0)).toString(); + + sbSymbolID = new StringBuffer(); + + for (k = 0; k < strSymbolID.length(); k++) + { + chr = new Character(strSymbolID.charAt(k)); + + if (Character.isLetter(chr)) + { + sbSymbolID.append(chr.toString()); + } + } + + if (sbSymbolID.length() > 2) + { + for (indx = 0; indx < elementName.length; indx++) + { + if ( (sbSymbolID.toString()).equalsIgnoreCase(elementName[indx]) ) + { + strSymbolID = atomicSymbol[indx]; + + break; + } + } + } + else + { + strSymbolID = sbSymbolID.toString(); + } + + symbolID[j] = strSymbolID; + } + + return symbolID; + } + + public String getCoordFormat(ArrayList alGeom, int natoms) + { + String geomFormat = new String(); + + ArrayList elemList01,elemList02,elemList03,elemList04; + + switch(natoms) + { + case 0: geomFormat = "undefined"; + break; + case 1: elemList01 = new ArrayList(); + elemList01 = (ArrayList)alGeom.get(0); + + if (elemList01.size() == 1) + { + geomFormat = "zmat"; + } + else if (elemList01.size() > 1) + { + geomFormat = "cartesian"; + } + break; + + case 2: elemList01 = new ArrayList(); + elemList02 = new ArrayList(); + + elemList01 = (ArrayList)alGeom.get(0); + elemList02 = (ArrayList)alGeom.get(1); + + if ((elemList01.size() == 1) && (elemList02.size() == 3) ) + { + geomFormat = "zmat"; + } + else if ((elemList01.size() > 1) || (elemList02.size() == 5) ) + { + geomFormat = "cartesian"; + } + break; + + case 3: elemList02 = new ArrayList(); + elemList03 = new ArrayList(); + + elemList02 = (ArrayList)alGeom.get(1); + elemList03 = (ArrayList)alGeom.get(2); + + if ((elemList02.size() == 3) && (elemList03.size() == 5) ) + { + geomFormat = "zmat"; + } + else if ((elemList02.size() == 5) || (elemList03.size() == 5) ) + { + geomFormat = "cartesian"; + } + + break; + + default: elemList03 = new ArrayList(); + elemList04 = new ArrayList(); + + elemList03 = (ArrayList)alGeom.get(2); + elemList04 = (ArrayList)alGeom.get(3); + + if ((elemList03.size() == 5) && (elemList04.size() >= 7) ) + { + geomFormat = "zmat"; + } + else if ((elemList03.size() == 5) || (elemList04.size() == 5) ) + { + geomFormat = "cartesian"; + } + + break; + } + return geomFormat; + } + + public double[] getAtomCoords(ArrayList alGeom, int natoms, String coordFormat) + { + int bondedAtomIndex, alphaAtomIndex, gammaAtomIndex; + double bd, dx, dy, dz, dx1, dy1, dz1, dx2, dy2, dz2, r, nx, ny, nz, n, alpha, gamma; + double[] prerotCoord = new double[3]; + double[] coords = new double[3*natoms]; + double[] rotCoord = new double[3]; + double[][] rotMatrix = new double[3][3]; + ArrayList elemList; + + if (coordFormat.equals("cartesian")) + { + for (j = 0; j < natoms; j++) + { + elemList = new ArrayList(); + elemList = (ArrayList)alGeom.get(j); + + if (elemList.size() == 2) + { + for (k = 0; k < 3; k++) + { + coords[(3*j + k)] = 0.00; + } + } + else if (elemList.size() == 3) + { + coords[(3*j)] = Double.parseDouble((elemList.get(2)).toString() ); + + for (k = 1; k < 3; k++) + { + coords[(3*j + k)] = 0.00; + } + } + else if (elemList.size() == 4) + { + coords[(3*j)] = Double.parseDouble((elemList.get(2)).toString() ); + coords[(3*j) + 1] = Double.parseDouble((elemList.get(3)).toString() ); + coords[(3*j) + 2] = 0.00; + } + else if (elemList.size() == 5) + { + coords[(3*j)] = Double.parseDouble((elemList.get(2)).toString() ); + coords[(3*j) + 1] = Double.parseDouble((elemList.get(3)).toString() ); + coords[(3*j) + 2] = -Double.parseDouble((elemList.get(4)).toString() ); + } + } + } + + if (coordFormat.equals("zmat")) + { + double dx12, dy12, dz12, dx23, dy23, dz23, dx34, dy34, dz34; + double r11, r22, r33, R; + double rx, ry, rz; + double n11, n22, n33; + double nx_prime, ny_prime, nz_prime; + + int atom1Index, atom2Index, atom3Index, atom4Index; + + + for (index = 0; index < natoms; index++) + { + elemList = new ArrayList(); + + switch(index) + { + case 0: coords[(3*index)] = 0.0; + coords[(3*index) + 1] = 0.0; + coords[(3*index) + 2] = 0.0; + break; + + case 1: elemList = (ArrayList)alGeom.get(index); + bd = Double.parseDouble( (elemList.get(2)).toString() ); + coords[(3*index)] = 0.0; + coords[(3*index) + 1] = 0.0; + coords[(3*index) + 2] = bd; + break; + + case 2: elemList = (ArrayList)alGeom.get(index); + +////////////////////////// +// // +// o 3 // +// / // +// / // +// 1 o ---- o 2 // +// // +////////////////////////// + + atom3Index = index; + atom2Index = (Integer.parseInt( (elemList.get(1)).toString() )) - 1; + atom1Index = (Integer.parseInt( (elemList.get(3)).toString() )) - 1; + + // Compute difference in coordinates between atom 1 and atom 2, R12 + dx12 = coords[(3*atom2Index)] - coords[(3*atom1Index)]; + dy12 = coords[(3*atom2Index) + 1] - coords[(3*atom1Index) + 1]; + dz12 = coords[(3*atom2Index) + 2] - coords[(3*atom1Index) + 2]; + + // Compute unit vector along bond from atom 2 to atom 1 + r = Math.sqrt( (dx12*dx12) + (dy12*dy12) + (dz12*dz12) ); + + nx = -dx12/r; + ny = -dy12/r; + nz = -dz12/r; + + // Compute unit vector along axis of rotation (alpha angle) centered on atom 2 + n11 = -1.0; + n22 = 0.0; + n33 = 0.0; + + // Retrieve alpha rotation angle + alpha = Double.parseDouble( (elemList.get(4)).toString() ); + + // (1) Convert bond angle (alpha) from degrees to radians + alpha = alpha * (Math.PI/180.0); + + // Compute rotation matrix + rotMatrix[0][0] = (n11 * n11) + ( Math.cos(alpha) * (1 - n11 * n11) ); + rotMatrix[0][1] = ( (n11 * n22) * (1 - Math.cos(alpha)) ) + (n33 * Math.sin(alpha)); + rotMatrix[0][2] = ( (n33 * n11) * (1 - Math.cos(alpha)) ) - (n22 * Math.sin(alpha)); + + rotMatrix[1][0] = ( (n11 * n22) * (1 - Math.cos(alpha)) ) - (n33 * Math.sin(alpha)); + rotMatrix[1][1] = (n22 * n22) + ( Math.cos(alpha) * (1 - n22 * n22) ); + rotMatrix[1][2] = ( (n22 * n33) * (1 - Math.cos(alpha)) ) + (n11 * Math.sin(alpha)); + + rotMatrix[2][0] = ( (n33 * n11) * (1 - Math.cos(alpha)) ) + (n22 * Math.sin(alpha)); + rotMatrix[2][1] = ( (n22 * n33) * (1 - Math.cos(alpha)) ) - (n11 * Math.sin(alpha)); + rotMatrix[2][2] = (n33 * n33) + ( Math.cos(alpha) * (1 - n33 * n33) ); + + // (3) Compute rotated unit vector along bond from atom 2 to atom 3 + nx_prime = rotMatrix[0][0] * nx + rotMatrix[0][1] * ny + rotMatrix[0][2] * nz; + ny_prime = rotMatrix[1][0] * nx + rotMatrix[1][1] * ny + rotMatrix[1][2] * nz; + nz_prime = rotMatrix[2][0] * nx + rotMatrix[2][1] * ny + rotMatrix[2][2] * nz; + + // Compute final cartesian coordinates for this atom + bd = Double.parseDouble( (elemList.get(2)).toString() ); + + coords[(3*index)] = coords[(3*atom2Index)] + (nx_prime * bd); + coords[(3*index) + 1] = coords[(3*atom2Index) + 1] + (ny_prime * bd); + coords[(3*index) + 2] = coords[(3*atom2Index) + 2] + (nz_prime * bd); + + break; + + default: elemList = (ArrayList)alGeom.get(index); + +///////////////////////////// +// // +// o 4 // +// / // +// / // +// 2 o ---- o 3 // +// / // +// / // +// 1 o // +// // +///////////////////////////// + + atom4Index = index; + atom3Index = (Integer.parseInt( (elemList.get(1)).toString() )) - 1; + atom2Index = (Integer.parseInt( (elemList.get(3)).toString() )) - 1; + atom1Index = (Integer.parseInt( (elemList.get(5)).toString() )) - 1; + + // Compute difference in coordinates between atom 1 and atom 2, R12 + dx12 = coords[(3*atom2Index)] - coords[(3*atom1Index)]; + dy12 = coords[(3*atom2Index) + 1] - coords[(3*atom1Index) + 1]; + dz12 = coords[(3*atom2Index) + 2] - coords[(3*atom1Index) + 2]; + + // Compute difference in coordinates between atom 2 and atom 3, R23 + dx23 = coords[(3*atom3Index)] - coords[(3*atom2Index)]; + dy23 = coords[(3*atom3Index) + 1] - coords[(3*atom2Index) + 1]; + dz23 = coords[(3*atom3Index) + 2] - coords[(3*atom2Index) + 2]; + + // Compute cross-product R12 x R23 = [ (dx12, dy12, dz12) X (dx23, dy23, dz23) ] + rx = (dy12 * dz23) - (dy23 * dz12); + ry = (dz12 * dx23) - (dz23 * dx12); + rz = (dx12 * dy23) - (dx23 * dy12); + + // Compute unit vector along axis of rotation (alpha angle) normal to plane of atoms 1, 2, and 3 and centered on atom 3 + r = Math.sqrt(rx*rx + ry*ry + rz*rz); + + n11 = rx/r; + n22 = ry/r; + n33 = rz/r; + + // Compute unit vector along bond from atom 3 to atom 2 + r = Math.sqrt( (dx23*dx23) + (dy23*dy23) + (dz23*dz23) ); + + nx = -dx23/r; + ny = -dy23/r; + nz = -dz23/r; + + // Retrieve alpha rotation angle + alpha = Double.parseDouble( (elemList.get(4)).toString() ); + + // (1) Convert bond angle (alpha) from degrees to radians + alpha = alpha * (Math.PI/180.0); + + // Compute rotation matrix + rotMatrix[0][0] = (n11 * n11) + ( Math.cos(alpha) * (1 - n11 * n11) ); + rotMatrix[0][1] = ( (n11 * n22) * (1 - Math.cos(alpha)) ) + (n33 * Math.sin(alpha)); + rotMatrix[0][2] = ( (n33 * n11) * (1 - Math.cos(alpha)) ) - (n22 * Math.sin(alpha)); + + rotMatrix[1][0] = ( (n11 * n22) * (1 - Math.cos(alpha)) ) - (n33 * Math.sin(alpha)); + rotMatrix[1][1] = (n22 * n22) + ( Math.cos(alpha) * (1 - n22 * n22) ); + rotMatrix[1][2] = ( (n22 * n33) * (1 - Math.cos(alpha)) ) + (n11 * Math.sin(alpha)); + + rotMatrix[2][0] = ( (n33 * n11) * (1 - Math.cos(alpha)) ) + (n22 * Math.sin(alpha)); + rotMatrix[2][1] = ( (n22 * n33) * (1 - Math.cos(alpha)) ) - (n11 * Math.sin(alpha)); + rotMatrix[2][2] = (n33 * n33) + ( Math.cos(alpha) * (1 - n33 * n33) ); + + // (3) Compute rotated unit vector along bond from atom 2 to atom 3 + nx_prime = rotMatrix[0][0] * nx + rotMatrix[0][1] * ny + rotMatrix[0][2] * nz; + ny_prime = rotMatrix[1][0] * nx + rotMatrix[1][1] * ny + rotMatrix[1][2] * nz; + nz_prime = rotMatrix[2][0] * nx + rotMatrix[2][1] * ny + rotMatrix[2][2] * nz; + + // Retrieve gamma rotation angle (dihedral angle) + gamma = Double.parseDouble( (elemList.get(6)).toString() ); + + // (1) Convert dihedral angle (gamma) from degrees to radians + gamma = gamma * (Math.PI/180.0); + + // Compute unit vector along axis of rotation (dihedral angle) = unit vector along bond from atom 3 to atom 2 + n11 = -dx23/r; + n22 = -dy23/r; + n33 = -dz23/r; + + // Compute rotation matrix + rotMatrix[0][0] = (n11 * n11) + ( Math.cos(gamma) * (1 - n11 * n11) ); + rotMatrix[0][1] = ( (n11 * n22) * (1 - Math.cos(gamma)) ) + (n33 * Math.sin(gamma)); + rotMatrix[0][2] = ( (n33 * n11) * (1 - Math.cos(gamma)) ) - (n22 * Math.sin(gamma)); + + rotMatrix[1][0] = ( (n11 * n22) * (1 - Math.cos(gamma)) ) - (n33 * Math.sin(gamma)); + rotMatrix[1][1] = (n22 * n22) + ( Math.cos(gamma) * (1 - n22 * n22) ); + rotMatrix[1][2] = ( (n22 * n33) * (1 - Math.cos(gamma)) ) + (n11 * Math.sin(gamma)); + + rotMatrix[2][0] = ( (n33 * n11) * (1 - Math.cos(gamma)) ) + (n22 * Math.sin(gamma)); + rotMatrix[2][1] = ( (n22 * n33) * (1 - Math.cos(gamma)) ) - (n11 * Math.sin(gamma)); + rotMatrix[2][2] = (n33 * n33) + ( Math.cos(gamma) * (1 - n33 * n33) ); + + // Compute unit vector along bond from atom 3 to atom 4 + nx = nx_prime; + ny = ny_prime; + nz = nz_prime; + + // Compute rotated unit vector along bond from atom 3 to atom 4 + nx_prime = rotMatrix[0][0] * nx + rotMatrix[0][1] * ny + rotMatrix[0][2] * nz; + ny_prime = rotMatrix[1][0] * nx + rotMatrix[1][1] * ny + rotMatrix[1][2] * nz; + nz_prime = rotMatrix[2][0] * nx + rotMatrix[2][1] * ny + rotMatrix[2][2] * nz; + + // Compute final cartesian coordinates for this atom + bd = Double.parseDouble( (elemList.get(2)).toString() ); + + coords[(3*index)] = coords[(3*atom3Index)] + (nx_prime * bd); + coords[(3*index) + 1] = coords[(3*atom3Index) + 1] + (ny_prime * bd); + coords[(3*index) + 2] = coords[(3*atom3Index) + 2] + (nz_prime * bd); + + break; + } + } + } + + return coords; + } + + public int[] getAtomicNumber(String[] atomID, int natoms) + { + int[] AN = new int[natoms]; + String[] atomicSymbol = {"H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd", "In", "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Ce", "Pr", "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm", "Yb", "Lu", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au", "Hg", "Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "Ac", "Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es", "Fm", "Md", "No", "Lr", "Rf", "Db", "Sg", "Bh", "Hs", "Mt", "Ds", "Rg"}; + + for (j = 0; j < natoms; j++) + { + for (k = 0; k < atomicSymbol.length; k++) + { + if (atomicSymbol[k].equalsIgnoreCase(atomID[j])) + { + AN[j] = k + 1; + break; + } + } + } + + return AN; + } + + public double[][] getZMatBondLength(ArrayList alGeom, int natoms) + { + ArrayList listElem; + int bondedAtomIndex; + double[][] bondLen; + + bondLen = new double[natoms][natoms]; + + for (j = 0; j < natoms; j++) + { + for (k = 0; k < natoms; k++) + { + bondLen[j][k] = 0.0; + } + } + + for (j = 1; j < natoms; j++) + { + listElem = new ArrayList(); + listElem = (ArrayList)alGeom.get(j); + + bondedAtomIndex = (Integer.parseInt( (listElem.get(1)).toString() )) - 1; + + bondLen[j][bondedAtomIndex] = Double.parseDouble( (listElem.get(2)).toString() ); + } + + return bondLen; + } + + public double[][] getBondLength(double[][] zmatBondLength, int natoms, double[] atomCoords, int[] atomicNumber, double bondParam) + { + double dx, dy, dz, r, bl; + double ar1, ar2, cr1, cr2; + + // VFI atomic radii (from CrystalMaker 1.4.0) + double[ ] ar = { 0.46, 1.22, 1.55, 1.13, 0.91, 0.77, 0.71, 0.48, 0.42, 1.60, 1.89, 1.60, 1.43, 1.34, 1.30, 0.88, 0.79, 1.92, 2.36, 1.97, 1.64, 1.46, 1.34, 1.40, 1.31, 1.26, 1.25, 1.24, 1.28, 1.27, 1.39, 1.39, 1.48, 1.43, 0.94, 1.98, 2.48, 2.15, 1.81, 1.60, 1.45, 1.39, 1.36, 1.34, 1.34, 1.37, 1.44, 1.56, 1.66, 1.58, 1.61, 1.70, 1.15, 2.18, 2.68, 2.21, 1.87, 1.83, 1.82, 1.82, 2.05, 1.81, 2.02, 1.79, 1.77, 1.77, 1.76, 1.75, 1.75, 1.93, 1.74, 1.59, 1.46, 1.40, 1.37, 1.35, 1.35, 1.38, 1.44, 1.60, 1.71, 1.75, 1.82, 1.35, 1.27, 1.20, 1.00, 1.00, 2.03, 1.80, 1.62, 1.53, 1.50, 1.50, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 }; + double[ ] covrad = { 0.37, 0.32, 1.34, 0.90, 0.82, 0.77, 0.75, 0.73, 0.71, 0.69, 1.54, 1.30, 1.18, 1.11, 1.06, 1.02, 0.99, 0.97, 1.96, 1.74, 1.44, 1.36, 1.25, 1.27, 1.39, 1.25, 1.26, 1.21, 1.38, 1.31, 1.26, 1.22, 1.19, 1.16, 1.14, 1.10, 2.11, 1.92, 1.62, 1.48, 1.37, 1.45, 1.56, 1.26, 1.35, 1.31, 1.53, 1.48, 1.44, 1.41, 1.38, 1.35, 1.33, 1.30, 2.25, 1.98, 1.69, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.60, 1.50, 1.38, 1.46, 1.59, 1.28, 1.37, 1.28, 1.44, 1.49, 1.48, 1.47, 1.46, 1.00, 1.00, 1.45, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 }; + + double[][] connectivity; + connectivity = new double[natoms][natoms]; + + for (j = 1; j < natoms; j++) + { + for (k = 0; k < j; k++) + { + connectivity[j][k] = zmatBondLength[j][k]; + } + } + + for (j = 1; j < natoms; j++) + { + for (k = 0; k < j; k++) + { + if (connectivity[j][k] == 0.0) + { + dx = atomCoords[(3*j)] - atomCoords[(3*k)]; + dy = atomCoords[(3*j) + 1] - atomCoords[(3*k) + 1]; + dz = atomCoords[(3*j) + 2] - atomCoords[(3*k) + 2]; + + r = Math.sqrt(dx*dx + dy*dy + dz*dz); + + ar1 = ar[(atomicNumber[j] - 1)]; + ar2 = ar[(atomicNumber[k] - 1)]; + + if ( r <= 0.4*bondParam*(ar1 + ar2) ) + { + connectivity[j][k] = r; + } + } + } + } + + return connectivity; + } + + public double getUnscaledAtomRadius(double[][] bondLength, int natoms) + { + double unscaledRadius; + int nbonds = 0; + + for (j = 1; j < natoms; j++) + { + for (k = 0; k < j; k++) + { + if (bondLength[j][k] > 0.0) + { + nbonds++; + } + } + } + + if (nbonds > 0) + { + double minBondLength = 1000.0; + + for (j = 1; j < natoms; j++) + { + for (k = 0; k < j; k++) + { + if ( (bondLength[j][k] != 0.0) && (bondLength[j][k] < minBondLength) ) + { + minBondLength = bondLength[j][k]; + } + } + } + + unscaledAtomRadius = 0.4*minBondLength; + } + else + { + unscaledAtomRadius = defaultAtomRadius; + } + + return unscaledAtomRadius; + } + + public double[] getScaledAtomRadius(int[] atomicNumber, double unscaledAtomRadius, int natoms) + { + double maxRadius; + double[] scaledRadius; + + // VFI atomic radii (from CrystalMaker 1.4.0) + double[ ] ar = { 0.46, 1.22, 1.55, 1.13, 0.91, 0.77, 0.71, 0.48, 0.42, 1.60, 1.89, 1.60, 1.43, 1.34, 1.30, 0.88, 0.79, 1.92, 2.36, 1.97, 1.64, 1.46, 1.34, 1.40, 1.31, 1.26, 1.25, 1.24, 1.28, 1.27, 1.39, 1.39, 1.48, 1.43, 0.94, 1.98, 2.48, 2.15, 1.81, 1.60, 1.45, 1.39, 1.36, 1.34, 1.34, 1.37, 1.44, 1.56, 1.66, 1.58, 1.61, 1.70, 1.15, 2.18, 2.68, 2.21, 1.87, 1.83, 1.82, 1.82, 2.05, 1.81, 2.02, 1.79, 1.77, 1.77, 1.76, 1.75, 1.75, 1.93, 1.74, 1.59, 1.46, 1.40, 1.37, 1.35, 1.35, 1.38, 1.44, 1.60, 1.71, 1.75, 1.82, 1.35, 1.27, 1.20, 1.00, 1.00, 2.03, 1.80, 1.62, 1.53, 1.50, 1.50, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 }; + double[ ] covrad = { 0.37, 0.32, 1.34, 0.90, 0.82, 0.77, 0.75, 0.73, 0.71, 0.69, 1.54, 1.30, 1.18, 1.11, 1.06, 1.02, 0.99, 0.97, 1.96, 1.74, 1.44, 1.36, 1.25, 1.27, 1.39, 1.25, 1.26, 1.21, 1.38, 1.31, 1.26, 1.22, 1.19, 1.16, 1.14, 1.10, 2.11, 1.92, 1.62, 1.48, 1.37, 1.45, 1.56, 1.26, 1.35, 1.31, 1.53, 1.48, 1.44, 1.41, 1.38, 1.35, 1.33, 1.30, 2.25, 1.98, 1.69, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.60, 1.50, 1.38, 1.46, 1.59, 1.28, 1.37, 1.28, 1.44, 1.49, 1.48, 1.47, 1.46, 1.00, 1.00, 1.45, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 }; + + scaledRadius = new double[natoms]; + maxRadius = ar[atomicNumber[0] - 1]; + + for (j = 1; j < natoms; j++) + { +// if (ar[atomicNumber[j] - 1] > maxRadius) + if (covrad[atomicNumber[j] - 1] > maxRadius) + { +// maxRadius = ar[(atomicNumber[j] - 1)]; + maxRadius = covrad[(atomicNumber[j] - 1)]; + } + } + + for (j = 0; j < natoms; j++) + { +// scaledRadius[j] = unscaledAtomRadius * (ar[(atomicNumber[j] - 1)]/maxRadius); + scaledRadius[j] = unscaledAtomRadius * (covrad[(atomicNumber[j] - 1)]/maxRadius); + } + + return scaledRadius; + } + + public float[] getAtomColors(int[] atomicNumber, int natoms) + { + float red, green, blue; + red = 1.0f; green = 1.0f; blue = 1.0f; + + float[] colors = new float[(3*natoms)]; + + for (j = 0; j < natoms; j++) + { + switch(atomicNumber[j]) + { + case 1: red = 0.600f; // H + green = 0.900f; + blue = 0.600f; + break; + case 2: red = 0.800f; // He + green = 0.925f; + blue = 1.000f; + break; + case 3: red = 0.800f; // Li + green = 0.000f; + blue = 1.000f; + break; + case 4: red = 0.600f; // Be + green = 0.400f; + blue = 1.000f; + break; + case 5: red = 0.000f; // B + green = 0.600f; + blue = 0.500f; + break; + case 6: red = 1.000f; // C + green = 1.000f; + blue = 0.7f; + break; + case 7: red = 0.000f; // N + green = 0.650f; + blue = 0.850f; + break; + case 8: red = 0.784f; // O + green = 0.000f; + blue = 0.098f; + break; + case 9: red = 1.000f; // F + green = 0.745f; + blue = 1.000f; + break; + case 10: red = 0.800f; // Ne + green = 1.000f; + blue = 1.000f; + break; + case 11: red = 1.000f; // Na + green = 1.000f; + blue = 0.000f; + break; + case 12: red = 0.608f; // Mg + green = 0.608f; + blue = 0.608f; + break; + case 13: red = 0.867f; // Al + green = 0.867f; + blue = 0.867f; + break; + case 14: red = 1.000f; // Si + green = 1.000f; + blue = 0.588f; + break; + case 15: red = 1.000f; // P + green = 0.000f; + blue = 0.000f; + break; + case 16: red = 1.000f; // S + green = 0.902f; + blue = 0.000f; + break; + case 17: red = 0.000f; // Cl + green = 0.804f; + blue = 0.333f; + break; + case 18: red = 0.000f; // Ar + green = 0.600f; + blue = 0.600f; + break; + case 19: red = 0.000f; // K + green = 0.196f; + blue = 0.765f; + break; + case 20: red = 1.000f; // Ca + green = 1.000f; + blue = 0.800f; + break; + case 21: red = 0.000f; // Sc + green = 1.000f; + blue = 0.000f; + break; + case 22: red = 0.000f; // Ti + green = 1.000f; + blue = 1.000f; + break; + case 23: red = 1.000f; // V + green = 1.000f; + blue = 0.400f; + break; + case 24: red = 0.200f; // Cr + green = 0.800f; + blue = 0.800f; + break; + case 25: red = 0.000f; // Mn + green = 0.800f; + blue = 0.600f; + break; + case 26: red = 0.800f; // Fe + green = 0.000f; + blue = 0.000f; + break; + case 27: red = 1.000f; // Co + green = 0.431f; + blue = 0.647f; + break; + case 28: red = 0.000f; // Ni + green = 0.373f; + blue = 0.980f; + break; + case 29: red = 1.000f; // Cu + green = 0.600f; + blue = 0.000f; + break; + case 30: red = 0.000f; // Zn + green = 0.800f; + blue = 0.800f; + break; + case 31: red = 0.000f; // Ga + green = 0.902f; + blue = 0.000f; + break; + case 32: red = 0.490f; // Ge + green = 0.800f; + blue = 0.800f; + break; + case 33: red = 0.000f; // As + green = 0.600f; + blue = 1.000f; + break; + case 34: red = 0.800f; // Se + green = 0.200f; + blue = 0.039f; + break; + case 35: red = 0.706f; // Br + green = 0.157f; + blue = 0.000f; + break; + case 36: red = 0.608f; // Kr + green = 1.000f; + blue = 0.800f; + break; + case 37: red = 0.600f; // Rb + green = 0.000f; + blue = 0.800f; + break; + case 38: red = 0.965f; // Sr + green = 0.980f; + blue = 0.647f; + break; + case 39: red = 0.961f; // Y + green = 0.510f; + blue = 1.000f; + break; + case 40: red = 0.549f; // Zr + green = 0.800f; + blue = 0.800f; + break; + case 41: red = 0.800f; // Nb + green = 1.000f; + blue = 0.200f; + break; + case 42: red = 0.800f; // Mo + green = 0.600f; + blue = 1.000f; + break; + case 43: red = 0.200f; // Tc + green = 0.400f; + blue = 0.600f; + break; + case 44: red = 0.000f; // Ru + green = 0.824f; + blue = 0.824f; + break; + case 45: red = 0.200f; // Rh + green = 0.400f; + blue = 0.824f; + break; + case 46: red = 0.451f; // Pd + green = 0.451f; + blue = 0.451f; + break; + case 47: red = 0.753f; // Ag + green = 0.753f; + blue = 0.753f; + break; + case 48: red = 0.902f; // Cd + green = 0.784f; + blue = 1.000f; + break; + case 49: red = 0.863f; // In + green = 0.706f; + blue = 0.824f; + break; + case 50: red = 0.863f; // Sn + green = 0.902f; + blue = 0.647f; + break; + case 51: red = 0.200f; // Sb + green = 0.647f; + blue = 0.200f; + break; + case 52: red = 0.800f; // Te + green = 1.000f; + blue = 0.600f; + break; + case 53: red = 0.863f; // I + green = 0.118f; + blue = 0.196f; + break; + case 54: red = 0.000f; // Xe + green = 0.510f; + blue = 0.294f; + break; + case 55: red = 1.000f; // Cs + green = 1.000f; + blue = 1.000f; + break; + case 56: red = 1.000f; // Ba + green = 1.000f; + blue = 1.000f; + break; + case 57: red = 1.000f; // La + green = 1.000f; + blue = 1.000f; + break; + case 58: red = 1.000f; // Ce + green = 1.000f; + blue = 1.000f; + break; + case 59: red = 1.000f; // Pr + green = 1.000f; + blue = 1.000f; + break; + case 60: red = 1.000f; // Nd + green = 1.000f; + blue = 1.000f; + break; + case 61: red = 1.000f; // Pm + green = 1.000f; + blue = 1.000f; + break; + case 62: red = 1.000f; // Sm + green = 1.000f; + blue = 1.000f; + break; + case 63: red = 1.000f; // Eu + green = 1.000f; + blue = 1.000f; + break; + case 64: red = 1.000f; // Gd + green = 1.000f; + blue = 1.000f; + break; + case 65: red = 1.000f; // Tb + green = 1.000f; + blue = 1.000f; + break; + case 66: red = 1.000f; // Dy + green = 1.000f; + blue = 1.000f; + break; + case 67: red = 1.000f; // Ho + green = 1.000f; + blue = 1.000f; + break; + case 68: red = 1.000f; // Er + green = 1.000f; + blue = 1.000f; + break; + case 69: red = 1.000f; // Tm + green = 1.000f; + blue = 1.000f; + break; + case 70: red = 1.000f; // Yb + green = 1.000f; + blue = 1.000f; + break; + case 71: red = 1.000f; // Lu + green = 1.000f; + blue = 1.000f; + break; + case 72: red = 1.000f; // Hf + green = 1.000f; + blue = 1.000f; + break; + case 73: red = 1.000f; // Ta + green = 1.000f; + blue = 1.000f; + break; + case 74: red = 1.000f; // W + green = 1.000f; + blue = 1.000f; + break; + case 75: red = 1.000f; // Re + green = 1.000f; + blue = 1.000f; + break; + case 76: red = 1.000f; // Os + green = 1.000f; + blue = 1.000f; + break; + case 77: red = 1.000f; // Ir + green = 1.000f; + blue = 1.000f; + break; + case 78: red = 0.918f; // Pt + green = 0.918f; + blue = 0.918f; + break; + case 79: red = 1.000f; // Au + green = 0.902f; + blue = 0.000f; + break; + case 80: red = 0.918f; // Hg + green = 0.953f; + blue = 0.914f; + break; + case 81: red = 1.000f; // Tl + green = 1.000f; + blue = 1.000f; + break; + case 82: red = 0.941f; // Pb + green = 0.941f; + blue = 0.941f; + break; + case 83: red = 1.000f; // Bi + green = 1.000f; + blue = 1.000f; + break; + case 84: red = 1.000f; // Po + green = 1.000f; + blue = 1.000f; + break; + case 85: red = 1.000f; // At + green = 1.000f; + blue = 1.000f; + break; + case 86: red = 1.000f; // Rn + green = 1.000f; + blue = 1.000f; + break; + case 87: red = 1.000f; // Fr + green = 1.000f; + blue = 1.000f; + break; + case 88: red = 1.000f; // Ra + green = 1.000f; + blue = 1.000f; + break; + case 89: red = 1.000f; // Ac + green = 1.000f; + blue = 1.000f; + break; + case 90: red = 1.000f; // Th + green = 1.000f; + blue = 1.000f; + break; + case 91: red = 1.000f; // Pa + green = 1.000f; + blue = 1.000f; + break; + case 92: red = 1.000f; // U + green = 1.000f; + blue = 1.000f; + break; + case 93: red = 1.000f; // Np + green = 1.000f; + blue = 1.000f; + break; + case 94: red = 1.000f; // Pu + green = 1.000f; + blue = 1.000f; + break; + case 95: red = 1.000f; // Am + green = 1.000f; + blue = 1.000f; + break; + case 96: red = 1.000f; // Cm + green = 1.000f; + blue = 1.000f; + break; + case 97: red = 1.000f; // Bk + green = 1.000f; + blue = 1.000f; + break; + case 98: red = 1.000f; // Cf + green = 1.000f; + blue = 1.000f; + break; + case 99: red = 1.000f; // Es + green = 1.000f; + blue = 1.000f; + break; + case 100: red = 1.000f; // Fm + green = 1.000f; + blue = 1.000f; + break; + case 101: red = 1.000f; // Md + green = 1.000f; + blue = 1.000f; + break; + case 102: red = 1.000f; // No + green = 1.000f; + blue = 1.000f; + break; + case 103: red = 1.000f; // Lr + green = 1.000f; + blue = 1.000f; + break; + case 104: red = 1.000f; // Rf + green = 1.000f; + blue = 1.000f; + break; + case 105: red = 1.000f; // Db + green = 1.000f; + blue = 1.000f; + break; + case 106: red = 1.000f; // Sg + green = 1.000f; + blue = 1.000f; + break; + case 107: red = 1.000f; // Bh + green = 1.000f; + blue = 1.000f; + break; + case 108: red = 1.000f; // Hs + green = 1.000f; + blue = 1.000f; + break; + case 109: red = 1.000f; // Mt + green = 1.000f; + blue = 1.000f; + break; + case 110: red = 1.000f; // Ds + green = 1.000f; + blue = 1.000f; + break; + case 111: red = 1.000f; // Rg + green = 1.000f; + blue = 1.000f; + break; + } + + colors[3*j] = red; + colors[(3*j) + 1] = green; + colors[(3*j) + 2] = blue; + } + + return colors; + } + + + // method definition "display" modified - 1st parameter changed to GLAutoDrawable from GLDrawable + //public void display(GLAutoDrawable gldraw) + public void display(GLAutoDrawable gldraw) + { + double height, width, aspect; + double fov, near, far; + boolean viewMolStructure; + + // parameter offsets // added by Narendra Kumar + int param_offsets = 0; // added by Narendra Kumar for "glLightfv" & "glMaterialfv" method call + + //Set initial display to true +// initDisplay = true; + +// gl = gldraw.getGL(); // method call not available - commented by narendra kumar + gl = (GL4bc)gldraw.getGL(); // method call modified - added by narendra kumar +// gl = gldraw.getGL().getGL4bc(); + +// glu = gldraw.getGLU(); // commented by Narendra Kumar + glu = new GLU(); // added by Narendra Kumar + + // Set up camera +// gl.glMatrixMode(GL.GL_PROJECTION); // static variable's class call not available - commented by narendra kumar + gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION); // static variable's class call modified - added by narendra kumar + gl.glLoadIdentity(); + + // Aspect ratio + height = ((Component)gldraw).getHeight(); + width = ((Component)gldraw).getWidth(); + aspect = width/height; + + fov = 60.0; + near = 0.01; + far = 1000.0; + + glu.gluPerspective(fov, aspect, near, far); + +// gl.glMatrixMode(GL.GL_MODELVIEW); // commented by narendra kumar + gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); // static variable's class call modified - added by narendra kumar + gl.glLoadIdentity(); + + // Set background color of canvas + gl.glClearColor(bkg_red, bkg_green, bkg_blue, color_alphaValue); + + // Define camera + glu.gluLookAt(0, 0, 0, 0, 0, 20, 0, 1, 0); + + // Set up light(s) + float position[] = {0.0f, 15.0f, -30.0f, 0.0f}; + + float diffuse[] = {0.7f, 0.7f, 0.7f, 0.5f}; + float ambient[] = {0.25f, 0.25f, 0.25f, 0.5f}; + + //add 4th parameter to method call "glLightfv" - param_offsets (int) -- Narendra Kumar +// gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, position); + gl.glLightfv(GLLightingFunc.GL_LIGHT0, GLLightingFunc.GL_POSITION, position,param_offsets); + + // add 4th parameter to method call "glLightfv" - param_offsets (int) -- Narendra Kumar +// gl.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, diffuse); + gl.glLightfv(GLLightingFunc.GL_LIGHT0, GLLightingFunc.GL_DIFFUSE, diffuse,param_offsets); + + // add 4th parameter to method call "glLightfv" - param_offsets (int) -- Narendra Kumar +// gl.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, ambient); + gl.glLightfv(GLLightingFunc.GL_LIGHT0, GLLightingFunc.GL_AMBIENT, ambient,param_offsets); + +// gl.glEnable(GL.GL_LIGHTING); + gl.glEnable(GLLightingFunc.GL_LIGHTING); // static variable's class call modified - added by narendra kumar + +// gl.glEnable(GL.GL_LIGHT0); + gl.glEnable(GLLightingFunc.GL_LIGHT0); // static variable's class call modified - added by narendra kumar + + gl.glEnable(GL.GL_DEPTH_TEST); + + gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); + + // Draw 3-D coordinate frame + float[] x_axismat = {0.7f, 0.2f, 0.2f, 1.0f}; + float[] y_axismat = {0.2f, 0.7f, 0.2f, 1.0f}; + float[] z_axismat = {0.2f, 0.2f, 0.7f, 1.0f}; + + gl.glLineWidth(3.5f); + + // added 4th parameter for method call "glMaterialfv" - param_offsets (int) && class call of static variable modified - narendra kumar +// gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE, x_axismat); + gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GLLightingFunc.GL_AMBIENT_AND_DIFFUSE, x_axismat, param_offsets); + gl.glBegin(GL.GL_LINES); + gl.glVertex3d(0.0, 0.0, 0.0); + gl.glVertex3d(1.0, 0.0, 0.0); + gl.glEnd(); + + // added 4th parameter for method call "glMaterialfv" - param_offsets (int) && class call of static variable modified - narendra kumar +// gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE, y_axismat); + gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GLLightingFunc.GL_AMBIENT_AND_DIFFUSE, y_axismat, param_offsets); + gl.glBegin(GL.GL_LINES); + gl.glVertex3d(0.0, 0.0, 0.0); + gl.glVertex3d(0.0, 1.0, 0.0); + gl.glEnd(); + + // added 4th parameter for method call "glMaterialfv" - param_offsets (int) && class call of static variable modified - narendra kumar +// gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE, z_axismat); + gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GLLightingFunc.GL_AMBIENT_AND_DIFFUSE, z_axismat, param_offsets); + gl.glBegin(GL.GL_LINES); + gl.glVertex3d(0.0, 0.0, 0.0); + gl.glVertex3d(0.0, 0.0, 1.0); + gl.glEnd(); + + gl.glPushMatrix(); + gl.glTranslated(-1.0, -1.0, 0.0); + gl.glPopMatrix(); + + float rgb[] = {0.9f, 0.0f, 0.0f, 0.0f, 0.9f, 0.3f, 0.0f, 0.0f, 0.9f}; + + drawMolecule(gldraw, theta, phi, atomCoords, displayGeom, bondsVisible, bondsColored, scaleRadius, scaleFactor, recomputeConnectivity); + + if(initDisplay == true) + { + bondParam = ((double)connSlider.getValue())/10.0; + recomputeConnectivity = true; + glcanvas.repaint(); + initDisplay = false; + } + } + + // method definition "drawMolecule" modified - 1st parameter changed to GLAutoDrawable from GLDrawable + //public void drawMolecule(GLAutoDrawable gldrawable, double theta, double phi, double[] coords, boolean displayGeom, boolean bondsVisible, boolean bondsColored, int scaleRadius, double scaleFactor, boolean recomputeConnectivity) + public void drawMolecule(GLAutoDrawable gldrawable, double theta, double phi, double[] coords, boolean displayGeom, boolean bondsVisible, boolean bondsColored, int scaleRadius, double scaleFactor, boolean recomputeConnectivity) + { +// gl = gldrawable.getGL(); // method call not available - commented by narendra kumar + gl = (GL4bc)gldrawable.getGL(); // method call modified - added by narendra kumar + +// glu = gldrawable.getGLU(); // commented by Narendra Kumar + glu = new GLU(); + + double radius =0 ; + + // parameter offsets // added by Narendra Kumar + int param_offsets = 0; // added by Narendra Kumar for "glLightfv" & "glMaterialfv" method call + + float[] defaultBondMat = {0.9f, 0.9f, 0.9f, 1.0f}; + + gl.glTranslated(x0, y0, (z0 + zloc)); + + gl.glRotated(theta, 0.0, 1.0, 0.0); + gl.glRotated(phi, 1.0, 0.0, 0.0); + + // Draw atoms + for (j = 0; j < natoms; j++) + { + red = atomColors[(3*j)]; + green = atomColors[(3*j) + 1]; + blue = atomColors[(3*j) + 2]; + + material_alphaValue = 1.0f; + + material = new float[4]; + + material[0] = red; + material[1] = green; + material[2] = blue; + material[3] = material_alphaValue; + + // add 4th parameter to method call "glMaterialfv"- param_offsets (int) -- Narendra Kumar +// gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE, material); + gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GLLightingFunc.GL_AMBIENT_AND_DIFFUSE, material,param_offsets); + + gl.glPushMatrix(); + + gl.glTranslated(coords[(3*j)], coords[(3*j) + 1], coords[(3*j) + 2]); + + if (scaleRadius == 0) + { + if (scaleFactor*unscaledAtomRadius < bondRadius) + { + radius = bondRadius; + } + else + { + radius = scaleFactor*unscaledAtomRadius; + } + + // commented by narendra kumar - 1st parameter not allowed for method call "glutSolidSphere" +// glut.glutSolidSphere(glu, radius, 100, 360); + glut.glutSolidSphere(radius, 100, 360); + } + else if (scaleRadius == 1) + { + if (scaleFactor*scaledAtomRadius[j] < bondRadius) + { + radius = bondRadius; // don't draw atoms smaller than radius of a bond + } + else + { + radius = scaleFactor*scaledAtomRadius[j]; + } + + // commented by narendra kumar - 1st parameter not allowed for method call "glutSolidSphere" +// glut.glutSolidSphere(glu, radius, 100, 360); + glut.glutSolidSphere(radius, 100, 360); + } + else if (scaleRadius == 2) + { + // commented by narendra kumar - 1st parameter not allowed for method call "glutSolidSphere" +// glut.glutSolidSphere(glu, radius, 100, 360); + glut.glutSolidSphere(radius, 100, 360); + } + + gl.glPopMatrix(); + } + + // Draw bonds + if ( (bondsVisible == true) && (natoms > 1) ) + { + float[] bondmat = {0.9f, 0.9f, 0.9f, 1.0f}; + // add 4th parameter to method call "glMaterialfv"- param_offsets (int) -- Narendra Kumar +// gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE, bondmat); + gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GLLightingFunc.GL_AMBIENT_AND_DIFFUSE, bondmat,param_offsets); + + // VFI atomic radii (from CrystalMaker 1.4.0) + double[ ] ar = { 0.46, 1.22, 1.55, 1.13, 0.91, 0.77, 0.71, 0.48, 0.42, 1.60, 1.89, 1.60, 1.43, 1.34, 1.30, 0.88, 0.79, 1.92, 2.36, 1.97, 1.64, 1.46, 1.34, 1.40, 1.31, 1.26, 1.25, 1.24, 1.28, 1.27, 1.39, 1.39, 1.48, 1.43, 0.94, 1.98, 2.48, 2.15, 1.81, 1.60, 1.45, 1.39, 1.36, 1.34, 1.34, 1.37, 1.44, 1.56, 1.66, 1.58, 1.61, 1.70, 1.15, 2.18, 2.68, 2.21, 1.87, 1.83, 1.82, 1.82, 2.05, 1.81, 2.02, 1.79, 1.77, 1.77, 1.76, 1.75, 1.75, 1.93, 1.74, 1.59, 1.46, 1.40, 1.37, 1.35, 1.35, 1.38, 1.44, 1.60, 1.71, 1.75, 1.82, 1.35, 1.27, 1.20, 1.00, 1.00, 2.03, 1.80, 1.62, 1.53, 1.50, 1.50, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 }; + double[ ] covrad = { 0.37, 0.32, 1.34, 0.90, 0.82, 0.77, 0.75, 0.73, 0.71, 0.69, 1.54, 1.30, 1.18, 1.11, 1.06, 1.02, 0.99, 0.97, 1.96, 1.74, 1.44, 1.36, 1.25, 1.27, 1.39, 1.25, 1.26, 1.21, 1.38, 1.31, 1.26, 1.22, 1.19, 1.16, 1.14, 1.10, 2.11, 1.92, 1.62, 1.48, 1.37, 1.45, 1.56, 1.26, 1.35, 1.31, 1.53, 1.48, 1.44, 1.41, 1.38, 1.35, 1.33, 1.30, 2.25, 1.98, 1.69, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.60, 1.50, 1.38, 1.46, 1.59, 1.28, 1.37, 1.28, 1.44, 1.49, 1.48, 1.47, 1.46, 1.00, 1.00, 1.45, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 }; + + if (recomputeConnectivity == true) + { + for (j = 1; j < natoms; j++) + { + for (k = 0; k < j; k++) + { + if (zmatBondLength[j][k] > 0.0) + { + bondLength[j][k] = zmatBondLength[j][k]; + } + else + { + bondLength[j][k] = 0.0; + } + } + } + + for (j = 1; j < natoms; j++) + { + for (k = 0; k < j; k++) + { + if (bondLength[j][k] == 0.0) + { + dx = atomCoords[(3*j)] - atomCoords[(3*k)]; + dy = atomCoords[(3*j) + 1] - atomCoords[(3*k) + 1]; + dz = atomCoords[(3*j) + 2] - atomCoords[(3*k) + 2]; + + r = Math.sqrt(dx*dx + dy*dy + dz*dz); + + ar1 = ar[(atomicNumber[j] - 1)]; + ar2 = ar[(atomicNumber[k] - 1)]; + + if ( r <= 0.3775*bondParam*(ar1 + ar2) ) + { + bondLength[j][k] = r; + } + } + } + } + + recomputeConnectivity = false; + } + + // Draw cylindrical bonds + GLUquadric quadric = glu.gluNewQuadric(); + + double bd, r, r1, r2; + double angle, rot_x, rot_y, rot_z; + double dx12, dy12, dz12; + double nx, ny, nz; + double n11, n22, n33; + + gl.glTranslated(0.0, 0.0, 0.0); + + for (j = 1; j < natoms; j++) + { + for (k = 0; k < j; k++) + { + if (bondLength[j][k] > 0.0) + { + bd = bondLength[j][k]; + + gl.glPushMatrix(); + + gl.glTranslated(coords[(3*k)], coords[(3*k) + 1], coords[(3*k) + 2]); + + dx12 = coords[(3*j)] - coords[(3*k)]; + dy12 = coords[(3*j) + 1] - coords[(3*k) + 1]; + dz12 = coords[(3*j) + 2] - coords[(3*k) + 2]; + + r = Math.sqrt(dx12*dx12 + dy12*dy12); + + if (r > 0.0) + { + n11 = -dy12/r; + n22 = dx12/r; + n33 = 0.0; + + if (dz12 >= 0.0) + { + angle = (180.0/Math.PI)*Math.acos(Math.abs(dz12)/bd); + } + else + { + angle = 180.0 - (180.0/Math.PI)*Math.acos(Math.abs(dz12)/bd); + } + } + else + { + n11 = 0.0; + n22 = 0.0; + n33 = 1.0; + + if (dz12 >= 0.0) + { + angle = 0.0; + } + else + { + angle = 180.0; + } + } + + if (bondsColored == false) + { + gl.glRotated(angle, n11, n22, n33); + + // add 4th parameter to method call "glMaterialfv"- param_offsets (int) -- Narendra Kumar +// gl.glMaterialfy(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE, defaultBondMat); + gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GLLightingFunc.GL_AMBIENT_AND_DIFFUSE, defaultBondMat,param_offsets); + glu.gluCylinder(quadric, bondRadius, bondRadius, bd, 20, 20); + } + else + { + bondMat1[0] = atomColors[(3*k)]; + bondMat1[1] = atomColors[(3*k) + 1]; + bondMat1[2] = atomColors[(3*k) + 2]; + bondMat1[3] = material_alphaValue; + + bondMat2[0] = atomColors[(3*j)]; + bondMat2[1] = atomColors[(3*j) + 1]; + bondMat2[2] = atomColors[(3*j) + 2]; + bondMat2[3] = material_alphaValue; + + gl.glRotated(angle, n11, n22, n33); + + // add 4th parameter to method call "glMaterialfv"- param_offsets (int) -- Narendra Kumar +// gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE, bondMat1); + gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GLLightingFunc.GL_AMBIENT_AND_DIFFUSE, bondMat1,param_offsets); + glu.gluCylinder(quadric, bondRadius, bondRadius, bd/2, 20, 20); + + gl.glRotated(-angle, n11, n22, n33); + gl.glTranslated(dx12/2, dy12/2, dz12/2); + gl.glRotated(angle, n11, n22, n33); + + // add 4th parameter to method call "glMaterialfv"- param_offsets (int) -- Narendra Kumar +// gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE, bondMat2); + gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GLLightingFunc.GL_AMBIENT_AND_DIFFUSE, bondMat2,param_offsets); + + glu.gluCylinder(quadric, bondRadius, bondRadius, bd/2, 20, 20); + } + + gl.glPopMatrix(); + } + } + } + } + } + + public void mouseDragged(MouseEvent e) + { + axisSelectionDimen = 0.02; + + x2 = e.getX(); + y2 = e.getY(); + + x_rot = true; + + if ( ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) && (x_rot == true) ) + { + if ( (x2 - x1) > 0 ) + { + theta += 15.0; + } + else if ( (x2 - x1)< 0 ) + { + theta -= 15.0; + } + + x1 = x2; + + if ( (y2 - y1) > 0 ) + { + phi += 5.0; + } + else if ( (y2 - y1)< 0 ) + { + phi -= 5.0; + } + + y1 = y2; + } + else if ((e.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK) + { + if ( (y2 - y1) > 0 ) + { + zloc -= 0.25; + } + else if ( (y2 - y1)< 0 ) + { + zloc += 0.25; + } + + y1 = y2; + } + +/* // Hide any popup mens that are visible + filePopupMenu.setVisible(false); + editPopupMenu.setVisible(false); + viewPopupMenu.setVisible(false); + helpPopupMenu.setVisible(false); + + // Hide any submenus that are visible + displayOptionsPopupSubmenu.setVisible(false); + showBondsPopupSubmenu.setVisible(false); + displayMOPopupSubmenu.setVisible(false); +*/ + glcanvas.repaint(); + } + + public void mouseMoved(MouseEvent e) + { + } + + public void reshape(GLAutoDrawable gldraw, int x, int y, int width, int height) + { + } + + public void displayChanged(GLAutoDrawable gldraw, boolean modeChanged, boolean deviceChanged) + { + } + + } + + class CanvasMouseListener extends MouseAdapter + { + public void mouseClicked(MouseEvent e) + { +/* // Hide any popup mens that are visible + filePopupMenu.setVisible(false); + editPopupMenu.setVisible(false); + viewPopupMenu.setVisible(false); + helpPopupMenu.setVisible(false); + + // Hide any submenus that are visible + displayOptionsPopupSubmenu.setVisible(false); + showBondsPopupSubmenu.setVisible(false); + displayMOPopupSubmenu.setVisible(false); +*/ + // Determine number of clicks + if (((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) && (e.getClickCount() == 2)) + { + } + } + } + + class CanvasKeyListener extends KeyAdapter + { + public void keyPressed(KeyEvent e) + { + if (e.getKeyCode() == KeyEvent.VK_LEFT) + { + x0 += 0.2; + glcanvas.repaint(); + } + else if (e.getKeyCode() == KeyEvent.VK_R) + { + theta += 2.0; + glcanvas.repaint(); + } + else if (e.getKeyCode() == KeyEvent.VK_RIGHT) + { + x0 -= 0.2; + glcanvas.repaint(); + } + else if (e.getKeyCode() == KeyEvent.VK_L) + { + theta -= 2.0; + glcanvas.repaint(); + } + else if (e.getKeyCode() == KeyEvent.VK_UP) + { + y0 += 0.2; + glcanvas.repaint(); + } + else if (e.getKeyCode() == KeyEvent.VK_U) + { + phi += 2.0; + glcanvas.repaint(); + } + else if (e.getKeyCode() == KeyEvent.VK_DOWN) + { + y0 -= 0.2; + glcanvas.repaint(); + } + else if (e.getKeyCode() == KeyEvent.VK_D) + { + phi -= 2.0; + glcanvas.repaint(); + } + + /*// Hide all popup menus that are visible + filePopupMenu.setVisible(false); + editPopupMenu.setVisible(false); + viewPopupMenu.setVisible(false); + helpPopupMenu.setVisible(false); + + // Hide all popup submenus that are visible + displayOptionsPopupSubmenu.setVisible(false); + showBondsPopupSubmenu.setVisible(false); + displayMOPopupSubmenu.setVisible(false);*/ + } + + public void keyReleased(KeyEvent e) + { + } + + public void keyTyped(KeyEvent e) + { + } + } + /* + class menuMouseListener extends MouseAdapter + { + public void mouseClicked(MouseEvent e) + { + mbHeight = (e.getComponent()).getHeight(); + mbWidth = (e.getComponent()).getWidth(); + + mbx = (int)(0.5*mbWidth); + mby = (int)(0.95*mbHeight); + + // Hide any submenus that are visible + displayOptionsPopupSubmenu.setVisible(false); + showBondsPopupSubmenu.setVisible(false); + displayMOPopupSubmenu.setVisible(false); + + if ((e.getComponent()).equals(fileMenu)) + { + editPopupMenu.setVisible(false); + viewPopupMenu.setVisible(false); + helpPopupMenu.setVisible(false); + connectivityAdjustmentFrame.setVisible(false); + radiusScalingFrame.setVisible(false); + + if (filePopupMenu.isVisible() == false) + { + filePopupMenu.show(e.getComponent(), mbx, mby); + } + else + { + filePopupMenu.setVisible(false); + } + } + else if ((e.getComponent()).equals(editMenu)) + { + filePopupMenu.setVisible(false); + viewPopupMenu.setVisible(false); + helpPopupMenu.setVisible(false); + connectivityAdjustmentFrame.setVisible(false); + radiusScalingFrame.setVisible(false); + + if (editPopupMenu.isVisible() == false) + { + editPopupMenu.show(e.getComponent(), mbx, mby); + } + else + { + editPopupMenu.setVisible(false); + } + } + else if ((e.getComponent()).equals(viewMenu)) + { + filePopupMenu.setVisible(false); + editPopupMenu.setVisible(false); + helpPopupMenu.setVisible(false); + connectivityAdjustmentFrame.setVisible(false); + radiusScalingFrame.setVisible(false); + + if (viewPopupMenu.isVisible() == false) + { + viewPopupMenu.show(e.getComponent(), mbx, mby); + } + else + { + viewPopupMenu.setVisible(false); + } + } + else if ((e.getComponent()).equals(helpMenu)) + { + filePopupMenu.setVisible(false); + editPopupMenu.setVisible(false); + viewPopupMenu.setVisible(false); + connectivityAdjustmentFrame.setVisible(false); + radiusScalingFrame.setVisible(false); + + if (helpPopupMenu.isVisible() == false) + { + helpPopupMenu.show(e.getComponent(), mbx, mby); + } + else + { + helpPopupMenu.setVisible(false); + } + } + } + } + + class submenuMouseListener extends MouseAdapter + { + public void mouseClicked(MouseEvent e) + { + mbHeight = (e.getComponent()).getHeight(); + mbWidth = (e.getComponent()).getWidth(); + + mbx = mbWidth; + mby = (int)(0.5*mbHeight); + } + } + + class displayOptionsSubmenuMouseListener extends MouseAdapter + { + public void mouseClicked(MouseEvent e) + { + mbHeight = (e.getComponent()).getHeight(); + mbWidth = (e.getComponent()).getWidth(); + + mbx = mbWidth; + mby = (int)(0.5*mbHeight); + + if (displayOptionsSubmenu.contains(e.getX(), e.getY())) + { + if (displayOptionsPopupSubmenu.isVisible() == false) + { + displayOptionsPopupSubmenu.show(e.getComponent(), mbx, mby); + } + else + { + if (displayOptionsPopupSubmenu.isVisible() == true) + { + displayOptionsPopupSubmenu.setVisible(false); + } + } + + displayMOPopupSubmenu.setVisible(false); + showBondsPopupSubmenu.setVisible(false); + } + } + } + */ + //class displayOptionMouseListener extends MouseAdapter + class displayOptionMouseListener implements ActionListener + { +// public void mouseClicked(MouseEvent e) + public void actionPerformed(ActionEvent e) + { + //if ((e.getComponent()).equals(displayOption2)) // ball & stick (scaled radii) + if ((e.getSource()).equals(displayOption2)) // ball & stick (scaled radii) + { + radiusSlider.setValue(100); + + scaleFactor = 1.0; + bondsVisible = true; + bondsColored = false; + scaleRadius = 1; +// viewPopupMenu.setVisible(false); + } + + //if ((e.getComponent()).equals(displayOption3)) // ball & stick (unscaled radii) + if ((e.getSource()).equals(displayOption3)) // ball & stick (unscaled radii) + { + radiusSlider.setValue(100); + + scaleFactor = 1.0; + bondsVisible = true; + bondsColored = false; + scaleRadius = 0; +// viewPopupMenu.setVisible(false); + } + //else if ((e.getComponent()).equals(displayOption4)) // wireframe + else if ((e.getSource()).equals(displayOption4)) // wireframe + { + scaleFactor = 1.0; + bondsVisible = true; + bondsColored = true; + scaleRadius = 2; + } + //else if ((e.getComponent()).equals(displayOption5)) // space filling + else if ((e.getSource()).equals(displayOption5)) // space filling + { +// radiusSlider.setValue((int)(100*scaleFactor)); + radiusSlider.setValue(100); + + scaleFactor = 1.0; + bondsVisible = true; + bondsColored = false; + scaleRadius = 1; + + // Get maximum bond length + int J= 0, K = 0; + double maxBondLength = 0.0; + + for (j = 1; j < natoms; j++) + { + for (k = 0; k < j; k++) + { + if (bondLength[j][k] > maxBondLength) + { + maxBondLength = bondLength[j][k]; + J = j; + K = k; + } + } + } + + scaleFactor = (1.40 * maxBondLength)/(scaledAtomRadius[J] + scaledAtomRadius[K]); + +// viewPopupMenu.setVisible(false); + + glcanvas.repaint(); + } + //else if ((e.getComponent()).equals(displayOption6)) // modify atom radius + else if ((e.getSource()).equals(displayOption6)) // modify atom radius + { + mbHeight = GamessGUI.frame.getHeight(); + mbWidth = GamessGUI.frame.getWidth(); + + mbx = (int)((mbWidth/2)-(radiusScalingFrame.getWidth()/2)); + mby = (int)((mbHeight/5)-(radiusScalingFrame.getHeight()/2)); + + Point P = GamessGUI.frame.getLocationOnScreen(); + int Px = (int)P.getX(); + int Py = (int)P.getY(); + + radiusScalingFrame.setLocation(Px + mbx, Py + mby); + + if (radiusScalingFrame.isVisible() == false) + { + radiusScalingFrame.setVisible(true); + +// viewPopupMenu.setVisible(false); + } + else + { + radiusScalingFrame.setVisible(false); + } + } + //else if ((e.getComponent()).equals(displayOption7)) // modify connectivity + else if ((e.getSource()).equals(displayOption7)) // modify connectivity + { + + mbHeight = (int)GamessGUI.frame.getHeight(); + mbWidth = (int)GamessGUI.frame.getWidth(); + + mbx = (int)((mbWidth/2)-(connectivityAdjustmentFrame.getWidth()/2)); + mby = (int)((mbHeight/5)-(connectivityAdjustmentFrame.getHeight()/2)); + + Point P = GamessGUI.frame.getLocationOnScreen(); + int Px = (int)P.getX(); + int Py = (int)P.getY(); + + connectivityAdjustmentFrame.setLocation(Px + mbx, Py + mby); + + if (connectivityAdjustmentFrame.isVisible() == false) + { + connectivityAdjustmentFrame.setVisible(true); + +// viewPopupMenu.setVisible(false); + } + else + { + connectivityAdjustmentFrame.setVisible(false); + } + } + //else if ((e.getComponent()).equals(displayOption8)) // label atoms + else if ((e.getSource()).equals(displayOption8)) // label atoms + { + } + +/* // Hide all popup submenus that are visible + displayOptionsPopupSubmenu.setVisible(false); + showBondsPopupSubmenu.setVisible(false); + displayMOPopupSubmenu.setVisible(false); +*/ + glcanvas.repaint(); + } + } + +// class showBondsSubmenuMouseListener extends MouseAdapter + class showBondsSubmenuMouseListener implements ActionListener + { +// public void mouseClicked(MouseEvent e) + public void actionPerformed(ActionEvent e) + { +/* mbHeight = (e.getComponent()).getHeight(); + mbWidth = (e.getComponent()).getWidth(); + + mbx = mbWidth; + mby = (int)(0.5*mbHeight); + + if (showBondsSubmenu.contains(e.getX(), e.getY())) + { + */ + if (bondsVisible == false) + { + bondsVisible = true; + + glcanvas.repaint(); + } + +/* if (showBondsPopupSubmenu.isVisible() == false) + { + showBondsPopupSubmenu.show(e.getComponent(), mbx, mby); + } + else + { + if (showBondsPopupSubmenu.isVisible() == true) + { + showBondsPopupSubmenu.setVisible(false); + } + } + + displayOptionsPopupSubmenu.setVisible(false); + displayMOPopupSubmenu.setVisible(false);*/ +// } + } + } + +// class colorBondsMouseListener extends MouseAdapter + class colorBondsMouseListener implements ActionListener + { +// public void mouseClicked(MouseEvent e) + public void actionPerformed(ActionEvent e) + { + if (bondsColored == false) + { + bondsColored = true; + + glcanvas.repaint(); + } + +/* // Hide all popup submenus that are visible + displayOptionsPopupSubmenu.setVisible(false); + showBondsPopupSubmenu.setVisible(false); + displayMOPopupSubmenu.setVisible(false);*/ + } + } + +// class uncolorBondsMouseListener extends MouseAdapter + class uncolorBondsMouseListener implements ActionListener + { +// public void mouseClicked(MouseEvent e) + public void actionPerformed(ActionEvent e) + { + if (bondsColored == true) + { + bondsColored = false; + + glcanvas.repaint(); + } + +/* // Hide all popup submenus that are visible + displayOptionsPopupSubmenu.setVisible(false); + showBondsPopupSubmenu.setVisible(false); + displayMOPopupSubmenu.setVisible(false); */ + } + } + +// class hideBondsMouseListener extends MouseAdapter + class hideBondsMouseListener implements ActionListener + { + //public void mouseClicked(MouseEvent e) + public void actionPerformed(ActionEvent e) + { + if (bondsVisible == true) + { + bondsVisible = false; + + glcanvas.repaint(); + } + +/* // Hide all popup submenus that are visible + displayOptionsPopupSubmenu.setVisible(false); + showBondsPopupSubmenu.setVisible(false); + displayMOPopupSubmenu.setVisible(false);*/ + } + } +/* + class displayMOSubmenuMouseListener extends MouseAdapter + { + public void mouseClicked(MouseEvent e) + { + mbHeight = (e.getComponent()).getHeight(); + mbWidth = (e.getComponent()).getWidth(); + + mbx = mbWidth; + mby = (int)(0.5*mbHeight); + + if (displayMOSubmenu.contains(e.getX(), e.getY())) + { + if (displayMOPopupSubmenu.isVisible() == false) + { + displayMOPopupSubmenu.show(e.getComponent(), mbx, mby); + } + else + { + if (displayMOPopupSubmenu.isVisible() == true) + { + displayMOPopupSubmenu.setVisible(false); + } + } + + displayOptionsPopupSubmenu.setVisible(false); + showBondsPopupSubmenu.setVisible(false); + } + } + } +*/ +// class animationSubmenuMouseListener extends MouseAdapter + class animationSubmenuMouseListener implements ActionListener + { + //public void mouseClicked(MouseEvent e) + public void actionPerformed(ActionEvent e) + { +/* showBondsPopupSubmenu.setVisible(false); + displayOptionsPopupSubmenu.setVisible(false); + displayMOPopupSubmenu.setVisible(false); */ + } + } + +// class outputdataSubmenuMouseListener extends MouseAdapter + class outputdataSubmenuMouseListener implements ActionListener + { + //public void mouseClicked(MouseEvent e) + public void actionPerformed(ActionEvent e) + { +/* showBondsPopupSubmenu.setVisible(false); + displayOptionsPopupSubmenu.setVisible(false); + displayMOPopupSubmenu.setVisible(false);*/ + } + } + + class SliderListener implements ChangeListener + { + public void stateChanged(ChangeEvent e) + { + JSlider jslider = (JSlider)e.getSource(); + + if (jslider.equals(radiusSlider)) + { + scaleFactor = ((double)radiusSlider.getValue())/100.0; + + glcanvas.repaint(); + } + else if (jslider.equals(connSlider)) + { + bondParam = ((double)connSlider.getValue())/10.0; + + recomputeConnectivity = true; + + glcanvas.repaint(); + } + } + } + + class DoneButtonListener implements ActionListener + { + public void actionPerformed(ActionEvent e) + { + JButton jbutton = (JButton)e.getSource(); + + if (jbutton.equals(radiusDoneButton)) + { + radiusScalingFrame.setVisible(false); + } + else if (jbutton.equals(connDoneButton)) + { + recomputeConnectivity = false; + + connectivityAdjustmentFrame.setVisible(false); + } + } + } +} diff --git a/src/main/java/gamess/Storage/DBInterface.java b/src/main/java/gamess/Storage/DBInterface.java new file mode 100644 index 0000000..c034b0b --- /dev/null +++ b/src/main/java/gamess/Storage/DBInterface.java @@ -0,0 +1,17 @@ +package gamess.Storage; + +import java.util.ArrayList; + + +public interface DBInterface { + boolean isAvailable(String Data); + boolean equal(String Data); + boolean Store(String Data); + String Retrieve(String Data); + boolean Remove(String Data); + boolean RemoveAll(); + boolean Overwrite(String fullGroupData); + String getKeywordValueSeperator(); + void registerDBChangeListeners(ArrayList listeners); + void setGroup(String Group); +} diff --git a/src/main/java/gamess/Storage/DefaultGroupStorage.java b/src/main/java/gamess/Storage/DefaultGroupStorage.java new file mode 100644 index 0000000..3bcd9de --- /dev/null +++ b/src/main/java/gamess/Storage/DefaultGroupStorage.java @@ -0,0 +1,314 @@ +package gamess.Storage; + +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Hashtable; + +import gamess.Dictionary; + + +public class DefaultGroupStorage implements DBInterface { + + private String Group = ""; + protected StorageHashTable storage = new StorageHashTable(); + protected String KeywordValueSeperator = "="; + protected ArrayList listenerList = null; + + public void setGroup(String Group) + { + this.Group = Group; + } + + public boolean Overwrite(String fullGroupData) { + //Convert the full group data to hash table + StorageHashTable currentGroupTable = ConvertGroupData(fullGroupData); + if(currentGroupTable == null) + { + //The group is empty. Remove full group + RemoveAll(); + storage.clear(); + return true; + } + //Compare the two list and make the DB consistent + return CompareAndWrite(storage , currentGroupTable); + } + + public boolean Remove(String Data) { + //Check the format of the Data + String Keyword = Data.trim(); + if(isSeperatorPresent(Data)) + { + //Seperator is present. Format keyword '=' value + //Get the keyword from the Data + Keyword = Data.split(KeywordValueSeperator)[0].trim(); + } + //Check if the keyword is available + if(!isAvailable(Keyword)) + { + //The keyword is not available. So return true. + return true; + } + + String removedValue = storage.get(Keyword); + + //The keyword is available. remove the keyword + storage.remove(Keyword); + + //Fire the remove event for the incompatibility + Keyword = Dictionary.getFormattedKeyword(Keyword); + for (int i = 0; i < listenerList.size(); i++) + { + listenerList.get(i).DataRemoved(Group + " " + Keyword + " " + removedValue); + listenerList.get(i).DataRemoved(Group + " " + Keyword); + } + return true; + } + + public String Retrieve(String Data) { + //Check the format of the Data + //Check if the data is empty + if(Data.trim().length() == 0) + { + //The Data is empty. Return the full list of keywords + StringBuilder returnValue = new StringBuilder(); + for( Enumeration keys = storage.keys() ; keys.hasMoreElements() ;) { + returnValue.append(keys.nextElement() + " "); + } + return returnValue.toString(); + } + + String keyword = Data.trim(); + //Check if the Data contains seperator + if(isSeperatorPresent(Data)) + { + //The Data contains seperator. + //The format is Keyword '=' value + //get the keyword form data + keyword = Data.split(KeywordValueSeperator)[0].trim(); + } + + //Check if the keyword is available + if(!isAvailable(keyword)) + return null; + return storage.get(keyword); + } + + public boolean Store(String Data) { + if(!isSeperatorPresent(Data)) + { + //wrong format. return false + return false; + } + //The format is Keyword '=' value + //seperate keyword and value + String[] splitData = getDataSplit(Data.trim()); + String Keyword = splitData[0].trim(); + String Value = splitData[1].trim(); + //check if storage already contains keyword + if(storage.containsKey(Keyword)) + { + if(((String)storage.get(Keyword)).equals(Value)) + { + //Same keyword and value is present + //return true + return true; + } + //Value is different + Remove(Keyword); + } + storage.put(Keyword, Value); + //Fire the event add for incompatibility + Keyword = Dictionary.getFormattedKeyword(Keyword); + for (int i = 0; i < listenerList.size(); i++) + { + listenerList.get(i).DataAdded(Group + " " + Keyword); + listenerList.get(i).DataAdded(Group + " " + Keyword + " " + Value); + } + return true; + } + + public boolean equal(String Data) { + //Check if the data is in the correct format + if(!isSeperatorPresent(Data)) + { + //The seperator is not present. So return if the + //keyword is available or not. + return isAvailable(Data); + } + //The format is Keyword '='value + //seperate keyword and value + String[] splitData = getDataSplit(Data.trim()); + String Keyword = splitData[0].trim(); + String Value = splitData[1].trim(); + //Check if the keyword is available + if(!isAvailable(Keyword)) + return false; + return ((String)storage.get(Keyword)).equals(Value); + } + + public boolean isAvailable(String Data) { + //Check if the data is in the correct format + if(isSeperatorPresent(Data)) + { + //The format is Keyword '='value + //Check if it is equal + return equal(Data); + } + //The data contains only keyword. Check if the keyword is present + return storage.containsKey(Data.trim()); + } + + public String getKeywordValueSeperator() { + return KeywordValueSeperator; + } + + public boolean RemoveAll() { + for(Enumeration keys = storage.keys(); keys.hasMoreElements();) + Remove(keys.nextElement()); + return true; + } + + public void registerDBChangeListeners(ArrayList listeners) { + listenerList = listeners; + } + + protected boolean isSeperatorPresent(String Data) + { + if(Data.trim().indexOf(KeywordValueSeperator) == -1) + return false; + return true; + } + + protected StorageHashTable ConvertGroupData(String GroupData) + { + //The group contains no data. Return null + if(GroupData.trim().length() == 0) + return null; + StorageHashTable returnTable = new StorageHashTable(); + //Split the complete group with = + String[] splitGroup = GroupData.trim().split(KeywordValueSeperator); + + //Get the first keyword + String CurrentKeyword = splitGroup[0].trim(); + returnTable.put(CurrentKeyword, ""); + + for (int i = 1; i < splitGroup.length; i++) { + //Add each keyword and value to the table + //The format here will be "value1 keyword2" + String valueKeyword = splitGroup[i].trim(); + int splitIndex = valueKeyword.lastIndexOf(" "); + if(splitIndex == -1 || i == splitGroup.length-1) + { + returnTable.put(CurrentKeyword, valueKeyword); + continue; + } + String CurrentValue = valueKeyword.substring(0,splitIndex); + returnTable.put(CurrentKeyword, CurrentValue.trim()); + CurrentKeyword = valueKeyword.substring(splitIndex).trim(); + } + //return the built table + return returnTable; + } + + protected boolean CompareAndWrite(StorageHashTable DBList, StorageHashTable GroupList) + { + for(Enumeration dbList = DBList.keys() ; dbList.hasMoreElements();) + { + //Get the first key + String dbkey = dbList.nextElement(); + //Check if the key is present in the Grouplist + if(!GroupList.containsKey(dbkey)) + { + //The current db key is not present in the group in the input file. + //Remove the current db key from the DBlist + Remove(dbkey); + } + else + { + //The group list contains the db key. + //The key is same in both the places + //Get the value in InputFile and write it here + String Data = dbkey + KeywordValueSeperator + (String)GroupList.get(dbkey); + Store(Data); + //note: Store writes the value only if they are different + GroupList.remove(dbkey); + } + } + + //Get the list of remaining keys in the grouplist and add it in this DB + for(Enumeration remainKeys = GroupList.keys() ; remainKeys.hasMoreElements() ;) + { + String inputkey = remainKeys.nextElement(); + String Data = inputkey + KeywordValueSeperator + (String)GroupList.get(inputkey); + Store(Data); + } + return true; + } + + protected String[] getDataSplit(String Data) + { + String[] splitData = Data.split(KeywordValueSeperator); + if(splitData.length == 1) + { + String[] newSplitData = new String[2]; + newSplitData[0] = splitData[0]; + newSplitData[1] = ""; + return newSplitData; + } + return splitData; + } + + protected class StorageHashTable extends Hashtable + { + private static final long serialVersionUID = -1644748080983543058L; + + @Override + public synchronized String get(Object oKey) { + //First check if the key is of type string + if(oKey instanceof String) + { + String key = (String)oKey; + if(key == null) + return null; + + //Check if the key contains an array index starting + key = Dictionary.getFormattedKeyword(key); + + //Convert the keyword to uppercase + return super.get(key.toUpperCase()); + } + return super.get(oKey); + } + + @Override + public synchronized String put(String key, String value) { + + if(key == null) + return null; + + //Check if the key contains an array index starting + key = Dictionary.getFormattedKeyword(key); + + //Convert the keyword and value to uppercase + return super.put(key.toUpperCase(), (value == null)? null : value.toUpperCase()); + } + + @Override + public synchronized boolean containsKey(Object oKey) { + //First check if the key is of type string + if(oKey instanceof String) + { + String key = (String)oKey; + if(key == null) + return super.containsKey(oKey); + + //Check if the key contains an array index starting + key = Dictionary.getFormattedKeyword(key); + + //Convert the keyword to uppercase + return super.containsKey(key.toUpperCase()); + } + return super.containsKey(oKey); + } + } +} diff --git a/src/main/java/gamess/Storage/IDBChangeListener.java b/src/main/java/gamess/Storage/IDBChangeListener.java new file mode 100644 index 0000000..e004605 --- /dev/null +++ b/src/main/java/gamess/Storage/IDBChangeListener.java @@ -0,0 +1,8 @@ +package gamess.Storage; + +public interface IDBChangeListener +{ + void DataAdded(String Data); + void DataRemoved(String Data); + void DropDB(); +} diff --git a/src/main/java/gamess/Storage/IRepository.java b/src/main/java/gamess/Storage/IRepository.java new file mode 100644 index 0000000..e83dd0c --- /dev/null +++ b/src/main/java/gamess/Storage/IRepository.java @@ -0,0 +1,17 @@ +package gamess.Storage; + +public interface IRepository +{ + boolean isAvailable(String Group); + boolean isAvailable(String Group, String Data); + boolean equal(String Group, String Data); + boolean Store(String Group, String Data); + String Retrieve(String Group); + String Retrieve(String Group, String Data); + boolean Remove(String Group); + boolean Remove(String Group, String Data); + boolean Overwrite(String Group, String Data); + void DropDB(); + String getKeywordValueSeperator(String group); + void registerDBChangeListener(IDBChangeListener listener); +} diff --git a/src/main/java/gamess/Storage/PlainDataStorage.java b/src/main/java/gamess/Storage/PlainDataStorage.java new file mode 100644 index 0000000..856bd4c --- /dev/null +++ b/src/main/java/gamess/Storage/PlainDataStorage.java @@ -0,0 +1,60 @@ +package gamess.Storage; + +import java.util.ArrayList; + +public class PlainDataStorage implements DBInterface { + + public String Group = ""; + private String storage = ""; + ArrayList listenerList = null; + + public void setGroup(String Group) + { + this.Group = Group; + } + + public boolean Overwrite(String fullGroupData) { + storage = fullGroupData; + return true; + } + + public boolean Remove(String Data) { + storage = ""; + return true; + } + + public String Retrieve(String Data) { + return storage; + } + + public boolean Store(String Data) { + storage = Data; + return true; + } + + public boolean equal(String Data) { + if(storage.trim().equals(Data.trim())) + return true; + return false; + } + + public boolean isAvailable(String Data) { + if(storage.trim().length() > 0) + return true; + return false; + } + + public String getKeywordValueSeperator() { + return ""; + } + + public boolean RemoveAll() { + storage = ""; + return true; + } + + public void registerDBChangeListeners(ArrayList listeners) { + listenerList = listeners; + } + +} diff --git a/src/main/java/gamess/Storage/Repository.java b/src/main/java/gamess/Storage/Repository.java new file mode 100644 index 0000000..b4cc5f1 --- /dev/null +++ b/src/main/java/gamess/Storage/Repository.java @@ -0,0 +1,293 @@ +package gamess.Storage; + +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Hashtable; + +import gamess.GlobalParameters; + +public class Repository implements IRepository { + + private static Repository provisionalInstance = new Repository(); + private static Repository instance = new Repository(); + private Groups groups = new Groups(); + private ArrayList listenerList = new ArrayList(); + + private Repository() + { + groups.setListeners(listenerList); + } + + public static Repository getInstance() + { + if(GlobalParameters.isProvisionalMode) + return provisionalInstance; + return instance; + } + + public void DropDB() + { + groups.removeAll(); + // Fire an event to drop all the incompatibilities generated + for (int i = 0; i < listenerList.size(); i++) + listenerList.get(i).DropDB(); + } + + public boolean Overwrite(String Group, String Data) { + //Check if the group is available + if(!isAvailable(Group)) + { + //if not available create it + groups.CreateGroupInterface(Group); + } + DBInterface storage = groups.getGroupInterface(Group); + return storage.Overwrite(Data); + } + + public boolean Remove(String Group) { + //Check if the group is available + if(!isAvailable(Group)) + { + //The group is not available. So return true + return true; + } + groups.removeGroup(Group); + return true; + } + + public boolean Remove(String Group, String Data) { + //Check if the group is available + if(!isAvailable(Group)) + { + //The group itself is not available. + //Cannot remove the data from the group + return false; + } + DBInterface storage = groups.getGroupInterface(Group); + return storage.Remove(Data); + } + + public String Retrieve(String Group) { + //Check if the group is available + if(!isAvailable(Group)) + { + //Group is not avaialble. Nothing to return. + //Check if this instance is provisionalInstance + //if it is then you are searching in the temporary DB + //try checking if it is available in the Main DB too. + if(this.equals(provisionalInstance)) + { + return instance.Retrieve(Group); + } + //return null + return null; + } + DBInterface storage = groups.getGroupInterface(Group); + //return complete group + return storage.Retrieve(""); + } + + public String Retrieve(String Group, String Data) { + //Check if the group is available + if(!isAvailable(Group)) + { + //Group is not avaialble. Nothing to return. + //Check if this instance is provisionalInstance + //if it is then you are searching in the temporary DB + //try checking if it is available in the Main DB too. + if(this.equals(provisionalInstance)) + { + return instance.Retrieve(Group, Data); + } + //return null + return null; + } + DBInterface storage = groups.getGroupInterface(Group); + //return complete group + return storage.Retrieve(Data); + } + + public boolean Store(String Group, String Data) { + //Check if the group is available + if(!isAvailable(Group)) + { + //Group is not available. + //Create the group and store the value in it. + groups.CreateGroupInterface(Group); + } + DBInterface storage = groups.getGroupInterface(Group); + return storage.Store(Data); + } + + public boolean equal(String Group, String Data) { + //Check if the group is available + if(!isAvailable(Group)) + { + //The group is not available. + //Check if this instance is provisionalInstance + //if it is then you are searching in the temporary DB + //try checking if it is available in the Main DB too. + if(this.equals(provisionalInstance)) + { + return instance.equal(Group, Data); + } + //nothing to compare. So return false + return false; + } + DBInterface storage = groups.getGroupInterface(Group); + boolean isEqual = storage.equal(Data); + //Check if this instance is provisionalInstance + //if it is then you are searching in the temporary DB + //try checking if it is available in the Main DB too. + if(this.equals(provisionalInstance) && isEqual == false) + { + isEqual = instance.equal(Group, Data); + } + + return isEqual; + } + + public boolean isAvailable(String Group) { + //Return is the group available in Main/Provisional DB + boolean isAvail = groups.isAvailable(Group); + return isAvail; + } + + public boolean isAvailable(String Group, String Data) { + //Check if the group is available + if(!isAvailable(Group)) + { + //The group itself is not available. + //Check if this instance is provisionalInstance + //if it is then you are searching in the temporary DB + //try checking if it is available in the Main DB too. + if(this.equals(provisionalInstance)) + { + return instance.isAvailable(Group, Data); + } + //So return false. + return false; + } + DBInterface storage = groups.getGroupInterface(Group); + boolean isAvail = storage.isAvailable(Data); + //Check if this instance is provisionalInstance + //if it is then you are searching in the temporary DB + //try checking if it is available in the Main DB too. + if(this.equals(provisionalInstance) && isAvail == false) + isAvail = instance.isAvailable(Group, Data); + return isAvail; + } + + public String getKeywordValueSeperator(String Group) { + //Check if the group is available + if(!isAvailable(Group)) + { + //The group itself is not available. + //Check if this instance is main instance + //if it is then try searching it in the provisional DB too. + if(this.equals(instance)) + { + return provisionalInstance.getKeywordValueSeperator(Group); + } + //Create a new group in the provisional DB. + groups.CreateGroupInterface(Group); + } + DBInterface storage = groups.getGroupInterface(Group); + return storage.getKeywordValueSeperator(); + } + + public void registerDBChangeListener(IDBChangeListener listener) + { + listenerList.add(listener); + } + + private class Groups + { + private ArrayList listenerList = new ArrayList(); + private Hashtable groups = new Hashtable(); + private ArrayList plainDataGroup = null; + + public Groups() + { + //Loading plain data group + plainDataGroup = GlobalParameters.plainDataGroup; + } + + public boolean isAvailable(String Group) + { + if(groups.containsKey(Group.toUpperCase())) + { + return true; + } + return false; + } + + public void CreateGroupInterface(String Group) + { + Group = Group.toUpperCase(); + removeGroup(Group); + DBInterface storageInterface = null; + if(Group.equals(("TDHFX"))) + { + //Create TDHFX group storage + storageInterface = new TDHFXGroupStorage(); + groups.put("TDHFX", storageInterface); + } + else if(plainDataGroup.contains(Group)) + { + //if the Group belongs to the plain data group. + //Create a plain data group + storageInterface = new PlainDataStorage(); + groups.put(Group, storageInterface); + } + else + { + //Create the default group + storageInterface = new DefaultGroupStorage(); + groups.put(Group, storageInterface); + } + //Add the listeners + storageInterface.registerDBChangeListeners(listenerList); + //Set the group the object belongs to + storageInterface.setGroup(Group); + // Fire an event "add group" to the incompatibility + for (int i = 0; i < listenerList.size(); i++) + listenerList.get(i).DataAdded(Group); + } + + public DBInterface getGroupInterface(String Group) + { + Group = Group.toUpperCase(); + if(isAvailable(Group)) + return groups.get(Group); + return null; + } + + public void removeGroup(String Group) + { + //remove the group if it is aviailable + if(isAvailable(Group)) + { + ((DBInterface)groups.get(Group.toUpperCase())).RemoveAll(); + groups.remove(Group.toUpperCase()); + // Fire an event "remove group" to the incompatibility + for (int i = 0; i < listenerList.size(); i++) + listenerList.get(i).DataRemoved(Group); + } + } + + public void removeAll() + { + for(Enumeration group = groups.keys(); group.hasMoreElements();) + { + groups.get(group.nextElement()).RemoveAll(); + } + groups.clear(); + } + + public void setListeners(ArrayList listeners) + { + listenerList = listeners; + } + } +} diff --git a/src/main/java/gamess/Storage/TDHFXGroupStorage.java b/src/main/java/gamess/Storage/TDHFXGroupStorage.java new file mode 100644 index 0000000..6911162 --- /dev/null +++ b/src/main/java/gamess/Storage/TDHFXGroupStorage.java @@ -0,0 +1,52 @@ +package gamess.Storage; + + +public class TDHFXGroupStorage extends DefaultGroupStorage { + + public TDHFXGroupStorage() + { + KeywordValueSeperator = " "; + } + + @Override + public boolean isAvailable(String Data) { + return storage.containsKey(getDataSplit(Data)[0]); + } + + @Override + protected boolean isSeperatorPresent(String Data) + { + return true; + } + + @Override + protected StorageHashTable ConvertGroupData(String GroupData) { + //The group contains no data. Return null + if(GroupData.trim().length() == 0) + return null; + StorageHashTable returnTable = new StorageHashTable(); + //Split the complete group with = + String[] splitGroup = GroupData.trim().split("\n"); + for (int i = 0; i < splitGroup.length; i++) { + String[] splitKeyword = getDataSplit(splitGroup[i].trim()); + returnTable.put(splitKeyword[0], splitKeyword[1]); + } + return returnTable; + } + + @Override + protected String[] getDataSplit(String Data) + { + int splitIndex = Data.indexOf(KeywordValueSeperator); + String[] splitString = new String[2]; + if(splitIndex == -1) + { + splitString[0] = Data; + splitString[1] = ""; + return splitString; + } + splitString[0] = Data.substring(0, splitIndex).trim(); + splitString[1] = Data.substring(splitIndex).trim(); + return splitString; + } +} diff --git a/src/main/java/gamess/UndoRedoHandler.java b/src/main/java/gamess/UndoRedoHandler.java new file mode 100644 index 0000000..23328b1 --- /dev/null +++ b/src/main/java/gamess/UndoRedoHandler.java @@ -0,0 +1,130 @@ +package gamess; + +import java.util.Stack; + +import javax.swing.AbstractButton; +import javax.swing.event.UndoableEditEvent; +import javax.swing.event.UndoableEditListener; +import javax.swing.undo.CannotRedoException; +import javax.swing.undo.CannotUndoException; +import javax.swing.undo.UndoManager; + +public class UndoRedoHandler extends UndoManager implements UndoableEditListener{ + + private static final long serialVersionUID = -3887860951075715652L; + private Stack undoClassifierStack = new Stack(); + private Stack redoClassifierStack = new Stack(); + private static boolean currentGroupClassifier = true; + private static boolean isLocked = false; + + public void undoableEditHappened(UndoableEditEvent e) + { + super.addEdit(e.getEdit()); + undoClassifierStack.push(currentGroupClassifier); + } + + @Override + public synchronized void undo() throws CannotUndoException { + //check if the changes can be undone + if(!canUndo()) + return; + //get the top classifier from undo stack + boolean groupClassifier = undoClassifierStack.peek(); + //undo all the edits that are classified as the same + //stop when the classifier changes + while(undoClassifierStack.isEmpty() == false && undoClassifierStack.peek() == groupClassifier && canUndo() == true) + { + //push the classifiers into the redo stack + redoClassifierStack.push(groupClassifier); + //undo the edit + super.undo(); + //remove the top item from the undo stack + undoClassifierStack.pop(); + } + + UpdateInputFile.startUpdate(); + MessageBox.excludes.UpdateList(); + MessageBox.requires.UpdateList(); + ResetUndoRedoButton(); + } + + @Override + public synchronized void redo() throws CannotRedoException { + //check if the changes can be redone + if(!canRedo()) + return; + //get the top classifier from redo stack + boolean groupClassifier = redoClassifierStack.peek(); + //redo all the edits that are classified as the same + //stop when the classifier changes + while(redoClassifierStack.isEmpty() == false && redoClassifierStack.peek() == groupClassifier && canRedo() == true) + { + //push the classifiers into the undo stack + undoClassifierStack.push(groupClassifier); + //redo the edit + super.redo(); + //remove the top item from the redo stack + redoClassifierStack.pop(); + } + + UpdateInputFile.startUpdate(); + MessageBox.excludes.UpdateList(); + MessageBox.requires.UpdateList(); + ResetUndoRedoButton(); + } + + public static void toggleGroupClassifier() + { + //toggle if this is not locked + if(isLocked == false) + currentGroupClassifier = !currentGroupClassifier; + } + + public static void setLock() + { + isLocked = true; + } + + public static void releaseLock() + { + isLocked = false; + + MessageBox.excludes.UpdateList(); + MessageBox.requires.UpdateList(); + } + + public static boolean isLocked() + { + return isLocked; + } + + AbstractButton undoButton = null; + public void setUndoButton(AbstractButton _undoButton) + { + undoButton = _undoButton; + } + + AbstractButton redoButton = null; + public void setRedoButton(AbstractButton _redoButton) + { + redoButton = _redoButton; + } + + public void ResetUndoRedoButton() + { + if(undoButton != null) + { + if(!this.canUndo()) + undoButton.setEnabled(false); + else + undoButton.setEnabled(true); + } + if(redoButton != null) + { + if(!this.canRedo()) + redoButton.setEnabled(false); + else + redoButton.setEnabled(true); + } + } +} diff --git a/src/main/java/gamess/UpdateInputFile.java b/src/main/java/gamess/UpdateInputFile.java new file mode 100644 index 0000000..24ff3b2 --- /dev/null +++ b/src/main/java/gamess/UpdateInputFile.java @@ -0,0 +1,564 @@ +/*Copyright (c) 2007, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ +/** + * @author Michael Sheetz + * @author Pavithra Koka + */ + +package gamess; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.StringTokenizer; + +import javax.swing.text.BadLocationException; +import javax.swing.text.Element; +import javax.swing.text.StyledDocument; + +import gamess.Dialogs.FormatParser; +import gamess.Dialogs.MatrixDialog; +import gamess.Dialogs.MolecularSpecification; +import gamess.Storage.Repository; + +public class UpdateInputFile implements ActionListener +{ + + public static UpdateInputFile instance = new UpdateInputFile(); + public static Hashtable snapshotGroup = null; + public static boolean isConsistent = true; + + private UpdateInputFile() + { + } + + public static UpdateInputFile getInstance() + { + return instance; + } + + public static void startUpdate() + { + if(UpdateInputFile.snapshotGroup == null) + { + UpdateInputFile.snapshotGroup = UpdateInputFile.getInstance().getValidInputGroups(false); + GamessGUI.setUpdateMode(true); + } + } + + private void stopUpdate() + { + GamessGUI.setUpdateMode(false); + snapshotGroup = null; + } + + public void actionPerformed(ActionEvent evt) { + //Do the update part + if(evt.getActionCommand().equalsIgnoreCase("update all")) + { + UpdateAll(); + } + else + { + if(snapshotGroup != null) + UpdateDifferences(); + else + UpdateAll(); + } + } + + //Full update + public boolean UpdateAll() + { + isConsistent = true; + Repository database = Repository.getInstance(); + //Drop the current DB + database.DropDB(); + + //Updates All the group freshly + Hashtable validGroups = null; + validGroups = getValidInputGroups(true); + for (Enumeration validGroup = validGroups.keys(); validGroup.hasMoreElements() ;) + { + String group = validGroup.nextElement(); + StringLocation groupContents = validGroups.get(group); + //groupContents = groupContents.replaceAll("\\s*!.*", " ").replace("\n", " "); + if(checkFormat(group, groupContents)) + database.Overwrite(group.substring(1), validGroups.get(group).content); + else + isConsistent = false; + } + + MessageBox.excludes.UpdateList(); + MessageBox.requires.UpdateList(); + + stopUpdate(); + + return true; + } + + //Update differences + public void UpdateDifferences() + { + //If there is no snapshot then do nothing + if(snapshotGroup == null) + return; + + isConsistent = true; + + Repository database = Repository.getInstance(); + + //else get the current group + Hashtable currentGroups = getValidInputGroups(true); + + //compare groups one by one + for (Enumeration currentGroup = currentGroups.keys(); currentGroup.hasMoreElements() ;) + { + String currentGroupKey = currentGroup.nextElement(); + //get the group value from the snapshot. + //if the current group is not available in the snapshot + //or if the values are different in both, + //update the current value as it has been modified. + StringLocation currentGroupContents = currentGroups.get(currentGroupKey); + if(snapshotGroup.get(currentGroupKey) == null || !snapshotGroup.get(currentGroupKey).content.equalsIgnoreCase(currentGroupContents.content)) + { + //currentGroupContents = currentGroupContents.replaceAll("\\s*!.*", " ").replace("\n", " "); + //Check the format of the group here + if(checkFormat(currentGroupKey, currentGroupContents)) + database.Overwrite(currentGroupKey.substring(1), currentGroupContents.content); + } + if(snapshotGroup.containsKey(currentGroupKey)) + snapshotGroup.remove(currentGroupKey); + } + + //delete all the groups that are left in the snapshot + for (Enumeration existedGroup = snapshotGroup.keys(); existedGroup.hasMoreElements() ;) + { + String currentGroupKey = existedGroup.nextElement(); + //remove the group from the database + database.Remove(currentGroupKey.substring(1)); + } + //reset the snapshot + snapshotGroup = null; + + stopUpdate(); + + MessageBox.excludes.UpdateList(); + MessageBox.requires.UpdateList(); + } + + public Hashtable getValidInputGroups(boolean validate) + { + Hashtable documentGroups = new Hashtable(); + //get the all the paragraph element and get the groups + StyledDocument inputDocument = GamessGUI.inputFilePane.getStyledDocument(); + Element rootElements = inputDocument.getDefaultRootElement(); + String currentGroup = null; + int currentGroupStatringOffset = -1; + + try + { + for (int i = 0; i < rootElements.getElementCount(); i++) + { + Element paragraphElement = rootElements.getElement(i); + + //skip the comment lines. + if(paragraphElement.getAttributes().containsAttributes(Cosmetics.COMMENTS_ATTRIBUTE)) + continue; + + //check if it has the group starting + String CurrentLine = inputDocument.getText(paragraphElement.getStartOffset(), paragraphElement.getEndOffset() - paragraphElement.getStartOffset()); + //skip blank lines + if(CurrentLine.trim().length() == 0) + continue; + if(currentGroup == null) + { + //There should be a group starting + if(!CurrentLine.startsWith(" $")) + { + //The line has an error line + if(validate) + { + //if the line starts with a $ then maybe the line is in correct format but there should be a space before it. + if(CurrentLine.startsWith("$")) + { + Cosmetics.setUnderline(paragraphElement.getStartOffset(), (CurrentLine.indexOf(" ") != -1)?CurrentLine.indexOf(" "):CurrentLine.length() , Cosmetics.ERROR_UNDERLINE); + Cosmetics.setTooltip(paragraphElement.getStartOffset(), (CurrentLine.indexOf(" ") != -1)?CurrentLine.indexOf(" "):CurrentLine.length() , "There should be a space before the group starting"); + isConsistent = false; + } + //The line is a junk of characters + else + { + Cosmetics.setUnderline(paragraphElement.getStartOffset(), paragraphElement.getEndOffset() - paragraphElement.getStartOffset(), Cosmetics.ERROR_UNDERLINE); + Cosmetics.setTooltip(paragraphElement.getStartOffset(), paragraphElement.getEndOffset() - paragraphElement.getStartOffset(), "Invalid line. The line should start with \" $\""); + isConsistent = false; + } + } + continue; + } + } + + //The group is a valid group + //get all the groups in this line + GroupRange range = null; + for(int currentLineOffset = 0 ; (range = getGroupRange(CurrentLine, currentLineOffset) ).Start != -1; ) + { + //Get the group + String Group = CurrentLine.substring(range.Start, range.End); + //check if the group is not a END group + if(!Group.equalsIgnoreCase("$END")) + { + if(range.Start != 1) + { + Cosmetics.setUnderline(paragraphElement.getStartOffset() + range.Start, range.End - range.Start , Cosmetics.ERROR_UNDERLINE); + Cosmetics.setTooltip(paragraphElement.getStartOffset() + range.Start, range.End - range.Start , "The group should start in a newline with a space before it"); + isConsistent = false; + currentGroup = null; + } + else if(currentGroup != null) + { + //The current group does not have an $END + if(validate) + { + Cosmetics.setUnderline(paragraphElement.getStartOffset() + range.Start, range.End - range.Start, Cosmetics.ERROR_UNDERLINE); + Cosmetics.setTooltip(paragraphElement.getStartOffset() + range.Start, range.End - range.Start , "Expected group ending for group " + currentGroup); + isConsistent = false; + } + + currentGroup = null; + } + //check if the group is a valid one + else if(isValidGroup(Group)) + { + //Set the group as the current group. + currentGroup = Group; + //Set the offset as the current group offset. + currentGroupStatringOffset = paragraphElement.getStartOffset() + range.End + 1; + } + else + { + //Set the current group to be an invalid group + if(validate) + { + Cosmetics.setUnderline(paragraphElement.getStartOffset() + range.Start, range.End - range.Start , Cosmetics.ERROR_UNDERLINE); + Cosmetics.setTooltip(paragraphElement.getStartOffset() + range.Start, range.End - range.Start , "Not a valid group"); + isConsistent = false; + } + + } + } + //else the group is $END + else + { + if(range.Start == 0) + { + Cosmetics.setUnderline(paragraphElement.getStartOffset() + range.Start, range.End - range.Start , Cosmetics.ERROR_UNDERLINE); + Cosmetics.setTooltip(paragraphElement.getStartOffset() + range.Start, range.End - range.Start , "The group ending should not be the starting of the line"); + isConsistent = false; + currentGroup = null; + } + else if(currentGroup != null) + { + String groupString = inputDocument.getText(currentGroupStatringOffset, paragraphElement.getStartOffset() + range.Start - currentGroupStatringOffset); + if(documentGroups.get(currentGroup) == null) + documentGroups.put(currentGroup, new StringLocation( currentGroupStatringOffset, groupString)); + else + { + //Warning the document already contains the group + if(validate) + { + Cosmetics.setUnderline(currentGroupStatringOffset - currentGroup.length(), currentGroup.length(), Cosmetics.WARNING_UNDERLINE); + Cosmetics.setTooltip(currentGroupStatringOffset - currentGroup.length(), currentGroup.length() , "The same group is available above"); + isConsistent = false; + } + } + currentGroup = null; + } + else + { + //$End does not match any group starting + if(validate) + { + Cosmetics.setUnderline(paragraphElement.getStartOffset() + range.Start, range.End - range.Start , Cosmetics.ERROR_UNDERLINE); + Cosmetics.setTooltip(paragraphElement.getStartOffset() + range.Start, range.End - range.Start , "$END does not match any group starting"); + isConsistent = false; + } + } + } + currentLineOffset = range.End; + } + } + if(currentGroup != null) + { + //$Group does not have an ending + if(validate) + { + Cosmetics.setUnderline(currentGroupStatringOffset - currentGroup.length(), currentGroup.length() , Cosmetics.ERROR_UNDERLINE); + Cosmetics.setTooltip(currentGroupStatringOffset - currentGroup.length(), currentGroup.length() , currentGroup + " does not have any group ending"); + isConsistent = false; + } + + } + } + catch(BadLocationException e){} + return documentGroups; + } + + public GroupRange getGroupRange(String currentLine , int offset) + { + GroupRange range = new GroupRange(); + //Get the current group starting offset + range.Start = currentLine.indexOf("$" , offset); + if(range.Start == -1) + return range; + //Get the current group ending offset + range.End = currentLine.indexOf(" ", range.Start + 1); + if(range.End == -1) + range.End = currentLine.length() - 1; + + return range; + } + + private boolean isValidGroup(String group) + { + return GlobalParameters.isGroupAvailable(group); + } + + private class GroupRange + { + int Start = -1; + int End = -1; + } + + private class StringLocation + { + int startLocation = -1; + String content = null; + + public StringLocation() {} + public StringLocation(int start, String content) { + startLocation = start; + this.content = content; + } + } + + private boolean checkFormat(String group, StringLocation content) + { + //First check if the group should be processed + //true - Proceed with validating keywords and value + //false - Check if the group is valid. (Possible only if group = "TDHFX", "DATA" or ... + if(shouldProcessGroup(group) == false) + { + return isGroupValid(group, content.content); + } + + + StringTokenizer tokens = new StringTokenizer(content.content , "="); + String currentKeyword = null; + int offset = 0; + for (int i = 0 ; tokens.hasMoreTokens(); i++,offset++) { + String token = tokens.nextToken(); + //Check if the loop is excuted first time + if(i == 0) + { + //if this is the first round then this is a keyword + if(token.trim().length() == 0) + { + Cosmetics.setUnderline(content.startLocation, 1 , Cosmetics.ERROR_UNDERLINE); + Cosmetics.setTooltip(content.startLocation, 1 , "Invalid keyword starting"); + return false; + } + if(!isKeyword(group, token, content.startLocation)) + return false; + currentKeyword = token; + } + //Check if the loop is executed last tim + else if(tokens.countTokens() == 0) + { + if(!isValue(group, currentKeyword, token, content.startLocation + offset)) + return false; + currentKeyword = null; + } + else + { + //Split the token into keyword and value + String keyword = null , value = null; + //Check if the keyword and a value is present. + //else show error + int seperationPosition = token.trim().lastIndexOf(" "); + if(seperationPosition == -1) + { + seperationPosition = token.trim().lastIndexOf("\n"); + if(seperationPosition == -1) + { + //there is no keyword or value seperation + Cosmetics.setUnderline(content.startLocation + offset, token.length() , Cosmetics.ERROR_UNDERLINE); + Cosmetics.setTooltip(content.startLocation + offset, token.length() , "Invalid keyword/value"); + return false; + } + } + seperationPosition++; + keyword = token.trim().substring(seperationPosition); + seperationPosition = token.indexOf(keyword); + value = token.substring(0, seperationPosition); + //check if the value is correct format. + if(!isValue(group , currentKeyword, value, content.startLocation + offset)) + return false; + currentKeyword = null; + //check if the keyword is in the correct format + offset += value.length(); + if(!isKeyword(group, keyword, content.startLocation + offset)) + return false; + + currentKeyword = keyword; + token = keyword; + } + offset += token.length(); + } + if(currentKeyword != null) + { + Cosmetics.setUnderline(content.startLocation + offset - currentKeyword.length() - 1, currentKeyword.length() , Cosmetics.ERROR_UNDERLINE); + Cosmetics.setTooltip(content.startLocation + offset - currentKeyword.length() - 1, currentKeyword.length() , "Keyword does not have an value"); + return false; + } + return true; + } + + private boolean shouldProcessGroup(String group) + { + if(group.equalsIgnoreCase("TDHFX") || GlobalParameters.plainDataGroup.contains(group.substring(1))) + return false; + return true; + } + + private boolean isGroupValid(String group, String content) + { + //TODO Hardcode the custom dialog validation + if(group.equalsIgnoreCase("$DATA")) + { + ((MolecularSpecification)Dictionary.dialogs.get("DATA")).ReadUpdate(); + } + return true; + } + + private boolean isKeyword(String group, String keyword, int offset) + { + if(keyword.trim().contains(" ")) + { + //Keyword format not proper + Cosmetics.setUnderline(offset, keyword.length() - 1 , Cosmetics.ERROR_UNDERLINE); + Cosmetics.setTooltip(offset, keyword.length() - 1 , "Invalid keyword format"); + return false; + } + //HARDCODED for $DATA group read + if(group.equalsIgnoreCase("$CONTRL") && (keyword.equalsIgnoreCase("ICHARG") || keyword.equalsIgnoreCase("MULT"))) + return true; + + //check if the keyword is valid + if(Dictionary.get(group.substring(1).trim(), keyword.trim()) == null) + { + Cosmetics.setCharacterAttributes(offset, keyword.length(), Cosmetics.NORMAL_ATTRIBUTE, true); + Cosmetics.setUnderline(offset, keyword.length(), Cosmetics.WARNING_UNDERLINE); + Cosmetics.setTooltip(offset, keyword.length(), Cosmetics.getInputFileToolTip("This keyword is not available in the database.
Possibilly not a valid keyword")); + } + else + Cosmetics.setCharacterAttributes(offset, keyword.length(), Cosmetics.KEYWORD_ATTRIBUTE, true); + return true; + } + + private boolean isValue(String group, String keyword, String value, int offset) + { + //Check if the value is empty + if(value.trim().length() == 0) + { + Cosmetics.setCharacterAttributes(offset, value.length(), Cosmetics.NORMAL_ATTRIBUTE, true); + Cosmetics.setUnderline(offset, value.length(), Cosmetics.ERROR_UNDERLINE); + Cosmetics.setTooltip(offset, value.length(), Cosmetics.getInputFileToolTip("Value is not valid
Please enter the value or
Press Ctrl + SPACE to open the dialog")); + return false; + } + + //check if the value is valid format + if(Dictionary.get(group.substring(1), keyword.trim(), value.trim()) == null) + { + //HARDCODED for $DATA group + if(group.equalsIgnoreCase("$CONTRL") && (keyword.equalsIgnoreCase("ICHARG") || keyword.equalsIgnoreCase("MULT"))) + ((MolecularSpecification)Dictionary.dialogs.get("DATA")).ReadUpdate(); + //The dictionary does not have the value for the specified keyword and the group. + //So the value should be a (Grid/Text) dialog or can be a textValue + //First check if the value is a TextValue + else if(Dictionary.get(group.substring(1), keyword.trim(), Dictionary.TEXTBOX_VALUE) != null) + { + //This is a text value. get the format and test it + FormatParser textFormat = FormatParser.getFormat(group.substring(1), keyword.trim(), null); + if(textFormat.isConsistent(value.trim()) == false) + { + //Wrong format + Cosmetics.setCharacterAttributes(offset, value.length(), Cosmetics.NORMAL_ATTRIBUTE, true); + Cosmetics.setUnderline(offset, value.length(), Cosmetics.ERROR_UNDERLINE); + Cosmetics.setTooltip(offset, value.length(), Cosmetics.getInputFileToolTip("This value is not in correct format.
Please enter the value in correct format or
Press Ctrl + SPACE to open the dialog")); + return false; + } + //Correct format + else + Cosmetics.setCharacterAttributes(offset, value.length(), Cosmetics.NORMAL_ATTRIBUTE, true); + } + //else check if the value is a dialog griddialog + else if(Dictionary.get(group.substring(1), keyword.trim(), Dictionary.GRID_DIALOG) != null) + { + //This is a grid dialog. Convert it to matrix dialog and test it + MatrixDialog dialog = (MatrixDialog)Dictionary.dialogs.get( Dictionary.getFormattedKeyword(group.substring(1) + " " + keyword.trim()) ); + if(dialog.testValue(group.substring(1), keyword, value) == false) + { + //Wrong format + Cosmetics.setCharacterAttributes(offset, value.length(), Cosmetics.NORMAL_ATTRIBUTE, true); + Cosmetics.setUnderline(offset, value.length(), Cosmetics.ERROR_UNDERLINE); + Cosmetics.setTooltip(offset, value.length(), Cosmetics.getInputFileToolTip("This value is not in correct format.
Please enter the value in correct format or
Press Ctrl + SPACE to open the dialog")); + return false; + //"This value is not available in the database for " + keyword + ".\nPossibilly not a valid value" + } + //Correct format + else + Cosmetics.setCharacterAttributes(offset, value.length(), Cosmetics.NORMAL_ATTRIBUTE, true); + } + } + else + Cosmetics.setCharacterAttributes(offset, value.length(), Cosmetics.NORMAL_ATTRIBUTE, true); + return true; + } + +}// end of class + + diff --git a/src/main/java/gamess/WavedUnderline.java b/src/main/java/gamess/WavedUnderline.java new file mode 100644 index 0000000..083400b --- /dev/null +++ b/src/main/java/gamess/WavedUnderline.java @@ -0,0 +1,21 @@ +package gamess; + +import java.awt.Graphics; +import java.awt.Shape; + +import javax.swing.text.DefaultHighlighter; +import javax.swing.text.JTextComponent; +import javax.swing.text.View; + +public class WavedUnderline extends DefaultHighlighter +{ + + @Override + public void paintLayeredHighlights(Graphics g, int p0, int p1, Shape viewBounds, JTextComponent editor, View view) { + super.paintLayeredHighlights(g, p0, p1, viewBounds, editor, view); + WavedUnderlinePen pen = (WavedUnderlinePen)view.getAttributes().getAttribute("UNDERLINE"); + if(pen != null) + pen.paintLayer(g, p0, p1, viewBounds, editor, view); + } + +} diff --git a/src/main/java/gamess/WavedUnderlinePen.java b/src/main/java/gamess/WavedUnderlinePen.java new file mode 100644 index 0000000..136aadb --- /dev/null +++ b/src/main/java/gamess/WavedUnderlinePen.java @@ -0,0 +1,56 @@ +package gamess; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Rectangle; +import java.awt.Shape; + +import javax.swing.text.JTextComponent; +import javax.swing.text.View; +import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter; + +public class WavedUnderlinePen extends DefaultHighlightPainter +{ + public WavedUnderlinePen(Color color) { + super(color); + } + + @Override + public Shape paintLayer(Graphics g, int p0, int p1, Shape viewBounds, JTextComponent editor, View view) { + if(viewBounds instanceof Rectangle) + { + //Get the bounds + Rectangle underlineArea = viewBounds.getBounds(); + g.setColor(super.getColor()); + + //Divide the total width into many division + //Set the width and the height of the single division + int divisionWidth = 2; + int divisionHeight = underlineArea.height - 3; + //get the number of division + int count = underlineArea.width/divisionWidth; + for (int i = 0; i < count; i++) { + //Start x + int x1, y1, x2 ,y2; + + x1 = i * divisionWidth + underlineArea.x; + x2 = (i + 1) * divisionWidth + underlineArea.x; + + if(i%2 == 0) + { + y1 = underlineArea.y + underlineArea.height - 1; + y2 = underlineArea.y + divisionHeight; + } + else + { + y1 = underlineArea.y + divisionHeight; + y2 = underlineArea.y + underlineArea.height - 1; + } + + g.drawLine(x1, y1, x2, y2); + } + return underlineArea; + } + return super.paintLayer(g, p0, p1, viewBounds, editor, view); + } +} \ No newline at end of file diff --git a/src/main/java/gamess/checkInputFile.java b/src/main/java/gamess/checkInputFile.java new file mode 100644 index 0000000..6432f07 --- /dev/null +++ b/src/main/java/gamess/checkInputFile.java @@ -0,0 +1,140 @@ +/*Copyright (c) 2007, Center for Computational Sciences, University of Kentucky. All rights reserved. + +Developed by: + +Center for Computational Sciences, University of Kentucky + +http://www.ccs.uky.edu + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Center for Computational Sciences, University of Kentucky + nor the names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ +/** + * @author Michael Sheetz + * @author Pavithra Koka + * @author Shreeram + */ + +package gamess; + +import javafx.application.Platform; +import legacy.editor.commons.Settings; +import org.seagrid.desktop.util.messaging.SEAGridEvent; +import org.seagrid.desktop.util.messaging.SEAGridEventBus; + +import java.awt.event.*; +import javax.swing.*; + +import java.util.*; +import javax.swing.text.*; + + + + +public class checkInputFile implements ActionListener{ + int temp; + final public int YES=1; + final public int NO=0; + int keywordpresent=NO; + int keywordinlist=NO; + ArrayList basisInputFile=new ArrayList(); + ArrayList controlInputFile=new ArrayList(); + StyledDocument document1; + + String inputDocumentName="gamessInput.xml"; + String inputDocumentName1="Input.xml"; + + + public void actionPerformed(ActionEvent event) { + try{ + if(!Settings.authenticated) + { + JOptionPane.showMessageDialog(GamessGUI.frame, "You are not authenticated to use this feature.\nPlease sign in to GridChem to use this feature." , "Access restriction", JOptionPane.ERROR_MESSAGE); + return; + } + + //Check if the document is a valid one + //Validate the complete document once again + + UpdateInputFile.getInstance().UpdateAll(); + + //Check for inconsistencies in the file + if(UpdateInputFile.isConsistent == false) + { + int response = JOptionPane.showConfirmDialog (GamessGUI.frame,"There are some errors in the document.\n\n Are you sure you want to proceed in submitting the inputfile?","Errors", + JOptionPane.YES_NO_OPTION, + JOptionPane.ERROR_MESSAGE); + if (response == JOptionPane.NO_OPTION) + return; + } + + //Check for exclude incompatibilities + MessageBox.excludes.UpdateList(); + if(MessageBox.excludes.incompList.size() != 0) + { + int response = JOptionPane.showConfirmDialog (GamessGUI.frame,"There are some inconsistencies in the document.\nSome items need to be excluded to make the inputfile valid.\nPlease see the \"Exclude incompatibility\" tab in the message window below\n\n Do you still want to proceed in submitting the inputfile?", "Input incompatibilities", + JOptionPane.YES_NO_OPTION, + JOptionPane.ERROR_MESSAGE); + if (response == JOptionPane.NO_OPTION) + return; + } + + //Check for Required incompatibilities + MessageBox.requires.UpdateList(); + if(MessageBox.requires.incompList.size() != 0) + { + int response = JOptionPane.showConfirmDialog (GamessGUI.frame,"There are some inconsistencies in the document.\nSome items need to be included to make the inputfile valid.\nPlease see the \"Required incompatibility\" tab in the message window below\n\n Do you still want to proceed in submitting the inputfile?", "Input incompatibilities", + JOptionPane.YES_NO_OPTION, + JOptionPane.ERROR_MESSAGE); + if (response == JOptionPane.NO_OPTION) + return; + } +// JOptionPane.showMessageDialog(GamessGUI.frame, "Your file is submitted." , ":)", JOptionPane.INFORMATION_MESSAGE); + +// if(GridChem.oc.sjw == null) +// GridChem.oc.doSubmission(); + +// FIXME-SEAGrid +// SubmitJobsWindow.getInstance(); +// EditJobPanel ejp = new EditJobPanel(); +// newNanocad.exportedApplication = Invariants.APP_NAME_GAMESS; +// ejp.changeApp(newNanocad.exportedApplication); +// ejp.populateMachineList(); + +// ejp.changeInputText(GamessGUI.inputFilePane.getText()); +// SubmitJobsWindow.si.mainFrame.dispose(); + Platform.runLater(() -> { + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType + .EXPORT_GAMESS_EXP, GamessGUI.inputFilePane.getText())); + }); + GamessGUI.frame.dispose(); + } + catch(Exception ee) + { + ee.printStackTrace(); + }//catch + } +}//end of class diff --git a/src/main/java/legacy/.DS_Store b/src/main/java/legacy/.DS_Store new file mode 100644 index 0000000..61ba687 Binary files /dev/null and b/src/main/java/legacy/.DS_Store differ diff --git a/src/main/java/legacy/._.DS_Store b/src/main/java/legacy/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/legacy/._.DS_Store differ diff --git a/src/main/java/legacy/editor/.DS_Store b/src/main/java/legacy/editor/.DS_Store new file mode 100644 index 0000000..d7aa4ed Binary files /dev/null and b/src/main/java/legacy/editor/.DS_Store differ diff --git a/src/main/java/legacy/editor/._.DS_Store b/src/main/java/legacy/editor/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/legacy/editor/._.DS_Store differ diff --git a/src/main/java/legacy/editor/commons/Settings.java b/src/main/java/legacy/editor/commons/Settings.java new file mode 100644 index 0000000..7cd7525 --- /dev/null +++ b/src/main/java/legacy/editor/commons/Settings.java @@ -0,0 +1,38 @@ +package legacy.editor.commons; + +import java.io.File; + +public class Settings { + public static final int ONE_SECOND = 1000; + public static final String APP_NAME_GAUSSIAN = "GAUSSIAN"; + public static final String APP_NAME_GAMESS = "GAMES"; + public static final String APP_NAME_NWCHEM = "NWCHEM"; + public static final String APP_NAME_MOLPRO = "MOLPRO"; + public static final String APP_NAME_PSI4 = "PSI4"; + public static final String APP_NAME_MOLCAS = "MOLCAS"; + + private static Settings ourInstance = new Settings(); + public static boolean authenticated = true; + public static String username = "master"; + public static String defaultDirStr = ""; + public static String fileSeparator = File.separator; + private static String applicationDataDir = defaultDataDirectory() + "legacy.editors"; + public static String jobDir = defaultDataDirectory() + "legacy.editors"; + public static String httpsGateway = "https://ccg-mw1.ncsa.uiuc.edu/cgi-bin/"; + + public static Settings getInstance() { + return ourInstance; + } + + private Settings() { + } + + public static String getApplicationDataDir() { + return applicationDataDir; + } + + private static String defaultDataDirectory() + { + return System.getProperty("user.home") + File.separator + "SEAGrid" + File.separator + ".ApplicationData" + File.separator; + } +} diff --git a/src/main/java/nanocad/.DS_Store b/src/main/java/nanocad/.DS_Store new file mode 100644 index 0000000..1369f01 Binary files /dev/null and b/src/main/java/nanocad/.DS_Store differ diff --git a/src/main/java/nanocad/._.DS_Store b/src/main/java/nanocad/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/nanocad/._.DS_Store differ diff --git a/src/main/java/nanocad/AtomDataFile.java b/src/main/java/nanocad/AtomDataFile.java new file mode 100644 index 0000000..6d9e7a2 --- /dev/null +++ b/src/main/java/nanocad/AtomDataFile.java @@ -0,0 +1,414 @@ +package nanocad; + +import java.io.*; +import java.util.*; + + +public class AtomDataFile +{ + private textwin debugWin; + String s = new String(""); + boolean closed, dataFound; + BufferedReader in; + + //Ying 04/03 + //data member; + public static int atomicNum =0; + public static double mass = 0; + public static int color1 = 255, color2 =255, color3 = 255; + public static double covalentRadius = 0 , vdwEnergy =0, vdwRadius =0; + public static int correctNumBonds =0; + public static String symbol = "H", name = "Hydrogen"; + + public AtomDataFile() + { + closed = true; + } + + public AtomDataFile(String fname) throws IOException + { + open(fname); + } + + public void close() throws IOException + { + if(!closed) { + in.close(); + closed = true; + } + } + + public boolean findData(int a1, int offset1) throws IOException + //reurns the valNumth value for the given atoms + { + String dataLine; + dataFound = readTo(a1, offset1); + return dataFound; + } + + public boolean findData(int a1, int a2, int offset1, int offset2) throws IOException + //reurns the valNumth value for the given atom pair + { + if(readTo(a1, offset1)) + dataFound = readTo(a2, offset2); + else + dataFound = false; + return dataFound; + } + + + public boolean findData(int a1, int a2, int a3, int offset1, int offset2, int offset3) throws IOException + //reurns the valNumth value for the given atom triplet + { + dataFound=false; + if(readTo(a1, offset1)) + if(readTo(a2, offset2)) + dataFound = readTo(a3, offset3); + return dataFound; + } + + public boolean findData(int a1, int a2, int a3, int a4, int offset1, int offset2, int offset3, int offset4) throws IOException + //reurns the valNumth value for the given atom quadruplet + { + dataFound=false; + if(readTo(a1, offset1)) + if(readTo(a2, offset2)) + if(readTo(a3, offset3)) + dataFound = readTo(a4, offset4); + return dataFound; + } + + public boolean findData(String symbol, int offset) throws IOException + { + return readTo(symbol, offset); + } + + //04/02 Ying prelude to compare the symbol; + + public String contains(String tar){ + //System.out.println("in contains 0, the tar is :"+tar); + //String tmp =null; + + //String modarate = "110 6 9 Ununnilium Uun 269 204 0 204 1.00 0.00 0.00"; + + String symWord = null; + Vector parsed = new Vector(); + char[] tmp = null; + int length=0; + length = tar.length(); + tmp= tar.toCharArray(); + char[] dest = new char[length+1]; + for (int i=0; i structures = new ArrayList(); + + private newNanocad nano; + /** + * Creates new form CSDSearch + */ + public CSDSearch(java.awt.Frame parent, boolean modal, newNanocad nano) { + super(parent, modal); + this.nano = nano; + this.setTitle("CSD Search"); + initComponents(); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jScrollPane2 = new javax.swing.JScrollPane(); + searchResults = new javax.swing.JTable(); + jPanel1 = new javax.swing.JPanel(); + jLabel1 = new javax.swing.JLabel(); + searchText = new javax.swing.JTextField(); + jButton1 = new javax.swing.JButton(); + searchLimit = new javax.swing.JTextField(); + jLabel2 = new javax.swing.JLabel(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + setAlwaysOnTop(true); + setResizable(true); + + searchResults.setModel(new javax.swing.table.DefaultTableModel( + new Object [][] { + + }, + new String [] { + "Formula", "Chemical Name" + } + ) { + Class[] types = new Class [] { + java.lang.String.class, java.lang.String.class + }; + boolean[] canEdit = new boolean [] { + false, false + }; + + public Class getColumnClass(int columnIndex) { + return types [columnIndex]; + } + + public boolean isCellEditable(int rowIndex, int columnIndex) { + return canEdit [columnIndex]; + } + }); + searchResults.addMouseListener(new java.awt.event.MouseAdapter() { + public void mouseClicked(java.awt.event.MouseEvent evt) { + searchResultsMouseClicked(evt); + } + }); + jScrollPane2.setViewportView(searchResults); + + jLabel1.setText("Search Text :"); + + searchText.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + searchTextActionPerformed(evt); + } + }); + + jButton1.setText("search"); + jButton1.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jButton1ActionPerformed(evt); + } + }); + + searchLimit.setText("5"); + + jLabel2.setText("Limit :"); + + javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); + jPanel1.setLayout(jPanel1Layout); + jPanel1Layout.setHorizontalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addComponent(jLabel1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(searchText, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jLabel2) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(searchLimit, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jButton1) + .addContainerGap()) + ); + jPanel1Layout.setVerticalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(searchText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel1) + .addComponent(jLabel2) + .addComponent(searchLimit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jButton1)) + .addContainerGap()) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 596, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(0, 0, Short.MAX_VALUE)) + .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 381, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + + pack(); + }// //GEN-END:initComponents + + private void searchTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchTextActionPerformed + // TODO add your handling code here: + }//GEN-LAST:event_searchTextActionPerformed + + private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed + this.structures = new ArrayList(); + String searchString = searchText.getText(); + String limit = searchLimit.getText(); + DefaultTableModel model = (DefaultTableModel) searchResults.getModel(); + int rowCount = model.getRowCount(); + for (int i = rowCount - 1; i >= 0; i--) { + model.removeRow(i); + } + if(limit.matches("-?\\d+(\\.\\d+)?")){ + try { + Integer number = Integer.parseInt(limit); + String encodedCompoundName = URLEncoder.encode(searchString); + //String databasecgi = "http://gw144.iu.xsede.org/cgi-bin/csd/csd_search.cgi?name=" + String databasecgi = "https://gridchem.uits.iu.edu/cgi-bin/csd/csd_search.cgi?name=" + + encodedCompoundName + "&limit=" + limit; + URL urlcgi = new URL(databasecgi); + URLConnection conn = urlcgi.openConnection(); + String line = null; + BufferedReader inStr = new BufferedReader(new InputStreamReader(conn.getInputStream())); + line = inStr.readLine(); + while(line != null){ + if(line.startsWith("START")){ + String formula = inStr.readLine(); + String chemicalName = inStr.readLine(); + String structure = ""; + line = inStr.readLine(); + while(line != null && !line.startsWith("END")){ + structure += line + "\n"; + line = inStr.readLine(); + } + structures.add(structure); + model.addRow(new String[]{formula, chemicalName}); + } + line = inStr.readLine(); + } + } catch (Exception ex) { + Logger.getLogger(CSDSearch.class.getName()).log(Level.SEVERE, null, ex); + } + } + }//GEN-LAST:event_jButton1ActionPerformed + + private void searchResultsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_searchResultsMouseClicked + Point p = evt.getPoint(); + if(evt.getClickCount() == 2){ + int row = searchResults.rowAtPoint(p); + if(row >= 0 && row < structures.size()){ + File temp = null; + try { + temp = File.createTempFile(System.currentTimeMillis() + "-mol", ".mol2"); + BufferedWriter bw = new BufferedWriter(new FileWriter(temp)); + bw.write(structures.get(row)); + bw.close(); + System.out.println( temp.getAbsolutePath() ); + nano.loadFile(temp.getAbsolutePath(), ""); + this.dispose(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + }//GEN-LAST:event_searchResultsMouseClicked + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton jButton1; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel2; + private javax.swing.JPanel jPanel1; + private javax.swing.JScrollPane jScrollPane2; + private javax.swing.JTextField searchLimit; + private javax.swing.JTable searchResults; + private javax.swing.JTextField searchText; + // End of variables declaration//GEN-END:variables +} diff --git a/src/main/java/nanocad/GeneralAtom.java b/src/main/java/nanocad/GeneralAtom.java new file mode 100644 index 0000000..dc81f18 --- /dev/null +++ b/src/main/java/nanocad/GeneralAtom.java @@ -0,0 +1,70 @@ +package nanocad; + +import java.awt.Color; + +public class GeneralAtom extends atom +{ + //private data members + private String name = new String(""); + private String symbol = new String(""); + private int atomicNumber = 0; + private double mass = 0.0; + private Color color = Color.black; + private double covalentRadius = 0.0; + private double vdwEnergy = 0.0; + private double vdwRadius = 0.0; + private int correctNumBonds = 0; + + public GeneralAtom() { + ; } + public GeneralAtom(GeneralAtom g) + { + super(g); + name = g.name; + symbol = g.symbol; + atomicNumber = g.atomicNumber; + mass = g.mass; + color = g.color; + covalentRadius = g.covalentRadius; + vdwEnergy = g.vdwEnergy; + vdwRadius = g.vdwRadius; + correctNumBonds = g.correctNumBonds; + } + //copy function + public GeneralAtom copy() + { + GeneralAtom copy = new GeneralAtom(); + copy.name = name; + copy.symbol = symbol; + copy.atomicNumber = atomicNumber; + copy.mass = mass; + copy.color = color; + copy.covalentRadius = covalentRadius; + copy.vdwEnergy = vdwEnergy; + copy.vdwRadius = vdwRadius; + copy.correctNumBonds = correctNumBonds; + return copy; + } + + //data acessing functions + public int atomicNumber (){ return atomicNumber; } + public Color color() { return color; } + public int correctNumBonds(){return correctNumBonds;} + public double covalentRadius(){return covalentRadius;} + public double mass(){return mass;} + public String name(){return name;} + public String symbol(){return symbol;} + public double vdwEnergy(){return vdwEnergy;} + public double vdwRadius(){return vdwRadius();} + + //data setting functions + public void setAtomicNumber(int newAtomicNumber){atomicNumber = newAtomicNumber;} + public void setColor(Color newColor){color = newColor;} + public void setCorrectNumBonds(int newCorrectNumBonds){correctNumBonds = newCorrectNumBonds;} + public void setCovalentRadius(double newCovalentRadius){covalentRadius = newCovalentRadius;} + public void setMass(double newMass){mass = newMass;} + public void setName(String newName){name = newName;} + public void setSymbol(String newSymbol){symbol = newSymbol;} + public void setVdwEnergy(double newVdwEnergy){vdwEnergy = newVdwEnergy;} + public void setVdwRadius(double newVdwRadius){vdwRadius = newVdwRadius;} +} diff --git a/src/main/java/nanocad/GetDataFile.java b/src/main/java/nanocad/GetDataFile.java new file mode 100644 index 0000000..90ac53a --- /dev/null +++ b/src/main/java/nanocad/GetDataFile.java @@ -0,0 +1,293 @@ +/*Copyright (c) 2004,University of Illinois at Urbana-Champaign. All rights reserved. + +Developed by: +Chemistry and Computational Biology Group + +NCSA, University of Illinois at Urbana-Champaign + +http://ncsa.uiuc.edu/GridChem + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software") to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Chemistry and Computational Biology Group , NCSA, + University of Illinois at Urbana-Champaign, nor the names of its contributors + may be used to endorse or promote products derived from this Software without + specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ + +// GetDataFile.java + +package nanocad; + +import legacy.editor.commons.Settings; + +import java.io.*; +import java.net.*; +import java.util.*; + +public class GetDataFile +{ + public File file; + public String system; + public String httpsGateway; + public String userid; + + public GetDataFile(String fileName) + { + file = new File(fileName); + system = "mss.ncsa.uiuc.edu"; + + String setsfile = ".settings"; + String line; + StringTokenizer st; + String temp; + + try + { + //lixh_4/27/05 + File sets = new File(newNanocad.applicationDataDir + + newNanocad.fileSeparator + setsfile); + //File sets = new File(System.getProperty("user.dir") + + // System.getProperty("file.separator") + setsfile); + BufferedReader br = new BufferedReader(new FileReader(sets)); + + line = br.readLine(); + st = new StringTokenizer(line); + temp = st.nextToken(); + userid = st.nextToken(); + line = br.readLine(); + st = new StringTokenizer(line); + temp = st.nextToken(); + httpsGateway = st.nextToken(); + + br.close(); + } + catch (IOException ioe) {} + +// httpsGateway = "https://swarna.ncsa.uiuc.edu/GAUSMON/"; + + try + { + URL cgiURL = new URL(httpsGateway + "getzipfile.cgi"); + initCGI(file, system, cgiURL); + } + catch (MalformedURLException mue) + { + System.err.println("GetDataFile: Malformed URLException"); + } + } + + public GetDataFile(File f) + { + file = f; + system = "mss.ncsa.uiuc.edu"; + //httpsGateway = "https://swarna.ncsa.uiuc.edu/GAUSMON/"; + + String setsfile = ".settings"; + String line; + StringTokenizer st; + String temp; + + try + { + File sets = new File(newNanocad.applicationDataDir + + newNanocad.fileSeparator + setsfile); + //File sets = new File(System.getProperty("user.dir") + + // System.getProperty("file.separator") + setsfile); + BufferedReader br = new BufferedReader(new FileReader(sets)); + + line = br.readLine(); + st = new StringTokenizer(line); + temp = st.nextToken(); + userid = st.nextToken(); + line = br.readLine(); + st = new StringTokenizer(line); + temp = st.nextToken(); + httpsGateway = st.nextToken(); + + br.close(); + } + catch (IOException ioe) {} + + try + { + URL cgiURL = new URL(httpsGateway + "getzipfile.cgi"); + initCGI(file, system, cgiURL); + } + catch (MalformedURLException mue) + { + System.err.println("GetDataFile: Malformed URLException"); + } + } + public GetDataFile(String fileName, String sysName) + { + file = new File(fileName); + system = sysName; + //httpsGateway = "https://swarna.ncsa.uiuc.edu/GAUSMON/"; + String setsfile = ".settings"; + String line; + StringTokenizer st; + String temp; + + try + { + File sets = new File(newNanocad.applicationDataDir + + newNanocad.fileSeparator + setsfile); + //File sets = new File(System.getProperty("user.dir") + + // System.getProperty("file.separator") + setsfile); + BufferedReader br = new BufferedReader(new FileReader(sets)); + + line = br.readLine(); + st = new StringTokenizer(line); + temp = st.nextToken(); + userid = st.nextToken(); + line = br.readLine(); + st = new StringTokenizer(line); + temp = st.nextToken(); + httpsGateway = st.nextToken(); + + br.close(); + } + catch (IOException ioe) {} + try + { + URL cgiURL = new URL(httpsGateway + "getzipfile.cgi"); + initCGI(file, system, cgiURL); + } + catch (MalformedURLException mue) + { + System.err.println("GetDataFile: Malformed URLException"); + } + } + + public GetDataFile(File f, String sysName) + { + file = f; + system = sysName; + //httpsGateway = "https://swarna.ncsa.uiuc.edu/GAUSMON/"; + + String setsfile = ".settings"; + String line; + StringTokenizer st; + String temp; + + try + { + File sets = new File(newNanocad.applicationDataDir + + newNanocad.fileSeparator + setsfile); + //File sets = new File(System.getProperty("user.dir") + + // System.getProperty("file.separator") + setsfile); + BufferedReader br = new BufferedReader(new FileReader(sets)); + + line = br.readLine(); + st = new StringTokenizer(line); + temp = st.nextToken(); + userid = st.nextToken(); + line = br.readLine(); + st = new StringTokenizer(line); + temp = st.nextToken(); + httpsGateway = st.nextToken(); + + br.close(); + } + catch (IOException ioe) {} + + try + { + URL cgiURL = new URL(httpsGateway + "getzipfile.cgi"); + initCGI(file, system, cgiURL); + } + catch (MalformedURLException mue) + { + System.err.println("GetDataFile: Malformed URLException"); + } + } + + void initCGI(File f, String system, URL cgiURL) + { + String line; + boolean append = false; + String dirOnMss = "/chembiodata/nanocad/"; + try + { + URLConnection connex = cgiURL.openConnection(); + connex.setDoOutput(true); + PrintWriter outStream = new PrintWriter(connex.getOutputStream()); + //String userName = URLEncoder.encode(legacy.editors.commons.Settings.name.getText()); + String userName = URLEncoder.encode(userid); + String fName = URLEncoder.encode(dirOnMss+f.getName()); + String sys = URLEncoder.encode(system); + + if (Settings.authenticated) { + userName = URLEncoder.encode("ccguser"); + outStream.println("IsGridChem=" + URLEncoder.encode("true")); + System.err.println("GetDataFile:IsGridChem=" + "true"); + } else { + outStream.println("IsGridChem=" + URLEncoder.encode("false")); + System.err.println("GetDataFile:IsGridChem=" + "false"); + } + outStream.println("Username=" + userName); + System.err.println("GetDataFile:Username=" + userName); + outStream.println("GridChemUsername=" + Settings.username); + System.err.println("GetDataFile:GridChemUsername=" + Settings.username); + outStream.println("System=" + sys); + System.err.println("GetDataFile:System=" + sys); + outStream.println("fileName=" + fName); + System.err.println("GetDataFile:fileName=" + fName); + + outStream.close(); + + // BufferedReader inStream = new BufferedReader(new +// InputStreamReader(connex.getInputStream())); + InputStream inStream = connex.getInputStream(); + //OutputStreamWriter fw = new OutputStreamWriter(new + // FileOutputStream(f, append)); + FileOutputStream fw = new FileOutputStream(f, append); + /* + while ((line = inStream.readLine()) != null) + { + int m = line.length(); + if (m > 0) + { + fw.write(line + "\n"); + //System.err.println(line); + } + } + */ + int sChunk = 8192; + byte[] buffer = new byte[sChunk]; + + int length; + while ((length = inStream.read(buffer, 0, sChunk)) != -1) + fw.write(buffer, 0, length); + + fw.close(); + } + catch (IOException ioe) + { + System.err.println("GetDataFile:initCGI:IOException"); + System.err.println(ioe.toString()); + ioe.printStackTrace(); + } + } +} diff --git a/src/main/java/nanocad/Indiana.java b/src/main/java/nanocad/Indiana.java new file mode 100644 index 0000000..dad5218 --- /dev/null +++ b/src/main/java/nanocad/Indiana.java @@ -0,0 +1,196 @@ +package nanocad; +import java.net.*; +import java.io.*; +import java.lang.*; +import java.util.*; +import java.lang.String; + +public class Indiana +{ + + // private static textwin saveWin; + public static String name,formula,a; + public static char g,j,t,special; + public static String search_str; + public static LinkedList tosend = new LinkedList(); + public static int chk; + // private static newNanocad newnano; + + public static void main(String []argv) + { + if( argv.length < 2 ) { + System.err.println( "Insufficient arguments" ); + System.exit(-1); + } + + System.err.println("In Java code"); + search_str = argv[0]; + + // get the integer from the argument + for( int i = 0; i < argv[1].length(); i++ ) + if( Character.isDigit(argv[1].charAt(i)) ) + chk = Character.digit(argv[1].charAt(i), 10 ); + + + String query_string="",query_st=""; + String atom1Name = null,atom1Num = null; + String atom2Name = null,atom2Num = null; + String atom3Name = null,atom3Num = null; + +// newnano.loadpdb("http://pine.ncsa.uiuc.edu/csd/temp/fileFromIndiana"); +// + + System.err.println("chk = " + chk + " search_str = " + search_str); + + if(chk == 0){ // => we passed a name + System.err.print("Hello world: "); + query_string ="http://www.iumsc.indiana.edu/db/search.jsp?start=1&compoundName=" + argv[0]+ "&raw=pdb"; + System.err.println("chk = " + chk + " query_string= " + query_string); + } else if(chk == 1) //=> we passed a Formula + { + //Parse the formula string into alphabets and numbers + // and then generate the query string reqd by Indiana + int k=0; + while(k= search_str.length()){ + tosend.add("1"); + break ; + } + j = search_str.charAt(k); + if(Character.isUpperCase(j)){ + tosend.add("1"); + asj = new Character(j); + tosend.add(asj.toString()); + k++; + + if(k>= search_str.length()){ + tosend.add("1"); + break ; + } + else if(Character.isDigit(t = search_str.charAt(k))){ + asj = new Character(t); + tosend.add(asj.toString()); + k++; + } + else if(Character.isLowerCase(t = search_str.charAt(k))){ + asj = new Character(t); + String add = tosend.getLast().toString(); + String after = add + asj.toString(); + tosend.removeLast(); + tosend.addLast(after); + k++; + + if(k>= search_str.length()){ + tosend.add("1"); + break ; + } + else if(Character.isDigit(t = search_str.charAt(k))){ + asj = new Character(t); + tosend.add(asj.toString()); + k++; + } + else + tosend.add("1"); + } + } + else if(Character.isDigit(j)){ + asj = new Character(j); + tosend.add(asj.toString()); + // tosend.add("1"); + k++; + if(k>= search_str.length()){ + break ; + } + } + else{ + asj = new Character(j); + String test = tosend.getLast().toString(); + String test1 = test + asj.toString(); + tosend.removeLast(); + tosend.addLast(test1); + k++; + + if(k>= search_str.length()){ + tosend.add("1"); + break ; + } + + else if(Character.isDigit(t = search_str.charAt(k))){ + asj = new Character(t); + tosend.add(asj.toString()); + k++; + } + else + tosend.add("1"); + + } + } + } + + atom1Name= tosend.get(0).toString(); + atom3Name= tosend.get(2).toString(); + atom1Num = tosend.get(1).toString(); + atom3Num = tosend.get(3).toString(); + + + + int o=0,anothernumber=0; + String initialquery = "", combined=""; + String must = "http://www.iumsc.indiana.edu/db/search.jsp?start=1"; + for(o=0;o= search_str.length()){ + tosend.add("1"); + break ; + } + j = search_str.charAt(k); + if(Character.isUpperCase(j)){ + tosend.add("1"); + asj = new Character(j); + tosend.add(asj.toString()); + k++; + + if(k>= search_str.length()){ + tosend.add("1"); + break ; + } + else if(Character.isDigit(t = search_str.charAt(k))){ + asj = new Character(t); + tosend.add(asj.toString()); + k++; + } + else if(Character.isLowerCase(t = search_str.charAt(k))){ + asj = new Character(t); + String add = tosend.getLast().toString(); + String after = add + asj.toString(); + tosend.removeLast(); + tosend.addLast(after); + k++; + + if(k>= search_str.length()){ + tosend.add("1"); + break ; + } + else if(Character.isDigit(t = search_str.charAt(k))){ + asj = new Character(t); + tosend.add(asj.toString()); + k++; + } + else + tosend.add("1"); + } + } + else if(Character.isDigit(j)){ + asj = new Character(j); + tosend.add(asj.toString()); + // tosend.add("1"); + k++; + if(k>= search_str.length()){ + break ; + } + } + else{ + asj = new Character(j); + String test = tosend.getLast().toString(); + String test1 = test + asj.toString(); + tosend.removeLast(); + tosend.addLast(test1); + k++; + + if(k>= search_str.length()){ + tosend.add("1"); + break ; + } + + else if(Character.isDigit(t = search_str.charAt(k))){ + asj = new Character(t); + tosend.add(asj.toString()); + k++; + } + else + tosend.add("1"); + + } + } + } + String toreturn = null; + for(int o = 0;o we passed a name + query_string ="http://www.iumsc.indiana.edu/db/search.jsp?start=1&compoundName=" + search_str+ "&raw=pdb"; + //System.out.println(" ***** "+ query_string); + if(chk.equals("1")) //=> we passed a Formula + { + //Parse the formula string into alphabets and numbers + // and then generate the query string reqd by Indiana + int k=0; + while(k= search_str.length()){ + tosend.add("1"); + break ; + } + j = search_str.charAt(k); + if(Character.isUpperCase(j)){ + tosend.add("1"); + asj = new Character(j); + tosend.add(asj.toString()); + k++; + + if(k>= search_str.length()){ + tosend.add("1"); + break ; + } + else if(Character.isDigit(t = search_str.charAt(k))){ + asj = new Character(t); + tosend.add(asj.toString()); + k++; + } + else if(Character.isLowerCase(t = search_str.charAt(k))){ + asj = new Character(t); + String add = tosend.getLast().toString(); + String after = add + asj.toString(); + tosend.removeLast(); + tosend.addLast(after); + k++; + + if(k>= search_str.length()){ + tosend.add("1"); + break ; + } + else if(Character.isDigit(t = search_str.charAt(k))){ + asj = new Character(t); + tosend.add(asj.toString()); + k++; + } + else + tosend.add("1"); + } + } + else if(Character.isDigit(j)){ + asj = new Character(j); + tosend.add(asj.toString()); + // tosend.add("1"); + k++; + if(k>= search_str.length()){ + break ; + } + } + else{ + asj = new Character(j); + String test = tosend.getLast().toString(); + String test1 = test + asj.toString(); + tosend.removeLast(); + tosend.addLast(test1); + k++; + + if(k>= search_str.length()){ + tosend.add("1"); + break ; + } + + else if(Character.isDigit(t = search_str.charAt(k))){ + asj = new Character(t); + tosend.add(asj.toString()); + k++; + } + else + tosend.add("1"); + + } + } } + + + + atom1Name= tosend.get(0).toString(); + atom2Name= tosend.get(2).toString(); + atom1Num = tosend.get(1).toString(); + atom2Num = tosend.get(3).toString(); + + + /* for(int o = 0;o= lengthOfTask) + return true; + else + return false; + } + +}// end public abstract class MyLongTask diff --git a/src/main/java/nanocad/MyLongTaskInterface.java b/src/main/java/nanocad/MyLongTaskInterface.java new file mode 100644 index 0000000..c17749e --- /dev/null +++ b/src/main/java/nanocad/MyLongTaskInterface.java @@ -0,0 +1,65 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package nanocad; +/*Copyright (c) 2004,University of Illinois at Urbana-Champaign. All rights reserved. + +Developed by: +Chemistry and Computational Biology Group + +NCSA, University of Illinois at Urbana-Champaign + +http://ncsa.uiuc.edu/GridChem + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Chemistry and Computational Biology Group , NCSA, + University of Illinois at Urbana-Champaign, nor the names of its contributors + may be used to endorse or promote products derived from this Software without + specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ + +public interface MyLongTaskInterface { + public void go() throws Exception; + public int getLengthOfTask(); + public int getCurrent(); + public void stop(); + public boolean done(); +}// end public interface MyLongTaskInterface diff --git a/src/main/java/nanocad/NanoCadTask.java b/src/main/java/nanocad/NanoCadTask.java new file mode 100644 index 0000000..bc6c089 --- /dev/null +++ b/src/main/java/nanocad/NanoCadTask.java @@ -0,0 +1,102 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package nanocad; + +import legacy.editor.commons.Settings; + +import javax.swing.*; +import java.io.File; +/** + * @author Xiaohai Li + * + * @see nanocadFrame2 + * @see MyLongTask + * NanocadTask subclasses MyLongTask which uses a SwingWorker to + * perform a time-consuming task. + * + */ +class NanocadTask extends MyLongTask implements MyLongTaskInterface { + + public static boolean DEBUG = true; + private JFrame frame; + + public NanocadTask(JFrame jf) { + super(); + frame = jf; + } + + public void go() { + current = 0; // from MyLongTask + final SwingWorker worker = new SwingWorker() { + public Object construct() { + return new ActualTask(); + } + }; + worker.start(); + } + +} + +/************************************************************ + Inner class ActualTask is need for the implementation of + a subclass of MyLongTask. It cannot be made static b/c of + the design of MyLongTask + */ +final class ActualTask { + ActualTask () { + //Check if molecular database is available on local machine + if (!((new File(Settings.defaultDirStr + Settings.fileSeparator + "common")).exists())) + { + //nanocadFrame2.progressLabel.setText("Retrieve Molecule Database Progress"); + String zipFileName = Settings.getApplicationDataDir() + Settings.fileSeparator + "nanocad" + File.separator + + "nanocaddata.zip"; + if (!((new File(zipFileName)).exists())) + { + nanocadFrame2.progressLabel.setText("Progress: Retrieve Molecule database from remote system..."); + GetDataFile gf = new GetDataFile(zipFileName); + } + //nanocadFrame2.progressLabel.setText("Progress: unzipping molecule database"); + //ZipExtractor uz = new ZipExtractor(zipFileName); + //System.err.println("Done with unzipping nanocaddata.zip"); + } + + //Check if txt files needed by nanocad is available on local machine + if (!((new File(Settings.defaultDirStr + Settings.fileSeparator + "txt")).exists())) + { + //nanocadFrame2.progressLabel.setText("Retrieve .txt files Progress"); + String zipFileName = Settings.getApplicationDataDir() + Settings.fileSeparator + "nanocad" + File.separator + + "txt.zip"; + if (!((new File(zipFileName)).exists())) + { + nanocadFrame2.progressLabel.setText("Progress: Retrieve .txt files from remote system..."); + GetDataFile gf = new GetDataFile(zipFileName); + } + //nanocadFrame2.progressLabel.setText("Done Retrieving files"); + //nanocadFrame2.progressLabel.setText("Progress: unzipping .txt files"); + //ZipExtractor uz = new ZipExtractor(zipFileName); + //System.err.println("Done with unzipping txt.zip"); + } + + nanocadFrame2.nanocadTask.stop(); + System.err.println("nanocadTask is done"); + + } +} diff --git a/src/main/java/nanocad/NcadMenu.java b/src/main/java/nanocad/NcadMenu.java new file mode 100644 index 0000000..6db9fc9 --- /dev/null +++ b/src/main/java/nanocad/NcadMenu.java @@ -0,0 +1,98 @@ +///////////////////////////////////////// +// NcadMenu.java +// Aug 2001 by Andrew Knox +// Provides a menu that looks similar on different platforms (windows, mac) +///////////////////////////////////////// + +package nanocad; + +import java.awt.*; +//import java.awt.event.MouseListener; +import java.awt.event.*; + +public class NcadMenu extends Label implements MouseListener +{ + PopupMenu theMenu; + NcadMenuBar theMenuBar; + public boolean menuShowing; + + public NcadMenu(String name) + { + super(name, Label.LEFT); + + setBackground(Color.lightGray); + + theMenu = new PopupMenu(name); + ((Component)this).add(theMenu); + addMouseListener(this); + menuShowing = false; + } + + public String toString() + { + return "NcadMenu"; + } + + public void add(MenuItem m) + { + theMenu.add(m); + } + + public void setMenuBar(NcadMenuBar m) + { + theMenuBar = m; + } + + public Dimension getMinimumSize() + { + Dimension d = super.getMinimumSize(); + d.height = this.getFont().getSize()+4; + return d; + } + + public Dimension getMaximumSize() + { + Dimension d = super.getMaximumSize(); + d.height = this.getFont().getSize()+4; + return d; + } + + public Dimension getPreferredSize() + { + Dimension d = super.getPreferredSize(); + d.height = this.getFont().getSize()+4; + return d; + } + + public Menu getMenu() + { + return (Menu) theMenu; + } + + public void show() + { + theMenu.show(this, 0, this.getSize().height + 2); + } + + public void mousePressed(MouseEvent e) + { + this.setBackground(Color.yellow); + theMenuBar.repaint(1); + this.show(); + } + + public void mouseReleased(MouseEvent e) + {;} + + public void mouseClicked(MouseEvent e) + {;} + + public void mouseEntered(MouseEvent e) + {;} + + public void mouseExited(MouseEvent e) + { + this.setBackground(Color.lightGray); + theMenuBar.repaint(); + } +} diff --git a/src/main/java/nanocad/NcadMenuBar.java b/src/main/java/nanocad/NcadMenuBar.java new file mode 100644 index 0000000..d03de7e --- /dev/null +++ b/src/main/java/nanocad/NcadMenuBar.java @@ -0,0 +1,110 @@ +/*Copyright (c) 2004,University of Illinois at Urbana-Champaign. All rights reserved. + +Developed by: +Chemistry and Computational Biology Group + +NCSA, University of Illinois at Urbana-Champaign + +http://ncsa.uiuc.edu/GridChem + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software", to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Chemistry and Computational Biology Group , NCSA, + University of Illinois at Urbana-Champaign, nor the names of its contributors + may be used to endorse or promote products derived from this Software without + specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ + +////////////////////////////////////////// +// NcadMenuBar.java +// Aug 2001 by Andrew Knox +// The menu bar for the cross-platform menu +// Note: it must be added to a frame like a panel +////////////////////////////////////////// + +package nanocad; + +import java.awt.*; + +public class NcadMenuBar extends Panel +{ + NcadMenu[] menus; + Frame parent; + boolean hasParent; + + public NcadMenuBar(NcadMenu[] m, int size) + { + super(new FlowLayout(FlowLayout.LEFT, 10, 0)); + menus = new NcadMenu[size]; + for (int i = 0; i < size; i++) + { + menus[i] = m[i]; + m[i].setMenuBar(this); + ((Panel)this).add(m[i]); + System.out.println("added"); + } + this.setBackground(Color.lightGray); + hasParent = false; + validate(); + } + + public void setParent(Frame f) + { + parent = f; + hasParent = true; + } + + public Dimension getMinimumSize() + { + if(hasParent == true) + { + Dimension d = menus[0].getSize(); + d.width = parent.getSize().width; + return d; + } + return this.getSize(); + } + + public Dimension getMaximumSize() + { + if(hasParent == true) + { + Dimension d = menus[0].getSize(); + d.width = parent.getSize().width; + return d; + } + return this.getSize(); + } + + public Dimension getPreferedSize() + { + if(hasParent == true) + { + Dimension d = menus[0].getSize(); + d.width = parent.getSize().width; + return d; + } + return this.getSize(); + } + +} diff --git a/src/main/java/nanocad/PDBParser.java b/src/main/java/nanocad/PDBParser.java new file mode 100644 index 0000000..87416d8 --- /dev/null +++ b/src/main/java/nanocad/PDBParser.java @@ -0,0 +1,191 @@ +/////////////////////////////////////////////////////// +// PDBParser.java +// September 2001 by Andrew Knox +// A parser for PDB Files. Extends Parser.java +/////////////////////////////////////////////////////// + +package nanocad; + +import java.lang.System; +import java.io.StreamTokenizer; +import java.io.*; + +public class PDBParser extends Parser +{ + + public PDBParser(String data) + { + super(data); + //System.out.println(data); + } + + public void process() throws IOException + { + int firstAtom = 0; + int columnNo = 0; + boolean eof = false; + boolean readingAtom = false; + boolean readingBond = false; + boolean newLine = true; + boolean noone = false; + boolean debug = true; + + inStream.eolIsSignificant(true); + inStream.slashSlashComments(false); + inStream.slashStarComments(false); + inStream.ordinaryChar('/'); + + //System.out.println("parsing..."); + do + { + int token = inStream.nextToken(); + switch(token) + { + case StreamTokenizer.TT_EOF: + eof = true; + break; + + case StreamTokenizer.TT_EOL: + //for whatever reason, streamTokenizer is never picking up eols; thus, this code isn't being reached + readingAtom = false; + readingBond = false; + newLine = true; + System.out.println("end of line"); + break; + + case StreamTokenizer.TT_WORD: + if (inStream.sval.equals("MASTER")) + { + eof = true; + } + if (inStream.sval.equals("ATOM") || inStream.sval.equals("HETATM")) + { + readingAtom = true; + readingBond = false; + newLine = false; + columnNo = 1; + } + else if (inStream.sval.equals("CONNECT") || inStream.sval.equals("CONECT")) + { + readingAtom = false; + readingBond = true; + newLine = false; + columnNo = 1; + } + else if (inStream.sval.equals("UNK")) + { + //dont' increment columnNo + break; + } + else if (readingAtom == true && columnNo == 2) + { + String symbol = inStream.sval; + //System.out.println(symbol); + //symbol = symbol.substring(1, symbol.length() - 3); + sym.addElement(symbol); + columnNo++; + } + else + { + if (newLine == true) + { + while (!inStream.sval.equals("ATOM") && !inStream.sval.equals("HETATM") && + !inStream.sval.equals("CONNECT") && !inStream.sval.equals("CONECT")) + { + inStream.nextToken(); + while(inStream.sval == null) + inStream.nextToken(); + if (inStream.sval.equals("/")) + inStream.nextToken(); + System.out.println("Skipped token:" + inStream.sval); + } + inStream.pushBack(); + } + else + columnNo++; //ignore word + //System.out.println("word " + inStream.sval + " ignored"); + } + break; + + case StreamTokenizer.TT_NUMBER: + if (readingAtom == true) + { + if (columnNo == 3) + if (inStream.nval != 1) + noone = true; + if ((columnNo == 4 && noone == false) || (columnNo == 3 && noone == true)) + atomX.addElement(new Double(inStream.nval)); + if ((columnNo == 5 && noone == false) || (columnNo == 4 && noone == true)) + atomY.addElement(new Double(inStream.nval)); + if ((columnNo == 6 && noone == false) || (columnNo == 5 && noone == true)) + { + atomZ.addElement(new Double(inStream.nval)); + noone = false; + } + columnNo++; + } + else if (readingBond == true) + { + if (columnNo == 1) + firstAtom = (int) inStream.nval; + else + { + System.out.println("column:" + String.valueOf(columnNo)); + boolean bondExists = false; + for (int i = 0; i < bAtom1.size(); i++) + { + if ( ((Double)bAtom1.elementAt(i)).intValue() == firstAtom && + ((Double)bAtom2.elementAt(i)).doubleValue() == inStream.nval) + { + int order = ((Double)bOrder.elementAt(i)).intValue(); + order++; + bOrder.setElementAt(new Double(order), i); + bondExists = true; + System.out.println("upped " + firstAtom + " " + inStream.nval + " order " + order); + } + } + if (bondExists == false && firstAtom < inStream.nval) + { + bAtom1.addElement( new Double(firstAtom)); + bAtom2.addElement( new Double(inStream.nval)); + bOrder.addElement( new Double(1) ); + System.out.println("added " + firstAtom + " " + inStream.nval + " order 1"); + } + } + columnNo++; + } + break; + + default: + System.out.println("Random token:" + token); + break; + } + } while(!eof); + + //sym.removeElementAt(sym.size()-1); + + if(debug == false) + { + System.out.println(sym.size() + " " + atomX.size() + " " + atomY.size() + " " + atomZ.size()); + for (int i=0; i< sym.size(); i++) { + System.out.println("i is :"+i+"\n"); + System.out.println("Sym contains : "+ sym.elementAt(i)); + System.out.println(atomX.size() + " " + atomY.size() + " " + atomZ.size()); + System.out.println("atomX : "+ atomX.elementAt(i)); + System.out.println("atomY : "+ atomY.elementAt(i)); + System.out.println("atomZ : "+ atomZ.elementAt(i)); + System.out.println("\n"); + } + System.out.println(bAtom1.size() + " " + bAtom2.size() + " " + bOrder.size()); + + for (int i=0; i=7) {System.out.println(" Line starts with "+ line.substring(0,7));} + if (line.startsWith("HEADER")) readHEADER(); + else if (line.startsWith("OBSLTE")) ; + else if (line.startsWith("TITLE ")) ; + else if (line.startsWith("CAVEAT")) ; + else if (line.startsWith("COMPND")) { readCOMPOUND();} + else if (line.startsWith("SOURCE")) ; + else if (line.startsWith("KEYWDS")) ; + else if (line.startsWith("EXPDTA")) ; + else if (line.startsWith("AUTHOR")) ; + else if (line.startsWith("REVDAT")) ; + else if (line.startsWith("JRNL ")) ; + else if (line.startsWith("REMARK")) ; + else if (line.startsWith("DBREF ")) ; + else if (line.startsWith("SEQADV")) ; + else if (line.startsWith("SEQRES")) {readSEQRES();} + else if (line.startsWith("MODRES")) ; + else if (line.startsWith("HET ")) ; + else if (line.startsWith("HETNAM")) ; + else if (line.startsWith("HETSYN")) ; + else if (line.startsWith("FORMUL")) ; + else if (line.startsWith("HELIX ")) ; + else if (line.startsWith("SHEET ")) ; + else if (line.startsWith("TURN ")) ; + else if (line.startsWith("SSBOND")) ; + else if (line.startsWith("LINK ")) ; + else if (line.startsWith("SLTBRG")) ; + else if (line.startsWith("SLTBRG")) ; + else if (line.startsWith("CISPEP")) ; + else if (line.startsWith("SITE ")) ; + else if (line.startsWith("CRYST1")) ; + else if (line.startsWith("ORIGX")) ; + else if (line.startsWith("SCALE")) ; + else if (line.startsWith("MTRIX")) ; + else if (line.startsWith("TVECT ")) ; + else if (line.startsWith("MODEL ")) ; + else if (line.startsWith("ATOM ")) {System.out.println(" Will read Atom info"); readATOM();return;} + else if (line.startsWith("SIGATM")) ; + else if (line.startsWith("ANISOU")) ; + else if (line.startsWith("SIGUIJ")) ; + else if (line.startsWith("TER ")) ; + else if (line.startsWith("HETATM")) {System.out.println(" Will read HeteroAtom info");readATOM();return;} + else if (line.startsWith("ENDMDL")) ; + else if (line.startsWith("CONNECT")) {System.out.println(" Will read Bond info");readBONDS();return;} + else if (line.startsWith("CONECT")) {System.out.println(" Will read Bond info");readBONDS();return;} + else if (line.startsWith("MASTER")) { eof= true; done = true;} + else if (line.startsWith("END ")) { eof= true; done = true; } + else if (line.startsWith("")){ eof= true; done = true; } + else System.out.println("Unknown record type (" + line.substring(0,6) + + ") in PDB entry at line " + + lineNumber); +} + +public void readHEADER () +throws IOException { + if (line.length() >= 66){ + String classification = line.substring(10, 50).trim(); + + + if (line.length() >= 66) { + String IDcode = line.substring(62, 66); + } + + int day = Integer.parseInt(line.substring(50,52)); + int month; + String monthString = line.substring(53,56); + int year = Integer.parseInt(line.substring(57,59)); + //MBDate date; + + if (monthString.equals("JAN")) month = 0; + else if (monthString.equals("FEB")) month = 1; + else if (monthString.equals("MAR")) month = 2; + else if (monthString.equals("APR")) month = 3; + else if (monthString.equals("MAY")) month = 4; + else if (monthString.equals("JUN")) month = 5; + else if (monthString.equals("JUL")) month = 6; + else if (monthString.equals("AUG")) month = 7; + else if (monthString.equals("SEP")) month = 8; + else if (monthString.equals("OCT")) month = 9; + else if (monthString.equals("NOV")) month = 10; + else if (monthString.equals("DEC")) month = 11; + else throw new IOException("Invalid month: " + monthString + + "(at line: " + lineNumber + ")"); + + year += (year > 70 ? 1900 : 2000); + } + else + { + System.out.println(" This is a non standard Header"); + + String classification = " "; + } + //date = new MBDate(year, month, day); + + +/* + if (entry != null) + throw new IOException("Header in the middle of a PDB entry" + + "(at line: " + lineNumber + ")"); + else + entry = new PDBEntry(IDcode, date, classification); +} +*/ +} + +public void readCOMPOUND() throws IOException { + if (line.length() >= 69) { + String compound = line.substring(10, 69).trim(); + } + else + { + String compound = line.substring(10); + } + + //entry.title.setCompoundName(compound); +} + +public void readSEQRES() throws IOException { + // lastRecordNumber = 0; + String residue; + String numResidues = line.substring(13, 17).trim(); + int chainID = Character.getNumericValue(line.charAt(11)); + // MBNode res; + + for (int ind = 19; ind < 68; ind = ind + 4) { + residue = line.substring(ind, ind+3); + if (residue.equals(" ")) break; + else { + //res = new PDBResidue(Registry.getLabelInt(residue)); + //entry.primary.addResidue(new Integer(chainID), res); + } + } +} + + +public void readATOM () throws IOException { + /* + inStream = new StreamTokenizer(in); + inStream.commentChar('#'); + inStream.eolIsSignificant(true); + inStream.slashSlashComments(false); + inStream.slashStarComments(false); + inStream.ordinaryChar('/'); + */ + System.out.println("readAtom: line: "+line); + String atomName = line.substring(12,16).trim(); + // The PDB atom names need to be properly typed. Since no protein force field ready convert + //them to regular atoms for now + // Sudhakar 8 Jan 08 + System.out.println("Atom:"+atomName); + atomName= atomName.substring(0,1);// Truncate to first character + //if (atomName.equals("CA")|atomName.equals("CB")|atomName.equals("CG")|atomName.equals("CE")| + //atomName.equals("CD1")|atomName.equals("CD2")|atomName.equals("CE1")|atomName.equals("CE2")| + //atomName.equals("CZ")|atomName.equals("CE3")) atomName="C"; + //if (atomName.equals("NH1")|atomName.equals("NH2")|atomName.equals("NE")| + //atomName.equals("NZ")) atomName="N"; + //if (atomName.equals("OE1")|atomName.equals("OE2")|atomName.equals("OXT")|atomName.equals("NZ")) atomName="N"; + + + sym.addElement(atomName); + System.out.println(" Atom:"+atomName); + int chainID = Character.getNumericValue(line.charAt(21)); + System.out.println("Chain Id:"+chainID); + String reNum = line.substring(22,26); + System.out.println("reNum:"+reNum+"#"); + int resSeq; + if (reNum.equals(" ")){resSeq = 0;} + else{ resSeq = Integer.parseInt(reNum.trim());} + System.out.println("Res Sequence ID:"+resSeq); + + Double xCoord = new Double(line.substring(30,38)); + Double yCoord = new Double(line.substring(38,46)); + Double zCoord; + //Some times the string may not be 54 characters long but still may be a valid input + //then try to the end of the string only! + if (line.length() < 54){ + zCoord = new Double(line.substring(46, line.length())); + } + else { + zCoord = new Double(line.substring(46,54));} + + atomX.addElement(xCoord); + atomY.addElement(yCoord); + atomZ.addElement(zCoord); + + System.out.println(" Atom "+atomName + " X:"+ xCoord+" Y:"+yCoord+" Z:"+zCoord); + // Remember that sequences in the PDB are 1 based! + //entry.primary.addAtom(new Integer(chainID), resSeq - 1, atom); + return; +} +public void readBONDS(){ + inStream = new StreamTokenizer(in); + inStream.commentChar('#'); + inStream.eolIsSignificant(true); + inStream.slashSlashComments(false); + inStream.slashStarComments(false); + inStream.ordinaryChar('/'); + + String [] bondTokens = new String[7]; + StringTokenizer ojt = new StringTokenizer(line," "); + int i = 0; + while (ojt.hasMoreTokens()) + { + bondTokens[i] = ojt.nextToken(); + i++; + } + System.out.println("Number of tokens in this file: "+i); + if ( i==1 ) { + System.out.println("No Atoms given for Connectivity"); + } + else if (i==2){ + firstAtom = Integer.valueOf(bondTokens[1].trim()).intValue(); + System.out.println("First Atom "+firstAtom); + } + else if (i==3){ + firstAtom = Integer.valueOf(bondTokens[1].trim()).intValue(); + System.out.println("First Atom "+firstAtom); + + currentAtom = Integer.valueOf(bondTokens[2].trim()).intValue(); + System.out.println("Second Atom "+currentAtom); + updatebondorder(); + } + else if (i==4){ + firstAtom = Integer.valueOf(bondTokens[1].trim()).intValue(); + System.out.println("First Atom "+firstAtom); + + currentAtom = Integer.valueOf(bondTokens[2].trim()).intValue(); + System.out.println("Second Atom "+currentAtom); + updatebondorder(); + + currentAtom = Integer.valueOf(bondTokens[3].trim()).intValue(); + System.out.println("Third Atom "+currentAtom); + updatebondorder(); + } + else if (i==5){ + firstAtom = Integer.valueOf(bondTokens[1].trim()).intValue(); + System.out.println("First Atom "+firstAtom); + + currentAtom = Integer.valueOf(bondTokens[2].trim()).intValue(); + System.out.println("Second Atom "+currentAtom); + updatebondorder(); + + currentAtom = Integer.valueOf(bondTokens[3].trim()).intValue(); + System.out.println("Third Atom "+currentAtom); + updatebondorder(); + + currentAtom = Integer.valueOf(bondTokens[4].trim()).intValue(); + System.out.println("Fourth Atom "+currentAtom); + updatebondorder(); + + } + else if (i==6){ + firstAtom = Integer.valueOf(bondTokens[1].trim()).intValue(); + System.out.println("First Atom "+firstAtom); + + currentAtom = Integer.valueOf(bondTokens[2].trim()).intValue(); + System.out.println("Second Atom "+currentAtom); + updatebondorder(); + + currentAtom = Integer.valueOf(bondTokens[3].trim()).intValue(); + System.out.println("Third Atom "+currentAtom); + updatebondorder(); + + currentAtom = Integer.valueOf(bondTokens[4].trim()).intValue(); + System.out.println("Fourth Atom "+currentAtom); + updatebondorder(); + + currentAtom = Integer.valueOf(bondTokens[5].trim()).intValue(); + System.out.println("Fifth Atom "+currentAtom); + updatebondorder(); + } + else if (i==7){ + firstAtom = Integer.valueOf(bondTokens[1].trim()).intValue(); + System.out.println("First Atom "+firstAtom); + + currentAtom = Integer.valueOf(bondTokens[2].trim()).intValue(); + System.out.println("Second Atom "+currentAtom); + updatebondorder(); + + currentAtom = Integer.valueOf(bondTokens[3].trim()).intValue(); + System.out.println("Third Atom "+currentAtom); + updatebondorder(); + + currentAtom = Integer.valueOf(bondTokens[4].trim()).intValue(); + System.out.println("Fourth Atom "+currentAtom); + updatebondorder(); + + currentAtom = Integer.valueOf(bondTokens[5].trim()).intValue(); + System.out.println("Fifth Atom "+currentAtom); + updatebondorder(); + + currentAtom = Integer.valueOf(bondTokens[6].trim()).intValue(); + System.out.println("Sixth Atom "+currentAtom); + updatebondorder(); + } +/* + if (line.length() >=11 ) { + if ( line.substring(6,11).equals("") ) { + System.out.println("No Atoms given for Connectivity"); + } + else{ + firstAtom = Integer.valueOf(line.substring(6,11).trim()).intValue(); + System.out.println("First Atom "+firstAtom); + } + if (line.length() < 16) { + int lci = line.length(); + currentAtom = Integer.valueOf(line.substring(11,lci).trim()).intValue(); + System.out.println("Second Atom "+currentAtom); + updatebondorder(); + } + else{ + if (line.substring(11,16).equals("") ) { + System.out.println("No Atoms given for Connectivity"); + } + else{ + currentAtom = Integer.valueOf(line.substring(11,16).trim()).intValue(); + System.out.println("Second Atom "+currentAtom); + updatebondorder(); + } + } + } + if ( line.length()>=21) { + if (line.substring(16,21).equals("") ) { + System.out.println("No Atoms given for Connectivity"); + } + else{ + currentAtom = Integer.valueOf(line.substring(16,21).trim()).intValue(); + System.out.println("Third Atom "+currentAtom); + updatebondorder(); + } + } + if (line.length()>=26) { + if (line.substring(21,26).equals("") ){ + System.out.println("No Atoms given for Connectivity"); + } + else{ + currentAtom = Integer.valueOf(line.substring(21,26).trim()).intValue(); + System.out.println("Fourth Atom "+currentAtom); + updatebondorder(); + } + } + if (line.length() >= 31) { + if (line.substring(26,31).equals("") ) { + System.out.println("No Atoms given for Connectivity"); + } + else{ + currentAtom = Integer.valueOf(line.substring(26,31).trim()).intValue(); + System.out.println("Fifth Atom "+currentAtom); + updatebondorder(); + } + } + */ +} + public void updatebondorder(){ + //firstAtom = (int)line.substring(6,11); + System.out.println("Bond:" + firstAtom+ " Totals BondedAtoms(1) "+bAtom1.size()); + boolean bondExists = false; + + for (int i = 0; i < bAtom1.size(); i++) + { + if ( ((Double)bAtom1.elementAt(i)).intValue() == new Double(firstAtom).intValue() && + ((Double)bAtom2.elementAt(i)).doubleValue() == new Double(currentAtom).intValue() ) + { + int order = ((Double)bOrder.elementAt(i)).intValue(); + order++; + bOrder.setElementAt(new Double(order), i); + bondExists = true; + System.out.println("upped " + firstAtom + " " + currentAtom + " order " + order); + } + } + System.out.println("readBonds: Bonds"+bondExists+" firstAtom "+firstAtom+" CurrentAtom "+currentAtom); + if (bondExists == false && firstAtom < currentAtom) + { + bAtom1.addElement( new Double(firstAtom)); + bAtom2.addElement( new Double(currentAtom)); + bOrder.addElement( new Double(1) ); + System.out.println("added " + firstAtom + " " + currentAtom + " order 1"); + } + + } + +public void process() throws IOException +{ + + +//sym.removeElementAt(sym.size()-1); + +if(debug == false) + { + System.out.println(sym.size() + " " + atomX.size() + " " + atomY.size() + " " + atomZ.size()); + for (int i=0; i< sym.size(); i++) { + System.out.println("i is :"+i+"\n"); + System.out.println("Sym contains : "+ sym.elementAt(i)); + System.out.println(atomX.size() + " " + atomY.size() + " " + atomZ.size()); + System.out.println("atomX : "+ atomX.elementAt(i)); + System.out.println("atomY : "+ atomY.elementAt(i)); + System.out.println("atomZ : "+ atomZ.elementAt(i)); + System.out.println("\n"); + } + System.out.println(bAtom1.size() + " " + bAtom2.size() + " " + bOrder.size()); + + for (int i=0; iget method. + */ + public abstract Object construct(); + + /** + * Called on the event dispatching thread (not on the worker thread) + * after the construct method has returned. + */ + public void finished() { + } + + /** + * A new method that interrupts the worker thread. Call this method + * to force the worker to stop what it's doing. + */ + public void interrupt() { + Thread t = threadVar.get(); + if (t != null) { + t.interrupt(); + } + threadVar.clear(); + } + + /** + * Return the value created by the construct method. + * Returns null if either the constructing thread or the current + * thread was interrupted before a value was produced. + * + * @return the value created by the construct method + */ + public Object get() { + while (true) { + Thread t = threadVar.get(); + if (t == null) { + return getValue(); + } + try { + t.join(); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); // propagate + return null; + } + } + } + + + /** + * Start a thread that will call the construct method + * and then exit. + */ + public SwingWorker() { + final Runnable doFinished = new Runnable() { + public void run() { finished(); } + }; + + Runnable doConstruct = new Runnable() { + public void run() { + try { + setValue(construct()); + } catch (Exception e) {} + finally { + threadVar.clear(); + } + + SwingUtilities.invokeLater(doFinished); + } + }; + + Thread t = new Thread(doConstruct); + threadVar = new ThreadVar(t); + } + + /** + * Start the worker thread. + */ + public void start() { + Thread t = threadVar.get(); + if (t != null) { + t.start(); + } + } +} diff --git a/src/main/java/nanocad/WaltzPanel.java b/src/main/java/nanocad/WaltzPanel.java new file mode 100644 index 0000000..e046ac7 --- /dev/null +++ b/src/main/java/nanocad/WaltzPanel.java @@ -0,0 +1,219 @@ +/*Copyright (c) 2004,University of Illinois at Urbana-Champaign. All rights reserved. + +Developed by: +Chemistry and Computational Biology Group + +NCSA, University of Illinois at Urbana-Champaign + +http://ncsa.uiuc.edu/GridChem + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software") to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Chemistry and Computational Biology Group , NCSA, + University of Illinois at Urbana-Champaign, nor the names of its contributors + may be used to endorse or promote products derived from this Software without + specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ + +package nanocad; + +import java.awt.*; +import java.awt.event.*; + +public class WaltzPanel extends Panel implements ActionListener +{ +//for the first page of waltz + private Label Formula; + private TextField theFormula; + private Label Calculate; + private Label Animate; + private Label CalculationTypes; + private Checkbox EDensity, EOrbital, None, Change, Position; + private CheckboxGroup Calc, Anim; + private Panel formPanel, calcPanel, animPanel, buttonPanel; + private Button Continue, SOver; + +//for the second page of waltz + private Label DelayHead, OptimizeHead, ChargeHead, MultiplicityHead, OrbitalHead, BasisHead, CoordinatesHead; + private Label DelayMessage, OptimizeMessage, Charge, Multiplicity, OrbitalMessage, Basis; + private Label Initial, Final; + private Label[] SymbolLabels, xLabels, yLabels, zLabels; + private Checkbox VerySlow, Slow, Normal, Fast, No, Yes; + private CheckboxGroup DelayCheck, OptimizeCheck; + private TextField MultiplicityField, OrbitalField, InitialField, FinalField; + private TextField[] AtomFields; + private Choice chargeChoice, BasisChoice; + private Button Gamess, RestartThis, RestartAll; + private Panel topsixPanel, coordPanel, DelayPanel, OptimizePanel, ChargePanel, OrbitalPanel, + BasisPanel, MultiplicityPanel, ButtonPanel, DelayCheckPanel; + private Panel[] atomPanels; + +//for both pages + private int pageno; + + WaltzPanel() + { + pageno = 1; + + Formula = new Label("Formula"); + theFormula = new TextField(20); + formPanel = new Panel(new FlowLayout(FlowLayout.LEFT)); + formPanel.add(Formula); + formPanel.add(theFormula); + + Calculate = new Label("Calculate"); + Calc = new CheckboxGroup(); + EDensity = new Checkbox("Electron Densities", Calc, true); + EOrbital = new Checkbox("Electron Orbitals", Calc, false); + calcPanel = new Panel(new FlowLayout(FlowLayout.LEFT)); + calcPanel.add(Calculate); + calcPanel.add(EDensity); + calcPanel.add(EOrbital); + + Animate = new Label("Animate"); + Anim = new CheckboxGroup(); + None = new Checkbox("None", Anim, true); + Change = new Checkbox("Change", Anim, false); + Position = new Checkbox("Position", Anim, false); + animPanel = new Panel(new FlowLayout(FlowLayout.LEFT)); + animPanel.add(Animate); + animPanel.add(None); + animPanel.add(Position); + animPanel.add(Change); + + Continue = new Button("Continue"); + SOver = new Button("Start Over"); + //addActionListener(Continue); //lixh_comment_out + //addActionListener(SOver); + buttonPanel = new Panel(new FlowLayout(FlowLayout.CENTER)); + buttonPanel.add(Continue); + buttonPanel.add(SOver); + + CalculationTypes = new Label("Calculation Types"); + CalculationTypes.setFont(new Font("Times New Roman", Font.BOLD, 18)); + + setLayout(new GridLayout(5, 1)); + add(formPanel); + add(CalculationTypes); + add(calcPanel); + add(animPanel); + add(buttonPanel); + + this.resize(200, 200); + } + + public void actionPerformed(ActionEvent e) + { + String s = e.getActionCommand(); + if (pageno == 1) + { + if (s.equals("Start Over")) + { + EDensity.setState(true); + None.setState(true); + theFormula.setText(""); + + //whatever other stuff we have to do + } + if (s.equals("Continue")) + { + remove(formPanel); + remove(calcPanel); + remove(animPanel); + remove(CalculationTypes); + setupSecondPage(); + } + } + theFormula.setText("Huh??????????"); + } + + public void setupSecondPage() + { + pageno = 2; + + DelayHead = new Label("Delay Between Frames"); + DelayHead.setFont(new Font("Times New Roman", Font.BOLD, 14)); + if (None.getState() == true) + { + DelayMessage = new Label("Frame Delay is only selectable in an Animation"); + DelayPanel = new Panel(); + DelayPanel.setLayout(new GridLayout(1, 2)); + DelayPanel.add(DelayHead); + DelayPanel.add(DelayMessage); + } + else + { + DelayMessage = new Label("Here you may increase or decrease the speed of the animation."); + DelayCheck = new CheckboxGroup(); + VerySlow = new Checkbox("Very Slow", DelayCheck, false); + Slow = new Checkbox("Slow", DelayCheck, false); + Normal = new Checkbox("Normal", DelayCheck, true); + Fast = new Checkbox("Fast", DelayCheck, false); + DelayCheckPanel = new Panel(); + DelayCheckPanel.add(VerySlow); + DelayCheckPanel.add(Slow); + DelayCheckPanel.add(Normal); + DelayCheckPanel.add(Fast); + DelayPanel = new Panel(); + DelayPanel.setLayout(new GridLayout(1, 3)); + DelayPanel.add(DelayHead); + DelayPanel.add(DelayMessage); + DelayPanel.add(DelayCheckPanel); + } + + OptimizeHead = new Label("Geometry Optimization"); + OptimizeHead.setFont(new Font("Times New Roman", Font.BOLD, 14)); + if (Position.getState() == true) + { + OptimizeMessage = new Label("Geometry cannot be optimized for a Position Animation"); + OptimizePanel = new Panel(); + OptimizePanel.setLayout(new GridLayout(1, 2)); + OptimizePanel.add(OptimizeHead); + OptimizePanel.add(OptimizeMessage); + } + else + { + OptimizeMessage = new Label("Optimize Geometry?"); + OptimizeCheck = new CheckboxGroup(); + No = new Checkbox("No", OptimizeCheck, true); + Yes = new Checkbox("Yes", OptimizeCheck, false); + OptimizePanel = new Panel(); + OptimizePanel.setLayout(new GridLayout(1, 4)); + OptimizePanel.add(OptimizeHead); + OptimizePanel.add(OptimizeMessage); + OptimizePanel.add(No); + OptimizePanel.add(Yes); + } + + + topsixPanel = new Panel(); + topsixPanel.setLayout(new GridLayout(3, 2)); + topsixPanel.add(DelayPanel); + topsixPanel.add(OptimizePanel); + + setLayout(new GridLayout(1,2)); + add(topsixPanel); + + } +} + diff --git a/src/main/java/nanocad/ZipExtractor.java b/src/main/java/nanocad/ZipExtractor.java new file mode 100644 index 0000000..fca5361 --- /dev/null +++ b/src/main/java/nanocad/ZipExtractor.java @@ -0,0 +1,100 @@ +/*Copyright (c) 2004,University of Illinois at Urbana-Champaign. All rights reserved. + +Developed by: +Chemistry and Computational Biology Group + +NCSA, University of Illinois at Urbana-Champaign + +http://ncsa.uiuc.edu/GridChem + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software") to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Chemistry and Computational Biology Group , NCSA, + University of Illinois at Urbana-Champaign, nor the names of its contributors + may be used to endorse or promote products derived from this Software without + specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ + +// Unzip.java + +package nanocad; + +import java.io.* ; +import java.util.zip.* ; +import java.text.SimpleDateFormat ; + +public class ZipExtractor { + static final int BUFFER = 1024 ; + public ZipExtractor ( String arg) { + String fileSeparator = System.getProperty("file.separator"); + try { + SimpleDateFormat sdf = new SimpleDateFormat( "mm:ss" ) ; + BufferedOutputStream dest = null ; + FileInputStream fis = new FileInputStream( arg ) ; + ZipInputStream zis = new ZipInputStream( new BufferedInputStream( fis )) ; + ZipEntry entry ; + System.out.println( "ZipExtractor.java::Starting Time : " + sdf.format( new java.util.Date() ) ) ; + while( ( entry = zis.getNextEntry() ) != null ) { + // System.out.println( "Extracting: " + entry ) ; + int count ; + byte data[] = new byte[ BUFFER ] ; + //prepare folders... + if( entry.isDirectory() ) { + //System.out.println("A directory "+entry.getName()+ " will be created"); + ( new File(newNanocad.applicationDataDir + newNanocad.fileSeparator + + entry.getName() ) ).mkdirs() ; + continue ; + } + + int iLastSlash = entry.getName().lastIndexOf("/"); + + /// 2005/10/31 11:37sk + //System.out.println (" The path for the new entry in Zip file is "+ entry.getName().substring( 0, iLastSlash +1)); + + + ( new File( newNanocad.applicationDataDir + newNanocad.fileSeparator + entry.getName().substring( 0, iLastSlash + 1) ) ).mkdirs() ; + ////( new File( entry.getName().substring( 0, iLastSlash + 1) ) ).mkdirs() ; + + //folders prepared + + FileOutputStream fos = new FileOutputStream(newNanocad.applicationDataDir + newNanocad.fileSeparator + + entry.getName()); + dest = new BufferedOutputStream(fos, BUFFER); + while ((count = zis.read(data, 0, BUFFER))!= -1) { + dest.write(data, 0, count); + } + dest.flush(); + dest.close(); + } + zis.close(); + System.out.println( "ZipExtractor.java::Ending Time : " + sdf.format( new java.util.Date() ) ) ; + } + catch(Exception e) { + e.printStackTrace(); + } + } +} + + + + diff --git a/src/main/java/nanocad/atom.java b/src/main/java/nanocad/atom.java new file mode 100644 index 0000000..8366e23 --- /dev/null +++ b/src/main/java/nanocad/atom.java @@ -0,0 +1,620 @@ +package nanocad; +/** + * atom.java - definition of an atom, elements are subclasses of atom + * Copyright (c) 1997,1998 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantabilityx + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.awt.Color; +import java.util.Vector; + +import nanocad.util.AtomTypeFile; + +public abstract class atom +{ + + public static final String rcsid = + "$Id: atom.java,v 1.3 2007/11/16 20:11:31 srb Exp $"; + // hybridizations are a virtual enum + public static final int SP3 = 0; + public static final int SP2 = 1; + public static final int SP = 2; + public static final int NONE = 3; + private static final String hybridnames[] = { "SP3", "SP2", "SP", "NONE" }; + + // these should be instance variables + public int Charge; + public double fractionalCharge; + public int hybridization; + public double[] x; + //public static double[] x; + public double[] v; + public double[] f; + public boolean isTetrahedral = false; + public Vector bonds; + public boolean isUFF = true; // Determines if this is a UFF simulation + // or an MM3 simulation. + public boolean resonant = false; // Flags whether this is part of a resonant chain. + public int myGeom = 0; // Flags the geometry of the atom: + // 1 = linear, 2 = trigonal, 3 = tetrahedral, + // 4 = square planar, 5 = bipyramidal, 6 = octahedral + + // type numbers for nanocad, mm3, uff + private int ncadTypeNum, mm3TypeNum, uffTypeNum; + private int ePairs, geom; + private String ncadTypeString = ""; + private String mm3TypeString = ""; + private String uffTypeString = ""; + + private group myGroup; + + private static AtomTypeFile typeFile; + private boolean marked = false; + private boolean highlighted = false; + private boolean selected = false; + private boolean keep = false; + + public atom () + { + hybridization = NONE; + bonds = new Vector(); + Charge = 0; + fractionalCharge = 0.0; + double zvec[] = { 0.0, 0.0, 0.0 }; + x = v = f = zvec; + } + + public abstract int atomicNumber (); + + public atom(atom a) + { + hybridization = a.hybridization; + Charge = a.Charge; + fractionalCharge = a.fractionalCharge; + x = new double[3]; + v = new double[3]; + f = new double[3]; + + for (int i = 0; i < 3; i++) + { + x[i] = a.x[i]; + v[i] = a.v[i]; + f[i] = a.f[i]; + } + selected = a.isSelected(); + bonds = new Vector(); //since the atom is a copy, it is not necessairly bonded to the same atoms + } + + public bond bondWith (atom a) + { + int i; + if (bonds == null) + return null; + for (i = 0; i < bonds.size(); i++) + { + bond b = (bond) bonds.elementAt(i); + if (b.contains(a)) + return b; + } + return null; + } + + public boolean isBondedWith(atom a) + { + for (int i = 0; i < bonds.size(); i++) + { + if (((bond)bonds.elementAt(i)).a1 == a || ((bond)bonds.elementAt(i)).a2 == a) + return true; + } + return false; + } + + /*** + * method getBond(atom a) + * returns the bond between this atom and atom a + * created 6/08/02, jstrutz + ***/ + public bond getBond(atom a){ + for (int i=0; i 22) && (an < 31)) || ((an > 38) && (an < 49)) || + ((an > 56) && (an < 81)) || (an > 88) ){ + // This is an organo-metallic phosphine + isMetal = true; + } + i++; + } + if(isMetal) uffTypeNum = 29; // else uffTypeNum = 27; + } + else if(myBonds == 3){ + // +5 ox state + uffTypeNum = 28; + } + break; + case 30: // Sulfur + myBonds = currentNumBonds(); + ePairs = 6-currentNumBonds(); + geom = ePairs/2 + currentSigmaBonds(); + if (geom != 4) uffTypeNum = 34; + else isTetrahedral = true; + break; + case 40: // Titanium + myBonds = currentSigmaBonds(); + if(myBonds == 6){ + // octahedral + uffTypeNum = 41; + } + else isTetrahedral = true; + break; + case 45: // Iron + myBonds = currentSigmaBonds(); + if(myBonds == 6){ + // octahedral + uffTypeNum = 46; + } + else isTetrahedral = true; + break; + case 62: // Molybdenum + myBonds = currentSigmaBonds(); + if(myBonds == 4){ + // tetrahedral + uffTypeNum = 63; + isTetrahedral = true; + } + break; + case 95: // Tungsten + myBonds = currentSigmaBonds(); + if(myBonds == 4){ + // tetrahedral + uffTypeNum = 96; + isTetrahedral = true; + } + break; + case 98: // Rhenium + myBonds = currentSigmaBonds(); + if(myBonds == 4){ + // tetrahedral + uffTypeNum = 97; + isTetrahedral = true; + } + break; + default: + } + + theFile.findData(uffTypeNum, 1); + myGeom = theFile.parseInt(8); + uffTypeString = "UFF: #"+uffTypeNum+" "+theFile.parseString(9); + } + catch(Exception e){ + System.out.println("Error in atom type lookup"); + uffTypeString = "UFF: Type Not Found, using Hydrogen"; + uffTypeNum = 1; + e.printStackTrace(); + } + return uffTypeNum; + } + + public void setUFFResonance(){ + // Resonant only if sp2, bonded to two other sp2 atoms. The + // other sp2 atoms bonded to it are also resonant. + System.out.println("Setting resonance"); + // In some circumstances, the apporder might have already been set + // as resonant. If the atom becomes non-resonant, the apporder should + // become _order. This takes care of it. + + // Cycle through all bonds, and set apporder to _order. + for(int i = 0; i < bonds.size(); i++){ + bond b = (bond)(bonds.elementAt(i)); + b.setAppOrder(b.order()); + } + if(myGeom == 2){ + System.out.println("Found sp2"); + int numSP2 = 0; // number of sp2 atoms bonded to this + atom[] resAtoms = new atom[2]; // the actual sp2 atoms bonded to this + // this is sp2 + // cycle through all bonds, and check if that atom is sp2. + // Store that atom, and set it resonant if necessary. + for(int i=0; ((i < bonds.size()) && (numSP2 < 2)); i++){ + bond b = (bond)(bonds.elementAt(i)); + atom a; + if(b.a1 == this) a = b.a2; + else a = b.a1; + if(a.myGeom == 2){ + resAtoms[numSP2] = a; + numSP2 ++; + } + } + if(numSP2 == 2){ + System.out.println("Found resonant structure"); + // Found resonance! + resonant = true; + resAtoms[0].resonant = true; + resAtoms[1].resonant = true; + + switch(this.uffTypeNum){ + case 10: // carbon + uffTypeNum = 9; + break; + case 14: // nitrogen + uffTypeNum = 13; + break; + case 19: // oxygen + uffTypeNum = 18; + break; + case 34: // sulfur + uffTypeNum = 33; + break; + default: + } + + switch(resAtoms[0].uffTypeNum){ + case 10: resAtoms[0].uffTypeNum = 9; break; // C + case 14: resAtoms[0].uffTypeNum = 13; break; // N + case 19: resAtoms[0].uffTypeNum = 18; break; // O + case 34: resAtoms[0].uffTypeNum = 33; break; // S + default: + } + + switch(resAtoms[1].uffTypeNum){ + case 10: resAtoms[1].uffTypeNum = 9; break; // C + case 14: resAtoms[1].uffTypeNum = 13; break; // N + case 19: resAtoms[1].uffTypeNum = 18; break; // O + case 34: resAtoms[1].uffTypeNum = 33; break; // S + default: + } + + // Have to change the typeStrings: + try{ + //AtomDataFile theFile = new AtomDataFile("uffdata.txt"); + AtomDataFile theFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "uffdata.txt"); + theFile.findData(uffTypeNum,1); + uffTypeString = "UFF: #"+uffTypeNum+" "+theFile.parseString(9); + + theFile.findData(resAtoms[0].uffTypeNum,1); + resAtoms[0].uffTypeString = "UFF: #"+resAtoms[0].uffTypeNum+" "+theFile.parseString(9); + + theFile.findData(resAtoms[1].uffTypeNum,1); + resAtoms[1].uffTypeString = "UFF: #"+resAtoms[1].uffTypeNum+" "+theFile.parseString(9); + } + catch(Exception e){ + System.out.println("ERROR: Cannot find UFF data in resonance detection."); + uffTypeString = uffTypeString + " Resonant"; + resAtoms[0].uffTypeString = resAtoms[0].uffTypeString + " Resonant"; + resAtoms[1].uffTypeString = resAtoms[1].uffTypeString + " Resonant"; + e.printStackTrace(); + } + + // Have to set apparent bond orders + getBond(resAtoms[0]).setAppOrder(1.5); + getBond(resAtoms[1]).setAppOrder(1.5); + } + } + } + + public int setMM3TypeNum() { return setMM3TypeNum(false); } + + public int setMM3TypeNum(boolean withPopups) { + int typeNum; + try + { + //AtomDataFile file = new AtomDataFile("pmm3convert.txt"); + AtomDataFile file = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "pmm3convert.txt"); + typeNum = setTypeNum(withPopups); + System.out.println("------------------------"); + System.out.println("ncadTypeNum = "+typeNum); + System.out.println("------------------------"); + if(typeNum < 0) + { + ncadTypeString = "NCAD: Type Not Found"; + mm3TypeString = "MM3: Type Not Found"; + typeNum = -1; + mm3TypeNum = -1; + return -1; + } + + file.skipLines(typeNum); + mm3TypeNum = file.parseInt(1); + if (mm3TypeNum == 50) + mm3TypeNum = 2; + if (mm3TypeNum == 5) + { + for(int i = 0; i < bonds.size(); i++) + { + atom testAtom = ((bond)bonds.elementAt(i)).otherAtom(this); + if (testAtom.atomicNumber() == 7) // N + mm3TypeNum = 23; + else if (testAtom.atomicNumber() == 8) // O + mm3TypeNum = 21; + else if (testAtom.atomicNumber() == 16) // S + mm3TypeNum = 44; + } + } + ncadTypeString = "NCAD: #"+typeNum; + mm3TypeString = "MM3: #"+mm3TypeNum+" "+file.parseString(2); + } + catch(Exception e) + { + System.err.println("Error occurred in MM3 Type Conversion read."); + ncadTypeString = "NCAD: Type Not Found"; + mm3TypeString = "MM3: Type Not Found"; + e.printStackTrace(); + mm3TypeNum = -1; + return -1; + } + return mm3TypeNum; + } + + public int setTypeNum(boolean withPopups) + { + verifyTypeFile(); + if(withPopups) ncadTypeNum = typeFile.getType(myGroup, this); + else ncadTypeNum = typeFile.getTypeWithoutPopups(myGroup, this); + return ncadTypeNum; + } + + public int getTypeNum(){ return getTypeNum(false); } + public int getTypeNum(boolean withPopups) + { + verifyTypeFile(); + int typeNum; + + if(withPopups) + typeNum = typeFile.getType(myGroup, this); + else + typeNum = typeFile.getTypeWithoutPopups(myGroup, this); + + return typeNum; + } + + public int getMM3TypeNum(){ return mm3TypeNum; } + public int getUFFTypeNum(){ return uffTypeNum; } + public String getUFFTypeString() { return uffTypeString; } + public int index () { return myGroup.atomList.indexOf (this); } + +/** + * Insert the method's description here. + * Creation date: (7/19/2000 2:19:42 PM) + * @return boolean + */ + public boolean isHighlighted() { return highlighted; } + +/** + * Insert the method's description here. + * Creation date: (7/7/2000 4:04:26 PM) + * @return boolean + */ + public boolean isMarked() { return marked; } + public boolean isSelected() { return selected; } + public boolean isKept() { return keep; } + + public abstract double mass (); + // these should be defined within elements, as class variables + + public abstract String name (); + // overload me, unless I'm hydrogen + + public void rehybridize () + { + hybridization = NONE; + } + + public String repr() + { + return "<" + symbol() + " " + + hybridnames[hybridization] + " " + + (new Double(x[0])).toString() + " " + + (new Double(x[1])).toString() + " " + + (new Double(x[2])).toString() + ">"; + } + + public void setGroup (group g) + { + myGroup = g; + } + + /** + * Insert the method's description here. + * Creation date: (7/19/2000 2:19:42 PM) + * @param newHighlighted boolean + */ + + public void setHighlighted(boolean newHighlighted) { + highlighted = newHighlighted; + } + + /** + * Insert the method's description here. + * Creation date: (7/7/2000 4:04:26 PM) + * @param newMarked boolean + */ + + //for shift + public void setMarked(boolean newMarked) { + marked = newMarked; + } + + //for alt + public void setSelected(boolean newSelected){ + selected = newSelected; + } + + public void setKept(boolean newKept){ + keep = newKept; + } + + public abstract String symbol (); + public String toString() + { + // Checks to see if the types need to be determined, then + // sets types for all atoms before returning the typeString. + if(myGroup.needsToGetTypes()) myGroup.setTypes(); + return ncadTypeString+" "+mm3TypeString+" "+uffTypeString; + } + + public abstract double vdwEnergy (); + public abstract double vdwRadius (); + /** + * Insert the method's description here. + * Creation date: (6/26/00 10:47:01 AM) + */ + + private static void verifyTypeFile() + { + if(typeFile == null) + { + typeFile = new AtomTypeFile(); + typeFile.readFile("aData2.dat"); + } + } + + public void zeroForce () + { + double newf[] = { 0.0, 0.0, 0.0 }; // Why don't we just set f = {0.0,0.0,0.0} ? + f = newf; + } +} diff --git a/src/main/java/nanocad/bond.java b/src/main/java/nanocad/bond.java new file mode 100644 index 0000000..ba05b69 --- /dev/null +++ b/src/main/java/nanocad/bond.java @@ -0,0 +1,138 @@ +package nanocad; + +/** + * bond.java - definition of a bond + * Copyright (c) 1998 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +public class bond +{ + public static final String rcsid = + "$Id: bond.java,v 1.2 2005/05/14 23:51:01 xli16 Exp $"; + private int _order; // number of bonds represented + private double apporder; // actual order based on resonance + public atom a1, a2; + + + public bond (atom atm1, atom atm2) + { + a1 = atm1; + a2 = atm2; + _order = 1; + apporder = 1; + a1.bonds.addElement (this); + a2.bonds.addElement (this); + a1.rehybridize(); + a2.rehybridize(); + } + + //Ying new constructor with order + public bond (atom atom1, atom atom2, int orders){ + { + a1 = atom1; + a2 = atom2; + _order = orders; + apporder = _order; + try{ +/* + if (a1 == null) + // a1 = new atom(); + a1 = a2; + System.out.println("In bond"); + System.out.println(" a1 = " + atom1); + System.out.println(" a2 = " + atom2);*/ + a1.bonds.addElement(this); + a2.bonds.addElement(this); + // System.out.println("After ....."); + } catch(Exception e1){ System.out.println("Exception in Bond.java " + e1); }; + + a1.rehybridize(); + a2.rehybridize(); + } + } + + //this constructor only copies the order, since we don't know what atoms the bond will go between + public bond(bond b) + { + a1 = null; + a2 = null; + _order = b._order; + apporder = _order; + } + + + public boolean contains (atom atm1) + { + return (a1 == atm1 || a2 == atm1); + } + public void delete () + { + a1.bonds.removeElement (this); + a2.bonds.removeElement (this); + } + public void incrOrder () + { + if (_order < 3) + _order++; + apporder = _order; + /* else throw an exception?? */ + } + + //Ying + + public void setOrder (int o){ + _order= o; + apporder = _order; + } + + public void setAppOrder(double o){ + apporder = o; + } + + public int order () + { + return _order; + } + + public double apporder(){ + return apporder; + } + + public atom otherAtom (atom atm1) + { + if (atm1 == a1) + return a2; + if (atm1 == a2) + return a1; + return null; + } + + public String repr() + { + + return ""; + } +} diff --git a/src/main/java/nanocad/carbon.java b/src/main/java/nanocad/carbon.java new file mode 100644 index 0000000..dc1ac64 --- /dev/null +++ b/src/main/java/nanocad/carbon.java @@ -0,0 +1,106 @@ +package nanocad; + +/** + * carbon.java + * Copyright (c) 1997,1998,1999 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.awt.Color; + +public class carbon extends atom +{ + public static final String rcsid = + "$Id: carbon.java,v 1.2 2005/05/14 23:51:01 xli16 Exp $"; + public carbon () + { + double newx[] = { 0.0, 0.0, 0.0 }; + x = newx; + hybridization = SP3; + } + public carbon (double x0, double x1, double x2) + { + double newx[] = { x0, x1, x2 }; + x = newx; + hybridization = SP3; + } + public carbon (int h, double x0, double x1, double x2) + { + double newx[] = { x0, x1, x2 }; + x = newx; + hybridization = h; + } + + public int atomicNumber () { return 6; } + public Color color () { return Color.gray; } + public int correctNumBonds () { return 4; } + + public double covalentRadius () + { + switch (hybridization) + { + default: + case SP3: return 0.77; + case SP2: return 0.67; + case SP: return 0.6; + } + } + public double mass () { return 12.0; } + public String name () { return "Carbon"; } + public void rehybridize () // based on number of bonds + { + int i, doubles = 0; + for (i = 0; bonds != null && i < bonds.size(); i++) + { + switch (((bond) bonds.elementAt(i)).order()) + { + case 2: + doubles++; + break; + case 3: + hybridization = SP; + return; + } + } + switch (doubles) + { + case 0: + hybridization = SP3; + break; + case 1: + hybridization = SP2; + break; + default: + hybridization = SP; + break; + } + } + public void rehybridize (int hybrid) + { + hybridization = hybrid; + } + public String symbol () { return "C"; } + public double vdwEnergy () { return 0.357; } + public double vdwRadius () { return 1.85; } +} + + diff --git a/src/main/java/nanocad/defineWindow.java b/src/main/java/nanocad/defineWindow.java new file mode 100644 index 0000000..a6b885c --- /dev/null +++ b/src/main/java/nanocad/defineWindow.java @@ -0,0 +1,129 @@ +package nanocad; +import java.awt.event.*; +import java.awt.*; +import java.io.*; +import java.lang.*; + +public class defineWindow extends Frame { + Panel plMain = new Panel(); + File filename = new File(".\\exelisting.txt"); + TextField CSD = new TextField(255); + TextField Chime = new TextField(255); + Label lChime = new Label("Chime: ",Label.RIGHT); + Label lCSD = new Label("CSD: ",Label.RIGHT); + Button browseChime = new Button("Find Chime"); + Button browseCSD = new Button("Find CSD"); + Button okbutt = new Button("OK"); + Button close = new Button("Close"); + textwin saveWin; + private newNanocad nano; + private boolean tocheck,type; + public defineWindow(newNanocad n1) { + if (filename.exists()) + { InputStream inputStream = getClass().getResourceAsStream(".\\exelisting.txt"); + BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); + try { + Chime.setText(in.readLine()); + CSD.setText(in.readLine()); + } + catch (IOException ex) { System.out.println(ex.toString()); } + } + nano = n1; + enableEvents(AWTEvent.WINDOW_EVENT_MASK); + try { + jbInit(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setTitle("Executable Definitions"); + this.add(plMain,null);//.getContentPane().add(plMain, null); + this.setSize(new Dimension(400,250)); + plMain.setLayout(null); + plMain.add(CSD,null); + plMain.add(Chime,null); + plMain.add(lCSD, null); + plMain.add(lChime, null); + plMain.add(browseCSD, null); + plMain.add(browseChime, null); + plMain.add(okbutt, null); + plMain.add(close,null); + lChime.setBounds(new Rectangle(34, 22, 60, 20)); + Chime.setBounds(new Rectangle(114, 22, 170, 20)); + lCSD.setBounds(new Rectangle(34, 52, 60, 20)); + CSD.setBounds(new Rectangle(114, 52, 170, 20)); + okbutt.setFont(new Font("SansSerif", 1, 12)); + okbutt.setBounds(new Rectangle(86, 120, 81, 25)); + okbutt.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + okbutt_actionPerformed(e); + } + }); + close.setFont(new Font("SansSerif", 1, 12)); + close.setBounds(new Rectangle(166, 120, 81, 25)); + close.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + close_actionPerformed(e); + } + }); + browseCSD.setFont(new Font("SansSerif", 1, 12)); + browseCSD.setBounds(new Rectangle(86, 100, 81, 25)); + browseCSD.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + browseCSD_actionPerformed(e); + } + }); + browseChime.setFont(new Font("SansSerif", 1, 12)); + browseChime.setBounds(new Rectangle(166, 100, 81, 25)); + browseChime.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + browseChime_actionPerformed(e); + } + }); + } + + void close_actionPerformed(ActionEvent e) + { + this.dispose(); + } + + void browseCSD_actionPerformed(ActionEvent e) + { + FileDialog f = new FileDialog(this, "Find File", FileDialog.LOAD); + f.show(); + String filename = f.getFile(); + String dirname = f.getDirectory(); + CSD.setText(dirname+filename); + } + + void browseChime_actionPerformed(ActionEvent e) + { + FileDialog f = new FileDialog(this, "Find File", FileDialog.LOAD); + f.show(); + String filename = f.getFile(); + String dirname = f.getDirectory(); + Chime.setText(dirname+filename); + } + + void okbutt_actionPerformed(ActionEvent e) + { + String CSDaddress = CSD.getText(); + String Chimeaddress = Chime.getText(); + + File info = new File(".\\exelisting.txt"); + try + { + System.out.println("Attempting write to .\\exelisting.txt"); + PrintWriter out1 = new PrintWriter((OutputStream)new FileOutputStream(info)); + out1.print(CSDaddress+"\n"); + out1.print(Chimeaddress+"\n"); + out1.close(); + } + catch (IOException ex) + { System.out.println(ex.toString()); } + } +} + diff --git a/src/main/java/nanocad/dipole.java b/src/main/java/nanocad/dipole.java new file mode 100644 index 0000000..ffaee08 --- /dev/null +++ b/src/main/java/nanocad/dipole.java @@ -0,0 +1,110 @@ +/*************************************** + *dipole.java + *Andrew Knox 6/27/01 + * + *This class was written as a way to hold information about dipoles + *for estaticterm.java. I'm not sure how usefull it would be as an + *actual model of a dipole. + */ + +package nanocad; + +public class dipole +{ + private atom firstAtom, secondAtom; + private double chargeConst; + private double distribution; + private boolean valid; + + public dipole(atom first, atom second, double charge, double dist) + { + if (first.isBondedWith(second) == true) + { + firstAtom = first; + secondAtom = second; + chargeConst = charge; + distribution = dist; + valid = true; + } + else + valid = false; + + if (charge == 0.0 || dist == 0.0) + valid = false; + } + + public dipole(atom first, atom second) + { + if (first.isBondedWith(second) == true) + { + firstAtom = first; + secondAtom = second; + } + chargeConst = 0.0; + distribution = 0.0; + valid = false; + } + + public dipole() + { + valid = false; + } + + public boolean isValid() + { + return valid; + } + + public void setConst(double charge, double dist) + { + chargeConst = charge; + distribution = dist; + valid = true; + } + + public double getChargeConst() + { + return chargeConst; + } + + public double getDistribution() + { + return distribution; + } + + public boolean isSameDipole(atom a, atom b) + { + if ((a == firstAtom && b == secondAtom) || (a == secondAtom && b == firstAtom)) + return true; + else + return false; + } + + public boolean isSameDipole(dipole d) + { + if ((firstAtom == d.firstAtom && secondAtom == d.secondAtom) || + (firstAtom == d.secondAtom && secondAtom == d.firstAtom)) + return true; + else + return false; + } + + public boolean sharesAtomWith(dipole d) + { + if (firstAtom == d.firstAtom || firstAtom == d.secondAtom + || secondAtom == d.firstAtom || secondAtom == d.secondAtom) + return true; + else + return false; + } + + public atom getFirst() + { + return firstAtom; + } + + public atom getSecond() + { + return secondAtom; + } +} diff --git a/src/main/java/nanocad/display.java b/src/main/java/nanocad/display.java new file mode 100644 index 0000000..f13bf26 --- /dev/null +++ b/src/main/java/nanocad/display.java @@ -0,0 +1,112 @@ +package nanocad; + +import java.awt.*; +import java.awt.List; +import java.lang.*; +import java.awt.event.*; + +public class display extends Frame { + +public boolean flagtoindicate=false; + + Panel plMain = new Panel(); + Button buttonOK = new Button("OK"); + Button buttonclose = new Button("Close"); + List todisplay = new List(50,false); + String dirname=null,username=null,user,dir; + List newlist; + private newNanocad nano; + textwin saveWin; + + public display(newNanocad n,List newlist,String dir,String user){ + //super(); + enableEvents(AWTEvent.WINDOW_EVENT_MASK); + try { + todisplay = newlist; + dirname= dir; + username = user; + nano = n; + jbInit(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + public void jbInit() throws Exception { + this.setTitle("Load file"); + this.add(plMain,null); + //this.setLayout(null);//.getContentPane().setLayout(null); + plMain.setLayout(null); + this.setSize(new Dimension(300,450)); + plMain.setLayout(null); + plMain.setBounds(new Rectangle(0, 0, 100, 100)); + // plMain.add(errormsg, null); + plMain.add(todisplay,null); + todisplay.setBounds(40,10,200,200); + + + plMain.add(buttonOK, null); + plMain.add(buttonclose,null); + todisplay.setVisible(true); + buttonOK.setFont(new Font("SansSerif", 1, 12)); + buttonOK.setBounds(new Rectangle(100, 278, 40, 32)); + buttonOK.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + buttonOK_actionPerformed(e); + } + } ); + buttonclose.setFont(new Font("SansSerif",1,12)); + buttonclose.setBounds(new Rectangle(160,278,40,32)); + buttonclose.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e){ + buttonclose_actionPerformed(e); + } + } ); + + + } + void buttonclose_actionPerformed(ActionEvent e) + { + this.dispose(); + } + + + + void buttonOK_actionPerformed(ActionEvent e) + { + String filename = todisplay.getSelectedItem(); + + // Check User directory! + String dirname ="/work/csd/temp/"+ username +"/"; + + // To get rid of ".pdb" from the list of files returned by cgi script + int pos; + if( (pos = filename.indexOf("pdb")) != -1) + { + System.out.println("pdb"); + String ext = filename.substring(pos, filename.length()); + String data = nano.receiveFile(filename, ext, dirname); + nano.drawFile(data,ext); + } + } + + /* public static void main(String args[]) + { + try + { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } + catch(Exception exp) + { + } + display aa = new display(); + aa.setVisible(true); + }*/ + + + + + } + + diff --git a/src/main/java/nanocad/dl_atom.java b/src/main/java/nanocad/dl_atom.java new file mode 100644 index 0000000..1e9102c --- /dev/null +++ b/src/main/java/nanocad/dl_atom.java @@ -0,0 +1,110 @@ +package nanocad; + +/** + * dl_atom.java - entry in a drawing list, for drawing an atom + * Copyright (c) 1997,1998 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.awt.*; + +public class dl_atom extends dlentry +{ + public static final String rcsid = + "$Id: dl_atom.java,v 1.2 2005/05/14 23:51:01 xli16 Exp $"; + private double x1[], r1; // screen coordinates for first atom + private atom atm1; + + //Ying 03/20 + private boolean markFlag; //is the atom marked or not + private boolean bogus; //is the atom highlighted or not + private boolean selectFlag; //is atom selected for functional group? + + public dl_atom (atom a, view v) + { + atm1 = a; + vw = v; + x1 = v.xyzToScreen (a.x); + r1 = radiusRatio * a.covalentRadius () * v.zoomFactor; + r1 *= v.perspectiveFactor (x1); + x1[0] -= r1; + x1[1] -= r1; + bogus = a.isHighlighted(); + markFlag = a.isMarked(); + selectFlag = a.isSelected(); + } + + //Ying 03/20 + /*public void paint (Graphics g) + { + int i; + g.setColor (atm1.color ()); + g.fillOval (doubleToInt (x1[0]), doubleToInt (x1[1]), + doubleToInt (2 * r1), doubleToInt (2 * r1)); + if (bogus) + g.setColor (Color.orange); + else + g.setColor (Color.black); + g.drawOval (doubleToInt (x1[0]), doubleToInt (x1[1]), + doubleToInt (2 * r1), doubleToInt (2 * r1)); + } + */ + + //new + + //04/05 Ying + public void paint (Graphics g) + { + int i; + g.setColor (atm1.color ()); + g.fillOval (doubleToInt (x1[0]), doubleToInt (x1[1]), + doubleToInt (2 * r1), doubleToInt (2 * r1)); + + if (atm1.isSelected() == true) + g.setColor(Color.orange); + else + g.setColor(Color.black); + + g.drawOval (doubleToInt (x1[0]), doubleToInt (x1[1]), + doubleToInt (2 * r1), doubleToInt (2 * r1)); + + } + + + public void quickpaint (Graphics g) + { + g.drawOval (doubleToInt (x1[0]), doubleToInt (x1[1]), + doubleToInt (2 * r1), doubleToInt (2 * r1)); + } + + public double zvalue () + { + return x1[2]; + } +} + + + + + + + diff --git a/src/main/java/nanocad/dl_bond.java b/src/main/java/nanocad/dl_bond.java new file mode 100644 index 0000000..fcf2cfc --- /dev/null +++ b/src/main/java/nanocad/dl_bond.java @@ -0,0 +1,149 @@ +package nanocad; + +/** + * dlentry.java - entry in a drawing list + * Copyright (c) 1997 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.awt.*; + +public class dl_bond extends dlentry +{ + public static final String rcsid = + "$Id: dl_bond.java,v 1.2 2005/05/14 23:51:01 xli16 Exp $"; + private double x1[], r1; // screen coordinates for first atom + private double x2[], r2; + private double x3[]; + private bond myBond; + // gap between lines in double and triple bonds, in angstroms + private static final double gap = 0.2; + public dl_bond (bond b, view v) + { + double m; + + x3 = new double[3]; + myBond = b; + vw = v; + + x1 = v.xyzToScreen (myBond.a1.x); + r1 = radiusRatio * myBond.a1.covalentRadius () * v.zoomFactor; + r1 *= v.perspectiveFactor (x1); + + x2 = v.xyzToScreen (myBond.a2.x); + r2 = radiusRatio * myBond.a2.covalentRadius () * v.zoomFactor; + r2 *= v.perspectiveFactor (x2); + + // compute the gap in screen space + x3[0] = x1[1] - x2[1] + x1[0]; + x3[1] = x2[0] - x1[0] + x1[1]; + x3[2] = x1[2]; + // move it back to atom space to correct the length + x3 = v.screenToXyz(x3); + int i; + for (i = 0, m = 0.0; i < 3; i++) + { + double dx = x3[i] - myBond.a1.x[i]; + m += dx * dx; + } + m = gap / Math.sqrt (m); + for (i = 0; i < 3; i++) + x3[i] = myBond.a1.x[i] + m * (x3[i] - myBond.a1.x[i]); + // move it back to screen space + x3 = v.xyzToScreen(x3); + for (i = 0; i < 3; i++) + x3[i] -= x1[i]; + } + public void paint (Graphics g) + { + int i; + double[] v1 = new double[3]; + double[] v2 = new double[3]; + double dv[] = new double[3]; + double lensq = 0.0; + double[] xdiff = new double[3]; + for (i = 0; i < 3; i++) + { + v1[i] = x1[i]; + v2[i] = x2[i]; + xdiff[i] = v1[i] - v2[i]; + lensq += xdiff[i] * xdiff[i]; + } + dv[0] = xdiff[1] * (gap / Math.sqrt(lensq)); + dv[1] = -xdiff[0] * (gap / Math.sqrt(lensq)); + dv[2] = 0.0; + r1 /= Math.sqrt(lensq); + for (i = 0; i < 3; i++) + v1[i] -= r1 * xdiff[i]; + r2 /= Math.sqrt(lensq); + for (i = 0; i < 3; i++) + v2[i] += r2 * xdiff[i]; + switch (myBond.order()) + { + default: + case 1: + drawBondLine (g, Color.black, Color.black, v1, v2); + break; + case 2: + for (i = 0; i < 3; i++) + { + v1[i] += 0.5 * x3[i]; + v2[i] += 0.5 * x3[i]; + } + drawBondLine (g, Color.black, Color.black, v1, v2); + for (i = 0; i < 3; i++) + { + v1[i] -= x3[i]; + v2[i] -= x3[i]; + } + drawBondLine (g, Color.black, Color.black, v1, v2); + break; + case 3: + drawBondLine (g, Color.black, Color.black, v1, v2); + for (i = 0; i < 3; i++) + { + v1[i] += x3[i]; + v2[i] += x3[i]; + } + drawBondLine (g, Color.black, Color.black, v1, v2); + for (i = 0; i < 3; i++) + { + v1[i] -= 2 * x3[i]; + v2[i] -= 2 * x3[i]; + } + drawBondLine (g, Color.black, Color.black, v1, v2); + } + } + public void quickpaint (Graphics g) + { + Color c1 = myBond.a1.color (); + Color c2 = myBond.a2.color (); + // Gray isn't quite dark enough to look good in a wireframe + if (c1 == Color.gray) c1 = Color.black; + if (c2 == Color.gray) c2 = Color.black; + drawBondLine (g, c1, c2, x1, x2); + } + public double zvalue () + { + return (x1[2] + x2[2]) / 2; + } +} diff --git a/src/main/java/nanocad/dlentry.java b/src/main/java/nanocad/dlentry.java new file mode 100644 index 0000000..72f94c8 --- /dev/null +++ b/src/main/java/nanocad/dlentry.java @@ -0,0 +1,124 @@ +package nanocad; + +/** + * dlentry.java - entry in a drawing list + * Copyright (c) 1997 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * or its derived works must display the following acknowledgement: + * This product includes software developed by Will Ware. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.awt.*; +import java.util.Vector; + +public abstract class dlentry +{ + public static final String rcsid = + "$Id: dlentry.java,v 1.2 2005/05/14 23:51:01 xli16 Exp $"; + protected view vw; + // empirical good-looking multiplier + protected static final double radiusRatio = 0.6; + public dlentry () { } + protected int doubleToInt (double x) + { + Double d = new Double (x); + return d.intValue (); + } + protected void drawBondLine (Graphics g, Color c1, Color c2, + double[] v1, double[] v2) + { + Color oldcolor = g.getColor (); + double[] u = new double[2], vmid = new double[3]; + vmid[0] = (v1[0] + v2[0]) / 2; + vmid[1] = (v1[1] + v2[1]) / 2; + vmid[2] = (v1[2] + v2[2]) / 2; + g.setColor (c1); + g.drawLine (doubleToInt (v1[0]), + doubleToInt (v1[1]), + doubleToInt (vmid[0]), + doubleToInt (vmid[1])); + g.setColor (c2); + g.drawLine (doubleToInt (vmid[0]), + doubleToInt (vmid[1]), + doubleToInt (v2[0]), + doubleToInt (v2[1])); + g.setColor (oldcolor); + } + public void drawLineToAtom (atom a, double x, double y, Graphics g) + { + double[] scr = vw.xyzToScreen (a.x); + g.setColor (Color.black); + g.drawLine (doubleToInt (scr[0]), + doubleToInt (scr[1]), + doubleToInt (x), + doubleToInt (y)); + } + public abstract void paint (Graphics g); + public void paint (Vector v, Graphics g) + { + int i; + zsort (v, 0, v.size() - 1); + for (i = 0; i < v.size (); i++) + ((dlentry) v.elementAt (i)).paint (g); + } + public abstract void quickpaint (Graphics g); + public void quickpaint (Vector v, Graphics g) + { + int i; + for (i = 0; i < v.size (); i++) + ((dlentry) v.elementAt (i)).quickpaint (g); + } + protected void zsort (Vector v, int lo0, int hi0) + { + int lo = lo0; + int hi = hi0; + double mid; + if (hi0 > lo0) + { + mid = ((dlentry) v.elementAt ((lo0 + hi0) / 2)).zvalue (); + while (lo <= hi) + { + while ((lo < hi0) && + (((dlentry) v.elementAt (lo)).zvalue () < mid)) + ++lo; + while ((hi > lo0) && + (((dlentry) v.elementAt (hi)).zvalue () > mid)) + --hi; + if (lo <= hi) + { + Object temp; + temp = v.elementAt (lo); + v.setElementAt (v.elementAt (hi), lo); + v.setElementAt (temp, hi); + ++lo; + --hi; + } + } + if (lo0 < hi) + zsort (v, lo0, hi); + if (lo < hi0) + zsort (v, lo, hi0); + } + } + public abstract double zvalue (); +} diff --git a/src/main/java/nanocad/dlforce.java b/src/main/java/nanocad/dlforce.java new file mode 100644 index 0000000..f943870 --- /dev/null +++ b/src/main/java/nanocad/dlforce.java @@ -0,0 +1,104 @@ +package nanocad; + +/** + * dlentry.java - entry in a drawing list + * Copyright (c) 1997 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * or its derived works must display the following acknowledgement: + * This product includes software developed by Will Ware. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.awt.*; + +public class dlforce extends dlentry +{ + public static final String rcsid = + "$Id: dlforce.java,v 1.2 2005/05/14 23:51:01 xli16 Exp $"; + private static Color force_color = Color.green; + private double begin[], end[], orig[], f[], zval; + private double forceMultiplier; + private double arrowHeadSize = 5; + private final static double sqrtHalf = Math.sqrt (0.5); + public dlforce (double origin[], double f0[], view v) + { + int i; + orig = new double[3]; + f = new double[3]; + vw = v; + begin = v.xyzToScreen (origin); + for (i = 0; i < 3; i++) + { + f[i] = f0[i]; + orig[i] = origin[i]; + } + setForceMultiplier (10.0); + } + public void paint (Graphics g) + { + /* dumb for now, smarten it up later */ + quickpaint (g); + } + public void quickpaint (Graphics g) + { + drawBondLine (g, force_color, force_color, begin, end); + double[] u = new double[3]; + double[] v = new double[3]; + u[0] = end[1] - begin[1]; + u[1] = begin[0] - end[0]; + v[0] = end[0] - begin[0]; + v[1] = end[1] - begin[1]; + double m = Math.sqrt (u[0] * u[0] + u[1] * u[1]); + if (m > arrowHeadSize) + m = sqrtHalf * arrowHeadSize / m; + else + m = sqrtHalf; + u[0] *= m; + u[1] *= m; + v[0] *= m; + v[1] *= m; + double m1 = Math.sqrt (u[0] * u[0] + u[1] * u[1]); + g.setColor (force_color); + g.drawLine (doubleToInt (end[0]), + doubleToInt (end[1]), + doubleToInt (end[0] + u[0] - v[0]), + doubleToInt (end[1] + u[1] - v[1])); + g.drawLine (doubleToInt (end[0]), + doubleToInt (end[1]), + doubleToInt (end[0] - u[0] - v[0]), + doubleToInt (end[1] - u[1] - v[1])); + } + public void setForceMultiplier (double fm) + { + int i; + end = new double[3]; + forceMultiplier = fm; + for (i = 0; i < 3; i++) + end[i] = orig[i] + f[i] * forceMultiplier; + end = vw.xyzToScreen (end); + zval = (begin[2] + end[2]) / 2; + } + public double zvalue () + { + return zval; + } +} diff --git a/src/main/java/nanocad/drawPanel.java b/src/main/java/nanocad/drawPanel.java new file mode 100644 index 0000000..978a98e --- /dev/null +++ b/src/main/java/nanocad/drawPanel.java @@ -0,0 +1,87 @@ +/////////////////////////////////////////// +// drawPanel.java +// July 2001 by Andrew Knox +// The panel class on which nanocad draws the molecule. +/////////////////////////////////////////// + +package nanocad; + +import java.awt.*; + +public class drawPanel extends Panel +{ + private group grp; + private boolean geomMode; + private double geomValue; + private int geomSize; + + public void setGroupToPaint (group g) + { + grp = g; + } + + public void clear() + { + Graphics g = this.getGraphics(); + char[] name = {'x','y','z'}; + Rectangle r = this.getBounds(); + g.clearRect (0, 0, r.width, r.height); + g.setColor (Color.red); + g.drawLine(550,100,600,100); + g.drawChars(name,0,1,610,110); + g.drawLine(550,100,550,50); + g.drawChars(name,1,1,540,50); + g.drawLine(550,100,510,120); + g.drawChars(name,2,1,500,130); + } + + public void wireframePaint() + { + grp.wireframePaint(); + } + + public void wireframePaint(group g) + { + g.wireframePaint(); + } + + public void paint(Graphics g) + { + this.clear(); + super.paint(g); + grp.paint(g); + if (geomMode == true) + paintGeometryInfo(); + } + + public void setGeometryMode(boolean v) + { + geomMode = v; + if(v) paintGeometryInfo(); + } + + public void setGeometryValue(int s, double v) + { + geomSize = s; + geomValue = v; + geomMode = true; + } + + //Andrew Knox 06/01/01 + public void paintGeometryInfo() + { + Graphics g = this.getGraphics(); + + geomValue *= 100; + geomValue = Math.round((float)geomValue); + geomValue /= 100; + + g.drawString ("Geometry mode: molecule alteration restricted.", 50, 30); + if (geomSize == 2) + g.drawString ("bond length: " + geomValue, 50, 50); + if (geomSize == 3) + g.drawString ("bond angle: " + geomValue, 50, 50); + if (geomSize == 4) + g.drawString ("dihedral: " + geomValue, 50, 50); + } +} diff --git a/src/main/java/nanocad/energyMinimizeAlgorythm.java b/src/main/java/nanocad/energyMinimizeAlgorythm.java new file mode 100644 index 0000000..2469043 --- /dev/null +++ b/src/main/java/nanocad/energyMinimizeAlgorythm.java @@ -0,0 +1,748 @@ +package nanocad; + +import nanocad.minimize.bracket; +import nanocad.minimize.calcval; +import nanocad.minimize.minval; + +import java.util.Vector; + +public abstract class energyMinimizeAlgorythm +//superclass of energyMinimization functions +{ +/* + protected Vector templist = null; + protected Vector temptermList = null; + // Tells us whether the temps have been inited + protected boolean tempsInited = false; +*/ + public static final int ITMAX = 200; + public static final double EPS = 1.0e-10; + public static final double GOLD = 1.618034; + public static final double GLIMIT = 100.0; + public static final double TINY = 1.0e-20; + public static final double TOL = 2.0e-8; + public static final double ZEPS = 1.0e-10; + public static final double CGOLD = 0.3819660; + protected double [] pcom; + protected double [] xicom; + protected group groupToMinimize; + protected Vector termList; + protected newNanocad windowForUpdates; + protected Vector atomList; + protected int funEvals = 0; // The number of function evaluations required. + +// public abstract void initTemps(Vector myAtomList); + + protected abstract void enumerateTerms(); + + /** + * Insert the method's description here. + * Creation date: (8/7/2000 10:48:49 AM) + * @return boolean + */ + public boolean defaultsUsed() + { + for(int i = 0; i < termList.size(); i++) + { if(((term) termList.elementAt(i)).defaultsUsed()) + { System.out.println("Defaults used with "+ + ((term) termList.elementAt(i)).name()+" term."); + return false; + } + + } + return true; + } + + public double potentialOnly(newNanocad windowForUpdates) + { if (groupToMinimize.needsToEnumerateTerms()) enumerateTerms(); + double maxForce = 0; + for(int i = 0; i < atomList.size(); i++) + { ((atom)(atomList.elementAt(i))).zeroForce(); + } + + System.out.println("Potential is:"); + for (int i = 0; i < termList.size(); i++) + { ((term) termList.elementAt(i)).computeForces(); + System.out.println (((term) termList.elementAt(i)).name()+": "+ + ((term) termList.elementAt(i)).getpotential()); + } + + System.out.println("Total sum of potentials:"); + String prevName = ((term) termList.elementAt(0)).name(); + double potentialSum = 0; + for (int i = 0; i < termList.size(); i++) + { + if (prevName.equals(((term) termList.elementAt(i)).name())) + potentialSum += ((term) termList.elementAt(i)).getpotential(); + else + { System.out.println (prevName+": "+potentialSum); + prevName = ((term) termList.elementAt(i)).name(); + potentialSum = ((term) termList.elementAt(i)).getpotential(); + } + } + System.out.println (prevName+": "+potentialSum); + + potentialSum = 0; + for(int i = 0; i < termList.size(); i++) + potentialSum += ((term)termList.elementAt(i)).getpotential(); + for(int i = 0; i < atomList.size(); i++) + { int j; + double flensq, force; + atom a = (atom) atomList.elementAt(i); + for(j=0, flensq = 0.0; j < 3; j++) + { flensq += a.f[j]*a.f[j]; + } + if(flensq > 0) + { // maxForce is max(magnitude of force,old maxForce) + maxForce = FMAX(Math.sqrt(flensq),maxForce); + } + } + maxForce *= 100000; + maxForce = (int) maxForce; + maxForce /= 100000; + potentialSum *= 100000; + potentialSum = (int) potentialSum; + potentialSum /= 100000; + windowForUpdates.atomInfo("Max force = "+maxForce+" Potential = "+potentialSum); + return potentialSum; + } + + /** + * Insert the method's description here. + * Creation date: (7/25/2000 3:08:36 PM) + * @return java.util.Vector + */ + public Vector getTermList() { + return termList; + } + + public boolean minimizeGroup(newNanocad windowForUpdates, boolean useCG) + { if (groupToMinimize.needsToEnumerateTerms()) + { //System.out.println("Needed to enumerate terms in minimizeGroup"); + enumerateTerms(); + potentialOnly(windowForUpdates); + } + // Set the types, and set resonance as well. + // Here we can ask if Sulfur is +2, +4, or +6; + // if Oxygen is zeolite; + // if Tungsten is +2 or +4. + + // **************************************************************************** + // * Conjugate Gradient Algorithm. + // **************************************************************************** + if(useCG) + { calcval myCalc = SteepestDescent(100); // We want to do this to get closer. + double ftol = 0.01; + myCalc = calculate(ftol); + double thepotential = myCalc.thepotential; + double theforce = myCalc.theforce; + thepotential *= 100000; + thepotential = (int) thepotential; + thepotential /= 100000; + theforce *= 100000; + theforce = (int) theforce; + theforce /= 100000; + windowForUpdates.atomInfo("CG done. Max force = "+theforce+" Potential = "+thepotential); + System.out.println(funEvals+" function evaluations in CG"); + System.out.println("Potential = "+myCalc.thepotential); + System.out.println("Force = "+myCalc.theforce); + System.out.println("-----------------------------------"); + for(int termsize = 0; termsize < termList.size(); termsize++){ + term tempTerm = (term)(termList.elementAt(termsize)); + System.out.println(tempTerm.repr()+" : "+tempTerm.getpotential()); + } + } + + // *************************************************************************** + // * Steepest Descent Algorithm. + // *************************************************************************** + + else{ + calcval myCalc = SteepestDescent(1000); + for (int i = 0; i < atomList.size(); i++) + { + atom currAtom = (atom)atomList.elementAt(i); + double[][] normal = new double[currAtom.bonds.size()-1][3]; + for (int k = 1; k < currAtom.bonds.size(); k++) + { + atom b1 = (atom) (((bond)currAtom.bonds.elementAt(0)).otherAtom(currAtom)); + atom b2 = (atom) (((bond)currAtom.bonds.elementAt(k)).otherAtom(currAtom)); + double pq[] = {0.0,0.0,0.0}; + double qr[] = {0.0,0.0,0.0}; + for (int f = 0; f < 3; f++) + { + pq[f] = b1.x[f] - currAtom.x[f]; + qr[f] = b2.x[f] - currAtom.x[f]; + } + normal[k-1] = windowForUpdates.crossProduct(pq,qr); + normal[k-1][0] /= Math.sqrt(windowForUpdates.dotProduct(normal[k-1],normal[k-1])); + normal[k-1][1] /= Math.sqrt(windowForUpdates.dotProduct(normal[k-1],normal[k-1])); + normal[k-1][2] /= Math.sqrt(windowForUpdates.dotProduct(normal[k-1],normal[k-1])); + } + if ((currAtom.bonds.size() > 2) && + (((normal[0][0] == normal[1][0]) && (normal[0][1] == normal[1][1]) + && (normal[0][2] == normal[1][2])) || + ((normal[0][0] == -normal[1][0]) && (normal[0][1] == -normal[1][1]) + && (normal[0][2] == -normal[1][2]))) + && currAtom.isTetrahedral) + { currAtom.x[0] += 0.001; + currAtom.x[1] -= 0.005; + currAtom.x[2] += 0.01; + SteepestDescent(50); + } + } + + double minPot = myCalc.thepotential; + double maxForce = myCalc.theforce; + double stepSize = myCalc.thestepsize; + System.out.println("Potential = "+myCalc.thepotential); + System.out.println("Force = "+maxForce); + System.out.println("Step size was "+stepSize); + maxForce *= 100000; + maxForce = (int) maxForce; + maxForce /= 100000; + minPot *= 100000; + minPot = (int) minPot; + minPot /= 100000; + windowForUpdates.atomInfo("SD done. Max force = "+maxForce+" Potential = "+minPot); + System.out.println(funEvals+" function evaluations in SD"); + System.out.println("-----------------------------------"); + for(int termsize = 0; termsize < termList.size(); termsize++) + { term tempTerm = (term)(termList.elementAt(termsize)); + System.out.println(tempTerm.repr()+" : "+tempTerm.getpotential()); + } + } + + // ****************************************************************************** + // * End Steepest Descent Algorithm + // ****************************************************************************** + + return defaultsUsed(); + + } //end minimize group function + + /** + * Insert the method's description here. + * Creation date: (7/25/2000 3:08:36 PM) + * @param newTermList java.util.Vector + */ + public void setTermList(Vector newTermList) + { + termList = newTermList; + } + + // Absolute value algorithm. + protected double fabs(double f) + { if(f >= 0.0) return f; + else return -f; + } + + // Returns a with b's sign (unless b is zero, then it returns a with negative.) + protected double SIGN(double a, double b) + { if(b>0.0) return fabs(a); + else return (- fabs(a)); + } + + // returns the max of a and b. + protected double FMAX(double a, double b) + { return a > b ? a : b; // if a > b return a, otherwise return b. + } + + /* p initially contains the starting point. + The convergence tolerance on the function + value is input as ftol. + Returned quantities are p + (the location of the minimum) + linmin is called to perform line minimizations. */ + public calcval calculate(double ftol) + { + double maxForce = 0.0; + + // The following are convenient numerically for CG + double dgg = 0.0; // |(gradient of next iteration)^2| + double gg = 0.0; // |gradient^2| + int n = atomList.size() * 3; // Size of the one-d array + double myMinPot = 0.0; // Return value, needs to be + // declared here so it can be + // reported after too many iterations. + + // Vectors needed to use CG... together, they represent an orthonormal basis + // from which to get the new direction. + double[] g = new double[n]; // g is the -gradient vector + double[] h = new double[n]; // h is the direction vector + double[] xi = new double[n]; // xi is the gradient vector + + for (int i = 0; i < atomList.size(); i++) + ((atom) atomList.elementAt(i)).zeroForce(); + + // Starting force values + for (int i = 0; i < termList.size(); i++) + { + term t1 = (term) termList.elementAt(i); + double value = t1.computeForces(); + } + + // Get the max force + for(int i = 0; i < atomList.size(); i++){ + double flensq, force; + int j; + atom a = (atom) atomList.elementAt(i); + for (j = 0, flensq = 0.0; j < 3; j++){ + flensq += a.f[j]*a.f[j]; + } + if(flensq > 0.0){ + force = Math.sqrt(flensq); + if (force > maxForce) maxForce = force; + } + } + + // xi contains the gradient, which was calculated as + // the force in the previous loop + for(int i=0; i 0.0){ + force = Math.sqrt(flensq); + if (force > maxForce) maxForce = force; + } + } + //System.out.println("************************"); + //System.out.println("Calculate iteration "+its); + //System.out.println("Max force is "+maxForce); + //System.out.println("Potential is "+myMinPot); + //System.out.println("************************"); + + // Terminate? + if((myMinPot < ftol) && (maxForce < ftol) && (myVal.xmin < 0.00001)){ + System.out.println(its+" iterations in calculate"); + System.out.println("xmin is "+myVal.xmin); + return new calcval(maxForce, myMinPot); + } + + for(int i=0; i cx ? ax : cx); + x = w = v = bx; + fw = fv = fx = f1dim(x); + for(iter = 1; iter <= ITMAX; iter++) + { + xm = 0.5 * ( a + b); + tol2 = 2.0 * (tol1 = tol * fabs(x) + ZEPS); + if(fabs(x-xm) <= (tol2-0.5*(b-a))) + { + xmin = x; + return new minval(fx,xmin); + } + if(fabs(e) > tol1) // Try a parabolic fit + { + r = (x-w)*(fx-fv); + q = (x-v)*(fx-fw); + p = (x-v)*q-(x-w)*r; + q = 2.0*(q-r); + if(q>0.0) p = -p; + q = fabs(q); + etemp = e; + e = d; + + // Is the fit acceptable? + if(fabs(p) >= fabs(0.5*q*etemp) || p <= q * (a-x) || p>= q*(b-x)) + d = CGOLD * (e = (x >= xm ? a-x : b-x)); + + + else // Take a golden section step + { + d = p / q; + u = x + d; + if(u-a < tol2 || b-u < tol2) + d = SIGN(tol1, xm-x); + } + } + else d = CGOLD * (e=(x>=xm ? a-x : b-x)); + u = (fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); + fu = f1dim(u); + if(fu<=fx) + { + if(u>=x) a = x; + else b = x; + // SHFT(v,w,x,u); + v = w; + w = x; + x = u; + + // SHFT(fv, fw, fx, fu); + fv = fw; + fw= fx; + fx= fu; + } + else + { + if(u fa) + { + // swapping ax and bx + dum = ax; + ax = bx; + bx = dum; + + // swapping fa and fb + dum = fb; + fb = fa; + fa = dum; + + } + + // Golden section step + double cx = bx + GOLD * (bx - ax); + double fc = f1dim(cx); + + int iter = 0; + while(fb > fc) + { + iter++; + r = (bx - ax) * (fb - fc); + q = (bx - cx) * (fb - fa); + u = bx - (( bx - cx) *q - (bx - ax) *r) / (2.0 * SIGN(FMAX(fabs(q-r), TINY),q-r)); + + ulim = bx + GLIMIT * (cx - bx); + + if((bx - u)*(u-cx) > 0.0) + { + fu = f1dim(u); + if(fu < fc) + { + ax = bx; + bx = u; + fa = fb; + fb = fu; + return new bracket(ax,bx,cx,fa,fb,fc); + } + else if(fu > fb) + { + cx = u; + fc = fu; + return new bracket(ax,bx,cx,fa,fb,fc); + } + u = cx+ GOLD * (cx - bx); + fu = f1dim(u); + } + else if( (cx - u) * (u - ulim) > 0.0) + { + fu = f1dim(u); + if(fu < fc) + { //SHFT(bx, cx, u, cx+GOLD*(cx-bx)) + bx = cx; + cx = u; + u = cx + GOLD * (cx - bx); + + // SHFT(fb, fc, fu, func(u)) + fb = fc; + fc = fu; + fu = f1dim(u); + } + } + else if( (u-ulim) * (ulim - cx) >= 0.0) + { + u = ulim; + fu = f1dim(u); + } + else + { + u = cx + GOLD * (cx - bx); + fu = f1dim(u); + } + // SHFT(*ax, *bx, *cx, u) + ax = bx; + bx = cx; + cx = u; + + // SHFT(*fa, *fb, *fc, fu) + fa = fb; + fb = fc; + fc = fu; + } + return new bracket(ax,bx,cx,fa,fb,fc); + } + + protected double f1dim(double x) + { +// if(!tempsInited) initTemps(atomList); + + int n = atomList.size() * 3; + double f = 0.0; + +// atomList -> templist + for(int i=0; i < n; i++) + { // Test the new value of x, and see what result we get. + ((atom) atomList.elementAt(i/3)).x[i%3] = pcom[i] + x*xicom[i]; + } + + funEvals ++; + for (int i = 0; i < atomList.size(); i++) + ((atom) atomList.elementAt(i)).zeroForce(); + + // termList -> temptermList + for (int i = 0; i < termList.size(); i++) + { double value = ((term) termList.elementAt(i)).computeForces(); + f += ((term) termList.elementAt(i)).getpotential(); + } + + // f is the sum of potentials of every element. + return f; + } + + public calcval SteepestDescent(int numIterations) + { int loopCtr = 0; // Control for the loop + double stepSize = 0.15; // Magnitude of the stepsize + double maxForce = 0.0; // max force seen after each iteration + double minPot = 0.0; // total potential seen at the end + + for (loopCtr = 0; loopCtr < numIterations; loopCtr++) + { double prevMaxForce = Double.POSITIVE_INFINITY; // max force seen at prev. iteration + double thePot = 0.0; // potential seen after each iteration + + // Zero all forces + for (int i = 0; i < atomList.size(); i++) + ((atom) atomList.elementAt(i)).zeroForce(); + funEvals ++; + maxForce = 0.0; + + // Compute the forces and get the potential; intially, no change to + // the atom, so this is the starting configuration + for (int i = 0; i < termList.size(); i++) + { // The following line is only here to calculate potential + term currentTerm = ((term) termList.elementAt(i)); + double value = currentTerm.computeForces(); + thePot += currentTerm.getpotential(); + } + // Analyze the force data, and step size + for (int i = 0; i < atomList.size(); i++) + { + int j; + double flensq = 0.0, force, m; + atom a = (atom) atomList.elementAt(i); + + // computes the total force on each atom + for (j = 0; j < 3; j++) + flensq += a.f[j] * a.f[j]; + if (flensq > 0.0) + { force = Math.sqrt(flensq); + // The stepsize is determined by the arbitrary multiplier + // stepSize, and normalized so each component steps a + // relative distance compared to the component of force + // on the atom. + if (force > stepSize) + m = stepSize / force; + else m = 1; + for(j=0; j<3; j++) + { a.x[j] += m*a.f[j]; + // Move the atom in the steepest descent dir by m. + } + maxForce = FMAX(force,maxForce); + } + + // Decrease the step size only if the current step actually + // decreased the force. Will lead to much slower convergence, + // but might also reduce oscillations when we get near the + // minimum. Has the effect of minimizing larger components of + // error (from the minimum), while oscillating around the smaller + // components until the step size is small enough to get closer + // to them. Also keeps step size constant if it is sufficiently small. + if((prevMaxForce >= maxForce) && (stepSize > 0.000002)) + stepSize *= 0.98; + + prevMaxForce = maxForce; // is this correct? -stenhous 12/9/02 + } + + //System.out.println("Iteration "+loopCtr); + //System.out.println("Max force is "+maxForce); + //System.out.println("Potential is "+thePot); + if (maxForce < .001) + { System.out.println("Finished early"); + minPot = thePot; + break; + } + if (loopCtr % 25 == 0) // print an update every 25 iterations + { windowForUpdates.atomInfo("Max force = " + maxForce+" Min pot = "+thePot); + } + minPot = thePot; + } + // Positions may have changed since the last calculation, so update forces. + // In particular, position has changed if we reach the maximum number + // of iterations. + maxForce = 0; + minPot = 0; + for(int i = 0; i < atomList.size(); i++) + { ((atom)(atomList.elementAt(i))).zeroForce(); + } + for(int i = 0; i < termList.size(); i++) + { term t1 = (term)(termList.elementAt(i)); + t1.computeForces(); + minPot += t1.getpotential(); + } + for(int i = 0; i < atomList.size(); i++) + { int j; + double flensq, force; + atom a = (atom) atomList.elementAt(i); + for(j=0, flensq = 0.0; j < 3; j++) + { flensq += a.f[j]*a.f[j]; + } + if(flensq > 0) + { // maxForce is max(magnitude of force,old maxForce) + maxForce = FMAX(Math.sqrt(flensq),maxForce); + } + } + return new calcval(maxForce, minPot, stepSize); + } +} diff --git a/src/main/java/nanocad/error.java b/src/main/java/nanocad/error.java new file mode 100644 index 0000000..5f017fd --- /dev/null +++ b/src/main/java/nanocad/error.java @@ -0,0 +1,69 @@ +package nanocad; + + +import java.awt.*; +import java.lang.*; +import java.awt.event.*; + +public class error extends Frame { + +public boolean flagtoindicate=false; + + Panel plMain = new Panel(); + Label errormsg = new Label(); + Button buttonOK = new Button(); + String message; + + public error() { } + public error(String msg) { + //super(); + enableEvents(AWTEvent.WINDOW_EVENT_MASK); + try { + message = msg; + jbInit(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setTitle("Error"); + this.add(plMain,null); + //this.setLayout(null);//.getContentPane().setLayout(null); + plMain.setLayout(null); + this.setSize(new Dimension(400,200)); + plMain.setLayout(null); + plMain.setBounds(new Rectangle(0,0,400,200)); + plMain.add(errormsg, null); + plMain.add(buttonOK, null); + errormsg.setText(message); + errormsg.setBounds(30,10,320,40); + buttonOK.setLabel("OK"); + buttonOK.setFont(new Font("SansSerif", 1, 12)); + buttonOK.setBounds(new Rectangle(125, 78, 40, 32)); + buttonOK.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + buttonOK_actionPerformed(e); + } + }); + + + //this.getLayout().addLayoutComponent(plMain);//.getContentPane().add(plMain, null); + + + + } + + void buttonOK_actionPerformed(ActionEvent e) + { + this.dispose(); + } + + + + + + } + + diff --git a/src/main/java/nanocad/gauss.example b/src/main/java/nanocad/gauss.example new file mode 100644 index 0000000..207170d --- /dev/null +++ b/src/main/java/nanocad/gauss.example @@ -0,0 +1,40 @@ + + case 2: // Create a Gaussian Template close and go back to edit mode + if (clearFlag == true) break; + else + { + // runAsApplication + System.out.println(" Case 2 Gaussian Input Template being Generated"); + // + // call editjobpaneltextwindow and add text to display + // RHB: change the text on the editJobPanel!!! + // This should not take too terribly long to do now that + // I have figured out where it goes + String gaussOut = GaussianOutput(grp.getXYZ()); + // write to a file now + boolean append = false; + try + { + File f = new File(defaultDirStr+fileSeparator + + "tmp.txt"); + FileWriter fw = new FileWriter(f, append); + fw.write(gaussOut); + System.err.println("gaussOut = "); + System.err.println(gaussOut); + fw.close(); + } + catch (IOException ioe) + { + System.err.println("newNanocad:output Gaussian:" + + "IOException"); + System.err.println(ioe.toString()); + ioe.printStackTrace(); + } + + + // + // close molecular editor + this.setVisible(false); + break; + } + diff --git a/src/main/java/nanocad/gauss_exam1 b/src/main/java/nanocad/gauss_exam1 new file mode 100644 index 0000000..b7e3002 --- /dev/null +++ b/src/main/java/nanocad/gauss_exam1 @@ -0,0 +1,27 @@ + public String GaussianOutput(String molInfo) + { + String templateTop = "# SP, RHF/STO-3G punch=archive trakio" + + " scf=conventional\n" + " \n" + + "Gaussian Test Job 00\n" + + "Water with archiving\n" + " \n" + + "0 1\n"; + //ArrayList molInfsplit = (ArrayList) Arrays.asList(molInfo.split("\n")); + String text = templateTop; + StringTokenizer molTok = new StringTokenizer(molInfo, "\n"); + //int n = molInfsplit.size(); + //int i; + // ignore first line of molInfo + String line = molTok.nextToken(); + int i = 0; + while (molTok.hasMoreTokens()) + { + line = molTok.nextToken(); + if ((line.length() > 0) && (i > 0)) + { + text = text + line + "\n"; + System.err.println(line); + } + i++; + } + return text; + } diff --git a/src/main/java/nanocad/getname.java b/src/main/java/nanocad/getname.java new file mode 100644 index 0000000..e4bb000 --- /dev/null +++ b/src/main/java/nanocad/getname.java @@ -0,0 +1,87 @@ +package nanocad; + +import java.lang.*; +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; + +public class getname extends Frame { + +// static LoginFailScreen frame3; + private String s; + JPanel plMain = new JPanel(); + JLabel labelfile = new JLabel(); + JTextField tffile= new JTextField(); + + JButton buttonOK = new JButton(); + JButton buttonCancel = new JButton(); + String s1 = new String(); + + + + + public getname() { + super(); + + try { + jbInit(); + } + catch (Exception e) { + System.out.println("wrong"); + e.printStackTrace(); + } + } + + private void jbInit() throws Exception { + // this.getContentPane().setLayout(null); + this.setSize(new Dimension(374, 226)); + plMain.setLayout(null); + plMain.setBounds(new Rectangle(0, 0, 392, 273)); + labelfile.setText("Filename:"); + labelfile.setFont(new Font("SansSerif", 0, 12)); + labelfile.setBounds(new Rectangle(24, 22, 41, 15)); + + tffile.setBounds(new Rectangle(96, 17, 120, 24)); + + buttonOK.setText("OK"); + buttonOK.setBounds(new Rectangle(16, 147, 81, 25)); + buttonOK.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + buttonOK_actionPerformed(e); + } + }); + buttonCancel.setText("Cancel"); + buttonCancel.setBounds(new Rectangle(112, 146, 81, 25)); + buttonCancel.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + buttonCancel_actionPerformed(e); + } + }); + this.setTitle("Login Screen"); + // this.getContentPane().add(plMain, null); + plMain.add(labelfile, null); + + plMain.add(tffile, null); + + plMain.add(buttonOK, null); + plMain.add(buttonCancel, null); + + } +void buttonOK_actionPerformed(ActionEvent e) + + { +s1 = tffile.getText(); + +} + + void buttonCancel_actionPerformed(ActionEvent e) + { + System.exit(0); + } +public static void main(String [] args){ +getname togetname = new getname(); +togetname.setVisible(true); +} + + +} diff --git a/src/main/java/nanocad/group.java b/src/main/java/nanocad/group.java new file mode 100644 index 0000000..5698e38 --- /dev/null +++ b/src/main/java/nanocad/group.java @@ -0,0 +1,1238 @@ +package nanocad; + +/** + * group.java - group of atoms and terms + * Copyright (c) 1997,1998,1999 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.awt.*; +import java.lang.Math; +import java.util.Vector; + +public class group +{ + public static final String rcsid = + "$Id: group.java,v 1.2 2005/05/14 23:51:01 xli16 Exp $"; + public Vector atomList; + public Vector bondList; + public boolean changedSinceLastSave = false; + private boolean needToEnumerateTerms; + private boolean needToGetTypes = true; + + private boolean showForces = false; + + private Vector drawingList; + public drawPanel mypanel; + public view v; + public double forceMultiplier = 100.0; + private textwin tw; + + //two group for rest group and changed group; + public group chgGrp; + public group restGrp; + + /* these are for formatting strings and numbers */ + private final static int LEFT = 0; + private final static int RIGHT = 1; + private String scanString; + + //these are used for coordintes changes + public double perspDist = 400; + public double zoomFactor = 25; + private double xCenter = 200; + private double yCenter = 200; + private double zCenter = 0; + private double x1[], r1; + + /* Let's support two standards for molecule file formats, PDB and XYZ. + * Also, support a "native" file format with hybridization and bond order. + * This enum must agree with the order of menu items in nanocad.java. + * That's ugly, and should be fixed. + */ + + public final static int SAVEPDB = 0; + public final static int SAVEXYZ = 1; + + public int fileMode; + + /** + *Following are different kinds of constructor for group + */ + public group () + { + v = new view (); + empty (); + } + + public group (drawPanel p) + { + mypanel = p; + v = new view (); + empty (); + } + + public group (drawPanel p, textwin d) + { + mypanel = p; + v = new view (); + empty (); + tw = d; + } + + /** + *This is a constructor from two sub-groups + */ + public group (group g1, group g2, drawPanel p){ + empty(); + mypanel = g2.mypanel; + + v = g2.v; + + for (int i = 0; i 3) + return; + while (true) + { + bond b = a1.bondWith(a2); + if (b != null) + { + if (b.order() == ord) + break; + else + b.incrOrder(); + } + else + { + b = new bond (a1, a2); + bondList.addElement (b); + } + } + needToEnumerateTerms = true; + needToGetTypes = true; + changedSinceLastSave = true; + } + + /** + *different paint functions + */ + private void bagLine () + { + int i; + for (i = 0; + i < scanString.length() && + scanString.charAt(i) != '\n'; + i++); + if (scanString.length() > (i + 1)) + scanString = + scanString.substring(i + 1); + else + scanString = ""; + } + + public void bubblePaint() + { + int i; + Vector dlist = new Vector (); + dl_atom dla = null; + for (i = 0; i < atomList.size (); i++) + { + dla = new dl_atom ((atom) atomList.elementAt (i), v); + dlist.addElement (dla); + } + if (dla != null) + dla.quickpaint (dlist, mypanel.getGraphics ()); + } + + /** + *recenter atoms + */ + public void centerAtoms () + { + int i, j; + atom a; + double[] x = { 0, 0, 0 }; + for (i = 0; i < atomList.size (); i++) + { + a = (atom) atomList.elementAt (i); + for (j = 0; j < 3; j++) + x[j] += a.x[j]; + } + for (j = 0; j < 3; j++) + x[j] /= atomList.size (); + for (i = 0; i < atomList.size (); i++) + { + a = (atom) atomList.elementAt (i); + for (j = 0; j < 3; j++) + a.x[j] -= x[j]; + } + updateViewSize (); + } + + /** + *delete atom + */ + public void deleteAtom (atom a) + { + int i; + if (atomList.size () == 0) + return; + needToEnumerateTerms = true; + needToGetTypes = true; + changedSinceLastSave = true; + // remove all bonds connected to the atom + while (a.bonds.size() > 0) + { + bond b = (bond) a.bonds.elementAt(0); + b.delete(); + bondList.removeElement(b); + } + // remove the atom + atomList.removeElement (a); + } + + /** + *delete bond + */ + public void deleteBond (atom a1, atom a2) + { + bond b = a1.bondWith (a2); + if (b == null) + { + b = a2.bondWith(a1); + if (b == null) + return; + } + needToEnumerateTerms = true; + needToGetTypes = true; + changedSinceLastSave = true; + bondList.removeElement (b); + a1.bonds.removeElement (b); + a2.bonds.removeElement (b); + a1.rehybridize (); + a2.rehybridize (); + } + + /** + *paint function + */ + public void drawLineToAtom (atom a, double x, double y) + { + dl_atom dummy = new dl_atom (a, v); + dummy.drawLineToAtom (a, x, y, mypanel.getGraphics ()); + } + + /** + *empty group data members + */ + public void empty () + { + needToEnumerateTerms = true; + needToGetTypes = true; + changedSinceLastSave = true; + atomList = new Vector (); + bondList = new Vector (); + } + + /** + *data format + */ + private String formatDouble (double x, int intpart, int fracpart) + { + boolean neg = false; + String fraction; + if (x < 0.0) + { + neg = true; + x = -x; + } + fraction = formatFractionalPart (x, fracpart); + if (neg) + { + if (((int) x) == 0) + { + String intstr = "-0"; + while (intstr.length() < intpart) + intstr = " " + intstr; + return intstr + "." + fraction; + } + else + return formatInt (-((int) x), intpart, RIGHT) + "." + fraction; + } + else + return formatInt (((int) x), intpart, RIGHT) + "." + fraction; + } + + private String formatFractionalPart (double x, int fracpart) + { + String fracstr = ""; + if (x < 0.0) x = -x; + x -= (int) x; + while (fracstr.length() < fracpart) + { + int xi; + x *= 10; + xi = (int) x; + x -= xi; + fracstr = fracstr + (char) (xi + '0'); + } + return fracstr; + } + + private String formatInt (int x, int spaces, int direction) + { + String intstr = ""; + boolean neg = false; + if (x < 0) + { + neg = true; + x = -x; + } + if (x == 0) + intstr = "0"; + else + while (x > 0) + { + intstr = ((char) ((x % 10) + '0')) + intstr; + x /= 10; + } + if (neg) + intstr = '-' + intstr; + if (direction == LEFT) + while (intstr.length() < spaces) + intstr = intstr + ' '; + else + while (intstr.length() < spaces) + intstr = ' ' + intstr; + return intstr; + } + + private String formatString (String x, int spaces, int direction) + { + int i; + String spc = ""; + for (i = 0; i < spaces - x.length(); i++) + spc += " "; + if (direction == LEFT) + return x + spc; + else + return spc + x; + } + + private String formatUnsignedInt (int x, int spaces, int direction) + { + String intstr = ""; + if (x == 0) + intstr = "0"; + else + while (x > 0) + { + intstr = ((char) ((x % 10) + '0')) + intstr; + x /= 10; + } + if (direction == LEFT) + while (intstr.length() < spaces) + intstr = intstr + ' '; + else + while (intstr.length() < spaces) + intstr = ' ' + intstr; + return intstr; + } + + /** + * Insert the method's description here. + * Creation date: (5/29/00 3:22:26 PM) + * @return java.util.Vector + */ + + public Vector getAllPairs() { + return null; // Should there be some other function also? + } + + /** + *get the native format for save, load or export + */ + public String getNativeFormat() + { + System.out.println("new into group"); + int i; + changedSinceLastSave = false; + + String s = atomList.size() + "\n"; + for (i = 0; i < atomList.size(); i++) + s += ((atom) atomList.elementAt(i)).repr() + "\n"; + + s += bondList.size() + "\n"; + for (i = 0; i < bondList.size(); i++) + s += ((bond) bondList.elementAt(i)).repr() + "\n"; + + + String c = "connectivity:\n " ; + int[] arr1 = new int[bondList.size()]; + int[] arr2 = new int[bondList.size()]; + double[] arr3 = new double[bondList.size()]; + + for (int k = 0; k< bondList.size(); k++) { + bond tmp = (bond)bondList.elementAt(k); + arr1[k]= tmp.a1.index(); + arr2[k] =tmp.a2.index(); + arr3[k]= tmp.order(); + } + + int t1,t2; + double t3; + for (int pass = 1; pass arr1[m+1]){ + + t1 = arr1[m]; + arr1[m]=arr1[m+1]; + arr1[m+1]= t1; + + t2 = arr2[m]; + arr2[m]=arr2[m+1]; + arr2[m+1]= t2; + + t3 = arr3[m]; + arr3[m]=arr3[m+1]; + arr3[m+1]= t3; + } + } + + } + + for (int l = 0; l < arr1.length; l++){ + c += "\n "; + } + + System.out.println("the connectivity is :" +c); + return (s + c); + } + + /** + *get the PDB format + */ + public String getPDB(boolean includeOne) + { + //change new sym from "C" to "C1"; + Vector v = newSymbol(atomList); + + int i; + changedSinceLastSave = false; + + String s =""; + for (i = 0; i < atomList.size(); i++) + { + atom a = (atom) atomList.elementAt(i); + s += "ATOM " + + formatInt(i+1, 5, RIGHT) + + " " + + //formatString(a.symbol()+"*", 4, LEFT) + + formatString((String)v.elementAt(i)+"*", 4, LEFT); + if (includeOne == true) + s += " 1 "; + s +=formatDouble(a.x[0], 4, 3) + + formatDouble(a.x[1], 4, 3) + + formatDouble(a.x[2], 4, 3) + + "\n"; + }//14 & 13 blank + + if (true) + for (i = 0; i < atomList.size(); i++) + { + int maxBondOrder = 0; + atom current = (atom) atomList.elementAt(i); + for (int k = 0; k < current.bonds.size(); k++) + maxBondOrder = Math.max(maxBondOrder, ((bond)current.bonds.elementAt(k)).order()); + + for (int k = 1; k <= maxBondOrder; k++) + { + s += "CONECT"; + s += formatInt(i + 1, 5, RIGHT); + for (int j = 0; j < current.bonds.size(); j++) + { + if ( ((bond)current.bonds.elementAt(j)).order() >= k) + s += formatInt( ((bond)current.bonds.elementAt(j)).otherAtom(current).index()+1, 5, RIGHT); + } + s += "\n"; + } + } + return s; + } + + + /** + * keeps solidarity between new and old code. + */ + public String getPDB() {return getPDB(true);} + + /** + *update symbol expression from "C" to "C1...Cn" + */ + public Vector newSymbol(Vector atomL){ + String tmp; + boolean change = false; + int j=0; + atom a, b; + Vector symV = new Vector(); + + for (int i = 0; i< atomL.size(); i++){ //21, 0->20 + + a = (atom) atomL.elementAt(i); + + if(i 0) + { + String zs, symbol, hybrid; + double x, y, z; + int h = atom.SP3; + if (scanString.charAt(0) != '<') + continue; + scanString = scanString.substring(1); + symbol = scanWord(); + hybrid = scanWord(); + x = scanDouble(); + y = scanDouble(); + zs = scanWord(); + if (zs.charAt(zs.length() - 1) != '>') + continue; + try { z = (new Double(zs.substring(0,zs.length() - 1))).doubleValue(); } + catch (Exception e) { z = 2.0; } + + /* hybridizations */ + if (hybrid.equals("NONE")) + h = atom.NONE; + else if (hybrid.equals("SP3")) + h = atom.SP3; + else if (hybrid.equals("SP2")) + h = atom.SP2; + else if (hybrid.equals("SP")) + h = atom.SP; + + /* which element */ + if (symbol.equals("H")) + addAtom (new hydrogen (x, y, z)); + else if (symbol.equals("C")) + addAtom (new carbon (h, x, y, z)); + else if (symbol.equals("O")) + addAtom (new oxygen (h, x, y, z)); + else if (symbol.equals("N")) + addAtom (new nitrogen (h, x, y, z)); + bagLine(); + } + + numbonds = scanInt(); + bagLine(); + while (numbonds-- > 0) + { + String ordstr; + int index1, index2, order; + if (!scanString.substring(0,6).equals(" 0) + { + symbol = scanWord(); + x = scanDouble(); + y = scanDouble(); + z = scanDouble(); + if (symbol.equals("H")) + addAtom (new hydrogen (x, y, z)); + else if (symbol.equals("C")) + addAtom (new carbon (atom.SP3, x, y, z)); + else if (symbol.equals("O")) + addAtom (new oxygen (atom.SP3, x, y, z)); + else if (symbol.equals("N")) + addAtom (new nitrogen (atom.SP3, x, y, z)); + } + guessBondInfo(); + } + + private void skipBlanks () + { + int i; + for (i = 0; + i < scanString.length() && + isBlank(scanString.charAt(i), false); + i++); + scanString = scanString.substring(i); + } + + /** + * Insert the method's description here. + * Creation date: (7/25/2000 3:21:45 PM) + */ + public void termsEnumerated() + { + needToEnumerateTerms = false; + } + + /** + *notify text window for events + */ + public void textWindowNotify(String s) + { + int i; + scanString = s; + + if (scanString.substring(0,5).equals("Paste")) + { + // If user left "Paste your..." in the window, skip over it. + bagLine (); + } + skipBlanks(); + + switch (fileMode) + { + case SAVEPDB: + getPDB(); + break; + + case SAVEXYZ: + getXYZ(); + break; + + case 2: + getPDB(); + break; + + default: + break; + } + } + + /** + *update view size + */ + public void updateViewSize () + { + Rectangle r = mypanel.bounds(); + v.updateSize (r.width, r.height); + } + + /** + *paint with wire frame only + */ + public void wireframePaint () + { + int i, j; + Vector dlist = new Vector (); + dl_atom dla = null; + dl_bond dlb = null; + + for (i = 0; i < atomList.size (); i++) + { + atom a = (atom) atomList.elementAt (i); + if (a.currentNumBonds () == 0) + { + dla = new dl_atom (a, v); + dlist.addElement (dla); + } + } + + for (i = 0; i < atomList.size (); i++) + { + atom a1 = (atom) atomList.elementAt (i); + for (j = 0; j < a1.bonds.size (); j++) + { + bond b = (bond) a1.bonds.elementAt(j); + atom a2 = b.otherAtom(a1); + if (a1.x[0] < a2.x[0]) + { + dlb = new dl_bond (b, v); + dlist.addElement (dlb); + } + } + } + + if (dla != null) { + dla.quickpaint (dlist, mypanel.getGraphics ()); + } + else if (dlb != null) { + dlb.quickpaint (dlist, mypanel.getGraphics ()); + } + } + + + /** + *consider the perspective factor + */ + public double perspectiveFactor (double z) + { + double denom = perspDist - z; + if (denom < 5) denom = 5; + return perspDist / denom; + } + + /** + *xyz to screen transformation + */ +/* public double[] xyzToScreen (double[] xyz) + { + double x, y, z, denom; + double[] rvec = new double[3]; + // rotate + x = m[0] * xyz[0] + m[1] * xyz[1] + m[2] * xyz[2]; + y = m[3] * xyz[0] + m[4] * xyz[1] + m[5] * xyz[2]; + z = m[6] * xyz[0] + m[7] * xyz[1] + m[8] * xyz[2]; + // zoom + x = zoomFactor * x; + y = zoomFactor * y; + z = zoomFactor * z; + // perspective + double perspective = perspectiveFactor (z); + x *= perspective; + y *= perspective; + // translation + rvec[0] = x + xCenter; + rvec[1] = y + yCenter; + rvec[2] = z + zCenter; + return rvec; + } */ + +} diff --git a/src/main/java/nanocad/hydrogen.java b/src/main/java/nanocad/hydrogen.java new file mode 100644 index 0000000..c9f22f9 --- /dev/null +++ b/src/main/java/nanocad/hydrogen.java @@ -0,0 +1,67 @@ +package nanocad; + +/** + * hydrogen.java + * Copyright (c) 1997 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * or its derived works must display the following acknowledgement: + * This product includes software developed by Will Ware. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.awt.Color; + +public class hydrogen extends atom +{ + public static final String rcsid = + "$Id: hydrogen.java,v 1.2 2005/05/14 23:51:01 xli16 Exp $"; + public hydrogen () + { + double newx[] = { 0.0, 0.0, 0.0 }; + x = newx; + hybridization = NONE; + } + public hydrogen (double x0, double x1, double x2) + { + double newx[] = { x0, x1, x2 }; + x = newx; + hybridization = NONE; + } + public int atomicNumber () { return 1; } + public Color color () { return Color.white; } + public int correctNumBonds () { return 1; } + public double covalentRadius () + { + return 0.3; + } + public double mass () { return 1.0; } + public String name () { return "Hydrogen"; } + public void rehybridize () + { + } + public void rehybridize (int hybrid) + { + } + public String symbol () { return "H"; } + public double vdwEnergy () { return 0.382; } + public double vdwRadius () { return 1.2; } +} diff --git a/src/main/java/nanocad/indianaWindow.java b/src/main/java/nanocad/indianaWindow.java new file mode 100644 index 0000000..4851e86 --- /dev/null +++ b/src/main/java/nanocad/indianaWindow.java @@ -0,0 +1,198 @@ +package nanocad; + +import java.awt.event.*; +import java.awt.*; +import java.io.*; +import java.lang.*; +import java.net.*; + +public class indianaWindow extends Frame { + Panel plMain = new Panel(); + TextField Formula = new TextField(7); + TextField CompoundName = new TextField(7); + TextField stoplimit = new TextField("5", 4); + Label lstoplimit = new Label("Stopping Limit: ", Label.LEFT); + Label lCompoundName = new Label("Compound Name: ", Label.RIGHT); + Label lFormula = new Label("Formula: ", Label.RIGHT); + Button okbutt = new Button("Search"); + Button close = new Button("Close"); + textwin saveWin; + private Indiana ind; + private newNanocad nano; + private boolean tocheck, type; + public searchResult result; + + public indianaWindow(newNanocad n1) { + + nano = n1; + + + enableEvents(AWTEvent.WINDOW_EVENT_MASK); + try { + jbInit(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void jbInit() throws Exception { +// this.setTitle("indianadata"); + if (nano.callDatabase == 1) + this.setTitle("Indiana Database Search"); + if (nano.callDatabase == 2) + this.setTitle("CSD Search"); + + this.add(plMain, null);//.getContentPane().add(plMain, null); +// this.getContentPane().setLayout(null); + this.setSize(new Dimension(400, 250)); + plMain.setLayout(null); + plMain.add(CompoundName, null); +// plMain.add(Formula,null); + plMain.add(lCompoundName, null); +// plMain.add(lFormula,null); + plMain.add(stoplimit, null); + plMain.add(lstoplimit, null); + plMain.add(okbutt, null); + plMain.add(close, null); +// lFormula.setBounds(new Rectangle(34, 22, 60, 20)); +// Formula.setBounds(new Rectangle(174, 22, 70, 20)); + lCompoundName.setBounds(new Rectangle(10, 52, 150, 20)); + CompoundName.setBounds(new Rectangle(174, 52, 70, 20)); + lstoplimit.setBounds(new Rectangle(42, 82, 110, 20)); + stoplimit.setBounds(new Rectangle(174, 82, 70, 20)); + okbutt.setFont(new Font("SansSerif", 1, 12)); + okbutt.setBounds(new Rectangle(86, 120, 81, 25)); + okbutt.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + okbutt_actionPerformed(e); + } + }); + + close.setFont(new Font("SansSerif", 1, 12)); + close.setBounds(new Rectangle(166, 120, 81, 25)); + close.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + close_actionPerformed(e); + } + }); + } + + void close_actionPerformed(ActionEvent e) { + this.dispose(); + } + + void okbutt_actionPerformed(ActionEvent e) { + String formu = Formula.getText(); + String comp = CompoundName.getText(); + + String chk = stoplimit.getText(); + String encodedchk = null; + + /*Generate query as required by Indiana Database and pass it to them, + obtain PDB file and reload PDB in nanocad interface */ + + + // if(CompoundName.getText() != "") + if (comp.length() > 1) { + chk = "0"; + tocheck = false; + } else if (Formula.getText() != "") { + chk = "1"; + tocheck = true; + //Process formula string + } + + + // To use CGI script to call Indiana.java and also to pass values of + // compound name and formula + + String encodedCompoundName = URLEncoder.encode(CompoundName.getText()); + String encodedFormula = URLEncoder.encode(Formula.getText()); + encodedchk = URLEncoder.encode(chk); + String databasecgi = null; + try { + if (nano.callDatabase == 1) + databasecgi = "http://chemviz.ncsa.uiuc.edu/cgi-bin/indiana.cgi"; + + //System.out.println("Before calling csd.cgi"); + if (nano.callDatabase == 2) + databasecgi = "http://gw144.iu.xsede.org/cgi-bin/csd/csd_search.cgi?name=" + encodedCompoundName + "&limit=1"; + + URL urlcgi = new URL(databasecgi); + URLConnection conn1 = urlcgi.openConnection(); +// conn1.setDoOutput(true); +// PrintWriter out1 = new PrintWriter(conn1.getOutputStream()); +// if(chk.equals("0")) +// out1.println(encodedCompoundName + "= 0=" + stoplimit.getText() ); +// else +// if(chk.equals("1")) +// out1.println(encodedFormula + "= 1=" + stoplimit.getText() ); + +/* +//CHK if following needed I doubt! + if(Formula.getText() != "") + out1.println(encodedFormula + "= 1"); + if(CompoundName.getText() != "") + { + out1.println(encodedCompoundName + "= 0"); + } +//CHK if following needed I doubt! TILL HERE +*/ +// out1.close(); + int count = 0; + + //Reading file from the cgi output + String line = null; + BufferedReader inStr1 = new BufferedReader(new InputStreamReader(conn1.getInputStream())); + String b = ""; + while ((line = inStr1.readLine()) != null) { + count++; + System.out.println("Line:" + line); + b = b + line + "\n"; + } + inStr1.close(); + if ((b.indexOf("ATOM") < 0)) { + // if((count==1) | (count==2)){ + if (count == 1) + type = true; + else + type = false; + String msgg = " "; + if (type) { + msgg = "The IUMSC database does not support this search"; + nano.atomInfo(" "); + error not_found = new error(msgg); + //searchResult sea = new searchResult("csdsearch-21744.pdb"); + //sea.setVisible(true); + not_found.setVisible(true); + } else { + nano.atomInfo(" "); + msgg = "The CSD database does not support this search"; + error not_found = new error(msgg); + not_found.setVisible(true); + } + } else { + if (nano.callDatabase == 1) { + File temp = File.createTempFile(System.currentTimeMillis() + "-mol", ".mol2"); + BufferedWriter bw = new BufferedWriter(new FileWriter(temp)); + bw.write(b); + bw.close(); + nano.loadFile(temp.getAbsolutePath(), ""); + }else + result = new searchResult(b, nano); + } + nano.callDatabase = 0; + } catch (MalformedURLException mx) { + saveWin = new textwin("URL Exception", "", false); + saveWin.setVisible(true); + saveWin.setText("Exception : " + mx.toString()); + } catch (IOException e1) { + saveWin = new textwin("IO Exception", "", false); + saveWin.setVisible(true); + saveWin.setText("Exception : " + e1.toString()); + } + + this.dispose(); + } +} + diff --git a/src/main/java/nanocad/indianadata.java b/src/main/java/nanocad/indianadata.java new file mode 100644 index 0000000..60a7704 --- /dev/null +++ b/src/main/java/nanocad/indianadata.java @@ -0,0 +1,154 @@ +package nanocad; + +//package nanocad; +//import mm3MinimizeAlgorythm; +import java.awt.event.*; +import java.awt.*; +import java.io.*; +import java.lang.*; +import java.net.*; +public class indianadata extends Frame { + Panel plMain = new Panel(); + TextField Formula = new TextField(7); + TextField CompoundName = new TextField(7); + Label lCompoundName = new Label("Compound Name: ",Label.RIGHT); + Label lFormula = new Label("Formula: ",Label.RIGHT); + Button okbutt = new Button("OK"); + Button close = new Button("Close"); + public indianadata() { + + enableEvents(AWTEvent.WINDOW_EVENT_MASK); + try { + jbInit(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + private void jbInit() throws Exception { + this.setTitle("indianadata"); + this.add(plMain,null);//.getContentPane().add(plMain, null); +// this.getContentPane().setLayout(null); + this.setSize(new Dimension(400,250)); + plMain.setLayout(null); + plMain.add(CompoundName,null); + plMain.add(Formula,null); + plMain.add(lCompoundName,null); + plMain.add(lFormula,null); + plMain.add(okbutt, null); + plMain.add(close,null); + lFormula.setBounds(new Rectangle(34, 22, 60, 20)); + Formula.setBounds(new Rectangle(174, 22, 70, 20)); + lCompoundName.setBounds(new Rectangle(34, 52, 110, 20)); + CompoundName.setBounds(new Rectangle(174, 52, 70, 20)); + okbutt.setFont(new Font("SansSerif", 1, 12)); + okbutt.setBounds(new Rectangle(86, 100, 81, 25)); + okbutt.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + okbutt_actionPerformed(e); + } + }); + + close.setFont(new Font("SansSerif", 1, 12)); + close.setBounds(new Rectangle(166, 100, 81, 25)); + close.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + close_actionPerformed(e); + } + }); + } + + void close_actionPerformed(ActionEvent e) +{ + this.dispose(); +} + void okbutt_actionPerformed(ActionEvent e) + { + String formu = Formula.getText(); + String comp = CompoundName.getText(); + + //textwin testWin = new textwin("ANUKaps","",false); + //testWin.setVisible(true); + //newNanocad inst=null; + + String query_string = null; + /*Generate query as required by Indiana Database and pass it to them, + obtain PDB file and reload PDB in nanocad interface */ + + if(CompoundName.getText() != "") + { + query_string = "http://www.iumsc.indiana.edu/db/search.jsp?start=1&compoundName=" + CompoundName.getText() + "&raw=pdb"; + + //testWin.setText(query_string); + } + // for parsing formula here atom1Relation is assumed to be "=" + // similarly for all other atoms + + + if(Formula.getText() != "") + { + //Parse the formula string into alphabets and numbers + // and then generate the query string reqd by Indiana + + String atom1Name = null,atom1Num = null; + String atom2Name = null,atom2Num = null; + String atom3Name = null,atom3Num = null; + + query_string = "http://www.iumsc.indiana.edu/db/search.jsp?start=1&atom1Name=" + atom1Name + "&atom1Relation==atom1Num=" + atom1Num + "&&atom2Name=" + atom2Name + "&atom2Relation==atom2Num=" + atom2Num + "&&atom3Name=" + atom3Name + "&atom3Relation==atom3Num=" + atom3Num + "&raw=pdb"; + + } + try{ + URL url_indiana = new URL(query_string); + URLConnection conn_indiana = url_indiana.openConnection(); + BufferedReader inFile = new BufferedReader (new InputStreamReader(conn_indiana.getInputStream())); + + +// testWin.setText(query_string); + String line = null; + String final_file = null; + int counter =0; + while ((line = inFile.readLine()) !=null) + { + + if(counter < 5) // we do not need 5 initial line REMARKS in the PDB file + counter++; else + final_file += line; + } + System.out.println(final_file); + //testWin.setText(final_file); + // testWin.setVisible(true); + // inst.drawFile(final_file); +}catch(Exception e1) +{ System.err.println(e1); } + + /* If Indiana people return us a file line by line, then + we can receive it as above and copy paste some 20 lines + of code from loadpdb() BUT if they give a file as a whole + then we should save it in some area on disc may be use Case 6 + save a file function and then call loadPdb(); */ + +/* + loadpdb(complete_path_of_file); +*/ + + + System.exit(0); + } + + + + public static void main(String args[]) + { + /* try + { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } + catch(Exception exp) + { + }*/ + indianadata aa = new indianadata(); + // aa.addWindowListener(new WindowAdapter(){ + aa.setVisible(true); + } +} + diff --git a/src/main/java/nanocad/minimize/.DS_Store b/src/main/java/nanocad/minimize/.DS_Store new file mode 100644 index 0000000..4e5b27b Binary files /dev/null and b/src/main/java/nanocad/minimize/.DS_Store differ diff --git a/src/main/java/nanocad/minimize/._.DS_Store b/src/main/java/nanocad/minimize/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/nanocad/minimize/._.DS_Store differ diff --git a/src/main/java/nanocad/minimize/bracket.java b/src/main/java/nanocad/minimize/bracket.java new file mode 100644 index 0000000..c4c7f84 --- /dev/null +++ b/src/main/java/nanocad/minimize/bracket.java @@ -0,0 +1,13 @@ +package nanocad.minimize; + +public class bracket{ + public double low,mid,high,flow,fmid,fhigh; + public bracket(double l,double m,double h,double fl,double fm,double fh){ + low = l; + mid = m; + high = h; + flow = fl; + fmid = fm; + fhigh = fh; + } +} diff --git a/src/main/java/nanocad/minimize/calcval.java b/src/main/java/nanocad/minimize/calcval.java new file mode 100644 index 0000000..3c4a2d4 --- /dev/null +++ b/src/main/java/nanocad/minimize/calcval.java @@ -0,0 +1,15 @@ +package nanocad.minimize; + +public class calcval{ + public double theforce, thepotential, thestepsize; + public calcval(double f, double p){ + this.theforce = f; + this.thepotential = p; + this.thestepsize = 0.0; + } + public calcval(double f, double p, double s){ + this.theforce = f; + this.thepotential = p; + this.thestepsize = s; + } +} diff --git a/src/main/java/nanocad/minimize/minval.java b/src/main/java/nanocad/minimize/minval.java new file mode 100644 index 0000000..d688fee --- /dev/null +++ b/src/main/java/nanocad/minimize/minval.java @@ -0,0 +1,9 @@ +package nanocad.minimize; + +public class minval{ + public double fret,xmin; + public minval(double fret, double xmin){ + this.fret = fret; + this.xmin = xmin; + } +} diff --git a/src/main/java/nanocad/minimize/mm3/angangterm.java b/src/main/java/nanocad/minimize/mm3/angangterm.java new file mode 100644 index 0000000..22d98a5 --- /dev/null +++ b/src/main/java/nanocad/minimize/mm3/angangterm.java @@ -0,0 +1,205 @@ +package nanocad.minimize.mm3; + +import java.lang.Math; +import java.util.Vector; + +import nanocad.*; + +public class angangterm extends nanocad.term +{ + private static final double angangunit = -0.02191418; + private static final double convert = 3.1415926 / 180; + private double k, idealAngle1, idealAngle2; + public static final double B = .014; + public final static double C = .00005; + public final static double D = .0000007; + public final static double E = .0000000009; + + public angangterm() {} + public angangterm (atom center, atom both, atom left, atom right) + { + myAtoms = new atom[4]; + myAtoms[0] = center; + myAtoms[1] = both; + myAtoms[2] = left; + myAtoms[3] = right; + setCalculationValues(); + } + + public void enumerate(Vector atomList, Vector termList) + { + for (int i = 0; i < atomList.size(); i++) + { + if ( ((atom)atomList.elementAt(i)).bonds.size() == 3) + { + atom tmp; + Vector v = new Vector(); + v.addElement((atom)atomList.elementAt(i)); + for (int j = 0; j < 3; j++) + { + if (((bond)((atom)v.elementAt(0)).bonds.elementAt(j)).a1 == (atom)v.elementAt(0)) + v.addElement(((bond)((atom)v.elementAt(0)).bonds.elementAt(j)).a2); + else + v.addElement(((bond)((atom)v.elementAt(0)).bonds.elementAt(j)).a1); + } + this.buildTerm(v, termList); + } + } + } + + protected void buildTerm(Vector v, Vector termList) + { + angangterm b = new angangterm((atom)v.elementAt(0), (atom)v.elementAt(1), (atom)v.elementAt(2), (atom)v.elementAt(3)); + if (b.k != 0.0) + { + termList.addElement(b); + } + b = new angangterm((atom)v.elementAt(0), (atom)v.elementAt(2), (atom)v.elementAt(3), (atom)v.elementAt(1)); + if (b.k != 0.0) + { + termList.addElement(b); + } + b = new angangterm((atom)v.elementAt(0), (atom)v.elementAt(3), (atom)v.elementAt(1), (atom)v.elementAt(2)); + if (b.k != 0.0) + { + termList.addElement(b); + } + } + + public double computeForces() + { + double[] ab = new double[3]; double[] bc = new double[3]; double[] bd = new double[3]; double[] dthda = new double[3]; double[] dthdb = new double[3]; + double[] dthdc = new double[3]; double[] dalda = new double[3]; double[] daldb = new double[3]; double daldd[] = new double[3]; + double theta, alpha, abdotbc, abdotbd, abdotab, bcdotbc, bddotbd, dedth, dedal, cdenominator, ddenominator; + + for (int i = 0; i < 3; i++) + { + ab[i] = myAtoms[1].x[i] - myAtoms[0].x[i]; + bc[i] = myAtoms[2].x[i] - myAtoms[0].x[i]; + bd[i] = myAtoms[3].x[i] - myAtoms[0].x[i]; + } + + abdotab = ab[0]*ab[0] + ab[1]*ab[1] + ab[2]*ab[2]; + abdotbc = ab[0]*bc[0] + ab[1]*bc[1] + ab[2]*bc[2]; + abdotbd = ab[0]*bd[0] + ab[1]*bd[1] + ab[2]*bd[2]; + bcdotbc = bc[0]*bc[0] + bc[1]*bc[1] + bc[2]*bc[2]; + bddotbd = bd[0]*bd[0] + bd[1]*bd[1] + bd[2]*bd[2]; + + if(abdotab <= 0) abdotab = mm3MinimizeAlgorythm.TINY; + if(bcdotbc <= 0) bcdotbc = mm3MinimizeAlgorythm.TINY; + if(bddotbd <= 0) bddotbd = mm3MinimizeAlgorythm.TINY; + + // Makes sure we don't get a divide by 0 or sqrt(negative). + double jtemp0 = abdotab * bcdotbc; + if(jtemp0 <= 0) jtemp0 = mm3MinimizeAlgorythm.TINY; + double jtemp1 = abdotab * bddotbd; + if(jtemp1 <= 0) jtemp1 = mm3MinimizeAlgorythm.TINY; + theta = Math.acos(abdotbc / Math.sqrt(jtemp0)); + alpha = Math.acos(abdotbd / Math.sqrt(jtemp1)); + + dedth = angangunit * k * (alpha - idealAngle2); + dedal = angangunit * k * (theta - idealAngle1); + + double jtemp2 = abdotab * bcdotbc - abdotbc * abdotbc; + if(jtemp2 == 0) jtemp2 = mm3MinimizeAlgorythm.TINY; + double jtemp3 = abdotab * bddotbd - abdotbd * abdotbd; + if(jtemp3 == 0) jtemp3 = mm3MinimizeAlgorythm.TINY; + cdenominator = Math.sqrt(jtemp2); + ddenominator = Math.sqrt(jtemp3); + + for (int i = 0; i < 3; i++) + { + dthda[i] = (bc[i] - abdotbc * ab[i] / abdotab) / cdenominator; + dthdc[i] = (ab[i] - abdotbc * bc[i] / abdotab) / cdenominator; + dthdb[i] = -(dthda[i] + dthdc[i]); + dalda[i] = (bd[i] - abdotbd * ab[i] / abdotab) / ddenominator; + daldd[i] = (ab[i] - abdotbd * bd[i] / abdotab) / ddenominator; + daldb[i] = -(dalda[i] + daldd[i]); + + myAtoms[0].f[i] += dedth * dthdb[i] + dedal * daldb[i]; + myAtoms[1].f[i] += dedth * dthda[i] + dedal * dalda[i]; + myAtoms[2].f[i] += dedth * dthdc[i]; + myAtoms[3].f[i] += dedal * daldd[i]; + } + + potential = computePotential(theta,alpha); + return myAtoms[0].f[0]; + } + + public double computePotential(double theta, double alpha){ + return k*angangunit*(theta-idealAngle1)*(alpha-idealAngle2); + } + + public void setCalculationValues() + { + int atomCenterType = myAtoms[0].getMM3TypeNum(); + int atomBothType = myAtoms[1].getMM3TypeNum(); + int atomLeftType = myAtoms[2].getMM3TypeNum(); + int atomRightType = myAtoms[3].getMM3TypeNum(); + + try + { + AtomDataFile dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "mm3angangdata.txt"); + //AtomDataFile dataFile = new AtomDataFile("mm3angangdata.txt"); + if (dataFile.findData(atomCenterType, 0)) + k = dataFile.parseDouble(2); + else + { + //System.out.println("no data for " + atomBothType + " " + atomCenterType + " angle angle"); + k = 0.0; + } + + dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "mm3adata.txt"); + //dataFile = new AtomDataFile("mm3adata.txt"); + if (dataFile.findData(atomCenterType, min(atomBothType, atomLeftType), max(atomBothType, atomLeftType), 1, 0, 2)) + idealAngle1 = convert * dataFile.parseDouble(4); + else + { + //System.out.println("no data for " + atomBothType + " " + atomCenterType + " angle angle"); + k = 0.0; + } + + dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "mm3adata.txt"); + //dataFile = new AtomDataFile("mm3adata.txt"); + if (dataFile.findData(atomCenterType, min(atomBothType, atomRightType), max(atomBothType, atomRightType), 1, 0, 2)) + idealAngle2 = convert * dataFile.parseDouble(4); + else + { + //System.out.println("no data for " + atomBothType + " " + atomCenterType + " angle angle"); + k = 0.0; + } + } + catch (java.io.IOException e) + { + System.err.println("Bend data lookup error"); + e.printStackTrace(); + } + } + + public int min(int a, int b) + { + if (a < b) + return a; + return b; + } + + public int max(int a, int b) + { + if (a > b) + return a; + return b; + } + + public int termLength() + { + return 4; + } + + public String name() + { + return "Angle Angle"; + } +} diff --git a/src/main/java/nanocad/minimize/mm3/aterm.java b/src/main/java/nanocad/minimize/mm3/aterm.java new file mode 100644 index 0000000..b6c8e79 --- /dev/null +++ b/src/main/java/nanocad/minimize/mm3/aterm.java @@ -0,0 +1,203 @@ +package nanocad.minimize.mm3; + +/** + * aterm.java - MM2-style angle energy term + * Copyright (c) 1997,1998 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + + +import java.lang.Math; +import java.util.Vector; + +import nanocad.*; + +public class aterm extends nanocad.term +{ + public static final String rcsid = + "$Id: aterm.java,v 1.2 2005/05/14 23:51:02 xli16 Exp $"; + private static final double convert = 3.1415926 / 180; // degrees to radians + private double kth, th0; + public static final double B = .014; + public final static double C = .00005; + public final static double D = .0000007; + public final static double E = .0000000009; +/** + * Insert the method's description here. + * Creation date: (6/19/00 4:10:14 PM) + */ +public aterm() {} +public aterm(atom a1, atom a2, atom a3) { + myAtoms = new atom[3]; + myAtoms[0] = a1; + myAtoms[1] = a2; + myAtoms[2] = a3; + setCalculationValues(); +} + protected void buildTerm (Vector v, Vector termList) + { + int atom1 = ((atom)v.elementAt(0)).getMM3TypeNum(); + int atom2 = ((atom)v.elementAt(1)).getMM3TypeNum(); + int atom3 = ((atom)v.elementAt(2)).getMM3TypeNum(); + + if (atom1 < atom3) + { + + aterm t = new aterm ((atom) v.elementAt(0), + (atom) v.elementAt(1), + (atom) v.elementAt(2)); + termList.addElement(t); + } + else if (atom1 == atom3) + { + if ( ((atom)v.elementAt(0)).x[0] < ((atom)v.elementAt(2)).x[0]) + { + aterm t = new aterm ((atom) v.elementAt(0), + (atom) v.elementAt(1), + (atom) v.elementAt(2)); + termList.addElement (t); + } + } + } +public double computeForces() { + if (kth == 0.0) + return 0.0; + int i; + // compute forces on each atom, add it to the atom's force vector + double[] ab = new double[3]; + double[] bc = new double[3]; + double abdotab = 0.0, abdotbc = 0.0, bcdotbc = 0.0, th, tdif, duDth; + for (i = 0; i < 3; i++) { + ab[i] = myAtoms[0].x[i] - myAtoms[1].x[i]; + bc[i] = myAtoms[2].x[i] - myAtoms[1].x[i]; + abdotab += ab[i] * ab[i]; + abdotbc += ab[i] * bc[i]; + bcdotbc += bc[i] * bc[i]; + } + if(abdotab <= 0) abdotab = mm3MinimizeAlgorythm.TINY; + if(bcdotbc <= 0) bcdotbc = mm3MinimizeAlgorythm.TINY; + + if (abdotab > 3.0 || bcdotbc > 3.0) + return 0.0; + + double jtemp1 = abdotbc/Math.sqrt(abdotab * bcdotbc); + if(jtemp1 < -1) jtemp1 = -1; + if(jtemp1 > 1) jtemp1 = 1; + th = Math.acos(jtemp1); + tdif = th - th0; + if(tdif == 0.0){ + potential = 0.0; + return 0.0; + } + potential = computePotential(tdif); + duDth = computePotentialDerivative(tdif); + + double[] dthda = new double[3]; + double[] dthdc = new double[3]; + + double jtemp2 = abdotab * bcdotbc - abdotbc*abdotbc; + if(jtemp2 <= 0) jtemp2 = mm3MinimizeAlgorythm.TINY; + double denominator = Math.sqrt(jtemp2); + for (i = 0; i < 3; i++) + { + dthda[i] = -(ab[i] * abdotbc / abdotab - bc[i]) / denominator; + dthdc[i] = -(bc[i] * abdotbc / bcdotbc - ab[i]) / denominator; + myAtoms[0].f[i] += duDth * dthda[i]; + myAtoms[1].f[i] += duDth * (-dthda[i] - dthdc[i]); + myAtoms[2].f[i] += duDth * dthdc[i]; + } + return duDth * dthda[0]; +} +/** + * Insert the method's description here. + * Creation date: (6/15/00 12:53:22 PM) + * @return double + * @param deltaTheta double + */ +protected double computePotentialDerivative(double deltaTheta) { + double deltaThetaSquared = deltaTheta*deltaTheta; + double bTerm = 3*B*deltaTheta; + double cTerm = 4*C*deltaThetaSquared; + double dTerm = 5*D*deltaThetaSquared*deltaTheta; + double eTerm = 6*E*deltaThetaSquared*deltaThetaSquared; + double force = kth*deltaTheta*(2 - bTerm + cTerm - dTerm + eTerm); + return force; +} + + protected double computePotential(double dT){ + return 0.5*kth*dT*dT*(1 - B*dT + C*dT*dT - D*dT*dT*dT + E*dT*dT*dT*dT); + } + + protected String repr2() + { + return " angle " + + (new Double(kth)).toString() + " " + + (new Double(th0)).toString(); + } +/** + * Insert the method's description here. + * Creation date: (6/15/00 12:41:20 PM) + */ +protected void setCalculationValues() { + int atomOneType = myAtoms[0].getMM3TypeNum(); + int atomTwoType = myAtoms[1].getMM3TypeNum(); + int atomThreeType = myAtoms[2].getMM3TypeNum(); + if ((atomOneType < 0) || (atomTwoType < 0) || (atomThreeType < 0)) { + setDefaultCalculationValues(); + return; + } + + try { + AtomDataFile dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "mm3adata.txt"); + //AtomDataFile dataFile = new AtomDataFile("mm3adata.txt"); + if (dataFile.findData(atomTwoType, atomOneType, atomThreeType, 1, 0, 2)) { + kth = dataFile.parseDouble(3); + th0 = dataFile.parseDouble(4) * convert; + } else { + setDefaultCalculationValues(); + return; + } + } catch (java.io.IOException e) { + System.err.println("Angle data lookup error"); + e.printStackTrace(); + } +} +/** + * Insert the method's description here. + * Creation date: (6/19/00 2:10:38 PM) + */ +protected void setDefaultCalculationValues() { + defaultsUsed = true; + kth = 0.3; + th0 = 120.0 * convert; + //System.out.println("No data for " + myAtoms[0].getMM3TypeNum() + " " + myAtoms[1].getMM3TypeNum() + " " + myAtoms[2].getMM3TypeNum() + " angle"); + } + public int termLength() + { + return 3; + } + public String name() + { + return "Angle"; + } +} diff --git a/src/main/java/nanocad/minimize/mm3/bracket.java b/src/main/java/nanocad/minimize/mm3/bracket.java new file mode 100644 index 0000000..aeaf773 --- /dev/null +++ b/src/main/java/nanocad/minimize/mm3/bracket.java @@ -0,0 +1,50 @@ +/*Copyright (c) 2004,University of Illinois at Urbana-Champaign. All rights reserved. + +Developed by: +Chemistry and Computational Biology Group + +NCSA, University of Illinois at Urbana-Champaign + +http://ncsa.uiuc.edu/GridChem + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software") to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Chemistry and Computational Biology Group , NCSA, + University of Illinois at Urbana-Champaign, nor the names of its contributors + may be used to endorse or promote products derived from this Software without + specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ + +package nanocad.minimize.mm3; + +public class bracket{ + double low,mid,high,flow,fmid,fhigh; + public bracket(double l,double m,double h,double fl,double fm,double fh){ + low = l; + mid = m; + high = h; + flow = fl; + fmid = fm; + fhigh = fh; + } +} diff --git a/src/main/java/nanocad/minimize/mm3/calcval.java b/src/main/java/nanocad/minimize/mm3/calcval.java new file mode 100644 index 0000000..22019a7 --- /dev/null +++ b/src/main/java/nanocad/minimize/mm3/calcval.java @@ -0,0 +1,46 @@ +/*Copyright (c) 2004,University of Illinois at Urbana-Champaign. All rights reserved. + +Developed by: +Chemistry and Computational Biology Group + +NCSA, University of Illinois at Urbana-Champaign + +http://ncsa.uiuc.edu/GridChem + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software") to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Chemistry and Computational Biology Group , NCSA, + University of Illinois at Urbana-Champaign, nor the names of its contributors + may be used to endorse or promote products derived from this Software without + specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ + +package nanocad.minimize.mm3; + +public class calcval{ + double theforce, thepotential; + public calcval(double f, double p){ + this.theforce = f; + this.thepotential = p; + } +} diff --git a/src/main/java/nanocad/minimize/mm3/estaticterm.java b/src/main/java/nanocad/minimize/mm3/estaticterm.java new file mode 100644 index 0000000..6ca3e96 --- /dev/null +++ b/src/main/java/nanocad/minimize/mm3/estaticterm.java @@ -0,0 +1,239 @@ +package nanocad.minimize.mm3; + +import java.util.Vector; + +import nanocad.*; + +public class estaticterm extends nanocad.term +{ + private final double e0 = 1.5; //8.854187817 * .000000000001; + private double firstCharge; + private double secondCharge; + private double firstDistribution; + private double secondDistribution; + + public estaticterm() {} + + public estaticterm(atom first1, atom first2, atom second1, atom second2) + { + myAtoms = new atom[4]; + myAtoms[0] = first1; + myAtoms[1] = first2; + myAtoms[2] = second1; + myAtoms[3] = second2; + setCalculationValues(); + } + + public void enumerate(Vector atomList, Vector termList) + { + Vector dipoleList = new Vector(); + int number = 0; + + System.out.println("enumerating"); + + //make a list of all dipoles + for (int i = 0; i < atomList.size(); i++) + { + atom tmpAtom = (atom)atomList.elementAt(i); + for (int j = 0; j < tmpAtom.bonds.size(); j++) + { + dipole temp; + if (((bond)tmpAtom.bonds.elementAt(j)).a1 == tmpAtom) + temp = new dipole(tmpAtom,((bond)tmpAtom.bonds.elementAt(j)).a2); + else + temp = new dipole(tmpAtom,((bond)tmpAtom.bonds.elementAt(j)).a1); + + boolean add = true; + + for (int k = 0; k < dipoleList.size(); k++) //aviod adding duplicate bonds + if (temp.isSameDipole((dipole)dipoleList.elementAt(k))) + add = false; + + if (add == true) + dipoleList.addElement(temp); + } + } + + //add terms for all dipoles that don't share common atoms + for (int i = 0; i < dipoleList.size(); i++) + { + for (int j = i + 1; j < dipoleList.size(); j++) + { + dipole temp1 = (dipole)dipoleList.elementAt(i); + dipole temp2 = (dipole)dipoleList.elementAt(j); + + Vector v = new Vector(); + + if (!temp1.sharesAtomWith(temp2)) + { + v.addElement(temp1); + v.addElement(temp2); + this.buildTerm(v, termList); + number++; + } + } + } + System.out.println(number + " terms added"); + } + + protected void buildTerm(Vector v, Vector termList) + { + estaticterm e = new estaticterm( ((dipole)v.elementAt(0)).getFirst(), ((dipole)v.elementAt(0)).getSecond(), + ((dipole)v.elementAt(1)).getFirst(), ((dipole)v.elementAt(1)).getSecond()); + if (!((e.firstCharge == 0.0 && e.firstDistribution == 0.0) || (e.secondCharge == 0.0 && e.secondDistribution == 0.0)) ) + termList.addElement(e); + } + + public double computeForces() + { + double ab[], cd[], uv[], abdotab, abdotcd, abdotuv, cddotcd, cddotuv, uvdotuv, abnorm, cdnorm, r, x, thetai, thetaj, dedr, dedx, + dedthi, dedthj, drda[], drdb[], drdc[], drdd[], dxda[], dxdb[], dxdc[], dxdd[], dthida[], dthidb[], dthjdc[], dthjdd[]; + ab = new double[3]; cd = new double [3]; uv = new double[3]; drda = new double[3]; drdb = new double[3]; drdc = new double[3]; + drdd = new double[3]; dxda = new double[3]; dxdb = new double[3]; dxdc = new double[3]; dxdd = new double[3]; + dthida = new double[3]; dthidb = new double[3]; dthjdc = new double[3]; dthjdd = new double[3]; + + for (int i = 0; i < 3; i++) + { + ab[i] = myAtoms[0].x[i] - myAtoms[1].x[i]; + cd[i] = myAtoms[2].x[i] - myAtoms[3].x[i]; + uv[i] = myAtoms[3].x[i] + secondDistribution * cd[i] - myAtoms[1].x[i] - firstDistribution * ab[i]; + } + + abdotab = ab[0]*ab[0] + ab[1]*ab[1] + ab[2]*ab[2]; + abdotcd = ab[0]*cd[0] + ab[1]*cd[1] + ab[2]*cd[2]; + abdotuv = ab[0]*uv[0] + ab[1]*uv[1] + ab[2]*uv[2]; + cddotcd = cd[0]*cd[0] + cd[1]*cd[1] + cd[2]*cd[2]; + cddotuv = cd[0]*uv[0] + cd[1]*uv[1] + cd[2]*uv[2]; + uvdotuv = uv[0]*uv[0] + uv[1]*uv[1] + uv[2]*uv[2]; + + if(abdotab <= 0) abdotab = mm3MinimizeAlgorythm.TINY; + if(cddotcd <= 0) cddotcd = mm3MinimizeAlgorythm.TINY; + if(uvdotuv <= 0) uvdotuv = mm3MinimizeAlgorythm.TINY; + + abnorm = Math.sqrt(abdotab); + cdnorm = Math.sqrt(cddotcd); + + //note : the variables x, thetai, and thetaj represent cos x, cos thetai and cos thetaj rather than the angles themselves. + + r = Math.sqrt(uvdotuv); + x = abdotcd / (abnorm * cdnorm); + thetai = abdotuv / (abnorm * r); + thetaj = cddotuv / (cdnorm * r); + + dedr = -3 * firstCharge * secondCharge / (e0 * r*r*r*r) * (x - 3 * thetai * thetaj); + dedx = firstCharge * secondCharge / (e0 * r*r*r) * Math.sin(Math.acos(x)); + dedthi = firstCharge * secondCharge / (e0 * r*r*r) * (-3 * thetaj * Math.sin(Math.acos(thetai))); + dedthj = firstCharge * secondCharge / (e0 * r*r*r) * (-3 * thetai * Math.sin(Math.acos(thetaj))); + + for (int i = 0; i < 3; i++) + { + drda[i] = - firstDistribution * uv[i] / r; + drdb[i] = - (1 - firstDistribution) * uv[i] / r; + drdc[i] = secondDistribution * uv[i] / r; + drdd[i] = (1 - secondDistribution) * uv[i] / r; + + dxda[i] = (cd[i] - ab[i] * abdotcd / abdotab) / (abnorm * cdnorm); + dxdb[i] = -dxda[i]; + dxdc[i] = (ab[i] - cd[i] * abdotcd / cddotcd) / (abnorm * cdnorm); + dxdd[i] = -dxdc[i]; + + dthida[i] = (uv[i] - firstDistribution * ab[i] - ab[i] * abdotuv / abdotab + uv[i] * abdotuv * firstDistribution / uvdotuv) / (abnorm * r); + dthidb[i] = (-uv[i] - (1 - firstDistribution) * ab[i] + ab[i] * abdotuv / abdotab + uv[i] * abdotuv * (1 - firstDistribution) / uvdotuv) / (abnorm * r); + + dthjdc[i] = (uv[i] + secondDistribution * cd[i] - cd[i] * cddotuv / cddotcd - uv[i] * cddotuv * secondDistribution / uvdotuv) / (cdnorm * r); + dthjdd[i] = (-uv[i] + (1 - secondDistribution) * cd[i] + cd[i] * cddotuv / cddotcd - uv[i] * cddotuv * (1 - secondDistribution) / uvdotuv) / (cdnorm * r); + + myAtoms[0].f[i] += dedr * drda[i] + dedx * dxda[i] + dedthi * dthida[i]; + myAtoms[1].f[i] += dedr * drdb[i] + dedx * dxdb[i] + dedthi * dthidb[i]; + myAtoms[2].f[i] += dedr * drdc[i] + dedx * dxdc[i] + dedthj * dthjdc[i]; + myAtoms[3].f[i] += dedr * drdd[i] + dedx * dxdd[i] + dedthj * dthjdd[i]; + } + + potential = computePotential(x,thetai,thetaj,r); + return myAtoms[0].x[0]; + } + + public double computePotential(double x, double alpha1, double alpha2, double d){ + return (firstCharge*secondCharge*(x-3*alpha1*alpha2)/(e0*d*d*d)); + } + + public void setCalculationValues() + { + atom tempa; + int temp; + int atom1 = myAtoms[0].getMM3TypeNum(); + int atom2 = myAtoms[1].getMM3TypeNum(); + int atom3 = myAtoms[2].getMM3TypeNum(); + int atom4 = myAtoms[3].getMM3TypeNum(); + + if (atom1 > atom2) + { + temp = atom1; + atom1 = atom2; + atom2 = temp; + tempa = myAtoms[0]; + myAtoms[0] = myAtoms[1]; + myAtoms[1] = tempa; + } + + if (atom3 > atom4) + { + temp = atom3; + atom3 = atom4; + atom4 = temp; + tempa = myAtoms[2]; + myAtoms[2] = myAtoms[3]; + myAtoms[3] = tempa; + } + + try + { + AtomDataFile dataFile= new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "mm3estaticdata.txt"); + //AtomDataFile dataFile= new AtomDataFile("mm3estaticdata.txt"); + if (dataFile.findData(atom1, atom2, 0, 1)) + { + firstCharge = dataFile.parseDouble(2); + firstDistribution = dataFile.parseDouble(3); + } + else + { + //System.out.println("No data for " + atom1 + " " + atom2 + " dipole."); + firstCharge = 0.0; + firstDistribution = 0.0; + } + + if (dataFile.findData(atom3, atom4, 0, 1)) + { + secondCharge = dataFile.parseDouble(2); + secondDistribution = dataFile.parseDouble(3); + } + else + { + //System.out.println("No data for " + atom3 + " " + atom4 + " dipole."); + secondCharge = 0.0; + secondDistribution = 0.0; + } + } + catch (java.io.IOException e) + { + System.err.println("Dipole data lookup error"); + e.printStackTrace(); + } + } + + public int termLength() + { + return 4; + } + + public String repr2() + { return " Electrostatic" + myAtoms[0].name() + "-" + myAtoms[1].name() + " " + + myAtoms[2].name() + "-" + myAtoms[3].name(); + } + + public String name() + { + return "Electrostatic"; + } +} diff --git a/src/main/java/nanocad/minimize/mm3/hbondterm.java b/src/main/java/nanocad/minimize/mm3/hbondterm.java new file mode 100644 index 0000000..53494d8 --- /dev/null +++ b/src/main/java/nanocad/minimize/mm3/hbondterm.java @@ -0,0 +1,250 @@ +package nanocad.minimize.mm3; + +/** + * lterm.java - MM2-style length energy term + * Copyright (c) 1997,1998 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * or its derived works must display the following acknowledgement: + * This product includes software developed by Will Ware. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.lang.Math; +import java.util.Vector; + +import nanocad.*; + +public class hbondterm extends nanocad.term +{ + public static final String rcsid = + "$Id: hbondterm.java,v 1.2 2005/05/14 23:51:02 xli16 Exp $"; + /* I've been hacking a bit with acceptable forms for the length-energy term. + * _Nanosystems_ lists one simple expression with a square and cubic term + * for close distances, and various kinds of exponential expressions for + * farther away. But these depend on numbers called De and beta and I don't + * have tables for those (just the few examples in _Nanosystems_). So after + * some puttering and graphing and algebra, I came up with the following. + * Energies are in attojoules (10^-18 joules), distances are in angstroms + * (10^-10 m), forces are in attojoules per angstrom (10^-8 N), and + * spring constants are in attojoules per angstrom-squared (100 N/m). This + * is consistent with the units in _Nanosystems_, and also the units used + * in the 'mm2.prm' parameter file I found on Jay Ponder's ftp site. + * Expressions for energy and force, where ks and r0 are a function of + * the two atoms involved: + * + * dr = r - r0; + * + * Energy (r) := + * if (dr < rthresh) + * { return 0.5 * ks * dr * dr * (1 - kc * dr) - z * ks; } + * else + * { return (-a * ks / beta) * exp (-beta * dr); } + * + * Force (r) := + * if (dr < rthresh) + * { return -(ks * dr * (1 - 1.5 * kc * dr)); } + * else + * { return -a * ks * exp (-beta * dr); } + * + * + * A, beta, z, kcubic, and rthresh are defined below. Notice my use of + * 'beta' differs from the use in _Nanosystems_, but plays a similar role. + * + * These follow Drexler's quadratic-cubic form for dr < rthresh, and for + * dr > rthresh, they follow an exponential drop-off which is pretty + * continuous for both energy and force. The only point that I think would + * be worth quibbling over would be the value of beta, which I picked so + * that it would look "reasonable" on a graph. + */ + private static final double kcubic = 2.0; /* (0.5 angstrom)^-1 */ + private static final double rthresh = 1 / (3 * kcubic); + private static final double beta = 3.0; + private static final double a = rthresh * (1 - 1.5 * kcubic * rthresh) * + Math.exp (beta * rthresh); + private static final double z = (a / beta) * Math.exp(-beta * rthresh) + + 0.5 * rthresh * rthresh * (1 - kcubic * rthresh); + public final static double B = 2.55; + public final static double C = .583333; + private double pij; + private double Dij; + public final static double MIN_ANGLE_FOR_HBOND = 150.0/180.0 * Math.PI;//150 degrees in radians + public final static double MAX_LENGTH_FOR_HBOND = 3.5; +/** + * Insert the method's description here. + * Creation date: (6/19/00 4:09:33 PM) + */ +public hbondterm() {} +public hbondterm(atom a1, atom a2, atom a3) { + myAtoms = new atom[3]; + myAtoms[0] = a1; + myAtoms[1] = a2; + myAtoms[2] = a3; + setCalculationValues(); +} + protected void buildTerm (Vector v, Vector termList) + { + System.err.println("buildTerm for hbond term should never be called."); + } + +protected boolean canFormHBonds(atom a) { + int atomicNumber = a.atomicNumber(); + if((atomicNumber == 7) || (atomicNumber == 8) || (atomicNumber == 16)) + return true; + return false; +} +public double computeForces() { + + if(defaultsUsed()) return 0.0; + + int i; + // compute forces on each atom, add it to the atom's force vector + double[] diff = new double[3]; + double r, m; + for (i = 0, r = 0.0; i < 3; i++) { + diff[i] = myAtoms[0].x[i] - myAtoms[1].x[i]; + r += diff[i] * diff[i]; + } + if(r <= 0) r = mm3MinimizeAlgorythm.TINY; + r = Math.sqrt(r); + + potential = computePotential(r); + m = computePotentialDerivative(r); + + // at this point, m is du/dr + m /= r; + // m > 0 attract, m < 0 repel + for (i = 0; i < 3; i++) { + myAtoms[0].f[i] -= m * diff[i]; + myAtoms[1].f[i] += m * diff[i]; + } + //return m * Math.sqrt(diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2]); + return m*r; +} +/** + * Insert the method's description here. + * Creation date: (6/15/00 1:22:01 PM) + * @return double + * @param lengthDifference double + */ +protected double computePotentialDerivative(double p) { + //p is the acutal distance between atoms + double exponentForE = -12*p/pij; + double firstTerm = -2.208e6*Math.pow(Math.E, exponentForE)/pij; + double secondTerm; + if (p < (pij/3)) + { + secondTerm = 4.5*Math.pow(pij, 2.0)/Math.pow(p, 3.0); + } + else + { + secondTerm = 13.5*Math.pow(pij, 6.0)/Math.pow(p, 7.0); + } + + double force = Dij*(firstTerm + secondTerm);; + return force; +} + +protected double computePotential(double p){ + return (Dij * ( 1.84E5 * Math.exp(-12 * p / pij) - 2.25 * Math.pow(pij / p, 6))); +} + +public void enumerate(Vector atomList, Vector termList) +{ + for(int i = 0; i < atomList.size(); i++) + { + atom hydrogen = (atom) atomList.elementAt(i); + if(hydrogen.atomicNumber() == 1) + { + for (int k = 0; k < hydrogen.bonds.size(); k++) + { + atom currentAtom = (atom) ((bond) hydrogen.bonds.elementAt(k)).otherAtom(hydrogen); + if(canFormHBonds(currentAtom)) + { + for(int j = 0; j < atomList.size(); j++) + { + atom otherAtom = (atom) atomList.elementAt(j); + if(otherAtom == currentAtom) + continue; + if(!canFormHBonds(otherAtom)) + continue; + if(findAngle(currentAtom, hydrogen, otherAtom) < MIN_ANGLE_FOR_HBOND) + continue; + if(lengthBetween(currentAtom, hydrogen) + lengthBetween(hydrogen, otherAtom) > MAX_LENGTH_FOR_HBOND) + continue; + + termList.addElement(new hbondterm(currentAtom, hydrogen, otherAtom)); + } + } + } + } + } + +} + protected String repr2() + { + return " length " + + (new Double(pij)).toString() + " " + + (new Double(Dij)).toString(); + } +protected void setCalculationValues() { + int atomOneType = myAtoms[0].getMM3TypeNum(); + int atomTwoType = myAtoms[2].getMM3TypeNum(); + if (atomOneType < 0 || atomTwoType < 0) { + setDefaultCalculationValues(); + return; + } + int biggerValue = Math.max(atomOneType, atomTwoType); + int smallerValue = Math.min(atomOneType, atomTwoType); + try { + AtomDataFile dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "mm3hbonddata.txt"); + //AtomDataFile dataFile = new AtomDataFile("mm3hbonddata.txt"); + if (dataFile.findData(smallerValue, biggerValue, 0, 1)) { + pij = dataFile.parseDouble(2); + Dij = dataFile.parseDouble(3); + } else { + setDefaultCalculationValues(); + return; + } + } catch (java.io.IOException e) { + System.err.println("Length data lookup error"); + e.printStackTrace(); + } +} +/** + * Insert the method's description here. + * Creation date: (6/19/00 1:50:46 PM) + */ +protected void setDefaultCalculationValues() +{ + defaultsUsed = true; + System.err.println("No data for " + myAtoms[0].getMM3TypeNum() + " " + myAtoms[2].getMM3TypeNum() + " hydrogen bond"); +} + public int termLength() + { + return 2; + } + public String name() + { + return "Hydrogen bond"; + } +} diff --git a/src/main/java/nanocad/minimize/mm3/lterm.java b/src/main/java/nanocad/minimize/mm3/lterm.java new file mode 100644 index 0000000..5864e66 --- /dev/null +++ b/src/main/java/nanocad/minimize/mm3/lterm.java @@ -0,0 +1,225 @@ +package nanocad.minimize.mm3; + +/** + * lterm.java - MM2-style length energy term + * Copyright (c) 1997,1998 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * or its derived works must display the following acknowledgement: + * This product includes software developed by Will Ware. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.lang.Math; +import java.util.Vector; + +import nanocad.*; + +public class lterm extends nanocad.term +{ + public static final String rcsid = + "$Id: lterm.java,v 1.2 2005/05/14 23:51:02 xli16 Exp $"; + private double ks, r0; + /* I've been hacking a bit with acceptable forms for the length-energy term. + * _Nanosystems_ lists one simple expression with a square and cubic term + * for close distances, and various kinds of exponential expressions for + * farther away. But these depend on numbers called De and beta and I don't + * have tables for those (just the few examples in _Nanosystems_). So after + * some puttering and graphing and algebra, I came up with the following. + * Energies are in attojoules (10^-18 joules), distances are in angstroms + * (10^-10 m), forces are in attojoules per angstrom (10^-8 N), and + * spring constants are in attojoules per angstrom-squared (100 N/m). This + * is consistent with the units in _Nanosystems_, and also the units used + * in the 'mm2.prm' parameter file I found on Jay Ponder's ftp site. + * Expressions for energy and force, where ks and r0 are a function of + * the two atoms involved: + * + * dr = r - r0; + * + * Energy (r) := + * if (dr < rthresh) + * { return 0.5 * ks * dr * dr * (1 - kc * dr) - z * ks; } + * else + * { return (-a * ks / beta) * exp (-beta * dr); } + * + * Force (r) := + * if (dr < rthresh) + * { return -(ks * dr * (1 - 1.5 * kc * dr)); } + * else + * { return -a * ks * exp (-beta * dr); } + * + * + * A, beta, z, kcubic, and rthresh are defined below. Notice my use of + * 'beta' differs from the use in _Nanosystems_, but plays a similar role. + * + * These follow Drexler's quadratic-cubic form for dr < rthresh, and for + * dr > rthresh, they follow an exponential drop-off which is pretty + * continuous for both energy and force. The only point that I think would + * be worth quibbling over would be the value of beta, which I picked so + * that it would look "reasonable" on a graph. + */ + private static final double kcubic = 2.0; /* (0.5 angstrom)^-1 */ + private static final double rthresh = 1 / (3 * kcubic); + private static final double beta = 3.0; + private static final double a = rthresh * (1 - 1.5 * kcubic * rthresh) * + Math.exp (beta * rthresh); + private static final double z = (a / beta) * Math.exp(-beta * rthresh) + + 0.5 * rthresh * rthresh * (1 - kcubic * rthresh); + public final static double B = 2.0; + public final static double C = .583333; +/** + * Insert the method's description here. + * Creation date: (6/19/00 4:09:33 PM) + */ +public lterm() {} +public lterm(atom a1, atom a2) { + myAtoms = new atom[2]; + myAtoms[0] = a1; + myAtoms[1] = a2; + setCalculationValues(); +} + protected void buildTerm (Vector v, Vector termList) + { + int atom1 = ((atom)v.elementAt(0)).getMM3TypeNum(); + int atom2 = ((atom)v.elementAt(1)).getMM3TypeNum(); + + if (atom1 < atom2) + { + lterm t = new lterm ((atom) v.elementAt(0), (atom) v.elementAt(1)); + termList.addElement(t); + } + else if(atom1 == atom2) + { + if ( ((atom)v.elementAt(0)).x[0] < ((atom)v.elementAt(1)).x[0] ) + { + lterm t = new lterm ((atom) v.elementAt(0), (atom) v.elementAt(1)); + termList.addElement (t); + } + } + + } +public double computeForces() { + int i; + + // compute forces on each atom, add it to the atom's force vector + double[] diff = new double[3]; + double r, m; + for (i = 0, r = 0.0; i < 3; i++) { + diff[i] = myAtoms[0].x[i] - myAtoms[1].x[i]; + r += diff[i] * diff[i]; + } + + if(r <= 0) r = mm3MinimizeAlgorythm.TINY; + r = Math.sqrt(r); + //System.out.println("r:"+r); + //System.out.println("r0:"+r0); + double rdiff = (r - r0); + if(rdiff == 0.0){ + potential = 0.0; + return 0.0; + } + potential = computePotential(rdiff); + // changed from m = 5* computePotentialDerivative(rdiff); + m = computePotentialDerivative(rdiff); + + // at this point, m is du/dr + m /= r; + // m > 0 attract, m < 0 repel + for (i = 0; i < 3; i++) { + myAtoms[0].f[i] -= m * diff[i]; + myAtoms[1].f[i] += m * diff[i]; + } + double jtemp1 = diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2]; + if(jtemp1 <= 0) jtemp1 = mm3MinimizeAlgorythm.TINY; + return m * Math.sqrt(jtemp1); + //return m*r; +} +/** + * Insert the method's description here. + * Creation date: (6/15/00 1:22:01 PM) + * @return double + * @param lengthDifference double + */ +protected double computePotentialDerivative(double lengthDifference) { + // Changed from 4*B*B*C*lengthDifference*lengthDifference; + double bcTerm = 4*B*C*lengthDifference*lengthDifference; + double force = .5*ks * lengthDifference * (2 - 3*B * lengthDifference + bcTerm); + return force; +} + + protected double computePotential(double lD){ + return 0.5*ks*lD*lD*(1-B*lD*(1-C*lD)); + } + + protected String repr2() + { + return " length " + + (new Double(ks)).toString() + " " + + (new Double(r0)).toString(); + } +/** + * Insert the method's description here. + * Creation date: (6/15/00 1:36:02 PM) + */ +protected void setCalculationValues() { + int atomOneType = myAtoms[0].getMM3TypeNum(); + int atomTwoType = myAtoms[1].getMM3TypeNum(); + if (atomOneType < 0 || atomTwoType < 0) { + setDefaultCalculationValues(); + return; + } + + try { + AtomDataFile dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "mm3ldata.txt"); + //AtomDataFile dataFile = new AtomDataFile("mm3ldata.txt"); + if (dataFile.findData(atomOneType, atomTwoType, 0, 1)) { + ks = dataFile.parseDouble(2); + r0 = dataFile.parseDouble(3); + } else { + setDefaultCalculationValues(); + return; + } + } catch (java.io.IOException e) { + System.err.println("Length data lookup error"); + e.printStackTrace(); + } +} +/** + * Insert the method's description here. + * Creation date: (6/19/00 1:50:46 PM) + */ +protected void setDefaultCalculationValues() +{ + defaultsUsed = true; + ks = 2.0; + r0 = 1.2; + //System.out.println("No data for " + myAtoms[0].getMM3TypeNum() + " " + myAtoms[1].getMM3TypeNum() + " bond"); +} + public int termLength() + { + return 2; + } + public String name() + { + return "Length"; + } +} diff --git a/src/main/java/nanocad/minimize/mm3/minval.java b/src/main/java/nanocad/minimize/mm3/minval.java new file mode 100644 index 0000000..aa82df5 --- /dev/null +++ b/src/main/java/nanocad/minimize/mm3/minval.java @@ -0,0 +1,46 @@ +/*Copyright (c) 2004,University of Illinois at Urbana-Champaign. All rights reserved. + +Developed by: +Chemistry and Computational Biology Group + +NCSA, University of Illinois at Urbana-Champaign + +http://ncsa.uiuc.edu/GridChem + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software") to deal with the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom +the Software is furnished to do so, subject to the following +conditions: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the documentation + and/or other materials provided with the distribution. +3. Neither the names of Chemistry and Computational Biology Group , NCSA, + University of Illinois at Urbana-Champaign, nor the names of its contributors + may be used to endorse or promote products derived from this Software without + specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS WITH THE SOFTWARE. + +*/ + +package nanocad.minimize.mm3; + +public class minval{ + double fret,xmin; + public minval(double fret, double xmin){ + this.fret = fret; + this.xmin = xmin; + } +} diff --git a/src/main/java/nanocad/minimize/mm3/mm3MinimizeAlgorythm.java b/src/main/java/nanocad/minimize/mm3/mm3MinimizeAlgorythm.java new file mode 100644 index 0000000..73ebf6f --- /dev/null +++ b/src/main/java/nanocad/minimize/mm3/mm3MinimizeAlgorythm.java @@ -0,0 +1,94 @@ + package nanocad.minimize.mm3; +/** + * Copyright (c) 1997 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ +import java.util.Vector; + +import nanocad.*; +import nanocad.term; + + public class mm3MinimizeAlgorythm extends energyMinimizeAlgorythm +{ +/* public void initTemps(Vector myAtomList){ + // This is a temporary vector that represents a clone of the + // original group. Save initializations later by doing them + // here one time, then just changing the position in f1dim(). + templist = (Vector) myAtomList.clone(); + temptermList = new Vector(); + term t = enumToTerm(templist, temptermList); + tempsInited = true; + } +*/ + protected nanocad.term enumToTerm(Vector argAtomList, Vector argTermList) + { + term t = new lterm(); + t.enumerate(argAtomList, argTermList); + t = new aterm(); + t.enumerate(argAtomList, argTermList); + t = new tterm(); + t.enumerate(argAtomList, argTermList); + t = new vdwterm(); + t.enumerate(argAtomList, argTermList); + t = new hbondterm(); + t.enumerate(argAtomList, argTermList); + t = new opbterm(); + t.enumerate(argAtomList, argTermList); + t = new estaticterm(); + t.enumerate(argAtomList, argTermList); + t = new strbendterm(); + t.enumerate(argAtomList, argTermList); + t = new strtorterm(); + t.enumerate(argAtomList, argTermList); + t = new angangterm(); + t.enumerate(argAtomList, argTermList); + + return t; + } + + + /** + * Insert the method's description here. + * Creation date: (7/25/2000 3:07:45 PM) + * @param newGroup group + */ + + public mm3MinimizeAlgorythm(group newGroup, newNanocad windowForUpdates) + { + funEvals = 0; +// tempsInited = false; + this.windowForUpdates = windowForUpdates; + groupToMinimize = newGroup; + atomList = groupToMinimize.atomList; + enumerateTerms(); + } + + /** + * Insert the method's description here. + * Creation date: (7/25/2000 3:04:23 PM) + */ + protected void enumerateTerms() + { termList = new Vector(); + term t = enumToTerm(atomList, termList); + groupToMinimize.termsEnumerated(); + } +} diff --git a/src/main/java/nanocad/minimize/mm3/opbterm.java b/src/main/java/nanocad/minimize/mm3/opbterm.java new file mode 100644 index 0000000..c607b91 --- /dev/null +++ b/src/main/java/nanocad/minimize/mm3/opbterm.java @@ -0,0 +1,185 @@ +/****************************************** + *opbterm.java -- nanocad + *Andrew Knox 06/25/01 + *implements out of plane angle bend term + ******************************************/ + +package nanocad.minimize.mm3; + +import java.lang.Math; +import java.util.Vector; + +import nanocad.*; + +public class opbterm extends nanocad.term +{ + private static final double opbunit = 0.02191418; + private static final double B = .014; + private final static double C = .00005; + private final static double D = .0000007; + private final static double E = .0000000009; + private double ks; + private double angle; + + public opbterm() {} + + public opbterm(atom center, atom bent, atom other1, atom other2) + { + myAtoms = new atom[4]; + + myAtoms[1] = bent; + myAtoms[0] = center; + myAtoms[2] = other1; + myAtoms[3] = other2; + setCalculationValues(); + } + + public void enumerate(Vector atomList, Vector termList) + { + for(int i = 0; i < atomList.size(); i++) + { + if ( ((atom)atomList.elementAt(i)).bonds.size() == 3) + { + atom tmp; + Vector v = new Vector(); + v.addElement((atom)atomList.elementAt(i)); + for (int j = 0; j < 3; j++) + { + if (((bond)((atom)v.elementAt(0)).bonds.elementAt(j)).a1 == (atom)v.elementAt(0)) + v.addElement(((bond)((atom)v.elementAt(0)).bonds.elementAt(j)).a2); + else + v.addElement(((bond)((atom)v.elementAt(0)).bonds.elementAt(j)).a1); + } + this.buildTerm(v, termList); + } + } + } + + protected void buildTerm(Vector v, Vector termList) + { + opbterm b = new opbterm((atom)v.elementAt(0), (atom)v.elementAt(1), (atom)v.elementAt(2), (atom)v.elementAt(3)); + if (b.ks != 0.0) + { + termList.addElement(b); + //System.out.println("added opb " + ((atom)v.elementAt(0)).getMM3TypeNum() + " " + ((atom)v.elementAt(1)).getMM3TypeNum() + " " + ((atom)v.elementAt(2)).getMM3TypeNum() + ((atom)v.elementAt(3)).getMM3TypeNum()); + } + b = new opbterm((atom)v.elementAt(0), (atom)v.elementAt(2), (atom)v.elementAt(3), (atom)v.elementAt(1)); + if (b.ks != 0.0) + { + termList.addElement(b); + //System.out.println("added opb " + ((atom)v.elementAt(0)).getMM3TypeNum() + " " + ((atom)v.elementAt(2)).getMM3TypeNum() + " " + ((atom)v.elementAt(3)).getMM3TypeNum() + ((atom)v.elementAt(1)).getMM3TypeNum()); + } + b = new opbterm((atom)v.elementAt(0), (atom)v.elementAt(3), (atom)v.elementAt(1), (atom)v.elementAt(2)); + if (b.ks != 0.0) + { + termList.addElement(b); + //System.out.println("added opb " + ((atom)v.elementAt(0)).getMM3TypeNum() + " " + ((atom)v.elementAt(3)).getMM3TypeNum() + " " + ((atom)v.elementAt(1)).getMM3TypeNum() + ((atom)v.elementAt(2)).getMM3TypeNum()); + } + } + + public double computeForces() + { + //calculate angle + double pq[], rq[], qs[], normal[], dthdpq[], dthdrq[], dthdqs[]; + pq = new double[3]; rq = new double[3]; qs = new double[3]; normal = new double[3]; + dthdpq = new double[3]; dthdrq = new double[3]; dthdqs = new double[3]; + double qsdotqs, ndotn, ndotqs, denominator, dEdth; + + for (int i = 0; i < 3; i++) + { + pq[i] = myAtoms[0].x[i] - myAtoms[3].x[i]; + rq[i] = myAtoms[0].x[i] - myAtoms[2].x[i]; + qs[i] = myAtoms[1].x[i] - myAtoms[0].x[i]; + } + + normal[0] = pq[1]*rq[2] - pq[2]*rq[1]; + normal[1] = pq[2]*rq[0] - pq[0]*rq[2]; + normal[2] = pq[0]*rq[1] - pq[1]*rq[0]; + + ndotn = normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2]; + qsdotqs = qs[0]*qs[0] + qs[1]*qs[1] + qs[2]*qs[2]; + ndotqs = normal[0]*qs[0] + normal[1]*qs[1] + normal[2]*qs[2]; + + if(ndotn <= 0) ndotn = mm3MinimizeAlgorythm.TINY; + if(qsdotqs <= 0) qsdotqs = mm3MinimizeAlgorythm.TINY; + + double jtemp1 = ndotn * qsdotqs - ndotqs * ndotqs; + if(jtemp1 <= 0) jtemp1 = mm3MinimizeAlgorythm.TINY; + denominator = Math.sqrt(jtemp1); + + double jtemp2 = ndotqs / Math.sqrt(ndotn * qsdotqs); + if(jtemp2 < -1) jtemp2 = -1; + if(jtemp2 > 1) jtemp2 = 1; + angle = Math.PI/2 - Math.acos(jtemp2); + + potential = computePotential(angle); + dEdth = computePotentialDerivative(angle); + + dthdpq[0] = (rq[2]*qs[1] - rq[1]*qs[2] - (rq[2]*normal[1] - rq[1]*normal[2]) * ndotqs / ndotn) / denominator; + dthdpq[1] = (rq[0]*qs[2] - rq[2]*qs[0] - (rq[0]*normal[2] - rq[2]*normal[0]) * ndotqs / ndotn) / denominator; + dthdpq[2] = (rq[1]*qs[0] - rq[0]*qs[1] - (rq[1]*normal[0] - rq[0]*normal[1]) * ndotqs / ndotn) / denominator; + + dthdrq[0] = (pq[1]*qs[2] - pq[2]*qs[1] - (pq[1]*normal[2] - pq[2]*normal[1]) * ndotqs / ndotn) / denominator; + dthdrq[1] = (pq[2]*qs[0] - pq[0]*qs[2] - (pq[2]*normal[0] - pq[0]*normal[2]) * ndotqs / ndotn) / denominator; + dthdrq[2] = (pq[0]*qs[1] - pq[1]*qs[0] - (pq[0]*normal[1] - pq[1]*normal[0]) * ndotqs / ndotn) / denominator; + + dthdqs[0] = (normal[0] - qs[0] * ndotqs / qsdotqs) / denominator; + dthdqs[1] = (normal[1] - qs[1] * ndotqs / qsdotqs) / denominator; + dthdqs[2] = (normal[2] - qs[2] * ndotqs / qsdotqs) / denominator; + + for (int i = 0; i < 3; i++) + { + myAtoms[0].f[i] += dEdth * (-dthdqs[i] + dthdrq[i] + dthdpq[i]); + myAtoms[1].f[i] += dEdth * dthdqs[i]; + myAtoms[2].f[i] += dEdth * -dthdrq[i]; + myAtoms[3].f[i] += dEdth * -dthdpq[i]; + } + return myAtoms[0].f[0]; + //return dTheta; + } + + public void setCalculationValues() + { + int atomBentType = myAtoms[1].getMM3TypeNum(); + int atomCenterType = myAtoms[0].getMM3TypeNum(); + + try + { + AtomDataFile dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "mm3opbdata.txt"); + //AtomDataFile dataFile = new AtomDataFile("mm3opbdata.txt"); + if (dataFile.findData(atomCenterType, atomBentType, 0, 1)) + ks = dataFile.parseDouble(2); + else + { + //System.out.println("no data for " + atomBentType + " " + atomCenterType + " bend"); + ks = 0.0; + } + } + catch (java.io.IOException e) + { + System.err.println("Bend data lookup error"); + e.printStackTrace(); + } + } + + protected double computePotential(double angle){ + return 0.5*ks*angle*angle; + } + + protected double computePotentialDerivative(double angle) + { + double force = ks * angle; + return force; + } + + public int termLength() + { + return 4; + } + + public String name() + { + return "Out of Plane Bend"; + } +} diff --git a/src/main/java/nanocad/minimize/mm3/strbendterm.java b/src/main/java/nanocad/minimize/mm3/strbendterm.java new file mode 100644 index 0000000..58bd97d --- /dev/null +++ b/src/main/java/nanocad/minimize/mm3/strbendterm.java @@ -0,0 +1,177 @@ +//////////////////////////////////// +// strbend.java +// written 8/6/01 by Andrew Knox +// implements stretch-bend term of +// energy minimization +//////////////////////////////////// + +package nanocad.minimize.mm3; + +import java.lang.Math; +import java.util.Vector; + +import nanocad.*; + +public class strbendterm extends nanocad.term +{ + private final double stbnunit = 2.51118; + private final double convert = 3.1415926 / 180; + private double idealAngle; + private double idealLength1; + private double idealLength2; + private double kBondAngle; + + public strbendterm() {} + + public strbendterm(atom center, atom other1, atom other2) + { + myAtoms = new atom[3]; + myAtoms[0] = center; + myAtoms[1] = other1; + myAtoms[2] = other2; + setCalculationValues(); + } + + + public void buildTerm(Vector v, Vector termList) + { + int atom1 = ((atom)v.elementAt(0)).getMM3TypeNum(); + int atom2 = ((atom)v.elementAt(1)).getMM3TypeNum(); + int atom3 = ((atom)v.elementAt(2)).getMM3TypeNum(); + + strbendterm b = new strbendterm((atom)v.elementAt(0), (atom)v.elementAt(1), (atom)v.elementAt(2)); + if ( b.kBondAngle != 0.0 && b.idealLength1 != 0.0 && b.idealLength2 != 0.0 && b.idealAngle != 0.0) + { + if (atom1 == atom3) + { + if (((atom)v.elementAt(0)).x[0] < ((atom)v.elementAt(2)).x[0]) + { + termList.addElement(b); + System.out.println("added:" + atom1 + " " + atom2 + " " + atom3); + System.out.println("k:" + b.kBondAngle + " angle:" + b.idealAngle + " len1:" + b.idealLength1 + " len2:" +b.idealLength2); + } + } + else + { + termList.addElement(b); + System.out.println("added:" + atom1 + " " + atom2 + " " + atom3); + } + } + } + + public double computeForces() + { + double ab[], bc[], abdotbc, abdotab, bcdotbc, dotnorm, angle, dedr, deds, dedth, s, r, + drda[], drdb[], dsdb[], dsdc[], dthda[], dthdb[], dthdc[], denominator; + ab = new double[3]; bc = new double[3]; drda = new double[3]; drdb = new double[3]; dsdb = new double[3]; + dsdc = new double[3]; dthda = new double[3]; dthdb = new double[3]; dthdc = new double[3]; + + for (int i = 0; i < 3; i++) + { + ab[i] = myAtoms[0].x[i] - myAtoms[1].x[i]; + bc[i] = myAtoms[2].x[i] - myAtoms[1].x[i]; + } + + abdotbc = ab[0] * bc[0] + ab[1] * bc[1] + ab[2] * bc[2]; + abdotab = ab[0] * ab[0] + ab[1] * ab[1] + ab[2] * ab[2]; + bcdotbc = bc[0] * bc[0] + bc[1] * bc[1] + bc[2] * bc[2]; + r = Math.sqrt(abdotab); + s = Math.sqrt(bcdotbc); + + angle = Math.acos(abdotbc / (r * s)); + + dedr = deds = stbnunit * kBondAngle * (angle - idealAngle); + dedth = stbnunit * kBondAngle * (r - idealLength1 + s - idealLength2); + + denominator = Math.sqrt(abdotab * bcdotbc - abdotbc * abdotbc); + + for (int i = 0; i < 3; i++) + { + drda[i] = ab[i] / r; + drdb[i] = -drda[i]; + dsdc[i] = bc[i] / r; + dsdb[i] = -dsdc[i]; + dthda[i] = (bc[i] - ab[i] * abdotbc / abdotab) / denominator; + dthdc[i] = (ab[i] - bc[i] * abdotbc / abdotab) / denominator; + dthdb[i] = -(dthda[i] + dthdc[i]); + + myAtoms[0].f[i] += dedr * drdb[i] + deds * dsdb[i] + dedth * dthdb[i]; + myAtoms[1].f[i] += dedr * drda[i] + dedth * dthda[i]; + myAtoms[2].f[i] += deds * dsdc[i] + dedth * dthdc[i]; + } + + return myAtoms[0].f[0]; + } + + + public void setCalculationValues() + { + int atom1 = myAtoms[0].getMM3TypeNum(); + int atom2 = myAtoms[1].getMM3TypeNum(); + int atom3 = myAtoms[2].getMM3TypeNum(); + + if (atom1 < atom3 || atom1 < 1 || atom2 < 1 || atom3 < 1) + { + kBondAngle = 0.0; + return; + } + + try + { + AtomDataFile dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "mm3strbenddata.txt"); + //AtomDataFile dataFile = new AtomDataFile("mm3strbenddata.txt"); + if (dataFile.findData(atom1, 0)) + kBondAngle = dataFile.parseDouble(1); + else + { + kBondAngle = 0.0; + return; + } + + dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "mm3adata.txt"); + //dataFile = new AtomDataFile("mm3adata.txt"); + if (dataFile.findData(atom2, atom1, atom3, 1, 0, 2)) + idealAngle = convert * dataFile.parseDouble(4); + else + { + idealAngle = 0.0; + return; + } + + dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "mm3ldata.txt"); + //dataFile = new AtomDataFile("mm3ldata.txt"); + if (dataFile.findData(Math.min(atom1, atom2), Math.max(atom1, atom2), 0, 1)) + idealLength1 = dataFile.parseDouble(3); + else + { + idealLength1 = 0.0; + return; + } + + if (dataFile.findData(Math.min(atom2, atom3), Math.max(atom2, atom3), 0, 1)) + idealLength2 = dataFile.parseDouble(3); + else + { + idealLength2 = 0.0; + return; + } + } catch(java.io.IOException e) + { + System.err.println("Stretch-bend data lookup error"); + e.printStackTrace(); + } + } + + public int termLength() + { + return 3; + } + + public String name() + { + return "Stretch-bend"; + } +} diff --git a/src/main/java/nanocad/minimize/mm3/strtorterm.java b/src/main/java/nanocad/minimize/mm3/strtorterm.java new file mode 100644 index 0000000..0153c7f --- /dev/null +++ b/src/main/java/nanocad/minimize/mm3/strtorterm.java @@ -0,0 +1,216 @@ +//////////////////////////////// +// strtorterm.java +// written by Andrew Knox +// May 29, 2002 +// the stretch-torsion term for mm3 energy minimization +//////////////////////////////// + +package nanocad.minimize.mm3; + +import java.lang.Math; +import java.util.Vector; + +import nanocad.*; + +public class strtorterm extends nanocad.term +{ + private double v1, v2, v3, r0; + public static double strtorunit = -5.9975; + public strtorterm() {} + + public strtorterm(atom a1, atom a2, atom a3, atom a4) + { + int i; + boolean found; + myAtoms = new atom[4]; + myAtoms[0] = a1; + myAtoms[1] = a2; + myAtoms[2] = a3; + myAtoms[3] = a4; + setCalculationValues(); + } + + protected void buildTerm (Vector v, Vector termList) + { + int atom1 = ((atom)v.elementAt(0)).getMM3TypeNum(); + int atom2 = ((atom)v.elementAt(1)).getMM3TypeNum(); + int atom3 = ((atom)v.elementAt(2)).getMM3TypeNum(); + int atom4 = ((atom)v.elementAt(3)).getMM3TypeNum(); + + if (atom2 < atom3 && atom1 < atom4) + { + strtorterm t = new strtorterm ((atom) v.elementAt(0), + (atom) v.elementAt(1), + (atom) v.elementAt(2), + (atom) v.elementAt(3)); + + + if (t.v3 != 0.0 || t.r0 != 0.0) + { + termList.addElement(t); + System.out.println("added stor: " + atom1 + " " + atom2 + " " + atom3 + " " + atom4); + } + } + else if (atom2 == atom3 && atom1 < atom4) + { + if ( ((atom)v.elementAt(1)).x[0] >= ((atom)v.elementAt(2)).x[0]) + { + strtorterm t = new strtorterm ((atom) v.elementAt(0), + (atom) v.elementAt(1), + (atom) v.elementAt(2), + (atom) v.elementAt(3)); + + if (t.v3 != 0.0 || t.r0 != 0.0) + { + termList.addElement(t); + System.out.println("added stor: " + atom1 + " " + atom2 + " " + atom3 + " " + atom4); + } + } + } + else if (atom2 == atom3 && atom1 == atom4) + { + if ( ((atom)v.elementAt(1)).x[0] >= ((atom)v.elementAt(2)).x[0] ) + { + + strtorterm t = new strtorterm ((atom) v.elementAt(0), + (atom) v.elementAt(1), + (atom) v.elementAt(2), + (atom) v.elementAt(3)); + + if (t.v3 != 0.0 || t.r0 != 0.0) + { + termList.addElement(t); + System.out.println("added stor: " + atom1 + " " + atom2 + " " + atom3 + " " + atom4); + } + } + } + } + + public double computeForces() + { + double ab[], bc[], cd[], na[], nd[], nadotna, nddotnd, nadotnd, theta, dedth, dthdab[], dthdbc[], dthdcd[], denominator; + double r, dedr, drdb[], drdc[]; + ab = new double[3]; bc = new double[3]; cd = new double[3]; na = new double[3]; nd = new double[3]; dthdab = new double[3]; + dthdbc = new double[3]; dthdcd = new double[3]; drdb = new double[3]; drdc = new double[3]; + + for (int i = 0; i < 3; i++) + { + ab[i] = myAtoms[1].x[i] - myAtoms[0].x[i]; + bc[i] = myAtoms[2].x[i] - myAtoms[1].x[i]; + cd[i] = myAtoms[3].x[i] - myAtoms[2].x[i]; + } + + na[0] = ab[1]*bc[2] - ab[2]*bc[1]; + na[1] = ab[2]*bc[0] - ab[0]*bc[2]; + na[2] = ab[0]*bc[1] - ab[1]*bc[0]; + + nd[0] = bc[1]*cd[2] - bc[2]*cd[1]; + nd[1] = bc[2]*cd[0] - bc[0]*cd[2]; + nd[2] = bc[0]*cd[1] - bc[1]*cd[0]; + + nadotna = na[0]*na[0] + na[1]*na[1] + na[2]*na[2]; + nadotnd = na[0]*nd[0] + na[1]*nd[1] + na[2]*nd[2]; + nddotnd = nd[0]*nd[0] + nd[1]*nd[1] + nd[2]*nd[2]; + + theta = Math.acos(nadotnd / Math.sqrt(nadotna * nddotnd)); + r = Math.sqrt(bc[0]*bc[0] + bc[1]*bc[1] + bc[2]*bc[2]); + + dedr = ( v1/2 * (1 + Math.cos(theta)) + v2/2 * (1 + Math.cos(2 * theta)) + v3/2 * (1 + Math.cos(3 * theta)) ); + dedth = (r - r0) * (-v1 / 2 * Math.sin(theta) - v2 * Math.sin(2 * theta) - v3 * 3 / 2 * Math.sin(3 * theta)); + + denominator = Math.sqrt(nadotna * nddotnd - nadotnd * nadotnd); + + dthdab[0] = (nd[1]*bc[2] - nd[2]*bc[1] + (na[2]*bc[1] - na[1]*bc[2]) * nadotnd / nadotna) / denominator; + dthdbc[0] = (nd[2]*ab[1] - nd[1]*ab[2] + na[1]*cd[2] - na[2]*cd[1] + (na[1]*ab[2] - na[2]*ab[1]) * nadotnd / nadotna + + (nd[2]*cd[1] - nd[1]*cd[2]) * nadotnd / nddotnd) / denominator; + dthdcd[0] = (na[2]*bc[1] - na[1]*bc[2] + (nd[1]*bc[2] - nd[2]*bc[1]) * nadotnd / nddotnd) / denominator; + + dthdab[1] = (nd[2]*bc[0] - nd[0]*bc[2] + (na[0]*bc[2] - na[2]*bc[0]) * nadotnd / nadotna) / denominator; + dthdbc[1] = (nd[0]*ab[2] - nd[2]*ab[0] + na[2]*cd[0] - na[0]*cd[2] + (na[2]*ab[0] - na[0]*ab[2]) * nadotnd / nadotna + + (nd[0]*cd[2] - nd[2]*cd[0]) * nadotnd / nddotnd) / denominator; + dthdcd[1] = (na[0]*bc[2] - na[2]*bc[0] + (nd[2]*bc[0] - nd[0]*bc[2]) * nadotnd / nddotnd) / denominator; + + dthdab[2] = (nd[0]*bc[1] - nd[1]*bc[0] + (na[1]*bc[0] - na[0]*bc[1]) * nadotnd / nadotna) / denominator; + dthdbc[2] = (nd[1]*ab[0] - nd[0]*ab[1] + na[0]*cd[1] - na[1]*cd[0] + (na[0]*ab[1] - na[1]*ab[0]) * nadotnd / nadotna + + (nd[1]*cd[0] - nd[0]*cd[1]) * nadotnd / nddotnd) / denominator; + dthdcd[2] = (na[1]*bc[0] - na[0]*bc[1] + (nd[0]*bc[1] - nd[1]*bc[0]) * nadotnd / nddotnd) / denominator; + + for (int i = 0; i < 3; i++) + { + drdb[i] = -bc[i] / r; + drdc[i] = bc[i] / r; + } + + for (int i = 0; i < 3; i++) + { + myAtoms[0].f[i] += (dedth * -dthdab[i]); + myAtoms[1].f[i] += (dedth * (dthdab[i] - dthdbc[i]) + dedr * drdb[i]); + myAtoms[2].f[i] += (dedth * (dthdbc[i] - dthdcd[i]) + dedr * drdc[i]); + myAtoms[3].f[i] += (dedth * dthdcd[i]); + } + return myAtoms[0].f[0]; + } + + protected double computePotential(double theta, double r) + { + return (r - r0) * (v1/2 * (1+Math.cos(theta)) + v2/2 * (1+Math.cos(2*theta)) + v3/2 * (1+Math.cos(3*theta)) ); + } + + protected void setCalculationValues() + { + int atomOneType = myAtoms[0].getMM3TypeNum(); + int atomTwoType = myAtoms[1].getMM3TypeNum(); + int atomThreeType = myAtoms[2].getMM3TypeNum(); + if (atomOneType < 0 || atomTwoType < 0) + { + setDefaultCalculationValues(); + return; + } + + try + { + AtomDataFile dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "mm3ldata.txt"); + //AtomDataFile dataFile = new AtomDataFile("mm3ldata.txt"); + if (dataFile.findData(atomTwoType, atomThreeType, 0, 1)) + { + r0 = dataFile.parseDouble(3); + } +// else if (dataFile.findData(atomThreeType, atomTwoType, 0, 1)) +// { +// r0 = dataFile.parseDouble(3); +// } + + dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "mm3strtordata.txt"); + //dataFile = new AtomDataFile("mm3strtordata.txt"); + if (dataFile.findData(atomTwoType, atomThreeType, 0, 1)) + { + v1 = dataFile.parseDouble(2); + v2 = dataFile.parseDouble(3); + v3 = dataFile.parseDouble(4); + } + } + catch (java.io.IOException e) { + System.err.println("Stretch-torsion data lookup error"); + e.printStackTrace(); + } + } + + public void setDefaultCalculationValues() + { + defaultsUsed = true; + v3 = 0.0; + System.out.println("No data for " + myAtoms[0].getMM3TypeNum() + " " + myAtoms[1].getMM3TypeNum() + " " + myAtoms[2].getMM3TypeNum() + " " + myAtoms[3].getMM3TypeNum() + " torsion"); + } + + public int termLength() + { + return 4; + } + + public String name() + { + return "Stretch-Torsion"; + } +} diff --git a/src/main/java/nanocad/minimize/mm3/term.java b/src/main/java/nanocad/minimize/mm3/term.java new file mode 100644 index 0000000..ca3ed53 --- /dev/null +++ b/src/main/java/nanocad/minimize/mm3/term.java @@ -0,0 +1,191 @@ +package nanocad.minimize.mm3; + +/** + * term.java - MM2-style energy term, for computing interatomic forces + * Copyright (c) 1997 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.lang.Math; +import java.util.Vector; + +import nanocad.atom; +import nanocad.bond; + +public abstract class term +{ + public static final String rcsid = + "$Id: term.java,v 1.2 2005/05/14 23:51:02 xli16 Exp $"; + public atom[] myAtoms; + public static final double pi = 3.1415926; + public double potential; + + protected boolean defaultsUsed = false; + public term () + { + // needed for termList + } + protected double acos (double x) + { + //makes no sense - Mike Hewner 8/7/00 + if (x >= 1.0) return pi / 2; + if (x <= -1.0) return -pi / 2; + return Math.acos (x); + } + + private void bondChain (atom a, int n, Vector termList) + { + Vector v = new Vector(); + v.addElement(a); + nextBondChain(v, n-1, termList); + } + + protected abstract void buildTerm(Vector v, Vector termList); + + public abstract double computeForces(); + public double getpotential() + { + return potential; + } + + // handy vector arithmetic + protected double[] crossProduct (double[] x, double[] y) + { + double[] z = new double[3]; + z[0] = x[1] * y[2] - x[2] * y[1]; + z[1] = x[2] * y[0] - x[0] * y[2]; + z[2] = x[0] * y[1] - x[1] * y[0]; + return z; + } +/** + * Insert the method's description here. + * Creation date: (7/17/2000 3:39:31 PM) + * @return boolean + */ +public boolean defaultsUsed() { + return defaultsUsed; +} + protected double dotProduct (double[] x, double[] y) + { + return x[0] * y[0] + x[1] * y[1] + x[2] * y[2]; + } + public void enumerate (Vector atomList, Vector termList) + { + int i; + for (i = 0; i < atomList.size (); i++) + bondChain ((atom) atomList.elementAt(i), termLength(), termList); + } + +protected double findAngle(atom a, atom b, atom c) +//returns the size of the angle abc in degrees +{ + double[] aCoordsRelativeToB = new double[3]; + double[] cCoordsRelativeToB = new double[3]; + double aLength = 0.0; + double cLength = 0.0; + for(int i = 0; i < 3; i++) + { + aCoordsRelativeToB[i] = a.x[i] - b.x[i]; + cCoordsRelativeToB[i] = c.x[i] - b.x[i]; + } + aLength = lengthBetween(a,b); + cLength = lengthBetween(b,c); + double cosTheta = dotProduct(aCoordsRelativeToB, cCoordsRelativeToB) / aLength / cLength; + return Math.acos(cosTheta); +} + +public double lengthBetween(atom a, atom b) { + double length = 0.0; + for(int i = 0; i < 3; i++) + { + double aCoordsRelativeToB = a.x[i] - b.x[i]; + length = length + aCoordsRelativeToB * aCoordsRelativeToB; + } + return Math.sqrt(length); +} + +private void nextBondChain (Vector v, int n, Vector termList) + { + int i; + atom a1, a2; + if (n == 0) + { + buildTerm (v, termList); + return; + } + a1 = (atom) v.elementAt(v.size()-1); + for (i = 0; i < a1.bonds.size(); i++) + { + a2 = ((bond) a1.bonds.elementAt(i)).otherAtom(a1); + if (!v.contains(a2)) + { + v.addElement(a2); + nextBondChain(v, n-1, termList); + v.removeElement(a2); + } + } + } + +public String repr() + { + int i; + if (myAtoms == null) + return ""; + + String s = ""; + } + protected String repr2() + { + return ""; + } + protected double[] scalevec (double m, double[] x) + { + double[] z = new double[3]; + int i; + for (i = 0; i < 3; i++) + z[i] = m * x[i]; + return z; + } +/** + * Insert the method's description here. + * Creation date: (6/15/00 1:34:52 PM) + */ +protected abstract void setCalculationValues(); + protected double sqrt (double x) + { + if (x <= 0.0) return 0.0; + return Math.sqrt (x); + } + protected abstract int termLength(); + protected String name() + { + return "default"; + } + protected double veclen (double[] x) + { + return Math.sqrt (dotProduct (x, x)); + } +} diff --git a/src/main/java/nanocad/minimize/mm3/tterm.java b/src/main/java/nanocad/minimize/mm3/tterm.java new file mode 100644 index 0000000..50a6421 --- /dev/null +++ b/src/main/java/nanocad/minimize/mm3/tterm.java @@ -0,0 +1,217 @@ +package nanocad.minimize.mm3; + +/** + * tterm.java - MM2-style torsion energy term + * Copyright (c) 1997,1998 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.lang.Math; +import java.util.Vector; + +import nanocad.*; + +public class tterm extends nanocad.term +{ + public static final String rcsid = + "$Id: tterm.java,v 1.2 2005/05/14 23:51:02 xli16 Exp $"; + private double v1, v2, v3; + private final static double PI = 3.14159265258979; + private final static double torsionunit = 0.125; +/** + * Insert the method's description here. + * Creation date: (6/19/00 4:09:57 PM) + */ +public tterm() {} +public tterm(atom a1, atom a2, atom a3, atom a4) { + int i; + boolean found; + myAtoms = new atom[4]; + myAtoms[0] = a1; + myAtoms[1] = a2; + myAtoms[2] = a3; + myAtoms[3] = a4; + setCalculationValues(); + } + protected void buildTerm (Vector v, Vector termList) + { + int atom1 = ((atom)v.elementAt(0)).getMM3TypeNum(); + int atom2 = ((atom)v.elementAt(1)).getMM3TypeNum(); + int atom3 = ((atom)v.elementAt(2)).getMM3TypeNum(); + int atom4 = ((atom)v.elementAt(3)).getMM3TypeNum(); + + if (atom1 < atom4 && atom2 < atom3) + { + tterm t = new tterm ((atom) v.elementAt(0), + (atom) v.elementAt(1), + (atom) v.elementAt(2), + (atom) v.elementAt(3)); + + + if (t.v1 != 0.0 || t.v2 != 0.0 || t.v3 != 0.0) + { + termList.addElement(t); + //System.out.println("added: " + atom1 + " " + atom2 + " " + atom3 + " " + atom4); + } + } + else if (atom2 == atom3 && atom1 < atom4) + { + if ( ((atom)v.elementAt(1)).x[0] >= ((atom)v.elementAt(2)).x[0]) + { + tterm t = new tterm ((atom) v.elementAt(0), + (atom) v.elementAt(1), + (atom) v.elementAt(2), + (atom) v.elementAt(3)); + if (t.v1 != 0.0 || t.v2 != 0.0 || t.v3 != 0.0) + { + termList.addElement(t); + //System.out.println("added: " + atom1 + " " + atom2 + " " + atom3 + " " + atom4); + } + } + } + else if (atom2 == atom3 && atom1 == atom4) + { + if ( ((atom)v.elementAt(1)).x[0] >= ((atom)v.elementAt(2)).x[0] ) + { + tterm t = new tterm ((atom) v.elementAt(0), + (atom) v.elementAt(1), + (atom) v.elementAt(2), + (atom) v.elementAt(3)); + if (t.v1 != 0.0 || t.v2 != 0.0 || t.v3 != 0.0) + { + termList.addElement(t); + //System.out.println("added: " + atom1 + " " + atom2 + " " + atom3 + " " + atom4); + } + } + } + } + + public double computePotential(double theta){ + return torsionunit*0.5*(v1*(1+Math.cos(theta)) + v2*(1-Math.cos(2*theta)) + v3*(1+Math.cos(3*theta))); + } + + public double computeForces () + { + double ij[], kj[], kl[], mj[], nk[], dxdi[], dxdj[], dxdk[], dxdl[]; + ij = new double[3]; kj = new double[3]; kl = new double[3]; + mj = new double[3]; nk = new double[3]; + dxdi = new double[3]; dxdj = new double[3]; dxdk = new double[3]; dxdl = new double[3]; + for (int i = 0; i < 3; i++) + { + ij[i] = myAtoms[0].x[i] - myAtoms[1].x[i]; + kj[i] = myAtoms[2].x[i] - myAtoms[1].x[i]; + kl[i] = myAtoms[2].x[i] - myAtoms[3].x[i]; + } + mj = crossProduct(ij,kj); + nk = crossProduct(kj,kl); + + double theta = dotProduct(mj,nk) / Math.sqrt(dotProduct(mj,mj)*dotProduct(nk,nk)); + if(theta < -1) theta = -1; + if(theta > 1) theta = 1; + theta = Math.acos(theta); + double dedth = torsionunit * (-v1/2 * Math.sin(theta) - v2 * Math.sin(2*theta) - v3*1.5 * Math.sin(3*theta)); + potential = computePotential(theta); + if (potential < 0.0001) return 0.0; + for (int i = 0; i < 3; i++) + { + dxdi[i] = Math.sqrt(dotProduct(kj,kj))/dotProduct(mj,mj)*mj[i]; + dxdk[i] = -Math.sqrt(dotProduct(kj,kj))/dotProduct(nk,nk)*nk[i]; + dxdj[i] = ((dotProduct(ij,kj) / dotProduct(kj,kj)) - 1.0)*dxdi[i] - + (dotProduct(kl,kj) / dotProduct(kj,kj))*dxdl[i]; + dxdk[i] = ((dotProduct(kl,kj) / dotProduct(kj,kj)) - 1.0)*dxdl[i] - + (dotProduct(ij,kj) / dotProduct(kj,kj))*dxdi[i]; + myAtoms[0].f[i] -= dedth * dxdi[i]; + myAtoms[1].f[i] -= dedth * dxdj[i]; + myAtoms[2].f[i] -= dedth * dxdk[i]; + myAtoms[3].f[i] -= dedth * dxdl[i]; + } + return myAtoms[0].f[0]; + } + + + protected String repr2() + { + return " torsion " + + (new Double(v1)).toString() + " " + + (new Double(v2)).toString() + " " + + (new Double(v3)).toString(); + } +/** + * Insert the method's description here. + * Creation date: (6/15/00 1:40:30 PM) + */ +protected void setCalculationValues() { + int atomOneType = myAtoms[0].getMM3TypeNum(); + int atomTwoType = myAtoms[1].getMM3TypeNum(); + int atomThreeType = myAtoms[2].getMM3TypeNum(); + int atomFourType = myAtoms[3].getMM3TypeNum(); + if ((atomOneType < 0) || (atomTwoType < 0) || (atomThreeType < 0) || (atomFourType < 0)) { + setDefaultCalculationValues(); + return; + } + try { + AtomDataFile dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "mm3tdata.txt"); + //AtomDataFile dataFile = new AtomDataFile("mm3tdata.txt"); + boolean dataFound = false; + + //it isn't necessary to make sure the atoms are in increasing order, since each bond chain is added both forwards and backwards. + + if (atomOneType == atomFourType && atomTwoType == atomThreeType) + { + if (myAtoms[0].x[0] > myAtoms[3].x[0]) + dataFound = dataFile.findData(atomOneType, atomTwoType, atomThreeType, atomFourType, 0, 1, 2, 3); + } + else + dataFound = dataFile.findData(atomOneType, atomTwoType, atomThreeType, atomFourType, 0, 1, 2, 3); + + if (dataFound) { + v1 = dataFile.parseDouble(4); + v2 = dataFile.parseDouble(7); + v3 = dataFile.parseDouble(10); + } else { + setDefaultCalculationValues(); + return; + } + } catch (java.io.IOException e) { + System.err.println("Torsion data lookup error"); + e.printStackTrace(); + } +} +/** + * Insert the method's description here. + * Creation date: (6/19/00 3:02:53 PM) + */ +public void setDefaultCalculationValues() { + defaultsUsed = true; + v1 = v2 = v3 = 0.0; + //System.out.println("No data for " + myAtoms[0].getMM3TypeNum() + " " + myAtoms[1].getMM3TypeNum() + " " + myAtoms[2].getMM3TypeNum() + " " + myAtoms[3].getMM3TypeNum() + " torsion"); +} + public int termLength() + { + return 4; + } + public String name() + { + return "Torsion"; + } +} diff --git a/src/main/java/nanocad/minimize/mm3/vdwterm.java b/src/main/java/nanocad/minimize/mm3/vdwterm.java new file mode 100644 index 0000000..cb28089 --- /dev/null +++ b/src/main/java/nanocad/minimize/mm3/vdwterm.java @@ -0,0 +1,248 @@ +package nanocad.minimize.mm3; + +/** + * lterm.java - MM2-style length energy term + * Copyright (c) 1997,1998 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * or its derived works must display the following acknowledgement: + * This product includes software developed by Will Ware. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.lang.Math; +import java.util.Vector; + +import nanocad.*; + +public class vdwterm extends nanocad.term +{ + public static final String rcsid = + "$Id: vdwterm.java,v 1.2 2005/05/14 23:51:02 xli16 Exp $"; + /* I've been hacking a bit with acceptable forms for the length-energy term. + * _Nanosystems_ lists one simple expression with a square and cubic term + * for close distances, and various kinds of exponential expressions for + * farther away. But these depend on numbers called De and beta and I don't + * have tables for those (just the few examples in _Nanosystems_). So after + * some puttering and graphing and algebra, I came up with the following. + * Energies are in attojoules (10^-18 joules), distances are in angstroms + * (10^-10 m), forces are in attojoules per angstrom (10^-8 N), and + * spring constants are in attojoules per angstrom-squared (100 N/m). This + * is consistent with the units in _Nanosystems_, and also the units used + * in the 'mm2.prm' parameter file I found on Jay Ponder's ftp site. + * Expressions for energy and force, where ks and r0 are a function of + * the two atoms involved: + * + * dr = r - r0; + * + * Energy (r) := + * if (dr < rthresh) + * { return 0.5 * ks * dr * dr * (1 - kc * dr) - z * ks; } + * else + * { return (-a * ks / beta) * exp (-beta * dr); } + * + * Force (r) := + * if (dr < rthresh) + * { return -(ks * dr * (1 - 1.5 * kc * dr)); } + * else + * { return -a * ks * exp (-beta * dr); } + * + * + * A, beta, z, kcubic, and rthresh are defined below. Notice my use of + * 'beta' differs from the use in _Nanosystems_, but plays a similar role. + * + * These follow Drexler's quadratic-cubic form for dr < rthresh, and for + * dr > rthresh, they follow an exponential drop-off which is pretty + * continuous for both energy and force. The only point that I think would + * be worth quibbling over would be the value of beta, which I picked so + * that it would look "reasonable" on a graph. + */ + private static final double kcubic = 2.0; /* (0.5 angstrom)^-1 */ + private static final double rthresh = 1 / (3 * kcubic); + private static final double beta = 3.0; + private static final double a = rthresh * (1 - 1.5 * kcubic * rthresh) * + Math.exp (beta * rthresh); + private static final double z = (a / beta) * Math.exp(-beta * rthresh) + + 0.5 * rthresh * rthresh * (1 - kcubic * rthresh); + public final static double B = 2.55; + public final static double C = .583333; + private double pij; + private double Dij; +/** + * Insert the method's description here. + * Creation date: (6/19/00 4:09:33 PM) + */ +public vdwterm() {} +public vdwterm(atom a1, atom a2) { + myAtoms = new atom[2]; + myAtoms[0] = a1; + myAtoms[1] = a2; + setCalculationValues(); +} + protected void buildTerm (Vector v, Vector termList) + { + System.out.println("buildTerm for vdw term should never be called."); + } +public double computeForces() { + + if(defaultsUsed()) return 0.0; + + int i; + // compute forces on each atom, add it to the atom's force vector + double[] diff = new double[3]; + double r, m; + for (i = 0, r = 0.0; i < 3; i++) { + diff[i] = myAtoms[0].x[i] - myAtoms[1].x[i]; + r += diff[i] * diff[i]; + } + + if(r <= 0) r = mm3MinimizeAlgorythm.TINY; + r = Math.sqrt(r); + //System.out.println("r:"+r); + //System.out.println("r0:"+r0); + + potential = computePotential(r); + m = computePotentialDerivative(r); + + // at this point, m is du/dr + m /= r; + // m > 0 attract, m < 0 repel + for (i = 0; i < 3; i++) { + myAtoms[0].f[i] -= m * diff[i]; + myAtoms[1].f[i] += m * diff[i]; + } + return m * Math.sqrt(diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2]); + //return m*r; +} +/** + * Insert the method's description here. + * Creation date: (6/15/00 1:22:01 PM) + * @return double + * @param lengthDifference double + */ +protected double computePotentialDerivative(double p) { + //p is the acutal distance between atoms + double exponentForE = -12*p/pij; + double firstTerm = -2.208e6*Math.pow(Math.E, exponentForE)/pij; + double secondTerm; + if (p < (pij/3)) + { + secondTerm = 4.5*Math.pow(pij, 2.0)/Math.pow(p, 3.0); + } + else + { + secondTerm = 13.5*Math.pow(pij, 6.0)/Math.pow(p, 7.0); + } + + double force = Dij*(firstTerm + secondTerm);; + return force; +} + +public double computePotential(double p){ + return (Dij * ( 1.84E5 * Math.exp(-12 * p / pij) - 2.25 * Math.pow(pij / p, 6))); +} + +public void enumerate(Vector atomList, Vector termList) +{ + for(int i = 0; i < atomList.size(); i++) + { + atom currentAtom = (atom) atomList.elementAt(i); + for(int j = i + 1; j < atomList.size(); j++) + { + atom otherAtom = (atom) atomList.elementAt(j); + if(currentAtom.bondWith(otherAtom) == null) + { + boolean oneAtomSeperates = false; + for(int k = 0; (k < otherAtom.bonds.size()) && !oneAtomSeperates; k++) + if(((bond) otherAtom.bonds.elementAt(k)).otherAtom(otherAtom).bondWith(currentAtom) != null) + oneAtomSeperates = true; + if(!oneAtomSeperates) + { + vdwterm t = new vdwterm(currentAtom, otherAtom); + termList.addElement(t); + } + } + } + } + +} + protected String repr2() + { + return " VDW " + + (new Double(pij)).toString() + " " + + (new Double(Dij)).toString(); + } +/** + * Insert the method's description here. + * Creation date: (6/15/00 1:36:02 PM) + */ +protected void setCalculationValues() { + double Di, Dj, pi, pj; + int atomOneType = myAtoms[0].getMM3TypeNum(); + int atomTwoType = myAtoms[1].getMM3TypeNum(); + if (atomOneType < 0 || atomTwoType < 0) { + setDefaultCalculationValues(); + return; + } + int biggerValue = Math.max(atomOneType, atomTwoType); + int smallerValue = Math.min(atomOneType, atomTwoType); + try { + AtomDataFile dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "mm3vdwdata.txt"); + //AtomDataFile dataFile = new AtomDataFile("mm3vdwdata.txt"); + if (dataFile.findData(smallerValue, 0)) { + pi = dataFile.parseDouble(2); + Di = dataFile.parseDouble(1); + } else { + setDefaultCalculationValues(); + return; + } + if (dataFile.findData(biggerValue, 0)) { + pj = dataFile.parseDouble(2); + Dj = dataFile.parseDouble(1); + } else { + setDefaultCalculationValues(); + return; + } + Dij = Math.sqrt(Di * Dj); + pij = .5*( pi + pj); + } catch (java.io.IOException e) { + System.err.println("VDW data lookup error"); + e.printStackTrace(); + } +} +/** + * Insert the method's description here. + * Creation date: (6/19/00 1:50:46 PM) + */ +protected void setDefaultCalculationValues() +{ + defaultsUsed = true; +} + public int termLength() + { + return 2; + } + public String name() + { + return "Van der Waals"; + } +} diff --git a/src/main/java/nanocad/minimize/nanocad/aterm.java b/src/main/java/nanocad/minimize/nanocad/aterm.java new file mode 100644 index 0000000..5980d68 --- /dev/null +++ b/src/main/java/nanocad/minimize/nanocad/aterm.java @@ -0,0 +1,205 @@ +package nanocad.minimize.nanocad; + +/** + * aterm.java - MM2-style angle energy term + * Copyright (c) 1997,1998 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + + +import java.util.Vector; + +import nanocad.atom; + +public class aterm extends term +{ + public static final String rcsid = + "$Id: aterm.java,v 1.2 2005/05/14 23:51:00 xli16 Exp $"; + private static final double convert = 3.1415926 / 180; // degrees to radians + private double kth, th0; + private final static double[][] angleCoeffs = + { + { C, atom.SP3, C, atom.SP3, C, atom.SP3, 0.450, 109.470 }, + { C, atom.SP3, C, atom.SP3, C, atom.SP2, 0.450, 109.470 }, + { C, atom.SP3, C, atom.SP3, C, atom.SP, 0.450, 109.470 }, + { C, atom.SP3, C, atom.SP3, H, atom.NONE, 0.360, 109.390 }, + { C, atom.SP3, C, atom.SP3, O, atom.SP3, 0.700, 107.500 }, + { C, atom.SP3, C, atom.SP3, N, atom.SP3, 0.570, 109.470 }, + { C, atom.SP3, C, atom.SP3, N, atom.SP2, 0.500, 109.280 }, + { C, atom.SP3, C, atom.SP3, N, atom.SP3, 0.570, 103.500 }, + { C, atom.SP3, C, atom.SP3, O, atom.SP2, 0.700, 107.500 }, + { C, atom.SP2, C, atom.SP3, C, atom.SP2, 0.450, 109.470 }, + { C, atom.SP2, C, atom.SP3, C, atom.SP, 0.470, 109.470 }, + { C, atom.SP2, C, atom.SP3, H, atom.NONE, 0.360, 109.390 }, + { C, atom.SP2, C, atom.SP3, O, atom.SP3, 0.700, 109.500 }, + { C, atom.SP2, C, atom.SP3, N, atom.SP3, 1.045, 110.740 }, + { C, atom.SP2, C, atom.SP3, N, atom.SP2, 0.500, 109.800 }, + { C, atom.SP2, C, atom.SP3, N, atom.SP3, 1.045, 110.740 }, + { C, atom.SP, C, atom.SP3, C, atom.SP, 0.470, 109.470 }, + { C, atom.SP, C, atom.SP3, H, atom.NONE, 0.360, 109.390 }, + { H, atom.NONE, C, atom.SP3, H, atom.NONE, 0.320, 109.400 }, + { H, atom.NONE, C, atom.SP3, O, atom.SP3, 0.540, 106.700 }, + { H, atom.NONE, C, atom.SP3, N, atom.SP3, 0.500, 108.800 }, + { H, atom.NONE, C, atom.SP3, N, atom.SP2, 0.420, 109.000 }, + { H, atom.NONE, C, atom.SP3, N, atom.SP3, 0.500, 108.800 }, + { H, atom.NONE, C, atom.SP3, O, atom.SP2, 0.540, 106.700 }, + { O, atom.SP3, C, atom.SP3, O, atom.SP3, 0.460, 99.900 }, + { N, atom.SP3, C, atom.SP3, N, atom.SP3, 1.045, 110.740 }, + { N, atom.SP3, C, atom.SP3, N, atom.SP3, 1.045, 110.740 }, + { C, atom.SP3, C, atom.SP2, C, atom.SP3, 0.450, 117.200 }, + { C, atom.SP3, C, atom.SP2, C, atom.SP2, 0.550, 121.400 }, + { C, atom.SP3, C, atom.SP2, C, atom.SP, 0.470, 122.000 }, + { C, atom.SP3, C, atom.SP2, H, atom.NONE, 0.360, 118.200 }, + { C, atom.SP3, C, atom.SP2, O, atom.SP3, 0.500, 120.000 }, + { C, atom.SP2, C, atom.SP2, C, atom.SP2, 0.430, 120.000 }, + { C, atom.SP2, C, atom.SP2, H, atom.NONE, 0.360, 120.000 }, + { C, atom.SP2, C, atom.SP2, O, atom.SP3, 0.700, 124.300 }, + { C, atom.SP2, C, atom.SP2, N, atom.SP3, 0.616, 123.000 }, + { C, atom.SP2, C, atom.SP2, N, atom.SP2, 0.500, 118.000 }, + { C, atom.SP2, C, atom.SP2, O, atom.SP2, 0.600, 120.000 }, + { C, atom.SP, C, atom.SP2, H, atom.NONE, 0.360, 121.100 }, + { H, atom.NONE, C, atom.SP2, H, atom.NONE, 0.320, 119.000 }, + { H, atom.NONE, C, atom.SP2, O, atom.SP3, 0.540, 116.400 }, + { H, atom.NONE, C, atom.SP2, N, atom.SP3, 0.540, 119.000 }, + { H, atom.NONE, C, atom.SP2, N, atom.SP2, 0.300, 109.000 }, + { H, atom.NONE, C, atom.SP2, O, atom.SP2, 0.450, 108.000 }, + { N, atom.SP2, C, atom.SP2, N, atom.SP2, 0.400, 120.000 }, + { C, atom.SP3, C, atom.SP, C, atom.SP, 0.200, 180.000 }, + { C, atom.SP3, C, atom.SP, N, atom.SP, 0.325, 180.000 }, + { C, atom.SP2, C, atom.SP, C, atom.SP2, 0.400, 180.000 }, + { C, atom.SP2, C, atom.SP, C, atom.SP, 0.470, 180.000 }, + { C, atom.SP, C, atom.SP, H, atom.NONE, 0.360, 180.000 }, + { C, atom.SP, C, atom.SP, O, atom.SP3, 0.360, 180.000 }, + { C, atom.SP, C, atom.SP, O, atom.SP2, 0.360, 180.000 }, + { C, atom.SP, C, atom.SP, N, atom.SP3, 0.360, 180.000 }, + { C, atom.SP, C, atom.SP, N, atom.SP2, 0.360, 180.000 }, + { C, atom.SP, C, atom.SP, N, atom.SP, 0.360, 180.000 }, + { C, atom.SP3, O, atom.SP3, C, atom.SP3, 0.770, 106.800 }, + { C, atom.SP3, O, atom.SP3, C, atom.SP2, 0.770, 110.800 }, + { C, atom.SP3, O, atom.SP3, O, atom.SP3, 0.635, 98.700 }, + { C, atom.SP3, N, atom.SP3, C, atom.SP3, 0.630, 107.700 }, + { C, atom.SP3, N, atom.SP3, C, atom.SP2, 0.698, 107.000 }, + { C, atom.SP3, N, atom.SP3, N, atom.SP3, 0.740, 105.500 }, + { C, atom.SP3, N, atom.SP2, C, atom.SP3, 0.760, 126.000 }, + { C, atom.SP3, N, atom.SP2, C, atom.SP2, 0.630, 119.900 }, + { C, atom.SP2, N, atom.SP2, C, atom.SP2, 0.400, 107.000 }, + { C, atom.SP3, N, atom.SP3, C, atom.SP3, 0.630, 108.600 }, + { C, atom.SP3, N, atom.SP3, H, atom.NONE, 0.500, 109.470 }, + { H, atom.NONE, N, atom.SP3, H, atom.NONE, 0.500, 104.500 }, + { C, atom.SP3, O, atom.SP2, C, atom.SP2, 0.770, 113.600 }, + { C, atom.SP2, O, atom.SP2, C, atom.SP2, 0.870, 113.950 } + }; + public aterm (atom a1, atom a2, atom a3) + { + int i; + boolean found; + myAtoms = new atom[3]; + myAtoms[0] = a1; + myAtoms[1] = a2; + myAtoms[2] = a3; + for (i = 0, found = false; i < angleCoeffs.length && !found; i++) + if ((a1.atomicNumber () == angleCoeffs[i][0] && + a1.hybridization == angleCoeffs[i][1] && + a2.atomicNumber () == angleCoeffs[i][2] && + a2.hybridization == angleCoeffs[i][3] && + a3.atomicNumber () == angleCoeffs[i][4] && + a3.hybridization == angleCoeffs[i][5]) || + (a1.atomicNumber () == angleCoeffs[i][4] && + a1.hybridization == angleCoeffs[i][5] && + a2.atomicNumber () == angleCoeffs[i][2] && + a2.hybridization == angleCoeffs[i][3] && + a3.atomicNumber () == angleCoeffs[i][0] && + a3.hybridization == angleCoeffs[i][1])) + { + found = true; + kth = angleCoeffs[i][6]; + th0 = angleCoeffs[i][7] * convert; + } + if (!found) + { + kth = 0.3; + th0 = 120.0 * convert; + } + } + protected void buildTerm (Vector v, Vector termList) + { + aterm t = new aterm ((atom) v.elementAt(0), + (atom) v.elementAt(1), + (atom) v.elementAt(2)); + if (t.myAtoms[0].x[0] < t.myAtoms[2].x[0]) + { + termList.addElement (t); + } + } + public void computeForces () + { + if (kth == 0.0) return; + int i; + // compute forces on each atom, add it to the atom's force vector + double[] adiff = new double[3]; + double[] bdiff = new double[3]; + double aa = 0.0, ab = 0.0, bb = 0.0, th, tdif, duDth; + for (i = 0; i < 3; i++) + { + adiff[i] = myAtoms[0].x[i] - myAtoms[1].x[i]; + bdiff[i] = myAtoms[2].x[i] - myAtoms[1].x[i]; + aa += adiff[i] * adiff[i]; + ab += adiff[i] * bdiff[i]; + bb += bdiff[i] * bdiff[i]; + } + if (aa > 3.0 || bb > 3.0) + return; + th = acos (ab / sqrt (aa * bb)); + tdif = th - th0; + duDth = kth * (tdif * (1.0 + 1.508 * tdif * tdif * tdif * tdif)); + double[] f0 = new double[3]; + double[] f2 = new double[3]; + double ff0 = 0.0, ff2 = 0.0; + for (i = 0; i < 3; i++) + { + f0[i] = aa * bdiff[i] - ab * adiff[i]; + ff0 += f0[i] * f0[i]; + f2[i] = bb * adiff[i] - ab * adiff[i]; + ff2 += f2[i] * f2[i]; + } + double m0 = duDth / sqrt (ff0 * aa); + double m2 = duDth / sqrt (ff2 * bb); + for (i = 0; i < 3; i++) + { + f0[i] *= m0; + f2[i] *= m2; + myAtoms[0].f[i] += f0[i]; + myAtoms[1].f[i] -= f0[i] + f2[i]; + myAtoms[2].f[i] += f2[i]; + } + } + protected String repr2() + { + return " angle " + + (new Double(kth)).toString() + " " + + (new Double(th0)).toString(); + } + public int termLength() + { + return 3; + } +} diff --git a/src/main/java/nanocad/minimize/nanocad/lrterm.java b/src/main/java/nanocad/minimize/nanocad/lrterm.java new file mode 100644 index 0000000..54a3211 --- /dev/null +++ b/src/main/java/nanocad/minimize/nanocad/lrterm.java @@ -0,0 +1,241 @@ +package nanocad.minimize.nanocad; + +/** + * lrterm.java - MM2-style long-range (electrostatic and vdw) energy term + * Copyright (c) 1997 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * or its derived works must display the following acknowledgement: + * This product includes software developed by Will Ware. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.lang.Math; +import java.util.Vector; + +import nanocad.atom; +import nanocad.bond; + +public class lrterm extends term +{ + public static final String rcsid = + "$Id: lrterm.java,v 1.2 2005/05/14 23:51:00 xli16 Exp $"; + + private int[][] exclusions; + Vector atomList; + + private final static double dontKnowCorrectUnits = 1.0; + + private final static int maxNumChained = 50; + /* units here are (maJ * nm) / (e * e), where e is charge on a proton */ + private final static double electricConstant = + // (8.9876 * 0.160206 * 0.160206 * 1000.0); + -1.0e-3; + + // These are covalent bond dipole moments, due to + // differences in electronegativity. Actually, these + // are dipoleMoments divided by bondLengths, which + // gives fractionalCharges + private final static double[][] dipoleMoments = + { + { C, atom.SP3, C, atom.SP2, 0.300 / 1.497 }, + { C, atom.SP3, C, atom.SP, 0.750 / 1.470 }, + { C, atom.SP3, O, atom.SP3, 0.440 / 1.402 }, + { C, atom.SP3, N, atom.SP3, 0.040 / 1.438 }, + { C, atom.SP3, N, atom.SP2, 1.470 / 1.437 }, + { C, atom.SP3, C, atom.SP3, 0.150 / 1.502 }, + { C, atom.SP3, N, atom.SP2, 1.260 / 1.470 }, + { C, atom.SP3, C, atom.SP2, 0.300 / 1.497 }, + { C, atom.SP3, O, atom.SP2, 0.220 / 1.414 }, + { C, atom.SP3, N, atom.SP2, 1.260 / 1.488 }, + { C, atom.SP3, N, atom.SP2, 1.350 / 1.498 }, + { C, atom.SP3, C, atom.SP2, 0.300 / 1.497 }, + { C, atom.SP3, O, atom.SP3, 1.900 / 1.480 }, + { C, atom.SP3, C, atom.SP3, 0.300 / 1.509 }, + { C, atom.SP3, N, atom.SP2, 1.260 / 1.470 }, + { C, atom.SP2, O, atom.SP3, 0.001 / 1.355 }, + { C, atom.SP2, N, atom.SP3, -0.400 / 1.377 }, + { C, atom.SP2, N, atom.SP2, 1.300 / 1.410 }, + { C, atom.SP2, C, atom.SP3, -0.150 / 1.467 }, + { C, atom.SP2, N, atom.SP2, 0.583 / 1.260 }, + { C, atom.SP2, N, atom.SP2, 0.870 / 1.266 }, + { C, atom.SP2, O, atom.SP2, 0.950 / 1.225 }, + { C, atom.SP2, N, atom.SP2, 1.700 / 1.463 }, + { C, atom.SP2, N, atom.SP2, 0.583 / 1.260 }, + { C, atom.SP, N, atom.SP, 3.400 / 1.158 }, + { O, atom.SP3, H, atom.NONE, -1.115 / 0.942 }, + { O, atom.SP3, H, atom.NONE, -0.700 / 0.972 }, + { O, atom.SP3, H, atom.NONE, -0.700 / 0.972 }, + { O, atom.SP2, N, atom.SP2, -2.600 / 1.268 }, + { O, atom.SP2, N, atom.SP2, -2.530 / 1.220 }, + { N, atom.SP3, H, atom.NONE, -0.760 / 1.020 }, + { N, atom.SP2, H, atom.NONE, -1.310 / 1.022 }, + { C, atom.SP3, N, atom.SP2, 1.700 / 1.477 }, + { H, atom.NONE, N, atom.SP2, 0.600 / 1.022 }, + { H, atom.NONE, N, atom.SP2, 0.600 / 1.022 }, + { H, atom.NONE, O, atom.SP2, 0.700 / 0.972 }, + { N, atom.SP2, N, atom.SP2, 0.300 / 1.230 }, + { O, atom.SP3, C, atom.SP3, -2.800 / 1.236 } + }; + private boolean bondChain (atom a1, atom a2, int depth) + { + int i; + if (a1 == a2) + return true; + if (depth == 0) + return false; + if (a1.bonds == null) + return false; + if (depth == 1) + return a1.bondWith(a2) != null; + for (i = 0; i < a1.bonds.size (); i++) + if (bondChain (((bond) a1.bonds.elementAt(i)).otherAtom(a1), + a2, depth - 1)) + return true; + return false; + } + public void buildTerm (Vector v, Vector termList) { } + public void computeForces () + { + int i, j, k, n; + n = atomList.size (); + for (i = 0; i < n; i++) + { + atom a1 = (atom) atomList.elementAt (i); + k = i + 1; + for (j = 0; j < exclusions[i].length; j++) + { + for ( ; k < exclusions[i][j]; k++) + { + atom a2 = (atom) atomList.elementAt (k); + computeForces (a1, a2); + } + k++; + } + for ( ; k < n; k++) + { + atom a2 = (atom) atomList.elementAt (k); + computeForces (a1, a2); + } + } + } + // should be negative, -1.0 is too big, -1.0e-12 is too small + // -1e-6 too small, -1.0e-3 is in the ballpark + + private void computeForces (atom a1, atom a2) + { + int i; + double rvdw = a1.vdwRadius () + a2.vdwRadius (); + double evdw = (a1.vdwEnergy () + a2.vdwEnergy ()) / 2; + // let's ignore integer charge for the time being + double q1q2 = a1.fractionalCharge * a2.fractionalCharge; + double[] diff = new double[3]; + double m, r, r2, r_1, r_2, r_6; + for (i = 0, r2 = 0.0; i < 3; i++) + { + diff[i] = a1.x[i] - a2.x[i]; + r2 += diff[i] * diff[i]; + } + r = Math.sqrt (r2); + // m = electricConstant * q1q2 / (r2 * r); + + r_1 = rvdw / r; + r_2 = r_1 * r_1; + r_6 = r_2 * r_2 * r_2; + // m -= 0.012 * evdw * r_1 * r_6 * (r_6 - 1.0); + m = -0.012 * evdw * r_1 * r_6 * (r_6 - 1.0); + + // m > 0 attract, m < 0 repel + for (i = 0; i < 3; i++) + { + a1.f[i] -= m * diff[i]; + a2.f[i] += m * diff[i]; + } + } + public void enumerate (Vector aList, Vector termList) + { + int i, j, n; + + atomList = aList; + hackCharges (); + n = atomList.size (); + exclusions = new int[n][maxNumChained]; + for (i = 0; i < n; i++) + { + int numChained = 0; + atom a1 = (atom) atomList.elementAt (i); + for (j = i + 1; j < n; j++) + { + atom a2 = (atom) atomList.elementAt (j); + if (bondChain (a1, a2, 2)) + exclusions[i][numChained++] = j; + } + /* trim each subarray to the smallest possible size */ + int[] temp = new int[numChained]; + for (j = 0; j < numChained; j++) + temp[j] = exclusions[i][j]; + exclusions[i] = temp; + } + termList.addElement (this); + } + private void hackCharges () + { + int i, j, k, n; + boolean found; + atom a1, a2; + + n = atomList.size (); + for (j = 0; j < n; j++) + { + a1 = (atom) atomList.elementAt (j); + for (k = 0; k < n; k++) + { + a2 = (atom) atomList.elementAt (k); + for (i = 0, found = false; i < dipoleMoments.length && !found; i++) + { + if (a1.atomicNumber () == dipoleMoments[i][0] && + a1.hybridization == dipoleMoments[i][1] && + a2.atomicNumber () == dipoleMoments[i][2] && + a2.hybridization == dipoleMoments[i][3]) + { + double diffCharge = + dontKnowCorrectUnits * dipoleMoments[i][4]; + found = true; + a1.fractionalCharge += diffCharge; + a2.fractionalCharge -= diffCharge; + } + else if (a1.atomicNumber () == dipoleMoments[i][2] && + a1.hybridization == dipoleMoments[i][3] && + a2.atomicNumber () == dipoleMoments[i][0] && + a2.hybridization == dipoleMoments[i][1]) + { + double diffCharge = + dontKnowCorrectUnits * dipoleMoments[i][4]; + found = true; + a1.fractionalCharge -= diffCharge; + a2.fractionalCharge += diffCharge; + } + } + } + } + } + public int termLength () { return 2; } +} diff --git a/src/main/java/nanocad/minimize/nanocad/lterm.java b/src/main/java/nanocad/minimize/nanocad/lterm.java new file mode 100644 index 0000000..6c629eb --- /dev/null +++ b/src/main/java/nanocad/minimize/nanocad/lterm.java @@ -0,0 +1,187 @@ +package nanocad.minimize.nanocad; + +/** + * lterm.java - MM2-style length energy term + * Copyright (c) 1997,1998 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * or its derived works must display the following acknowledgement: + * This product includes software developed by Will Ware. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.lang.Math; +import java.util.Vector; + +import nanocad.atom; + +public class lterm extends term +{ + public static final String rcsid = + "$Id: lterm.java,v 1.2 2005/05/14 23:51:00 xli16 Exp $"; + private double ks, r0; + /* I've been hacking a bit with acceptable forms for the length-energy term. + * _Nanosystems_ lists one simple expression with a square and cubic term + * for close distances, and various kinds of exponential expressions for + * farther away. But these depend on numbers called De and beta and I don't + * have tables for those (just the few examples in _Nanosystems_). So after + * some puttering and graphing and algebra, I came up with the following. + * Energies are in attojoules (10^-18 joules), distances are in angstroms + * (10^-10 m), forces are in attojoules per angstrom (10^-8 N), and + * spring constants are in attojoules per angstrom-squared (100 N/m). This + * is consistent with the units in _Nanosystems_, and also the units used + * in the 'mm2.prm' parameter file I found on Jay Ponder's ftp site. + * Expressions for energy and force, where ks and r0 are a function of + * the two atoms involved: + * + * dr = r - r0; + * + * Energy (r) := + * if (dr < rthresh) + * { return 0.5 * ks * dr * dr * (1 - kc * dr) - z * ks; } + * else + * { return (-a * ks / beta) * exp (-beta * dr); } + * + * Force (r) := + * if (dr < rthresh) + * { return -(ks * dr * (1 - 1.5 * kc * dr)); } + * else + * { return -a * ks * exp (-beta * dr); } + * + * + * A, beta, z, kcubic, and rthresh are defined below. Notice my use of + * 'beta' differs from the use in _Nanosystems_, but plays a similar role. + * + * These follow Drexler's quadratic-cubic form for dr < rthresh, and for + * dr > rthresh, they follow an exponential drop-off which is pretty + * continuous for both energy and force. The only point that I think would + * be worth quibbling over would be the value of beta, which I picked so + * that it would look "reasonable" on a graph. + */ + private static final double kcubic = 2.0; /* (0.5 angstrom)^-1 */ + private static final double rthresh = 1 / (3 * kcubic); + private static final double beta = 3.0; + private static final double a = rthresh * (1 - 1.5 * kcubic * rthresh) * + Math.exp (beta * rthresh); + private static final double z = (a / beta) * Math.exp(-beta * rthresh) + + 0.5 * rthresh * rthresh * (1 - kcubic * rthresh); + // Coefficient data + // Forces are in aJ per square angstrom (spring constants) + private final static double[][] lengthCoeffs = + { + { C, atom.SP3, C, atom.SP3, 4.400, 1.523 }, + { C, atom.SP3, C, atom.SP2, 4.400, 1.497 }, + { C, atom.SP3, C, atom.SP, 5.200, 1.470 }, + { C, atom.SP3, H, atom.NONE, 4.600, 1.113 }, + { C, atom.SP3, O, atom.SP3, 5.360, 1.402 }, + { C, atom.SP3, N, atom.SP3, 5.100, 1.438 }, + { C, atom.SP3, N, atom.SP2, 3.520, 1.437 }, + { C, atom.SP3, N, atom.SP3, 5.100, 1.499 }, + { C, atom.SP3, O, atom.SP2, 5.360, 1.414 }, + { C, atom.SP2, C, atom.SP2, 9.600, 1.337 }, + { C, atom.SP2, C, atom.SP, 9.900, 1.313 }, + { C, atom.SP2, H, atom.NONE, 4.600, 1.101 }, + { C, atom.SP2, O, atom.SP3, 6.000, 1.355 }, + { C, atom.SP2, N, atom.SP3, 6.320, 1.377 }, + { C, atom.SP2, N, atom.SP2, 5.000, 1.410 }, + { C, atom.SP2, O, atom.SP2, 10.000, 1.225 }, + { C, atom.SP, C, atom.SP, 15.600, 1.212 }, + { C, atom.SP, H, atom.NONE, 5.900, 1.090 }, + { C, atom.SP, N, atom.SP, 17.730, 1.158 }, + { O, atom.SP3, O, atom.SP3, 3.950, 1.428 }, + { N, atom.SP3, N, atom.SP3, 5.600, 1.381 }, + { N, atom.SP3, H, atom.NONE, 6.100, 1.045 } + }; + public lterm (atom a1, atom a2) + { + int i; + boolean found; + myAtoms = new atom[2]; + myAtoms[0] = a1; + myAtoms[1] = a2; + for (i = 0, found = false; i < lengthCoeffs.length && !found; i++) + if ((a1.atomicNumber () == lengthCoeffs[i][0] && + a1.hybridization == lengthCoeffs[i][1] && + a2.atomicNumber () == lengthCoeffs[i][2] && + a2.hybridization == lengthCoeffs[i][3]) || + (a1.atomicNumber () == lengthCoeffs[i][2] && + a1.hybridization == lengthCoeffs[i][3] && + a2.atomicNumber () == lengthCoeffs[i][0] && + a2.hybridization == lengthCoeffs[i][1])) + { + found = true; + ks = lengthCoeffs[i][4]; + r0 = lengthCoeffs[i][5]; + } + if (!found) + { + // something innocuous + ks = 2.0; + r0 = 1.2; + } + } + protected void buildTerm (Vector v, Vector termList) + { + lterm t = new lterm ((atom) v.elementAt(0), + (atom) v.elementAt(1)); + if (t.myAtoms[0].x[0] < t.myAtoms[1].x[0]) + { + termList.addElement (t); + } + } + public void computeForces () + { + int i; + + // compute forces on each atom, add it to the atom's force vector + double[] diff = new double[3]; + double r, m; + for (i = 0, r = 0.0; i < 3; i++) + { + diff[i] = myAtoms[0].x[i] - myAtoms[1].x[i]; + r += diff[i] * diff[i]; + } + r = Math.sqrt (r); + double rdiff = (r - r0), expr; + if (rdiff < rthresh) + m = ks * rdiff * (1 - 1.5 * kcubic * rdiff); + else + m = a * ks * Math.exp (-beta * rdiff); + // at this point, m is du/dr + m /= r; + // m > 0 attract, m < 0 repel + for (i = 0; i < 3; i++) + { + myAtoms[0].f[i] -= m * diff[i]; + myAtoms[1].f[i] += m * diff[i]; + } + } + protected String repr2() + { + return " length " + + (new Double(ks)).toString() + " " + + (new Double(r0)).toString(); + } + public int termLength() + { + return 2; + } +} diff --git a/src/main/java/nanocad/minimize/nanocad/nanoMinimizeAlgorythm.java b/src/main/java/nanocad/minimize/nanocad/nanoMinimizeAlgorythm.java new file mode 100644 index 0000000..3fa1144 --- /dev/null +++ b/src/main/java/nanocad/minimize/nanocad/nanoMinimizeAlgorythm.java @@ -0,0 +1,75 @@ +package nanocad.minimize.nanocad; + +/** + * Copyright (c) 1997 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.lang.Math; +import java.util.Vector; + +import nanocad.atom; +import nanocad.carbon; +import nanocad.energyMinimizeAlgorythm; +import nanocad.group; + +public abstract class nanoMinimizeAlgorythm extends energyMinimizeAlgorythm +{ + +public boolean minimizeGroup(group g) { + int i; + Vector atomList = g.atomList; + Vector termList = new Vector(); + for (i = 0; i < atomList.size(); i++) + ((atom) atomList.elementAt(i)).rehybridize(); + termList = new Vector(); + atom a = new carbon(); + term t; + t = new lterm(a, a); + t.enumerate(atomList, termList); + t = new aterm(a, a, a); + t.enumerate(atomList, termList); + t = new tterm(a, a, a, a); + t.enumerate(atomList, termList); + for (double stepsize = 0.1; stepsize > 0.0001; stepsize *= 0.9) + //step loop + { + for (i = 0; i < atomList.size(); i++) + ((atom) atomList.elementAt(i)).zeroForce(); + for (i = 0; i < termList.size(); i++) + ((term) termList.elementAt(i)).computeForces(); + for (i = 0; i < atomList.size(); i++) { + int j; + double flensq, m; + a = (atom) atomList.elementAt(i); + for (j = 0, flensq = 0.0; j < 3; j++) + flensq += a.f[j] * a.f[j]; + if (flensq > 0.0) { + m = stepsize / Math.sqrt(flensq); + for (j = 0; j < 3; j++) + a.x[j] += m * a.f[j]; + } + } + } //end step loop + return true; +} //end minimize group function +} diff --git a/src/main/java/nanocad/minimize/nanocad/term.java b/src/main/java/nanocad/minimize/nanocad/term.java new file mode 100644 index 0000000..53431ca --- /dev/null +++ b/src/main/java/nanocad/minimize/nanocad/term.java @@ -0,0 +1,137 @@ +package nanocad.minimize.nanocad; + +/** + * term.java - MM2-style energy term, for computing interatomic forces + * Copyright (c) 1997 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.lang.Math; +import java.util.Vector; + +import nanocad.bond; +import nanocad.atom; + +public abstract class term +{ + public static final String rcsid = + "$Id: term.java,v 1.2 2005/05/14 23:51:00 xli16 Exp $"; + public atom[] myAtoms; + public static final double pi = 3.1415926; + + // atomic numbers, used to look up coefficients + protected final static int H = 1; + protected final static int C = 6; + protected final static int N = 7; + protected final static int O = 8; + + public term () + { + // needed for termList + } + protected double acos (double x) + { + if (x >= 1.0) return pi / 2; + if (x <= -1.0) return -pi / 2; + return Math.acos (x); + } + private void bondChain (atom a, int n, Vector termList) + { + Vector v = new Vector(); + v.addElement(a); + nextBondChain(v, n-1, termList); + } + protected abstract void buildTerm(Vector v, Vector termList); + public abstract void computeForces(); + // handy vector arithmetic + protected double[] crossProduct (double[] x, double[] y) + { + double[] z = new double[3]; + z[0] = x[1] * y[2] - x[2] * y[1]; + z[1] = x[2] * y[0] - x[0] * y[2]; + z[2] = x[0] * y[1] - x[1] * y[0]; + return z; + } + protected double dotProduct (double[] x, double[] y) + { + return x[0] * y[0] + x[1] * y[1] + x[2] * y[2]; + } + public void enumerate (Vector atomList, Vector termList) + { + int i; + for (i = 0; i < atomList.size (); i++) + bondChain ((atom) atomList.elementAt(i), termLength(), termList); + } + private void nextBondChain (Vector v, int n, Vector termList) + { + int i; + atom a1, a2; + if (n == 0) + { + buildTerm (v, termList); + return; + } + a1 = (atom) v.elementAt(v.size()-1); + for (i = 0; i < a1.bonds.size(); i++) + { + a2 = ((bond) a1.bonds.elementAt(i)).otherAtom(a1); + if (!v.contains(a2)) + { + v.addElement(a2); + nextBondChain(v, n-1, termList); + v.removeElement(a2); + } + } + } + public String repr() + { + int i; + if (myAtoms == null) + return ""; + String s = ""; + } + protected String repr2() + { + return ""; + } + protected double[] scalevec (double m, double[] x) + { + double[] z = new double[3]; + int i; + for (i = 0; i < 3; i++) + z[i] = m * x[i]; + return z; + } + protected double sqrt (double x) + { + if (x <= 0.0) return 0.0; + return Math.sqrt (x); + } + protected abstract int termLength(); + protected double veclen (double[] x) + { + return Math.sqrt (dotProduct (x, x)); + } +} diff --git a/src/main/java/nanocad/minimize/nanocad/tterm.java b/src/main/java/nanocad/minimize/nanocad/tterm.java new file mode 100644 index 0000000..c1d21e2 --- /dev/null +++ b/src/main/java/nanocad/minimize/nanocad/tterm.java @@ -0,0 +1,478 @@ +package nanocad.minimize.nanocad; + +/** + * tterm.java - MM2-style torsion energy term + * Copyright (c) 1997,1998 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.lang.Math; +import java.util.Vector; + +import nanocad.atom; + +public class tterm extends term +{ + public static final String rcsid = + "$Id: tterm.java,v 1.2 2005/05/14 23:51:00 xli16 Exp $"; + private double v1, v2, v3; + private final static double PI = 3.14159265258979; + private final static double[][] torsionCoeffs = + { + { C, atom.SP3, C, atom.SP3, C, atom.SP3, C, atom.SP3, 0.200, 0.270, 0.093 }, + { C, atom.SP3, C, atom.SP3, C, atom.SP3, C, atom.SP2, 0.170, 0.270, 0.093 }, + { C, atom.SP3, C, atom.SP3, C, atom.SP3, C, atom.SP, 0.200, -0.260, 0.093 }, + { C, atom.SP3, C, atom.SP3, C, atom.SP3, H, atom.NONE, 0.000, 0.000, 0.267 }, + { C, atom.SP3, C, atom.SP3, C, atom.SP3, O, atom.SP3, 0.100, 0.100, 0.180 }, + { C, atom.SP3, C, atom.SP3, C, atom.SP3, N, atom.SP3, 0.100, 0.400, 0.500 }, + { C, atom.SP3, C, atom.SP3, C, atom.SP3, N, atom.SP2, 0.000, 0.000, 0.400 }, + { C, atom.SP3, C, atom.SP3, C, atom.SP3, N, atom.SP3, 0.100, 0.400, 0.500 }, + { C, atom.SP2, C, atom.SP3, C, atom.SP3, C, atom.SP2, 2.100, 0.270, 0.093 }, + { C, atom.SP2, C, atom.SP3, C, atom.SP3, C, atom.SP, 0.000, 0.000, 0.093 }, + { C, atom.SP2, C, atom.SP3, C, atom.SP3, H, atom.NONE, 0.000, 0.000, 0.500 }, + { C, atom.SP2, C, atom.SP3, C, atom.SP3, O, atom.SP3, 0.000, 0.000, 0.180 }, + { C, atom.SP2, C, atom.SP3, C, atom.SP3, N, atom.SP3, 0.000, 0.000, 0.180 }, + { C, atom.SP2, C, atom.SP3, C, atom.SP3, N, atom.SP2, 0.000, 0.000, 0.000 }, + { C, atom.SP2, C, atom.SP3, C, atom.SP3, N, atom.SP3, 0.000, 0.000, 0.180 }, + { C, atom.SP, C, atom.SP3, C, atom.SP3, C, atom.SP, 1.000, 0.000, 0.093 }, + { C, atom.SP, C, atom.SP3, C, atom.SP3, H, atom.NONE, 0.000, 0.000, 0.400 }, + { C, atom.SP, C, atom.SP3, C, atom.SP3, O, atom.SP3, 0.000, -0.400, 0.180 }, + { H, atom.NONE, C, atom.SP3, C, atom.SP3, H, atom.NONE, 0.000, 0.000, 0.237 }, + { H, atom.NONE, C, atom.SP3, C, atom.SP3, O, atom.SP3, 0.000, 0.000, 0.180 }, + { H, atom.NONE, C, atom.SP3, C, atom.SP3, N, atom.SP3, -0.150, 0.000, 0.150 }, + { H, atom.NONE, C, atom.SP3, C, atom.SP3, N, atom.SP2, 0.000, 0.000, 0.400 }, + { H, atom.NONE, C, atom.SP3, C, atom.SP3, N, atom.SP3, -0.150, 0.000, 0.150 }, + { H, atom.NONE, C, atom.SP3, C, atom.SP3, O, atom.SP2, 0.000, 0.000, 0.180 }, + { O, atom.SP3, C, atom.SP3, C, atom.SP3, O, atom.SP3, 0.000, -0.600, 0.300 }, + { O, atom.SP3, C, atom.SP3, C, atom.SP3, N, atom.SP3, 0.000, 0.000, 0.000 }, + { O, atom.SP3, C, atom.SP3, C, atom.SP3, N, atom.SP2, 0.000, 0.000, 0.000 }, + { O, atom.SP3, C, atom.SP3, C, atom.SP3, N, atom.SP3, 0.000, -0.600, 0.300 }, + { N, atom.SP3, C, atom.SP3, C, atom.SP3, N, atom.SP3, -0.400, -1.100, 1.200 }, + { N, atom.SP3, C, atom.SP3, C, atom.SP3, N, atom.SP2, 1.170, -1.263, 2.064 }, + { N, atom.SP2, C, atom.SP3, C, atom.SP3, N, atom.SP2, 0.000, 0.000, -0.500 }, + { O, atom.SP2, C, atom.SP3, C, atom.SP3, O, atom.SP2, 0.000, -0.600, 0.300 }, + { C, atom.SP3, C, atom.SP3, C, atom.SP2, C, atom.SP3, 0.400, 0.030, 0.500 }, + { C, atom.SP3, C, atom.SP3, C, atom.SP2, C, atom.SP2, -0.440, 0.240, 0.060 }, + { C, atom.SP3, C, atom.SP3, C, atom.SP2, C, atom.SP, -0.440, 0.240, 0.060 }, + { C, atom.SP3, C, atom.SP3, C, atom.SP2, H, atom.NONE, 0.000, 0.000, 0.010 }, + { C, atom.SP3, C, atom.SP3, C, atom.SP2, O, atom.SP3, 0.000, 0.000, 0.000 }, + { C, atom.SP2, C, atom.SP3, C, atom.SP2, C, atom.SP3, 0.000, 0.000, 0.300 }, + { C, atom.SP2, C, atom.SP3, C, atom.SP2, C, atom.SP2, 0.100, 0.000, 0.500 }, + { C, atom.SP2, C, atom.SP3, C, atom.SP2, H, atom.NONE, 0.000, 0.000, 0.600 }, + { C, atom.SP2, C, atom.SP3, C, atom.SP2, O, atom.SP3, 0.000, 0.000, 0.000 }, + { C, atom.SP, C, atom.SP3, C, atom.SP2, C, atom.SP3, 0.000, 0.000, 0.780 }, + { C, atom.SP, C, atom.SP3, C, atom.SP2, C, atom.SP2, 0.000, 0.000, 0.100 }, + { C, atom.SP, C, atom.SP3, C, atom.SP2, H, atom.NONE, 0.000, 0.000, 0.780 }, + { H, atom.NONE, C, atom.SP3, C, atom.SP2, C, atom.SP3, 0.000, 0.000, 0.540 }, + { H, atom.NONE, C, atom.SP3, C, atom.SP2, C, atom.SP2, 0.000, 0.000, -0.240 }, + { H, atom.NONE, C, atom.SP3, C, atom.SP2, C, atom.SP, 0.000, 0.000, -0.240 }, + { H, atom.NONE, C, atom.SP3, C, atom.SP2, H, atom.NONE, 0.000, 0.000, 0.520 }, + { H, atom.NONE, C, atom.SP3, C, atom.SP2, O, atom.SP3, 0.000, 0.000, 0.540 }, + { O, atom.SP3, C, atom.SP3, C, atom.SP2, C, atom.SP3, 0.000, 0.000, 0.000 }, + { O, atom.SP3, C, atom.SP3, C, atom.SP2, C, atom.SP2, 0.000, 0.000, 0.000 }, + { O, atom.SP3, C, atom.SP3, C, atom.SP2, H, atom.NONE, 0.000, 0.000, 0.000 }, + { N, atom.SP3, C, atom.SP3, C, atom.SP2, C, atom.SP3, 0.000, 0.000, 0.000 }, + { N, atom.SP3, C, atom.SP3, C, atom.SP2, C, atom.SP2, 0.000, 0.000, 0.000 }, + { N, atom.SP3, C, atom.SP3, C, atom.SP2, H, atom.NONE, 0.000, 0.000, 0.000 }, + { N, atom.SP3, C, atom.SP3, C, atom.SP2, C, atom.SP2, 0.000, 0.000, 0.000 }, + { C, atom.SP3, C, atom.SP3, C, atom.SP, C, atom.SP, 0.000, 0.001, 0.000 }, + { H, atom.NONE, C, atom.SP3, C, atom.SP, C, atom.SP, 0.000, 0.001, 0.000 }, + { C, atom.SP3, C, atom.SP3, O, atom.SP3, C, atom.SP3, 0.400, 0.520, 0.467 }, + { C, atom.SP3, C, atom.SP3, O, atom.SP3, C, atom.SP2, 0.000, 0.000, 0.400 }, + { C, atom.SP3, C, atom.SP3, O, atom.SP3, O, atom.SP3, 0.000, 0.000, 0.400 }, + { C, atom.SP2, C, atom.SP3, O, atom.SP3, C, atom.SP3, 0.000, 0.000, 0.403 }, + { H, atom.NONE, C, atom.SP3, O, atom.SP3, C, atom.SP3, 0.000, 0.000, 0.530 }, + { H, atom.NONE, C, atom.SP3, O, atom.SP3, C, atom.SP2, 0.000, 0.000, 0.530 }, + { H, atom.NONE, C, atom.SP3, O, atom.SP3, O, atom.SP3, 0.000, 0.000, 0.465 }, + { O, atom.SP3, C, atom.SP3, O, atom.SP3, C, atom.SP3, -0.170, -1.200, 0.000 }, + { O, atom.SP3, C, atom.SP3, O, atom.SP3, O, atom.SP3, 0.000, 0.000, 0.403 }, + { C, atom.SP3, C, atom.SP3, N, atom.SP3, C, atom.SP3, -0.200, 0.730, 0.800 }, + { C, atom.SP3, C, atom.SP3, N, atom.SP3, N, atom.SP3, -0.200, 0.730, 0.800 }, + { C, atom.SP2, C, atom.SP3, N, atom.SP3, C, atom.SP3, 0.000, 0.000, 0.000 }, + { C, atom.SP2, C, atom.SP3, N, atom.SP3, N, atom.SP3, 0.000, 0.000, 0.000 }, + { H, atom.NONE, C, atom.SP3, N, atom.SP3, C, atom.SP3, 0.000, 0.000, 0.520 }, + { H, atom.NONE, C, atom.SP3, N, atom.SP3, C, atom.SP2, 0.000, 0.000, 0.450 }, + { H, atom.NONE, C, atom.SP3, N, atom.SP3, N, atom.SP3, 0.000, 0.000, 0.520 }, + { N, atom.SP3, C, atom.SP3, N, atom.SP3, C, atom.SP3, 0.000, 0.000, 0.350 }, + { N, atom.SP3, C, atom.SP3, N, atom.SP3, N, atom.SP3, 0.000, 0.000, 0.350 }, + { N, atom.SP3, C, atom.SP3, N, atom.SP3, C, atom.SP3, 0.000, 0.000, 0.350 }, + { C, atom.SP3, C, atom.SP3, N, atom.SP2, C, atom.SP3, 0.000, 0.000, 0.910 }, + { C, atom.SP3, C, atom.SP3, N, atom.SP2, C, atom.SP2, 0.000, 0.000, 0.000 }, + { H, atom.NONE, C, atom.SP3, N, atom.SP2, C, atom.SP3, 0.000, 0.000, -0.200 }, + { H, atom.NONE, C, atom.SP3, N, atom.SP2, C, atom.SP2, 0.000, 0.000, 0.000 }, + { H, atom.NONE, C, atom.SP3, N, atom.SP2, C, atom.SP2, 0.000, 0.000, 0.650 }, + { C, atom.SP3, C, atom.SP3, N, atom.SP3, C, atom.SP3, -0.200, 0.730, 0.800 }, + { C, atom.SP3, C, atom.SP3, N, atom.SP3, H, atom.NONE, 0.000, 0.120, 0.100 }, + { C, atom.SP2, C, atom.SP3, N, atom.SP3, C, atom.SP3, 0.000, 0.000, 0.000 }, + { C, atom.SP2, C, atom.SP3, N, atom.SP3, H, atom.NONE, 0.000, 0.000, 0.000 }, + { H, atom.NONE, C, atom.SP3, N, atom.SP3, C, atom.SP3, 0.000, 0.000, 0.520 }, + { H, atom.NONE, C, atom.SP3, N, atom.SP3, H, atom.NONE, 0.000, 0.000, 0.250 }, + { N, atom.SP3, C, atom.SP3, N, atom.SP3, C, atom.SP3, 0.000, 0.000, 0.350 }, + { C, atom.SP3, C, atom.SP3, O, atom.SP2, C, atom.SP2, 0.000, 0.000, 0.400 }, + { H, atom.NONE, C, atom.SP3, O, atom.SP2, C, atom.SP2, 0.000, 0.000, 0.350 }, + { C, atom.SP3, C, atom.SP2, C, atom.SP2, C, atom.SP3, -0.100, 10.000, 0.000 }, + { C, atom.SP3, C, atom.SP2, C, atom.SP2, C, atom.SP2, -0.270, 10.000, 0.000 }, + { C, atom.SP3, C, atom.SP2, C, atom.SP2, H, atom.NONE, 0.000, 12.500, 0.000 }, + { C, atom.SP3, C, atom.SP2, C, atom.SP2, O, atom.SP3, -1.200, 16.250, 0.000 }, + { C, atom.SP2, C, atom.SP2, C, atom.SP2, C, atom.SP2, -0.930, 8.000, 0.000 }, + { C, atom.SP2, C, atom.SP2, C, atom.SP2, C, atom.SP, 0.000, 15.000, 0.000 }, + { C, atom.SP2, C, atom.SP2, C, atom.SP2, H, atom.NONE, 0.000, 9.000, -1.060 }, + { C, atom.SP2, C, atom.SP2, C, atom.SP2, O, atom.SP3, 0.000, 16.250, 0.000 }, + { C, atom.SP2, C, atom.SP2, C, atom.SP2, N, atom.SP3, 0.000, 15.000, 0.000 }, + { C, atom.SP2, C, atom.SP2, C, atom.SP2, N, atom.SP2, 0.000, 12.000, 0.000 }, + { C, atom.SP2, C, atom.SP2, C, atom.SP2, O, atom.SP2, 0.000, 15.000, 0.000 }, + { C, atom.SP, C, atom.SP2, C, atom.SP2, H, atom.NONE, 0.000, 15.000, 0.000 }, + { H, atom.NONE, C, atom.SP2, C, atom.SP2, H, atom.NONE, 0.000, 15.000, 0.000 }, + { H, atom.NONE, C, atom.SP2, C, atom.SP2, O, atom.SP3, 0.000, 16.250, 0.000 }, + { H, atom.NONE, C, atom.SP2, C, atom.SP2, N, atom.SP3, 0.000, 15.000, 0.000 }, + { H, atom.NONE, C, atom.SP2, C, atom.SP2, N, atom.SP2, 0.000, 12.000, 0.000 }, + { H, atom.NONE, C, atom.SP2, C, atom.SP2, O, atom.SP2, 0.000, 15.000, 0.000 }, + { O, atom.SP3, C, atom.SP2, C, atom.SP2, O, atom.SP3, -2.000, 16.250, 0.000 }, + { O, atom.SP2, C, atom.SP2, C, atom.SP2, O, atom.SP2, -2.000, 15.000, 0.000 }, + { C, atom.SP2, C, atom.SP2, C, atom.SP, C, atom.SP, 0.000, 0.001, 0.000 }, + { C, atom.SP3, C, atom.SP2, O, atom.SP3, C, atom.SP3, 2.300, 4.000, 0.000 }, + { C, atom.SP3, C, atom.SP2, O, atom.SP3, C, atom.SP2, 0.000, 0.000, 0.000 }, + { C, atom.SP2, C, atom.SP2, O, atom.SP3, C, atom.SP3, 3.530, 2.300, -3.530 }, + { C, atom.SP2, C, atom.SP2, O, atom.SP3, C, atom.SP2, 0.000, 0.000, 0.000 }, + { H, atom.NONE, C, atom.SP2, O, atom.SP3, C, atom.SP3, 3.000, 3.100, 0.000 }, + { H, atom.NONE, C, atom.SP2, O, atom.SP3, C, atom.SP2, 0.000, 0.000, 0.000 }, + { C, atom.SP2, C, atom.SP2, N, atom.SP3, C, atom.SP3, -1.570, 3.200, 0.000 }, + { H, atom.NONE, C, atom.SP2, N, atom.SP3, C, atom.SP3, 1.570, 1.690, 0.000 }, + { C, atom.SP2, C, atom.SP2, N, atom.SP2, C, atom.SP3, 0.000, 2.000, 0.000 }, + { C, atom.SP2, C, atom.SP2, N, atom.SP2, C, atom.SP2, 0.000, 0.000, 1.490 }, + { N, atom.SP2, C, atom.SP2, N, atom.SP2, C, atom.SP3, 0.000, 0.000, 0.000 }, + { C, atom.SP2, C, atom.SP2, O, atom.SP2, C, atom.SP3, 0.000, 9.200, 0.000 }, + { C, atom.SP2, C, atom.SP2, O, atom.SP2, C, atom.SP2, 0.000, 8.300, -0.800 }, + { H, atom.NONE, C, atom.SP2, O, atom.SP2, C, atom.SP3, -0.820, 9.200, 3.700 }, + { H, atom.NONE, C, atom.SP2, O, atom.SP2, C, atom.SP2, -0.460, 2.700, 0.700 }, + { C, atom.SP3, C, atom.SP, C, atom.SP, C, atom.SP2, 0.000, 0.001, 0.000 }, + { C, atom.SP3, C, atom.SP, C, atom.SP, C, atom.SP, 0.000, 0.001, 0.000 }, + { C, atom.SP2, C, atom.SP, C, atom.SP, C, atom.SP2, 0.000, 0.001, 0.000 }, + { C, atom.SP2, C, atom.SP, C, atom.SP, C, atom.SP, 0.000, 0.001, 0.000 }, + { C, atom.SP2, C, atom.SP, C, atom.SP, H, atom.NONE, 0.000, 0.001, 0.000 }, + { C, atom.SP, C, atom.SP, C, atom.SP, C, atom.SP, 0.000, 0.001, 0.000 }, + { C, atom.SP3, O, atom.SP3, O, atom.SP3, C, atom.SP3, 2.095, -2.155, -0.113 }, + { C, atom.SP3, N, atom.SP3, N, atom.SP3, C, atom.SP3, 0.900, -6.800, 0.210 }, + }; + public tterm (atom a1, atom a2, atom a3, atom a4) + { + int i; + boolean found; + myAtoms = new atom[4]; + myAtoms[0] = a1; + myAtoms[1] = a2; + myAtoms[2] = a3; + myAtoms[3] = a4; + for (i = 0, found = false; i < torsionCoeffs.length && !found; i++) + if ((a1.atomicNumber () == torsionCoeffs[i][0] && + a1.hybridization == torsionCoeffs[i][1] && + a2.atomicNumber () == torsionCoeffs[i][2] && + a2.hybridization == torsionCoeffs[i][3] && + a3.atomicNumber () == torsionCoeffs[i][4] && + a3.hybridization == torsionCoeffs[i][5] && + a4.atomicNumber () == torsionCoeffs[i][6] && + a4.hybridization == torsionCoeffs[i][7]) || + (a1.atomicNumber () == torsionCoeffs[i][6] && + a1.hybridization == torsionCoeffs[i][7] && + a2.atomicNumber () == torsionCoeffs[i][4] && + a2.hybridization == torsionCoeffs[i][5] && + a3.atomicNumber () == torsionCoeffs[i][2] && + a3.hybridization == torsionCoeffs[i][3] && + a4.atomicNumber () == torsionCoeffs[i][0] && + a4.hybridization == torsionCoeffs[i][1])) + { + found = true; + // convert table numbers from maJ to aJ (10^-18 joules) + v1 = 0.001 * torsionCoeffs[i][8]; + v2 = 0.001 * torsionCoeffs[i][9]; + v3 = 0.001 * torsionCoeffs[i][10]; + } + if (!found) + v1 = v2 = v3 = 0.0; + } + protected void buildTerm (Vector v, Vector termList) + { + tterm t = new tterm ((atom) v.elementAt(0), + (atom) v.elementAt(1), + (atom) v.elementAt(2), + (atom) v.elementAt(3)); + if (v1 == 0.0 && v2 == 0.0 && v3 == 0.0) + return; + if (t.myAtoms[0].x[0] < t.myAtoms[3].x[0]) + { + termList.addElement (t); + } + } + // I found, much to my dismay, that I had been miscalculating torsion + // forces for years! How embarassing. Now I've decided to just steal the + // correct torsion code from the NAMD program and translate it from C++ + // to Java. + public void computeForces () + { + double r12[], r23[], r34[]; // Vectors between atoms + double f1[], f2[], f3[]; // Forces 1 through 3 + double A[], B[], C[]; // Cross product vectors + double dcosdA[]; // Derivative d(cos(phi))/dA + double dcosdB[]; // Derivative d(cos(phi))/dB + double dsindC[]; // Derivative d(sin(phi))/dC + double dsindB[]; // Derivative d(sin(phi))/dB + double rA, rB, rC; // Length of vectors A, B, and C + double phi; // angle between the plans + double cos_phi; // cos(phi) + double sin_phi; // sin(phi) + double delta; // Phase shift of the current dihedral + double k; // Force constant of the current dihedral + int n; // Periodicity + double K, K1; // Calculated factor + double diff; // Difference between phi and phi0 + int mult_num; // Current multiple we are calculating + + if (v1 == 0.0 && v2 == 0.0 && v3 == 0.0) + return; + + r12 = new double[3]; + r23 = new double[3]; + r34 = new double[3]; + f1 = new double[3]; + f2 = new double[3]; + f3 = new double[3]; + A = new double[3]; + B = new double[3]; + C = new double[3]; + dcosdA = new double[3]; + dcosdB = new double[3]; + dsindC = new double[3]; + dsindB = new double[3]; + + // Calculate the vectors between atoms + r12[0] = myAtoms[0].x[0] - myAtoms[1].x[0]; + r12[1] = myAtoms[0].x[1] - myAtoms[1].x[1]; + r12[2] = myAtoms[0].x[2] - myAtoms[1].x[2]; + + r23[0] = myAtoms[1].x[0] - myAtoms[2].x[0]; + r23[1] = myAtoms[1].x[1] - myAtoms[2].x[1]; + r23[2] = myAtoms[1].x[2] - myAtoms[2].x[2]; + + r34[0] = myAtoms[2].x[0] - myAtoms[3].x[0]; + r34[1] = myAtoms[2].x[1] - myAtoms[3].x[1]; + r34[2] = myAtoms[2].x[2] - myAtoms[3].x[2]; + + // Calculate the cross products + A[0] = r12[1]*r23[2] - r23[1]*r12[2]; + A[1] = -r12[0]*r23[2] + r23[0]*r12[2]; + A[2] = r12[0]*r23[1] - r23[0]*r12[1]; + + B[0] = r23[1]*r34[2] - r34[1]*r23[2]; + B[1] = -r23[0]*r34[2] + r34[0]*r23[2]; + B[2] = r23[0]*r34[1] - r34[0]*r23[1]; + + C[0] = r23[1]*A[2] - A[1]*r23[2]; + C[1] = -r23[0]*A[2] + A[0]*r23[2]; + C[2] = r23[0]*A[1] - A[0]*r23[1]; + + // Calculate the distances + rA = Math.sqrt(A[0]*A[0] + A[1]*A[1] + A[2]*A[2]); + rB = Math.sqrt(B[0]*B[0] + B[1]*B[1] + B[2]*B[2]); + rC = Math.sqrt(C[0]*C[0] + C[1]*C[1] + C[2]*C[2]); + + // Calculate the sin and cos + // cos = A*B/(rA*rB) + // sin = C*B/(rC*rB) + cos_phi = (A[0]*B[0] + A[1]*B[1] + A[2]*B[2])/(rA*rB); + sin_phi = (C[0]*B[0] + C[1]*B[1] + C[2]*B[2])/(rC*rB); + + // Normalize B + rB = 1/rB; + + B[0] *= rB; + B[1] *= rB; + B[2] *= rB; + + // Get phi, assign the sign based on the sine value + + // Make sure that the cosine value is acceptable. With roundoff, you + // can get values like 1.0+2e-16, which makes acos puke. So instead, + // just set these kinds of values to exactly 1.0 + // if (cos_phi>1.0) + // cos_phi = 1.0; + // else if (cos_phi < -1.0) + // cos_phi = -1.0; + + // phi = acos(cos_phi); + // CHECK_DOMAIN(); + // phi = -copysign(phi, sin_phi); + + // I think atan2 will do all the above stuff accurately + // RKB + phi = -Math.atan2(sin_phi,cos_phi); + // CHECK_DOMAIN(); ?????? + + // if (fabs(sin_phi) > 0.1) + if (sin_phi > 0.1 || sin_phi < -0.1) + { + // Normalize A + rA = 1/rA; + + A[0] *= rA; + A[1] *= rA; + A[2] *= rA; + + dcosdA[0] = -rA*(B[0] - cos_phi*A[0]); + dcosdA[1] = -rA*(B[1] - cos_phi*A[1]); + dcosdA[2] = -rA*(B[2] - cos_phi*A[2]); + + dcosdB[0] = -rB*(A[0] - cos_phi*B[0]); + dcosdB[1] = -rB*(A[1] - cos_phi*B[1]); + dcosdB[2] = -rB*(A[2] - cos_phi*B[2]); + } + else + { + // Normalize C + rC = 1/rC; + + C[0] *= rC; + C[1] *= rC; + C[2] *= rC; + + dsindC[0] = -rC*(B[0]-sin_phi*C[0]); + dsindC[1] = -rC*(B[1]-sin_phi*C[1]); + dsindC[2] = -rC*(B[2]-sin_phi*C[2]); + + dsindB[0] = -rB*(C[0]-sin_phi*B[0]); + dsindB[1] = -rB*(C[1]-sin_phi*B[1]); + dsindB[2] = -rB*(C[2]-sin_phi*B[2]); + } + + // Loop through the multiple parameter sets for this + // bond. We will only loop more than once if this + // has multiple parameter sets from Charmm22 + for (mult_num=0; mult_num < 3; mult_num++) + { + switch (mult_num) + { + case 0: + n = 1; + k = v1; + break; + case 1: + n = 2; + k = -v2; + break; + default: + n = 3; + k = v3; + break; + } + delta = 0; + + if (k != 0.0) + { + // Calculate the energy + K = k*(1+Math.cos(n*phi + delta)); + K1 = -n*k*Math.sin(n*phi + delta); + + // Next, we want to calculate the forces. In order + // to do that, we first need to figure out whether the + // sin or cos form will be more stable. For this, + // just look at the value of phi + // if (fabs(sin_phi) > 0.1) + if (sin_phi > 0.1 || sin_phi < -0.1) + { + // use the sin version to avoid 1/cos terms + K1 = K1/sin_phi; + + f1[0] = K1*(r23[1]*dcosdA[2] - r23[2]*dcosdA[1]); + f1[1] = K1*(r23[2]*dcosdA[0] - r23[0]*dcosdA[2]); + f1[2] = K1*(r23[0]*dcosdA[1] - r23[1]*dcosdA[0]); + + f3[0] = K1*(r23[2]*dcosdB[1] - r23[1]*dcosdB[2]); + f3[1] = K1*(r23[0]*dcosdB[2] - r23[2]*dcosdB[0]); + f3[2] = K1*(r23[1]*dcosdB[0] - r23[0]*dcosdB[1]); + + f2[0] = K1*(r12[2]*dcosdA[1] - r12[1]*dcosdA[2] + + r34[1]*dcosdB[2] - r34[2]*dcosdB[1]); + f2[1] = K1*(r12[0]*dcosdA[2] - r12[2]*dcosdA[0] + + r34[2]*dcosdB[0] - r34[0]*dcosdB[2]); + f2[2] = K1*(r12[1]*dcosdA[0] - r12[0]*dcosdA[1] + + r34[0]*dcosdB[1] - r34[1]*dcosdB[0]); + } + else + { + // This angle is closer to 0 or 180 than it is to + // 90, so use the cos version to avoid 1/sin terms + K1 = -K1/cos_phi; + + f1[0] = K1*( (r23[1]*r23[1] + r23[2]*r23[2])*dsindC[0] + - r23[0]*r23[1]*dsindC[1] - r23[0]*r23[2]*dsindC[2]); + f1[1] = K1*( (r23[2]*r23[2] + r23[0]*r23[0])*dsindC[1] + - r23[1]*r23[2]*dsindC[2] - r23[1]*r23[0]*dsindC[0]); + f1[2] = K1*( (r23[0]*r23[0] + r23[1]*r23[1])*dsindC[2] + - r23[2]*r23[0]*dsindC[0] - r23[2]*r23[1]*dsindC[1]); + + f3[0] = K1*(dsindB[1]*r23[2] - r23[1]*dsindB[2]); + f3[1] = K1*(dsindB[2]*r23[0] - r23[2]*dsindB[0]); + f3[2] = K1*(dsindB[0]*r23[1] - r23[0]*dsindB[1]); + + f2[0] = K1*(-(r23[1]*r12[1] + r23[2]*r12[2])*dsindC[0] + + (2.0*r23[0]*r12[1] - r12[0]*r23[1])*dsindC[1] + + (2.0*r23[0]*r12[2] - r12[0]*r23[2])*dsindC[2] + + dsindB[2]*r34[1] - dsindB[1]*r34[2]); + f2[1] = K1*(-(r23[2]*r12[2] + r23[0]*r12[0])*dsindC[1] + +(2.0*r23[1]*r12[2] - r12[1]*r23[2])*dsindC[2] + +(2.0*r23[1]*r12[0] - r12[1]*r23[0])*dsindC[0] + +dsindB[0]*r34[2] - dsindB[2]*r34[0]); + f2[2] = K1*(-(r23[0]*r12[0] + r23[1]*r12[1])*dsindC[2] + +(2.0*r23[2]*r12[0] - r12[2]*r23[0])*dsindC[0] + +(2.0*r23[2]*r12[1] - r12[2]*r23[1])*dsindC[1] + +dsindB[1]*r34[0] - dsindB[0]*r34[1]); + } + + myAtoms[0].f[0] += f1[0]; + myAtoms[0].f[1] += f1[1]; + myAtoms[0].f[2] += f1[2]; + + myAtoms[1].f[0] += f2[0] - f1[0]; + myAtoms[1].f[1] += f2[1] - f1[1]; + myAtoms[1].f[2] += f2[2] - f1[2]; + + myAtoms[2].f[0] += f3[0] - f2[0]; + myAtoms[2].f[1] += f3[1] - f2[1]; + myAtoms[2].f[2] += f3[2] - f2[2]; + + myAtoms[3].f[0] -= f3[0]; + myAtoms[3].f[1] -= f3[1]; + myAtoms[3].f[2] -= f3[2]; + } + } + } + protected String repr2() + { + return " torsion " + + (new Double(v1)).toString() + " " + + (new Double(v2)).toString() + " " + + (new Double(v3)).toString(); + } + public int termLength() + { + return 4; + } +} diff --git a/src/main/java/nanocad/minimize/uff/aterm.java b/src/main/java/nanocad/minimize/uff/aterm.java new file mode 100644 index 0000000..5d5e151 --- /dev/null +++ b/src/main/java/nanocad/minimize/uff/aterm.java @@ -0,0 +1,317 @@ +package nanocad.minimize.uff; + +/** + * aterm.java - MM2-style angle energy term + * Copyright (c) 1997,1998 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + + +import java.lang.Math; +import java.util.Vector; + +import nanocad.*; + +public class aterm extends term +{ + private static final double convert = pi / 180; // degrees to radians + double k,k0,k1,k2, th0; // force constants, and standard bond angle. It would be preferable + // to use just one force constant, and have it calculated and assigned + // during setCalculationValues, but k depends on theta, which is not + // available until the calculation begins. Therefore, k is broken + // into 3 separate constants. + int n; // constant multiplier; 1,3,4,or 4 for linear, trigonal-planar, + // square-planar, or octahedral respectively. Not used for + // general non-linear cases (where geometry is with respect to + // the central atom in the term). + double rij, rjk; // natural bond lengths, as explained in lterm.java. These should + // probably be moved to be member variables of bond.java, if possible. + + /** + * Calculates forces and potential for the angle term. + * For linear or planar geometries (wrt the central atom), + * E = k/n^2*(1-cos(n*theta); + * n depends on the orientation, see below where n is assigned + * For general non-linear, + * E = k*(c0 + c1*cos(theta) + c2*cos(2*theta)) + * c2 = 1/(4*sin^2(th0)); + * c1 = -4*c2*cos(th0); + * c0 = c2*(2*cos^2(2*th0) + 1); + * k = 664.12/(rij*rjk)*zi*zk/(rik^5)*rij*rjk*(3*rij*rjk*(1-cos^2(th0)) - rik^2*cos(th0)); + * + * Creation date: (6/08/02 jstrutz) + */ + public aterm() {} + public aterm(atom a1, atom a2, atom a3) { + myAtoms = new atom[3]; + myAtoms[0] = a1; + myAtoms[1] = a2; + myAtoms[2] = a3; + setCalculationValues(); + } + + protected void buildTerm (Vector v, Vector termList) + { + myGroup = ((atom)v.elementAt(0)).getGroup(); + if(myGroup.needsToGetTypes()) myGroup.setTypes(); + int atom1 = ((atom)v.elementAt(0)).getUFFTypeNum(); + int atom2 = ((atom)v.elementAt(1)).getUFFTypeNum(); + int atom3 = ((atom)v.elementAt(2)).getUFFTypeNum(); + + if ((atom1 < atom3) || ((atom1 == atom3)&&(((atom)v.elementAt(0)).x[0] < ((atom)v.elementAt(2)).x[0]))) + { + aterm t = new aterm ((atom) v.elementAt(0), + (atom) v.elementAt(1), + (atom) v.elementAt(2)); + termList.addElement(t); + } + } + + public double computeForces() { + int i; + // compute forces on each atom, add it to the atom's force vector + double[] ab = new double[3]; + double[] bc = new double[3]; + double abdotab = 0.0, abdotbc = 0.0, bcdotbc = 0.0, th, duDth = 0.0; + for (i = 0; i < 3; i++) { + ab[i] = myAtoms[0].x[i] - myAtoms[1].x[i]; + bc[i] = myAtoms[2].x[i] - myAtoms[1].x[i]; // isn't this cb? + } + abdotab = dotProduct(ab,ab); + abdotbc = dotProduct(ab,bc); + bcdotbc = dotProduct(bc,bc); + if(abdotab <= 0) abdotab = uffMinimizeAlgorythm.TINY; + if(bcdotbc <= 0) bcdotbc = uffMinimizeAlgorythm.TINY; + +// if (abdotab > 3.0 || bcdotbc > 3.0) return 0.0; // Why? + + double jtemp1 = abdotbc/Math.sqrt(abdotab * bcdotbc); + if(jtemp1 < -1) jtemp1 = -1; + if(jtemp1 > 1) jtemp1 = 1; + th = Math.acos(jtemp1); + + // now we can finish computing k + double jtemp3 = rij*rij + rjk*rjk - 2*rij*rjk*Math.cos(th); + if(jtemp3 <= 0) jtemp3 = uffMinimizeAlgorythm.TINY; + double rik = Math.sqrt(jtemp3); + k = k0/(jtemp3*jtemp3*rik)*(k1 - k2*jtemp3); // Keep in mind jtemp3 = rik^2. + + // potential and force depend on the angle, different + // expressions are used depending on the geometry. + potential = computePotential(th); + duDth = computePotentialDerivative(th); + + double[] dthda = new double[3]; + double[] dthdc = new double[3]; + + double jtemp2 = abdotab * bcdotbc - abdotbc*abdotbc; + if(jtemp2 <= 0) jtemp2 = uffMinimizeAlgorythm.TINY; + double denominator = Math.sqrt(jtemp2); + for (i = 0; i < 3; i++) + { + dthda[i] = -(ab[i] * abdotbc / abdotab - bc[i]) / denominator; + dthdc[i] = -(bc[i] * abdotbc / bcdotbc - ab[i]) / denominator; + myAtoms[0].f[i] += duDth * dthda[i]; + myAtoms[1].f[i] += duDth * (-dthda[i] - dthdc[i]); + myAtoms[2].f[i] += duDth * dthdc[i]; + } + return duDth * dthda[0]; + } + + /** + * Insert the method's description here. + * Creation date: (6/15/00 12:53:22 PM) + * @return double + * @param deltaTheta double + */ + protected double computePotentialDerivative(double theta) { + if(computePotential(theta) < 0.00001) return 0; + if(n == 0){ // general non-linear case + double c2 = 0.25/(Math.sin(th0)*Math.sin(th0)); + double c1 = -4*c2*Math.cos(th0); + return (-k*(c1*Math.sin(theta) + 2*c2*Math.sin(2*theta))); + } + // specific linear case, simplified 2 term fourier expansion + return (k/n*(Math.sin(n*theta) - 2/n*(1 - Math.cos(n*theta)))); + } + + protected double computePotential(double theta){ + if(n == 0){ // general non-linear case + double c2 = 0.25/(Math.sin(th0)*Math.sin(th0)); + double c1 = -4*c2*Math.cos(th0); + double c0 = c2*(2*Math.cos(th0)*Math.cos(th0) + 1); + return (k*(c0 + c1*Math.cos(theta) + c2*Math.cos(2*theta))); + } + // specific linear case, simplified 2 term fourier expansion + return (k/n/n*(1 - Math.cos(n*theta))); + } + + protected String repr2() + { + return " angle " + + (new Double(k)).toString() + " " + + (new Double(th0)).toString()+ " " + + (new Double(n)).toString(); + } + + /** + * Insert the method's description here. + * Creation date: (6/15/00 12:41:20 PM) + */ + protected void setCalculationValues() { + System.out.println("Creating aterm"); + double ri=0, rj=0, rk=0; // natural bond distance + double xi=0, xj=0, xk=0; // natural non-bond distance + double zi=0, zj=0, zk=0; // effective charge + myGroup = myAtoms[0].getGroup(); + if(myGroup.needsToGetTypes()) myGroup.setTypes(); + int atomOneType = myAtoms[0].getUFFTypeNum(); + int atomTwoType = myAtoms[1].getUFFTypeNum(); + int atomThreeType = myAtoms[2].getUFFTypeNum(); + if ((atomOneType < 0) || (atomTwoType < 0) || (atomThreeType < 0)) { + // Should never happen; uff has types for all atoms. + System.out.println("ERROR: Atom types not found "+myAtoms[0].repr()+", "+myAtoms[1].repr()+", "+myAtoms[2].repr()); + return; + } + + try { + AtomDataFile dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "uffdata.txt"); + //AtomDataFile dataFile = new AtomDataFile("uffdata.txt"); + if (dataFile.findData(atomTwoType, 1)) { + th0 = dataFile.parseDouble(3)*convert; + rj = dataFile.parseDouble(2); + xj = dataFile.parseDouble(4); + zj = dataFile.parseDouble(7); + n = dataFile.parseInt(8); + System.out.println("th0:rj:xj:zj"); + System.out.println(th0/convert+" : "+rj+" : "+xj+" : "+zj); + } + else { + // Should never happen; uff has parameters for all atoms. + System.out.println("ERROR: Angle parameters not found for "+myAtoms[1].repr()); + return; + } + + dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "uffdata.txt"); + //dataFile = new AtomDataFile("uffdata.txt"); + if (dataFile.findData(atomOneType, 1)) { + ri = dataFile.parseDouble(2); + xi = dataFile.parseDouble(4); + zi = dataFile.parseDouble(7); + System.out.println("ri:xi:zi"); + System.out.println(ri+" : "+xi+" : "+zi); + } + else{ + // should never happen; uff has parameters for all atoms. + System.out.println("ERROR: Angle parameters not found for "+myAtoms[0].repr()); + return; + } + + dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "uffdata.txt"); + //dataFile = new AtomDataFile("uffdata.txt"); + if (dataFile.findData(atomThreeType, 1)) { + rk = dataFile.parseDouble(2); + xk = dataFile.parseDouble(4); + zk = dataFile.parseDouble(7); + System.out.println("rk:xk:zk"); + System.out.println(rk+" : "+xk+" : "+zk); + } + else{ + // should never happen; uff has parameters for all atoms. + System.out.println("ERROR: Angle parameters not found for "+myAtoms[2].repr()); + return; + } + } + catch (java.io.IOException e) { + System.err.println("Angle data lookup error"); + e.printStackTrace(); + } + + // Change the value of n so it matches the required term. + // Linear = 1 + // Trigonal = 3 + // Square-planar = 4 + // Octahedral = 4 + // General non-linear = 0 + // Basically, these terms ensure that the energy falls to 0 when + // theta approaches theta0 (th0 = 180, 120, 90, 90/180, respectively). + // The general non-linear is 0 because a more descriptive, 3 term cosine + // fourier expansion is used. + switch(n){ + // NOTE!! This has been changed to 2, because the expression is + // E = k/n^2 * (1 - cos(n*th)), which leads to a maximum at th = 180. + case 1: n = 2; + break; + case 2: n = 3; + break; + case 3: n = 0; + break; + // case 4: n = 4; + // break; + case 5: n = 0; + break; + case 6: n = 4; + break; + default: n = 0; + break; + } + + // Find the ij bond order + bond myBond1 = myAtoms[0].getBond(myAtoms[1]); + double rbo1 = -0.1332*(ri + rj)*Math.log(myBond1.apporder()); + + // Note here that x,r are > 0 for all atoms + double temp1 = Math.sqrt(xi) - Math.sqrt(xj); + double ren1 = ri*rj*temp1*temp1 / (xi*ri + xj*rj); + rij = ri + rj + rbo1 + ren1; + + // Find the jk bond order + bond myBond2 = myAtoms[2].getBond(myAtoms[1]); + double rbo2 = -0.1332*(rk + rj)*Math.log(myBond2.apporder()); + + // Note here that x,r are > 0 for all atoms + double temp2 = Math.sqrt(xk) - Math.sqrt(xj); + double ren2 = rk*rj*temp2*temp2 / (xk*rk + xj*rj); + rjk = rk + rj + rbo2 + ren2; + + k0 = 664.12*zi*zk/rij/rjk; + k1 = 3*rij*rjk*(1-Math.cos(th0)*Math.cos(th0)); + k2 = Math.cos(th0); + //System.out.println("*************************"); + //System.out.println("Angle rij = "+rij); + //System.out.println("Angle rjk = "+rjk); + //System.out.println("Angle k0 = "+k0); + //System.out.println("Angle k1 = "+k1); + //System.out.println("Angle k2 = "+k2); + //System.out.println("*************************"); + } + + public int termLength() { return 3; } + + public String name() + { + return "Angle"; + } +} diff --git a/src/main/java/nanocad/minimize/uff/estaticterm.java b/src/main/java/nanocad/minimize/uff/estaticterm.java new file mode 100644 index 0000000..b6d299f --- /dev/null +++ b/src/main/java/nanocad/minimize/uff/estaticterm.java @@ -0,0 +1,239 @@ +package nanocad.minimize.uff; + +import java.util.Vector; + +import nanocad.*; + +public class estaticterm extends term +{ + private final double e0 = 1.5; //8.854187817 * .000000000001; + private double firstCharge; + private double secondCharge; + private double firstDistribution; + private double secondDistribution; + + public estaticterm() {} + + public estaticterm(atom first1, atom first2, atom second1, atom second2) + { + myGroup = first1.getGroup(); + myAtoms = new atom[4]; + myAtoms[0] = first1; + myAtoms[1] = first2; + myAtoms[2] = second1; + myAtoms[3] = second2; + setCalculationValues(); + } + + public void enumerate(Vector atomList, Vector termList) + { + Vector dipoleList = new Vector(); + int number = 0; + + System.out.println("enumerating"); + + //make a list of all dipoles + for (int i = 0; i < atomList.size(); i++) + { + atom tmpAtom = (atom)atomList.elementAt(i); + for (int j = 0; j < tmpAtom.bonds.size(); j++) + { + dipole temp; + if (((bond)tmpAtom.bonds.elementAt(j)).a1 == tmpAtom) + temp = new dipole(tmpAtom,((bond)tmpAtom.bonds.elementAt(j)).a2); + else + temp = new dipole(tmpAtom,((bond)tmpAtom.bonds.elementAt(j)).a1); + + boolean add = true; + + for (int k = 0; k < dipoleList.size(); k++) //aviod adding duplicate bonds + if (temp.isSameDipole((dipole)dipoleList.elementAt(k))) + add = false; + + if (add == true) + dipoleList.addElement(temp); + } + } + + //add terms for all dipoles that don't share common atoms + for (int i = 0; i < dipoleList.size(); i++) + { + for (int j = i + 1; j < dipoleList.size(); j++) + { + dipole temp1 = (dipole)dipoleList.elementAt(i); + dipole temp2 = (dipole)dipoleList.elementAt(j); + + Vector v = new Vector(); + + if (!temp1.sharesAtomWith(temp2)) + { + v.addElement(temp1); + v.addElement(temp2); + this.buildTerm(v, termList); + number++; + } + } + } + System.out.println(number + " terms added"); + } + + protected void buildTerm(Vector v, Vector termList) + { + estaticterm e = new estaticterm( ((dipole)v.elementAt(0)).getFirst(), ((dipole)v.elementAt(0)).getSecond(), + ((dipole)v.elementAt(1)).getFirst(), ((dipole)v.elementAt(1)).getSecond()); + if (!((e.firstCharge == 0.0 && e.firstDistribution == 0.0) || (e.secondCharge == 0.0 && e.secondDistribution == 0.0)) ) + termList.addElement(e); + } + + public double computeForces() + { + double ab[], cd[], uv[], abdotab, abdotcd, abdotuv, cddotcd, cddotuv, uvdotuv, abnorm, cdnorm, r, x, thetai, thetaj, dedr, dedx, + dedthi, dedthj, drda[], drdb[], drdc[], drdd[], dxda[], dxdb[], dxdc[], dxdd[], dthida[], dthidb[], dthjdc[], dthjdd[]; + ab = new double[3]; cd = new double [3]; uv = new double[3]; drda = new double[3]; drdb = new double[3]; drdc = new double[3]; + drdd = new double[3]; dxda = new double[3]; dxdb = new double[3]; dxdc = new double[3]; dxdd = new double[3]; + dthida = new double[3]; dthidb = new double[3]; dthjdc = new double[3]; dthjdd = new double[3]; + + for (int i = 0; i < 3; i++) + { + ab[i] = myAtoms[0].x[i] - myAtoms[1].x[i]; + cd[i] = myAtoms[2].x[i] - myAtoms[3].x[i]; + uv[i] = myAtoms[3].x[i] + secondDistribution * cd[i] - myAtoms[1].x[i] - firstDistribution * ab[i]; + } + + // A bunch of dot products- left here because they looked unobtrusive. + abdotab = ab[0]*ab[0] + ab[1]*ab[1] + ab[2]*ab[2]; + abdotcd = ab[0]*cd[0] + ab[1]*cd[1] + ab[2]*cd[2]; + abdotuv = ab[0]*uv[0] + ab[1]*uv[1] + ab[2]*uv[2]; + cddotcd = cd[0]*cd[0] + cd[1]*cd[1] + cd[2]*cd[2]; + cddotuv = cd[0]*uv[0] + cd[1]*uv[1] + cd[2]*uv[2]; + uvdotuv = uv[0]*uv[0] + uv[1]*uv[1] + uv[2]*uv[2]; + + if(abdotab <= 0) abdotab = uffMinimizeAlgorythm.TINY; + if(cddotcd <= 0) cddotcd = uffMinimizeAlgorythm.TINY; + if(uvdotuv <= 0) uvdotuv = uffMinimizeAlgorythm.TINY; + + abnorm = Math.sqrt(abdotab); + cdnorm = Math.sqrt(cddotcd); + + //note : the variables x, thetai, and thetaj represent cos x, cos thetai and cos thetaj rather than the angles themselves. + + r = Math.sqrt(uvdotuv); + x = abdotcd / (abnorm * cdnorm); + thetai = abdotuv / (abnorm * r); + thetaj = cddotuv / (cdnorm * r); + + dedr = -3 * firstCharge * secondCharge / (e0 * r*r*r*r) * (x - 3 * thetai * thetaj); + dedx = firstCharge * secondCharge / (e0 * r*r*r); + dedthi = firstCharge * secondCharge / (e0 * r*r*r) * (-3 * thetaj); + dedthj = firstCharge * secondCharge / (e0 * r*r*r) * (-3 * thetai); + + for (int i = 0; i < 3; i++) + { + drda[i] = - firstDistribution * uv[i] / r; + drdb[i] = - (1 - firstDistribution) * uv[i] / r; + drdc[i] = secondDistribution * uv[i] / r; + drdd[i] = (1 - secondDistribution) * uv[i] / r; + + dxda[i] = (cd[i] - ab[i] * abdotcd / abdotab) / (abnorm * cdnorm); + dxdb[i] = -dxda[i]; + dxdc[i] = (ab[i] - cd[i] * abdotcd / cddotcd) / (abnorm * cdnorm); + dxdd[i] = -dxdc[i]; + + dthida[i] = (uv[i] - firstDistribution * ab[i] - ab[i] * abdotuv / abdotab + uv[i] * abdotuv * firstDistribution / uvdotuv) / (abnorm * r); + dthidb[i] = (-uv[i] - (1 - firstDistribution) * ab[i] + ab[i] * abdotuv / abdotab + uv[i] * abdotuv * (1 - firstDistribution) / uvdotuv) / (abnorm * r); + + dthjdc[i] = (uv[i] + secondDistribution * cd[i] - cd[i] * cddotuv / cddotcd - uv[i] * cddotuv * secondDistribution / uvdotuv) / (cdnorm * r); + dthjdd[i] = (-uv[i] + (1 - secondDistribution) * cd[i] + cd[i] * cddotuv / cddotcd - uv[i] * cddotuv * (1 - secondDistribution) / uvdotuv) / (cdnorm * r); + + myAtoms[0].f[i] += dedr * drda[i] + dedx * dxda[i] + dedthi * dthida[i]; + myAtoms[1].f[i] += dedr * drdb[i] + dedx * dxdb[i] + dedthi * dthidb[i]; + myAtoms[2].f[i] += dedr * drdc[i] + dedx * dxdc[i] + dedthj * dthjdc[i]; + myAtoms[3].f[i] += dedr * drdd[i] + dedx * dxdd[i] + dedthj * dthjdd[i]; + } + + potential = computePotential(x,thetai,thetaj,r); + return myAtoms[0].x[0]; + } + + public double computePotential(double x, double alpha1, double alpha2, double d){ + return (firstCharge*secondCharge*(x-3*alpha1*alpha2)/(e0*d*d*d)); + } + + public void setCalculationValues() + { + System.out.println("Creating estaticterm"); + atom tempa; + int temp; + myGroup = myAtoms[0].getGroup(); + if(myGroup.needsToGetTypes()) myGroup.setTypes(); + int atom1 = myAtoms[0].getUFFTypeNum(); + int atom2 = myAtoms[1].getUFFTypeNum(); + int atom3 = myAtoms[2].getUFFTypeNum(); + int atom4 = myAtoms[3].getUFFTypeNum(); + + if (atom1 > atom2) + { + temp = atom1; + atom1 = atom2; + atom2 = temp; + tempa = myAtoms[0]; + myAtoms[0] = myAtoms[1]; + myAtoms[1] = tempa; + } + + if (atom3 > atom4) + { + temp = atom3; + atom3 = atom4; + atom4 = temp; + tempa = myAtoms[2]; + myAtoms[2] = myAtoms[3]; + myAtoms[3] = tempa; + } + + try + { + AtomDataFile dataFile= new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "mm3estaticdata.txt"); + //AtomDataFile dataFile= new AtomDataFile("mm3estaticdata.txt"); + if (dataFile.findData(atom1, atom2, 0, 1)) + { + firstCharge = dataFile.parseDouble(2); + firstDistribution = dataFile.parseDouble(3); + } + else + { + //System.out.println("No data for " + atom1 + " " + atom2 + " dipole."); + firstCharge = 0.0; + firstDistribution = 0.0; + } + + if (dataFile.findData(atom3, atom4, 0, 1)) + { + secondCharge = dataFile.parseDouble(2); + secondDistribution = dataFile.parseDouble(3); + } + else + { + //System.out.println("No data for " + atom3 + " " + atom4 + " dipole."); + secondCharge = 0.0; + secondDistribution = 0.0; + } + } + catch (java.io.IOException e) + { + System.err.println("Dipole data lookup error"); + e.printStackTrace(); + } + } + + public int termLength() + { + return 4; + } + + public String name() + { + return "Electrostatic"; + } +} diff --git a/src/main/java/nanocad/minimize/uff/lterm.java b/src/main/java/nanocad/minimize/uff/lterm.java new file mode 100644 index 0000000..8f22b98 --- /dev/null +++ b/src/main/java/nanocad/minimize/uff/lterm.java @@ -0,0 +1,200 @@ +package nanocad.minimize.uff; + +/** + * lterm.java - MM2-style length energy term + * Copyright (c) 1997,1998 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * or its derived works must display the following acknowledgement: + * This product includes software developed by Will Ware. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.lang.Math; +import java.util.Vector; + +import nanocad.*; + +public class lterm extends term +{ + /** + * Represents the bond stretch term of UFF. + * E = 0.5*k(r-rij)^2 + * rij = ri + rj + rbo + ren + * rbo = -0.1332*(ri + rj)*ln(n) + * n = bond order + * ren = ri*rj*(sqrt(xi) - sqrt(xj))^2 / (xi*ri + xj*rj) + * k = 664.12*zi*zj / rij^3 + * ri, rj, xi, xj, zi, zj are parameters found in uffdata.txt + * k and rij are computed when terms are read from uffdata.txt + * + * Creation date: (6/08/02) + */ + + double k; // force constant + double rij; // natural stretch distance + + public lterm() {} + public lterm(atom a1, atom a2) { + myAtoms = new atom[2]; + myAtoms[0] = a1; + myAtoms[1] = a2; + setCalculationValues(); + } + + protected void buildTerm (Vector v, Vector termList) + { + myGroup = ((atom)v.elementAt(0)).getGroup(); + if(myGroup.needsToGetTypes()) myGroup.setTypes(); + int atom1 = ((atom)v.elementAt(0)).getUFFTypeNum(); + int atom2 = ((atom)v.elementAt(1)).getUFFTypeNum(); + + if (atom1 < atom2) + { + lterm t = new lterm ((atom) v.elementAt(0), (atom) v.elementAt(1)); + termList.addElement(t); + } + else if(atom1 == atom2) + { + if ( ((atom)v.elementAt(0)).x[0] < ((atom)v.elementAt(1)).x[0] ) + { + lterm t = new lterm ((atom) v.elementAt(0), (atom) v.elementAt(1)); + termList.addElement (t); + } + } + } + + public double computeForces() + { int i; + + // compute forces on each atom, add it to the atom's force vector + double[] diff = new double[3]; + double r = 0.0, m = 0.0; + for (i = 0; i < 3; i++) + { diff[i] = myAtoms[0].x[i] - myAtoms[1].x[i]; + r += diff[i] * diff[i]; + } + + if(r <= 0) r = uffMinimizeAlgorythm.TINY; + r = Math.sqrt(r); + potential = computePotential(r); + + m = computePotentialDerivative(r); + + // at this point, m is du/dr + m /= r; + // m > 0 attract, m < 0 repel + for (i = 0; i < 3; i++) + { myAtoms[0].f[i] -= m * diff[i]; + myAtoms[1].f[i] += m * diff[i]; + } + double jtemp1 = dotProduct(diff,diff); + if(jtemp1 <= 0) jtemp1 = uffMinimizeAlgorythm.TINY; + return m * Math.sqrt(jtemp1); + //return m*r; + } + + /** + * Insert the method's description here. + * Creation date: (6/15/00 1:22:01 PM) + * @return double + * @param lengthDifference double + */ + protected double computePotentialDerivative(double stretch) + { // if (computePotential(stretch) < 0.00001) return 0; + return (k*(stretch - rij)); } + + protected double computePotential(double stretch) + { return (0.5*k*(stretch - rij)*(stretch - rij)); } + + protected String repr2() + { return " length " + (new Double(k)).toString() + " " + (new Double(rij)).toString(); } + + /** + * Sets the force constant and the natural radius. + * + * Creation date: (6/08/02) + */ + protected void setCalculationValues() + { + System.out.println("Creating lterm"); + double ri = 0, rj = 0; // natural bond distance, for regular stretch + double xi = 0, xj = 0; // natural non-bond distance, for electronegativity + double zi = 0, zj = 0; // effective charge, for electronegativity + myGroup = myAtoms[0].getGroup(); + if(myGroup.needsToGetTypes()) myGroup.setTypes(); + int atomOneType = myAtoms[0].getUFFTypeNum(); + int atomTwoType = myAtoms[1].getUFFTypeNum(); + if (atomOneType < 0 || atomTwoType < 0) + { // This should never happen, all atom types are > 0 in uff + System.out.println("ERROR: Atom types not found "+myAtoms[0].repr()+", "+myAtoms[1].repr()); + return; + } + + try { + AtomDataFile dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "uffdata.txt"); + //AtomDataFile dataFile = new AtomDataFile("uffdata.txt"); + if (dataFile.findData(atomOneType, 1)) { + ri = dataFile.parseDouble(2); + xi = dataFile.parseDouble(4); + zi = dataFile.parseDouble(7); + //System.out.println("ri:xi:zi"); + //System.out.println(ri+" : "+xi+" : "+zi); + } + else System.out.println("ERROR: Data not found for "+atomOneType); + + dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "uffdata.txt"); + //dataFile = new AtomDataFile("uffdata.txt"); + if(dataFile.findData(atomTwoType, 1)) + { rj = dataFile.parseDouble(2); + xj = dataFile.parseDouble(4); + zj = dataFile.parseDouble(7); + //System.out.println("rj:xj:zj"); + //System.out.println(rj+" : "+xj+" : "+zj); + } + else // This should never happen; uff has terms for every atom. + { System.out.println("ERROR: Data not found for "+atomTwoType); } + } + catch (java.io.IOException e) + { System.err.println("Length data lookup error"); + e.printStackTrace(); + } + + // Get the bond order by finding the bond between i and j. + bond myBond = myAtoms[0].getBond(myAtoms[1]); + System.out.println("BO = "+myBond.apporder()); + double rbo = -0.1332*(ri + rj)*Math.log(myBond.apporder()); + + // Note here that x,r are > 0 for all atoms + double temp = Math.sqrt(xi) - Math.sqrt(xj); + double ren = ri*rj*temp*temp / (xi*ri + xj*rj); + + rij = ri + rj + rbo + ren; + k = 664.12*zi*zj / (rij*rij*rij); + System.out.println("length K = "+k); + System.out.println("length rij = "+rij); + } + + public int termLength() { return 2; } + public String name() { return "Length"; } +} diff --git a/src/main/java/nanocad/minimize/uff/opbterm.java b/src/main/java/nanocad/minimize/uff/opbterm.java new file mode 100644 index 0000000..3a28863 --- /dev/null +++ b/src/main/java/nanocad/minimize/uff/opbterm.java @@ -0,0 +1,220 @@ +/****************************************** + *opbterm.java -- nanocad + *Andrew Knox 06/25/01 + *implements out of plane angle bend term + ******************************************/ + +package nanocad.minimize.uff; + +import java.lang.Math; +import java.util.Vector; + +import nanocad.atom; +import nanocad.bond; +import nanocad.term; + +public class opbterm extends term +{ + private double k0, k1, k2; + private double angle; + + public opbterm() {} + + public opbterm(atom center, atom bent, atom other1, atom other2) + { + myGroup = center.getGroup(); + myAtoms = new atom[4]; + + myAtoms[1] = bent; + myAtoms[0] = center; + myAtoms[2] = other1; + myAtoms[3] = other2; + setCalculationValues(); + } + + public void enumerate(Vector atomList, Vector termList) + { + for(int i = 0; i < atomList.size(); i++) + { + if ( ((atom)atomList.elementAt(i)).bonds.size() == 3) + { + atom tmp; + Vector v = new Vector(); + v.addElement((atom)atomList.elementAt(i)); + for (int j = 0; j < 3; j++) + { + if (((bond)((atom)v.elementAt(0)).bonds.elementAt(j)).a1 == (atom)v.elementAt(0)) + v.addElement(((bond)((atom)v.elementAt(0)).bonds.elementAt(j)).a2); + else + v.addElement(((bond)((atom)v.elementAt(0)).bonds.elementAt(j)).a1); + } + this.buildTerm(v, termList); + } + } + } + + protected void buildTerm(Vector v, Vector termList) + { + opbterm b; + for (int i = 0; i<3; i++) + { + b = new opbterm((atom)v.elementAt(0), (atom)v.elementAt((i%3)+1), + (atom)v.elementAt(((i+1)%3)+1), (atom)v.elementAt(((i+2)%3)+1)); + if (b.k0 != 0.0) + { + termList.addElement(b); + } + } + } + + public double computeForces() + { + //calculate angle + double pq[], rq[], qs[], normal[], dthdpq[], dthdrq[], dthdqs[]; + pq = new double[3]; rq = new double[3]; qs = new double[3]; normal = new double[3]; + dthdpq = new double[3]; dthdrq = new double[3]; dthdqs = new double[3]; + double qsdotqs, ndotn, ndotqs, denominator, dEdth; + + for (int i = 0; i < 3; i++) + { + pq[i] = myAtoms[0].x[i] - myAtoms[3].x[i]; + rq[i] = myAtoms[0].x[i] - myAtoms[2].x[i]; + qs[i] = myAtoms[1].x[i] - myAtoms[0].x[i]; + } + + normal[0] = pq[1]*rq[2] - pq[2]*rq[1]; + normal[1] = pq[2]*rq[0] - pq[0]*rq[2]; + normal[2] = pq[0]*rq[1] - pq[1]*rq[0]; + + ndotn = dotProduct(normal,normal); + qsdotqs = dotProduct(qs,qs); + ndotqs = dotProduct(normal,qs); + + if(ndotn <= 0) ndotn = uffMinimizeAlgorythm.TINY; + if(qsdotqs <= 0) qsdotqs = uffMinimizeAlgorythm.TINY; + + double jtemp1 = ndotn * qsdotqs - ndotqs * ndotqs; + if(jtemp1 <= 0) jtemp1 = uffMinimizeAlgorythm.TINY; + denominator = Math.sqrt(jtemp1); + + double jtemp2 = ndotqs / Math.sqrt(ndotn * qsdotqs); + if(jtemp2 < -1) jtemp2 = -1; + if(jtemp2 > 1) jtemp2 = 1; + angle = Math.PI/2 - Math.acos(jtemp2); + + // These are divided by 3 because we consider each + // of the 3 bent atoms separately. + potential = computePotential(angle) / 3; + dEdth = computePotentialDerivative(angle) / 3; + + double RQcrossQS[] = crossProduct(rq,qs); + double RQcrossNorm[] = crossProduct(rq,normal); + dthdpq[0] = (-RQcrossQS[0] + RQcrossNorm[0] * ndotqs / ndotn) / denominator; + dthdpq[1] = (-RQcrossQS[1] + RQcrossNorm[1] * ndotqs / ndotn) / denominator; + dthdpq[2] = (-RQcrossQS[2] + RQcrossNorm[2] * ndotqs / ndotn) / denominator; + + double PQcrossQS[] = crossProduct(pq,qs); + double PQcrossNorm[] = crossProduct(pq,normal); + dthdrq[0] = (PQcrossQS[0] + PQcrossNorm[0] * ndotqs / ndotn) / denominator; + dthdrq[1] = (PQcrossQS[1] + PQcrossNorm[1] * ndotqs / ndotn) / denominator; + dthdrq[2] = (PQcrossQS[2] + PQcrossNorm[2] * ndotqs / ndotn) / denominator; + + dthdqs[0] = (normal[0] - qs[0] * ndotqs / qsdotqs) / denominator; + dthdqs[1] = (normal[1] - qs[1] * ndotqs / qsdotqs) / denominator; + dthdqs[2] = (normal[2] - qs[2] * ndotqs / qsdotqs) / denominator; + + for (int i = 0; i < 3; i++) + { + myAtoms[0].f[i] += dEdth * (-dthdqs[i] + dthdrq[i] + dthdpq[i]); + myAtoms[1].f[i] += dEdth * dthdqs[i]; + myAtoms[2].f[i] += dEdth * -dthdrq[i]; + myAtoms[3].f[i] += dEdth * -dthdpq[i]; + } + return myAtoms[0].f[0]; + //return dTheta; + } + + public void setCalculationValues() + { + myGroup = myAtoms[0].getGroup(); + if(myGroup.needsToGetTypes()) myGroup.setTypes(); + int atomBentType = myAtoms[1].getUFFTypeNum(); + int atomCenterType = myAtoms[0].getUFFTypeNum(); + + // Force constants for this guy came from solving 12 + // linear equations in 12 unknowns for the Group V hydrides. + // A three term cosine fourier expansion was used, with constants + // fit to have a minimum (derivative is 0) at the natural angle, + // and that minimum is set to 0. Also, at 0 degrees, the function + // has a maximum of Ebarrier. + // Atom Angle Ebarrier + // N 107.5 5.8 + // P 93.5 37 + // As 91.8 40 + // Sb 91.3 46 + // Bi ? ? + // Energies are in kilocalories per mole. Note that the angle given is + // a published value for the H-X-H angle, while UFF instead uses the angle + // between the IL axis and the IJK plane, for a opbterm consisting of atoms + // IJKL. Values for Bismuth were unavailable, so Bi and Po are assumed + // to have the same values as Sb and Te. + // + // Terms for carbon come directly from the literature. + + switch(myAtoms[0].atomicNumber()){ + case 7: // Nitrogen and Oxygen + case 8: k0 = 18.2169897839; + k1 = -24.4237325078; + k2 = 12.0067427239; + break; + case 15: // Phosphorus and Sulfur + case 16: k0 = 22.6500766206; + k1 = -7.94615918416; + k2 = 22.2960825616; + break; + case 33: // Arsenic and Selenium + case 34: k0 = 22.0248498374; + k1 = -3.96032299431; + k2 = 21.9354731569; + break; + case 51: // Antimony, Tellurium, Bismuth, and Polonium + case 52: + case 83: + case 84: k0 = 25.1558772986; + k1 = -3.25887125444; + k2 = 25.1089939559; + break; + case 6: // Carbon, the most complicated one. + if(atomBentType == 19){ + // if it's bonded to O_2... + k0 = 50; + k1 = -50; + k2 = 0; + } + else{ + k0 = 6; + k1 = -6; + k2 = 0; + } + break; + default: k0 = 0; + k1 = 0; + k2 = 0; + } + + } + + protected double computePotential(double angle) + { return k0 + k1*Math.cos(angle) + k2*Math.cos(2*angle); } + + protected double computePotentialDerivative(double angle) + { return -k1*Math.sin(angle) - 2*k2*Math.sin(2*angle); } + + public String repr2() { return " OPB"; } + + public int termLength() + { return 4; } + + public String name() + { return "Out of Plane Bend"; } +} diff --git a/src/main/java/nanocad/minimize/uff/tterm.java b/src/main/java/nanocad/minimize/uff/tterm.java new file mode 100644 index 0000000..000bff3 --- /dev/null +++ b/src/main/java/nanocad/minimize/uff/tterm.java @@ -0,0 +1,421 @@ +package nanocad.minimize.uff; + +/** + * tterm.java - MM2-style torsion energy term + * Copyright (c) 1997,1998 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.lang.Math; +import java.util.Vector; + +import nanocad.term; +import nanocad.atom; + +public class tterm extends term +{ + private double vphi; + private int n; + private double phi0; +/** + * Insert the method's description here. + * Creation date: (6/19/00 4:09:57 PM) + */ + public tterm() {} + + public tterm(atom a1, atom a2, atom a3, atom a4) { + int i; + boolean found; + myAtoms = new atom[4]; + myAtoms[0] = a1; + myAtoms[1] = a2; + myAtoms[2] = a3; + myAtoms[3] = a4; + setCalculationValues(); + } + + protected void buildTerm (Vector v, Vector termList) + { + myGroup = ((atom)v.elementAt(0)).getGroup(); + if(myGroup.needsToGetTypes()) myGroup.setTypes(); + int atom1 = ((atom)v.elementAt(0)).getUFFTypeNum(); + int atom2 = ((atom)v.elementAt(1)).getUFFTypeNum(); + int atom3 = ((atom)v.elementAt(2)).getUFFTypeNum(); + int atom4 = ((atom)v.elementAt(3)).getUFFTypeNum(); + + if (atom1 < atom4 && atom2 < atom3) + { + tterm t = new tterm ((atom) v.elementAt(0), + (atom) v.elementAt(1), + (atom) v.elementAt(2), + (atom) v.elementAt(3)); + if (t.vphi != 0.0) + { + termList.addElement(t); + //System.out.println("added: " + atom1 + " " + atom2 + " " + atom3 + " " + atom4); + } + } + else if (atom2 == atom3 && atom1 <= atom4) + { + if ( ((atom)v.elementAt(1)).x[0] > ((atom)v.elementAt(2)).x[0]) + { + tterm t = new tterm ((atom) v.elementAt(0), + (atom) v.elementAt(1), + (atom) v.elementAt(2), + (atom) v.elementAt(3)); + if (t.vphi != 0.0) + { + termList.addElement(t); + //System.out.println("added: " + atom1 + " " + atom2 + " " + atom3 + " " + atom4); + } + } + } + } + + public double computePotential(double phi){ + double temp1 = (n*phi0)%(2*Math.PI); + double temp2 = (n*phi)%(2*Math.PI); +/* + if(temp1 > 1) temp1 = 1; + if(temp1 < -1) temp1 = -1; + if(temp2 > 1) temp2 = 1; + if(temp2 < -1) temp2 = -1; +*/ + return 0.5*vphi*(1-Math.cos(temp1)*Math.cos(temp2)); + } + + public double computePotentialDerivative(double phi){ + double temp1 = (n*phi0)%(2*Math.PI); + double temp2 = (n*phi)%(2*Math.PI); +/* + if(temp1 > 1) temp1 = 1; + if(temp1 < -1) temp1 = -1; + if(temp2 > 1) temp2 = 1; + if(temp2 < -1) temp2 = -1; +*/ + + // The following line gives the force a stopping condition. + // If things didn't force a movement of a certain size, this + // wouldn't have been necessary. + if (computePotential(phi) < 0.001) return 0; + return 0.5*n*vphi*Math.cos(temp1)*Math.sin(temp2); + } + + public double computeForces() + { + double ij[], kj[], kl[], mj[], nk[], dxdi[], dxdj[], dxdk[], dxdl[]; + ij = new double[3]; kj = new double[3]; + kl = new double[3]; mj = new double[3]; + nk = new double[3]; dxdi = new double[3]; + dxdj = new double[3]; dxdk = new double[3]; dxdl = new double[3]; + + double phi = CalculateDihedral(); + potential = computePotential(phi); + double dedth = computePotentialDerivative(phi); + + for (int i = 0; i < 3; i++) + { + ij[i] = myAtoms[0].x[i] - myAtoms[1].x[i]; + kj[i] = myAtoms[2].x[i] - myAtoms[1].x[i]; + kl[i] = myAtoms[2].x[i] - myAtoms[3].x[i]; + } + + mj = crossProduct(ij,kj); + nk = crossProduct(kj,kl); + + for (int i = 0; i < 3; i++) + { + dxdi[i] = Math.sqrt(dotProduct(kj,kj))/dotProduct(mj,mj)*mj[i]; + dxdk[i] = -Math.sqrt(dotProduct(kj,kj))/dotProduct(nk,nk)*nk[i]; + dxdj[i] = ((dotProduct(ij,kj) / dotProduct(kj,kj)) - 1.0)*dxdi[i] - + (dotProduct(kl,kj) / dotProduct(kj,kj))*dxdl[i]; + dxdk[i] = ((dotProduct(kl,kj) / dotProduct(kj,kj)) - 1.0)*dxdl[i] - + (dotProduct(ij,kj) / dotProduct(kj,kj))*dxdi[i]; + myAtoms[0].f[i] -= dedth * dxdi[i]; + myAtoms[1].f[i] -= dedth * dxdj[i]; + myAtoms[2].f[i] -= dedth * dxdk[i]; + myAtoms[3].f[i] -= dedth * dxdl[i]; + } + return myAtoms[0].f[0]; + } + + + protected String repr2() + { + return new String(" torsion "+vphi+" "+n); + } +/** + * Insert the method's description here. + * Creation date: (6/15/00 1:40:30 PM) + */ +protected void setCalculationValues() { + //System.out.println("Creating tterm"); + myGroup = myAtoms[0].getGroup(); + if(myGroup.needsToGetTypes()) myGroup.setTypes(); + int atomOneType = myAtoms[0].getUFFTypeNum(); + int atomTwoType = myAtoms[1].getUFFTypeNum(); + int atomThreeType = myAtoms[2].getUFFTypeNum(); + int atomFourType = myAtoms[3].getUFFTypeNum(); +/* + System.out.print("Torsion term"); + for (int i = 0; i < 4; i++) + System.out.print(" | "+myAtoms[i].getUFFTypeString()+" "+myAtoms[i].myGeom); + System.out.print("\n"); +*/ + if ((atomOneType < 0) || (atomTwoType < 0) || (atomThreeType < 0) || (atomFourType < 0)) { + System.out.println("ERROR: No UFF Type for "+myAtoms[0].toString()+", "+myAtoms[1].toString()+", "+myAtoms[2].toString()+", "+myAtoms[3].toString()); + return; + } + + // Need to determine the group and hybridization of the atoms, so we + // can determine the form vphi should take. The following order is important; + // the first if stmts are exceptions to the more general rules that follow. + // Order of atoms is 0,3:edge, 1,2: central + + // to determine if either central atom is from group 6 + boolean bfromG6 = false; + boolean cfromG6 = false; + + // to determine the sp3 params for atoms b,c; easier to do it here than + // to reproduce it in each sp3 case. + double Uj = 0.0; + double Uk = 0.0; + double Vj = 0.0; + double Vk = 0.0; + switch (myAtoms[1].atomicNumber()){ + case 6: Vj = 2.119; + break; + case 7: Vj = 0.450; + break; + case 8: Vj = 0.018; + break; + case 14: Vj = 1.225; + break; + case 15: Vj = 2.400; + break; + case 16: Vj = 0.484; + break; + case 32: Vj = 0.701; + break; + case 33: Vj = 1.5; + break; + case 34: Vj = 0.335; + break; + case 50: Vj = 0.199; + break; + case 51: Vj = 1.1; + break; + case 52: Vj =0.3 ; + break; + case 82: Vj = 0.1; + break; + case 83: Vj = 1.0; + break; + case 84: Vj = 0.3; + break; + default: Vj = 0.0; + } + + switch (myAtoms[2].atomicNumber()){ + case 6: Vk = 2.119; + break; + case 7: Vk = 0.450; + break; + case 8: Vk = 0.018; + break; + case 14: Vk = 1.225; + break; + case 15: Vk = 2.400; + break; + case 16: Vk = 0.484; + break; + case 32: Vk = 0.701; + break; + case 33: Vk = 1.5; + break; + case 34: Vk = 0.335; + break; + case 50: Vk = 0.199; + break; + case 51: Vk = 1.1; + break; + case 52: Vk =0.3; + break; + case 82: Vk = 0.1; + break; + case 83: Vk = 1.0; + break; + case 84: Vk = 0.3; + break; + default: Vk = 0.0; + } + + // to determine bond order between the central atoms + double order = (myAtoms[1].getBond(myAtoms[2])).apporder(); + int an1 = myAtoms[1].atomicNumber(); + int an2 = myAtoms[2].atomicNumber(); + + // if either central atom (ca) is from a B-group, or either is linear, vphi = 0 + if((an1 == 8) || (an1 == 16) || (an1 == 34) || (an1 == 52) || (an1 == 84)){ + bfromG6 = true; + } + if((an2 == 8) || (an2 == 16) || (an2 == 34) || (an2 == 52) || (an2 == 84)){ + cfromG6 = true; + } + + // if non main group, vphi = 0 + if(( ((an1>20) && (an1<30)) || ((an1>38) && (an1<49)) || ((an1>57) && (an1<80)) || ((an1>88) && (an1<113)) ) || ( ((an2>20) && (an2<30)) || ((an2>38) && (an2<49)) || ((an2>57) && (an2<80)) || ((an2>88) && (an2<113)) )){ + vphi = 0; + n = 0; + phi0 = 0; + } + + // if one ca is sp3 and the other is sp2 with the fringe atom connected to sp2 also sp2 + else if( (order == 1) && (((myAtoms[1].myGeom == 3) && (myAtoms[2].myGeom == 2) && (myAtoms[3].myGeom == 2)) || ((myAtoms[2].myGeom == 3) && (myAtoms[1].myGeom == 2) && (myAtoms[0].myGeom == 2)) ) ){ + n = 3; + phi0 = Math.PI; // 180 degrees + vphi = 2; + } + + // if one ca is sp3 from group 6 and the other is sp2 not from group 6 + else if( (order == 1) && ( ((bfromG6) && (myAtoms[1].myGeom == 3) && (!cfromG6) && (myAtoms[2].myGeom == 2)) || ((cfromG6) && (myAtoms[2].myGeom == 3) && (!bfromG6) && (myAtoms[1].myGeom == 2)) ) ){ + // set Uj, Uk based on the row + Uj = 0.1; + if(an1 < 55) Uj = 0.2; + if(an1 < 37) Uj = 0.7; + if(an1 < 19) Uj = 1.25; + if(an1 < 11) Uj = 2; + + Uk = 0.1; + if(an2 < 55) Uk = 0.2; + if(an2 < 37) Uk = 0.7; + if(an2 < 19) Uk = 1.25; + if(an2 < 11) Uk = 2; + + n = 2; + phi0 = Math.PI/2; // 90 degrees + vphi = 5*Math.sqrt(Uj*Uk)*(1+4.18*Math.log(order)); + } + + // if both ca's are sp3 from group 6 + else if( (order == 1) && ((myAtoms[1].myGeom == 3) && (myAtoms[2].myGeom == 3) && (bfromG6) && (cfromG6)) ){ + // set Uj, Uk to 2 for oxygen, 6.8 otherwise + if(an1 == 8) Vj = 2; + else Vj = 6.8; + if(an2 == 8) Vk = 2; + else Vk = 6.8; + + vphi = Math.sqrt(Vj*Vk); + n = 2; + phi0 = Math.PI/2; // 90 degrees + } + + // if both ca's are sp2 + else if((myAtoms[1].myGeom == 2) && (myAtoms[2].myGeom == 2)){ + // get Uj, Uk based on the row + Uj = 0.1; + if(an1 < 55) Uj = 0.2; + if(an1 < 37) Uj = 0.7; + if(an1 < 19) Uj = 1.25; + if(an1 < 11) Uj = 2; + + Uk = 0.1; + if(an2 < 55) Uk = 0.2; + if(an2 < 37) Uk = 0.7; + if(an2 < 19) Uk = 1.25; + if(an2 < 11) Uk = 2; + n = 2; + vphi = 5*Math.sqrt(Uj*Uk)*(1+4.18*Math.log(order)); + phi0 = CalculateDihedral(); + if (order == 1.5 || order == 2) // fudge factor from DREIDING + { if (Math.abs(180 - phi0) > phi0) + phi0 = 0; + else phi0 = Math.PI; + } + else + { if (Math.abs(180 - phi0) > Math.abs(phi0 - 60)) + phi0 = Math.PI/3; // 60 degrees + else phi0 = Math.PI; // 180 degrees + } + } + + // if one ca is sp3 and the other is sp2 + else if( ((myAtoms[1].myGeom == 2) && (myAtoms[2].myGeom == 3)) || ((myAtoms[2].myGeom == 2) && (myAtoms[1].myGeom == 3)) ) + { + n = 6; + vphi = 1; + phi0 = 0; + } + + // if both ca's are sp3 + else if((myAtoms[1].myGeom == 3) && (myAtoms[2].myGeom == 3)){ + vphi = Math.sqrt(Vj*Vk); + n = 3; + phi0 = CalculateDihedral(); + if (Math.abs(180 - phi0) > Math.abs(phi0 - 60)) + phi0 = Math.PI/3; // 60 degrees + else phi0 = Math.PI; // 180 degrees + } + + // else vphi = 0 and n = 0 + else{ + vphi = 0; + n = 0; + phi0 = 0; + } +// System.out.println("Vphi = "+vphi+"; n = "+n+"; phi_0 = "+phi0+"; order = "+order); + } + + public int termLength() { return 4; } + public String name() { return "Torsion"; } + + // Jeff Stenhouse 02/05/2003 + // A method that calculates the dihedral angle of 4 atoms. + public double CalculateDihedral() + { + double dihedral, dp2, dotProduct; + double pq[] = {0.0, 0.0, 0.0}; + double rq[] = {0.0, 0.0, 0.0}; + double rs[] = {0.0, 0.0, 0.0}; + double normal[] = {0.0, 0.0, 0.0}; + double normal2[] = {0.0, 0.0, 0.0}; + for (int i = 0; i < 3; i++) + { pq[i] = myAtoms[0].x[i] - myAtoms[1].x[i]; + rq[i] = myAtoms[2].x[i] - myAtoms[1].x[i]; + rs[i] = myAtoms[2].x[i] - myAtoms[3].x[i]; + } + normal = crossProduct(pq,rq); + normal2 = crossProduct(rq,rs); + dotProduct = dotProduct(normal,normal); // length^2 of normal + dp2 = dotProduct(normal2,normal2); // length^2 of normal2 + for (int i = 0; i < 3; i++) + { normal[i] = normal[i]/Math.sqrt(dotProduct); + normal2[i]=normal2[i]/Math.sqrt(dp2); + } + dihedral = dotProduct(normal,normal2); // cos(theta) + dihedral = Math.acos(dihedral); + double direction = dotProduct(rq, + crossProduct(crossProduct(pq,rq),crossProduct(rq,rs))); + if (direction < 0) dihedral = -dihedral; + return dihedral; + } +} diff --git a/src/main/java/nanocad/minimize/uff/uffMinimizeAlgorythm.java b/src/main/java/nanocad/minimize/uff/uffMinimizeAlgorythm.java new file mode 100644 index 0000000..313fdfd --- /dev/null +++ b/src/main/java/nanocad/minimize/uff/uffMinimizeAlgorythm.java @@ -0,0 +1,95 @@ + package nanocad.minimize.uff; +/** + * Copyright (c) 1997 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ +import java.util.Vector; + +import nanocad.energyMinimizeAlgorythm; +import nanocad.group; +import nanocad.newNanocad; +import nanocad.term; + + public class uffMinimizeAlgorythm extends energyMinimizeAlgorythm +{ +/* + public void initTemps(Vector myAtomList){ + // This is a temporary vector that represents a clone of the + // original group. Save initializations later by doing them + // here one time, then just changing the position in f1dim(). + templist = (Vector) myAtomList.clone(); + temptermList = new Vector(); + term t = enumToTerm(templist, temptermList); + tempsInited = true; + } +*/ + + /** + * Insert the method's description here. + * Creation date: (7/25/2000 3:07:45 PM) + * @param newGroup group + */ + + public uffMinimizeAlgorythm(group newGroup, newNanocad windowForUpdates) + { + funEvals = 0; +// tempsInited = false; + this.windowForUpdates = windowForUpdates; + groupToMinimize = newGroup; + atomList = groupToMinimize.atomList; + enumerateTerms(); + } + + /** + * Insert the method's description here. + * Creation date: (7/25/2000 3:04:23 PM) + */ + protected void enumerateTerms() + { + termList = new Vector(); + term t = enumToTerm(atomList, termList); + groupToMinimize.termsEnumerated(); + } + + // Created 12/11/02 by Jeff Stenhouse because enumerateTerms() and + // initTemps were almost the same method. Returns term t, + // which I'm not convinced is necessary but now it acts exactly + // as if it wasn't changed anyway. + protected term enumToTerm(Vector argAtomList, Vector argTermList) + { + term t = new lterm(); + t.enumerate(argAtomList, argTermList); + t = new aterm(); + t.enumerate(argAtomList, argTermList); + t = new tterm(); + t.enumerate(argAtomList, argTermList); + t = new vdwterm(); + t.enumerate(argAtomList, argTermList); + t = new opbterm(); + t.enumerate(argAtomList, argTermList); +// t = new estaticterm(); +// t.enumerate(argAtomList, argTermList); + + return t; + } + +} diff --git a/src/main/java/nanocad/minimize/uff/vdwterm.java b/src/main/java/nanocad/minimize/uff/vdwterm.java new file mode 100644 index 0000000..479c2db --- /dev/null +++ b/src/main/java/nanocad/minimize/uff/vdwterm.java @@ -0,0 +1,161 @@ +package nanocad.minimize.uff; + +/** + * lterm.java - MM2-style length energy term + * Copyright (c) 1997,1998 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * or its derived works must display the following acknowledgement: + * This product includes software developed by Will Ware. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.lang.Math; +import java.util.Vector; + +import nanocad.*; + +public class vdwterm extends term +{ + private double xij; + private double Dij; + +/** + * Insert the method's description here. + * Creation date: (6/19/00 4:09:33 PM) + */ + public vdwterm() {} + public vdwterm(atom a1, atom a2) { + myGroup = a1.getGroup(); + myAtoms = new atom[2]; + myAtoms[0] = a1; + myAtoms[1] = a2; + setCalculationValues(); + } + + protected void buildTerm (Vector v, Vector termList) + { System.out.println("buildTerm for vdw term should never be called."); } + + public double computeForces() { + int i; + // compute forces on each atom, add it to the atom's force vector + double[] diff = new double[3]; + double r, m; + for (i = 0, r = 0.0; i < 3; i++) { + diff[i] = myAtoms[0].x[i] - myAtoms[1].x[i]; + r += diff[i] * diff[i]; + } + + if(r <= 0) r = uffMinimizeAlgorythm.TINY; + r = Math.sqrt(r); + + potential = computePotential(r); + m = computePotentialDerivative(r)/r; // at this point, m is (1/r)*(du/dr) + // m > 0 attract, m < 0 repel + for (i = 0; i < 3; i++) { + myAtoms[0].f[i] -= m * diff[i]; + myAtoms[1].f[i] += m * diff[i]; + } + return m * Math.sqrt(dotProduct(diff,diff)); + //return m*r; + } + + protected double computePotentialDerivative(double x) + { //p is the acutal distance between atoms + return Dij*(12*Math.pow(xij,6)*Math.pow(x,-7) - 12*Math.pow(xij,12)*Math.pow(x,-13)); } + + public double computePotential(double x) + { return (Dij*(-2*Math.pow(xij/x, 6) + Math.pow(xij / x, 12))); } + + public void enumerate(Vector atomList, Vector termList) + { + for(int i = 0; i < atomList.size(); i++) + { + atom currentAtom = (atom) atomList.elementAt(i); + for(int j = i + 1; j < atomList.size(); j++) + { + atom otherAtom = (atom) atomList.elementAt(j); + if(currentAtom.bondWith(otherAtom) == null) + { + boolean oneAtomSeperates = false; + for(int k = 0; (k < otherAtom.bonds.size()) && !oneAtomSeperates; k++) + if(((bond) otherAtom.bonds.elementAt(k)).otherAtom(otherAtom).bondWith(currentAtom) != null) + oneAtomSeperates = true; + if(!oneAtomSeperates) + { + vdwterm t = new vdwterm(currentAtom, otherAtom); + termList.addElement(t); + } + } + } + } + } + + protected String repr2() { + return " VDW " + (new Double(xij)).toString() + " " + + (new Double(Dij)).toString(); } + +/** + * Insert the method's description here. + * Creation date: (6/15/00 1:36:02 PM) + */ + protected void setCalculationValues() { + System.out.println("Creating vdwterm"); + double Di = 0, Dj = 0, xi = 0, xj = 0; // Natural non-bond energies and distances. + myGroup = myAtoms[0].getGroup(); + if(myGroup.needsToGetTypes()) myGroup.setTypes(); + int atomOneType = myAtoms[0].getUFFTypeNum(); + int atomTwoType = myAtoms[1].getUFFTypeNum(); + if (atomOneType < 0 || atomTwoType < 0) { + setDefaultCalculationValues(); + return; + } + int biggerValue = Math.max(atomOneType, atomTwoType); + int smallerValue = Math.min(atomOneType, atomTwoType); + try { + AtomDataFile dataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "uffdata.txt"); + //AtomDataFile dataFile = new AtomDataFile("uffdata.txt"); + if (dataFile.findData(smallerValue, 1)) { + xi = dataFile.parseDouble(4); + Di = dataFile.parseDouble(5); + } else { + setDefaultCalculationValues(); + return; + } + if (dataFile.findData(biggerValue, 1)) { + xj = dataFile.parseDouble(4); + Dj = dataFile.parseDouble(5); + } + Dij = Math.sqrt(Di*Dj); + xij = Math.sqrt(xi*xj); + System.out.println("Xij = "+xij); + System.out.println("Dij = "+Dij); + } catch (java.io.IOException e) { + System.err.println("VDW data lookup error"); + e.printStackTrace(); + } + } + + protected void setDefaultCalculationValues() { defaultsUsed = true; } + public int termLength() { return 2; } + public String name() { return "Van der Waals"; } +} diff --git a/src/main/java/nanocad/mol2parser.java b/src/main/java/nanocad/mol2parser.java new file mode 100644 index 0000000..4dac2f9 --- /dev/null +++ b/src/main/java/nanocad/mol2parser.java @@ -0,0 +1,565 @@ +/////////////////////////////////////////////////////// +// mol2parser.java +// June 2006 by Sudhakar Pamidighantam +// A parser for Mol2 Files. Extends Parser.java +/////////////////////////////////////////////////////// + +package nanocad; + +import java.lang.System; +import java.io.StreamTokenizer; +import java.io.*; +import java.util.*; + +public class mol2parser extends Parser{ + //static PDBEntry entry = null; // Entry being parsed + LineNumberReader input; + int lineNumber; + boolean done = false; + boolean needLine; + int lastRecordNum; + String line; + StreamTokenizer inStream; + int firstAtom = 0; + int currentAtom; +int columnNo = 0; +boolean eof = false; +boolean readingAtom = false; +boolean AtomSection = false; +boolean BondSection = false; +boolean SubStSection = false; +boolean MolSection = false; +boolean readingBond = false; +boolean newLine = true; +boolean noone = false; +boolean debug = true; +int Mollinn; int Atomlinn; int Bondlinn;int SubStlinn; +int atomVSize; int bondVSize; int substVSize; + + +public mol2parser(String filename, String data){ + + super(data); + + + //entry = null; // Entry being parsed + done = false; + needLine = true; + String inFile=filename; + try { + + input = new LineNumberReader(new FileReader(inFile)); + done = false; + + for ( ; done == false; ) { + if (needLine) + { + line = input.readLine(); + } else { + needLine = true; + } + + lineNumber = input.getLineNumber(); + //System.out.println("Getting Line number "+lineNumber+" in Structure file "); + if (line != null) {System.out.println(" Current line is \n"+line); + if (line.trim().equals("@MOLECULE")) + { MolSection = true; Mollinn = lineNumber; + System.out.println(" To Read Molecular Information at line number "+Mollinn); + } + else if (line.trim().equals("@ATOM")) + { MolSection= false; AtomSection = true; + Atomlinn=lineNumber; + System.out.println("to Read Atom Information from line number "+lineNumber); + } + else if (line.trim().equals("@BOND")) + { AtomSection=false; BondSection = true; + Bondlinn=lineNumber; + } + else if (line.trim().equals("@SUBSTRUCTURE")) + { + BondSection = false; + SubStSection = true; + SubStlinn = lineNumber; + System.out.println("to Read Substructure Information from line number "+lineNumber); + } + //} + if (MolSection) { + if (lineNumber > Mollinn){ System.out.println("calling readMolInfo ");readMolInfo(); } + } + if (AtomSection){ + if (line.equals("")){ + //Ignore this line + Atomlinn++; + //System.out.println(" Blank Encountered. Starting Atom line number is incremented"); + } + else{ + if (lineNumber > Atomlinn && lineNumber <= Atomlinn+atomVSize ) readATOM();} + } + if (BondSection){ + if (line.equals("")){ + //Ignore this line + Bondlinn++; + //System.out.println(" Blank Encountered. Starting Atom line number is incremented"); + } + else{ + if (lineNumber > Bondlinn && lineNumber <= Bondlinn+bondVSize) readBONDS();} + } + if (SubStSection){ + if (line.equals("")){ + //Ignore this line + SubStlinn++; + //System.out.println(" Blank Encountered. Starting Atom line number is incremented"); + }else{ + if (lineNumber > SubStlinn && lineNumber <= SubStlinn+substVSize){ + readSubStruct(); + //line=""; + done=true; + }} + } + + } + //return; + //lineDispatch(line); + } + } catch (Exception fnf){System.out.println("mol2parser:"+fnf);} + +} + public void readSubStruct (){ + // Read Substructure Information + StringTokenizer st = new StringTokenizer (line); + if (st.countTokens() >= 1){ + int subsid = (new Integer (st.nextToken())).intValue(); + String subs = st.nextToken(); + int rootatom = (new Integer (st.nextToken())).intValue(); + System.out.println("SubStructure:"+ subs); + } + } + + public void readMolInfo (){ + if (lineNumber == Mollinn+1) { + // Read Molecule Name + String compound = line; + System.out.println("Compound is"+compound); + } + else if (lineNumber == Mollinn+2){ + //read Atom, Bond and SubStructure record sizes + //byte[] moldata = new byte[400]; + //moldata = line.getBytes(); + StringTokenizer st = new StringTokenizer(line); + int colcounter=0; + //while (st.hasMoreTokens()) { + //int token = (new Integer (st.nextToken())).intValue(); + do { + colcounter++; + //switch (token){ + //case StringTokenizer.TT_EOL : + //eof = true; + //break; + //case StringTokenizer.TT_NUMBER : + if (st.countTokens() >= 1) + { + atomVSize = (new Integer(st.nextToken())).intValue(); + System.out.println("MolInfo: " + atomVSize); + } + //else if (colcounter == 2){ + bondVSize = (new Integer(st.nextToken())).intValue(); + System.out.println("MolInfo: " + bondVSize); + //}else if (colcounter == 3) { + substVSize = (new Integer(st.nextToken())).intValue(); + System.out.println("MolInfo: " + substVSize); + //} + System.out.println("MolInfo: " + atomVSize + bondVSize + substVSize); + }while (st.countTokens() == 1); + + //} + //System.out.println("MolInfo: " + atomVSize + bondVSize + substVSize); + + //System.exit(-1); + } + //System.out.println("MolInfo: " + atomVSize + bondVSize + substVSize); + // read other molecule records + //} + /* + + if (false) { + // Wait till you've parsed the PDB entry before creating the + // output file. + FileWriter fout = new FileWriter(outFile); + + // Write out the PDB entry to the output file + // Base64.translate(entry, fout); + // fout.write(entry.toString()); + MBParen.translate(entry, fout); + fout.close(); + } else { + FileOutputStream fout = new FileOutputStream(outFile); + // ObjectOutputStream out = new ObjectOutputStream(fout); + // out.writeObject(entry); + int numNodes = entry.nSubterms(); + Object a = entry.Subterm(1); + Object b = entry.Subterm(2); + MathBus2XML.parse2XML(entry, new FileWriter(outFile));; + fout.close(); + } + */ + + /* + System.out.println(); + System.out.println("(press Enter to exit)"); + System.out.println(""); + + System.in.read(); + + } + catch (Exception e) { + System.out.println(); + System.out.println("Exception caught: " + e.getMessage()); + e.printStackTrace(); + try { + System.out.println(); + System.out.println("(press Enter to exit)"); + System.out.println(""); + + System.in.read(); + } + catch (IOException e1) { + return; + } + return; + } + */ +} +/* +public void lineDispatch (String line) throws IOException { + + if (line.length() >=6) {System.out.println(" Line starts with "+ line.substring(0,6));} + if (line.startsWith("@MOLECULE")) readHEADER(); + else if (line.startsWith("@ATOM")) readATOM() ; + else if (line.startsWith("@BOND")) readBONDS(); + else if (line.startsWith("@SUBSTRUCTURE")) reaSubStructure(); + else if (line.startsWith("ATOM ")) {System.out.println(" Will read Atom info"); readATOM();return;} + else if (line.startsWith("HETATM")) {System.out.println(" Will read HeteroAtom info");readATOM();return;} + if (line.startsWith("CONNECT")) {System.out.println(" Will read Bond info");readBONDS();return;} + else if (line.startsWith("CONECT")) {System.out.println(" Will read Bond info");readBONDS();return;} + else if (line.startsWith("MASTER")) { eof= true; done = true;} + else if (line.startsWith("END ")) { eof= true; done = true; } + else if (line.startsWith("")){ eof= true; done = true; } + else System.out.println("Unknown record type (" + line.substring(0,6) + + ") in PDB entry at line " + + lineNumber); +} + +*/ +public void readHEADER () +throws IOException { + if (line.length() >= 66){ + String classification = line.substring(10, 50).trim(); + + + if (line.length() >= 66) { + String IDcode = line.substring(62, 66); + } + + int day = Integer.parseInt(line.substring(50,52)); + int month; + String monthString = line.substring(53,56); + int year = Integer.parseInt(line.substring(57,59)); + //MBDate date; + + if (monthString.equals("JAN")) month = 0; + else if (monthString.equals("FEB")) month = 1; + else if (monthString.equals("MAR")) month = 2; + else if (monthString.equals("APR")) month = 3; + else if (monthString.equals("MAY")) month = 4; + else if (monthString.equals("JUN")) month = 5; + else if (monthString.equals("JUL")) month = 6; + else if (monthString.equals("AUG")) month = 7; + else if (monthString.equals("SEP")) month = 8; + else if (monthString.equals("OCT")) month = 9; + else if (monthString.equals("NOV")) month = 10; + else if (monthString.equals("DEC")) month = 11; + else throw new IOException("Invalid month: " + monthString + + "(at line: " + lineNumber + ")"); + + year += (year > 70 ? 1900 : 2000); + } + else + { + System.out.println(" This is a non standard Header"); + + String classification = " "; + } + //date = new MBDate(year, month, day); + + +/* + if (entry != null) + throw new IOException("Header in the middle of a PDB entry" + + "(at line: " + lineNumber + ")"); + else + entry = new PDBEntry(IDcode, date, classification); +} +*/ +} + +public void readCOMPOUND() throws IOException { + if (line.length() >= 69) { + String compound = line.substring(10, 69).trim(); + } + else + { + String compound = line.substring(10); + } + + //entry.title.setCompoundName(compound); +} + +public void readSEQRES() throws IOException { + // lastRecordNumber = 0; + String residue; + String numResidues = line.substring(13, 17).trim(); + int chainID = Character.getNumericValue(line.charAt(11)); + // MBNode res; + + for (int ind = 19; ind < 68; ind = ind + 4) { + residue = line.substring(ind, ind+3); + if (residue.equals(" ")) break; + else { + //res = new PDBResidue(Registry.getLabelInt(residue)); + //entry.primary.addResidue(new Integer(chainID), res); + } + } +} + + +public void readATOM () throws IOException { + /* + inStream = new StreamTokenizer(in); + inStream.commentChar('#'); + inStream.eolIsSignificant(true); + inStream.slashSlashComments(false); + inStream.slashStarComments(false); + inStream.ordinaryChar('/'); + */ + String atomName=""; + double xCoord=0D; + double yCoord=0D; + double zCoord=0D; + System.out.println("readAtom: line: "+line); + //Byte[] atomdata = new Byte[400]; + //atomdata = line.getBytes(); + StringTokenizer st = new StringTokenizer(line); + int colcounter=0; + do { + //int token = (new Integer (st.nextToken())).intValue(); + colcounter++; + //switch (token){ + //case StreamTokenizer.TT_EOF : + // eof = true; + //break; + //case StreamTokenizer.TT_NUMBER : + System.out.println(" Column Counter:"+colcounter); + if (st.countTokens() >= 1) {int atomidn = (new Integer (st.nextToken())).intValue(); + System.out.println("AtomID:"+atomidn); + } + //else if (colcounter == 2) { + atomName = st.nextToken().trim(); + sym.addElement(atomName); + System.out.println(" Atom:"+atomName); + //} + //else if (colcounter == 3){ + xCoord = (new Double(st.nextToken())).doubleValue(); + atomX.addElement(new Double (xCoord)); + //}else if (colcounter == 4) { + yCoord = (new Double(st.nextToken())).doubleValue(); + atomY.addElement(new Double (yCoord)); + //}else if (colcounter == 5) { + zCoord = (new Double(st.nextToken())).doubleValue(); + atomZ.addElement(new Double (zCoord)); + //} + System.out.println(" Atom: "+atomName + ": X:"+ xCoord+" Y:"+yCoord+" Z:"+zCoord); + //} + }while (st.countTokens() == 1); + + /* + String atomName = line.substring(12,16).trim(); + sym.addElement(atomName); + System.out.println(" Atom:"+atomName); + int chainID = Character.getNumericValue(line.charAt(21)); + System.out.println("Chain Id:"+chainID); + String reNum = line.substring(22,26); + System.out.println("reNum:"+reNum+"#"); + int resSeq; + if (reNum.equals(" ")){resSeq = 0;} + else{ resSeq = Integer.parseInt(reNum.trim());} + System.out.println("Res Sequence ID:"+resSeq); + + Double xCoord = new Double(line.substring(30,38)); + Double yCoord = new Double(line.substring(38,46)); + Double zCoord = new Double(line.substring(46,54)); + + atomX.addElement(xCoord); + atomY.addElement(yCoord); + atomZ.addElement(zCoord); + System.out.println(" Atom "+atomName + " X:"+ xCoord+" Y:"+yCoord+" Z:"+zCoord); + */ + // Remember that sequences in the PDB are 1 based! + //entry.primary.addAtom(new Integer(chainID), resSeq - 1, atom); + //return; +} + +public void readBONDS(){ + + System.out.println("readBONDS: line: "+line); + //Byte[] bonddata = new Byte[400]; + //bonddata = line.getBytes(); + StringTokenizer st = new StringTokenizer(line); + int colcounter=0; + do { + //int token = (new Integer(st.nextToken())).intValue(); + colcounter++; + //switch (token){ + // case StreamTokenizer.TT_EOF : + // eof = true; + // break; + //case StreamTokenizer.TT_NUMBER : + if (st.countTokens() >= 1) {int bondidn = (new Integer(st.nextToken())).intValue() ; + System.out.println(" Bond ID:"+bondidn); + } + //else if (colcounter==2) { + double firstAtom = (new Double(st.nextToken())).doubleValue(); + bAtom1.addElement(new Double (firstAtom)); + //}else if (colcounter==3){ + double secondAtom = (new Double(st.nextToken())).doubleValue(); + bAtom2.addElement(new Double (secondAtom)); + //}else if (colcounter==4) { + double b_order = (new Double(st.nextToken())).doubleValue(); + bOrder.addElement(new Double (b_order)); + System.out.println("Bond: Atom1 "+firstAtom+" Atom2:"+secondAtom+" Order:"+b_order); + //}else if (colcounter==4) { + if (st.countTokens() >= 1){ + String b_status = st.nextToken(); + } + //} + //} + + }while (st.countTokens() == 1 ); + + /* + inStream = new StreamTokenizer(in); + inStream.commentChar('#'); + inStream.eolIsSignificant(true); + inStream.slashSlashComments(false); + inStream.slashStarComments(false); + inStream.ordinaryChar('/'); + + if (line.length() >=16 ) { + if ( line.substring(6,11).equals("") ) { + System.out.println("No Atoms given for Connectivity"); + } + else{ + firstAtom = Integer.valueOf(line.substring(6,11).trim()).intValue(); + System.out.println("First Atom "+firstAtom); + } + if (line.substring(11,16).equals("") ) { + System.out.println("No Atoms given for Connectivity"); + } + else{ + currentAtom = Integer.valueOf(line.substring(11,16).trim()).intValue(); + System.out.println("Second Atom "+currentAtom); + updatebondorder(); + } + } + if ( line.length()>=21) { + if (line.substring(16,21).equals("") ) { + System.out.println("No Atoms given for Connectivity"); + } + else{ + currentAtom = Integer.valueOf(line.substring(16,21).trim()).intValue(); + System.out.println("Third Atom "+currentAtom); + updatebondorder(); + } + } + if (line.length()>=26) { + if (line.substring(21,26).equals("") ){ + System.out.println("No Atoms given for Connectivity"); + } + else{ + currentAtom = Integer.valueOf(line.substring(21,26).trim()).intValue(); + System.out.println("Fourth Atom "+currentAtom); + updatebondorder(); + } + } + if (line.length() >= 31) { + if (line.substring(26,31).equals("") ) { + System.out.println("No Atoms given for Connectivity"); + } + else{ + currentAtom = Integer.valueOf(line.substring(26,31).trim()).intValue(); + System.out.println("Fifth Atom "+currentAtom); + updatebondorder(); + + } + } + */ + //updatebondorder(); +} + public void updatebondorder(){ + //firstAtom = (int)line.substring(6,11); + System.out.println("Bond:" + firstAtom+ " Totals BondedAtoms(1) "+bAtom1.size()); + boolean bondExists = false; + + for (int i = 0; i < bAtom1.size(); i++) + { + if ( ((Double)bAtom1.elementAt(i)).intValue() == new Double(firstAtom).intValue() && + ((Double)bAtom2.elementAt(i)).doubleValue() == new Double(currentAtom).intValue() ) + { + int order = ((Double)bOrder.elementAt(i)).intValue(); + order++; + bOrder.setElementAt(new Double(order), i); + bondExists = true; + System.out.println("upped " + firstAtom + " " + currentAtom + " order " + order); + } + } + System.out.println("readBonds: Bonds"+bondExists+" firstAtom "+firstAtom+" CurrentAtom "+currentAtom); + if (bondExists == false && firstAtom < currentAtom) + { + bAtom1.addElement( new Double(firstAtom)); + bAtom2.addElement( new Double(currentAtom)); + bOrder.addElement( new Double(1) ); + System.out.println("added " + firstAtom + " " + currentAtom + " order 1"); + } + + } + +public void process() throws IOException +{ + + +//sym.removeElementAt(sym.size()-1); + +if(debug == true) + { + System.out.println(sym.size() + " " + atomX.size() + " " + atomY.size() + " " + atomZ.size()); + for (int i=0; i< sym.size(); i++) { + System.out.println("i is :"+i+"\n"); + System.out.println("Sym contains : "+ sym.elementAt(i)); + System.out.println(atomX.size() + " " + atomY.size() + " " + atomZ.size()); + System.out.println("atomX : "+ atomX.elementAt(i)); + System.out.println("atomY : "+ atomY.elementAt(i)); + System.out.println("atomZ : "+ atomZ.elementAt(i)); + System.out.println("\n"); + } + System.out.println(bAtom1.size() + " " + bAtom2.size() + " " + bOrder.size()); + + for (int i=0; i { + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType + .EXPORT_NWCHEM_EXP, nwchemOut)); + }); + break; + } + } + case 9: // Create a Molpro Input Template close and go back to edit mode //lixh_3_4 + if (clearFlag) + break; +// FIXME-SEAGrid +// if(optsComponent.selectedFrontPanel==1){ +// //confirmation to save pdb file or not +// int result = JOptionPane.showConfirmDialog( +// this, +// "Exporting to Molpro is not possible from here. Go to Nanocad through Submit Jobs to use this option.\n" + +// " Do you want to save current Nanocad workspace as a PDB file and close Nanocad?", +// "Confirmation Message", +// JOptionPane.YES_NO_OPTION +// ); +// //if yes (save as pdb file and exit nanocad) +// if (result == 0){ +// if (!runAsApplication) +// { +// tosave = new savewin("Save file", "", false, this); +// tosave.setVisible(true); +// String tosavefile = null; +// String fileName = new String(); +// } +// else +// { +// JFileChooser chooser = new JFileChooser(); +// chooser.setDialogTitle("Save as pdb file"); +// int retVal = chooser.showSaveDialog(null); +// if (retVal == JFileChooser.APPROVE_OPTION) +// { +// String filename = chooser.getSelectedFile().getAbsolutePath(); +// if (filename != null) +// { +// if (filename.indexOf(".pdb") == -1) filename = filename + ".pdb"; +// getSetStructure.select(0); +// chooser.setSelectedFile(new File(filename)); +// saveFile(filename); +// } +// +// } +// +// } +// if ( t != null){ +// t.setVisible(false); +// } +// this.setVisible(false); +// optsComponent.selectedFrontPanel=0; +// break; +// }else{ +// getSetStructure.select(0); +// optsComponent.selectedFrontPanel=1; +// break; +// } +// +// } + else { + if (clearFlag == true) break; + else { + // runAsApplication + System.out.println(" Case 9 PSI4 Input Template being Generated"); + // + // call editjobpaneltextwindow and add text to display + // RHB: change the text on the editJobPanel!!! + // This should not take too terribly long to do now that + // I have figured out where it goes + JOptionPane.showMessageDialog(null, "WARNING: Molecule information" + + " has been exported into template input.dat. Make sure\n" + + "to edit this file from the Experiment Panel.", + "SEAGrid: PSI4 input Template", + JOptionPane.WARNING_MESSAGE); + String PSI4Out = PSI4Output(grp.getXYZ()); + // write to a file now + boolean append = false; + try { + File f = new File(applicationDataDir + fileSeparator + + "tmp.txt"); + FileWriter fw = new FileWriter(f, append); + fw.write(PSI4Out); + System.err.println("PSI4Out = "); + System.err.println(PSI4Out); + fw.close(); + + exportedApplication = Settings.APP_NAME_PSI4; + + } catch (IOException ioe) { + System.err.println("newNanocad:output PSI4:" + + "IOException"); + System.err.println(ioe.toString()); + ioe.printStackTrace(); + } + + // close molecular editor +// close the structure panel + if (t != null) { + t.setVisible(false); + } + //this.setVisible(false); + Platform.runLater(() -> { + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType + .EXPORT_PSI4_EXP, PSI4Out)); + }); + break; + } + } + /* + else { + if (clearFlag == true) break; + else { + // runAsApplication + System.out.println(" Case 9 Molpro Input Template being Generated"); + // + // call editjobpaneltextwindow and add text to display + // RHB: change the text on the editJobPanel!!! + // This should not take too terribly long to do now that + // I have figured out where it goes + String molproOut = MolproOutput(grp.getXYZ()); + // write to a file now + boolean append = false; + try { + File f = new File(applicationDataDir + fileSeparator + + "tmp.txt"); + FileWriter fw = new FileWriter(f, append); + fw.write(molproOut); + System.err.println("molproOut = "); + System.err.println(molproOut); + fw.close(); + + exportedApplication = Settings.APP_NAME_MOLPRO; + + } catch (IOException ioe) { + System.err.println("newNanocad:output Molpro:" + + "IOException"); + System.err.println(ioe.toString()); + ioe.printStackTrace(); + } + + // close molecular editor +// close the structure panel + if (t != null) { + t.setVisible(false); + } + this.setVisible(false); + break; + } + } */ + + case 10: // Create a Molpro Input Template close and go back to edit mode //lixh_3_4 + if (clearFlag) + break; + else { + + if (clearFlag == true) break; + else { + // runAsApplication + System.out.println( " Case 10 Molcas Input Template being Generated" ); + JOptionPane.showMessageDialog(null, "WARNING: Molecule information" + + " has been exported into template molcas.input. Make sure\n" + + "to edit this file from the Experiment Panel.", + "SEAGrid: Molcas input Template", + JOptionPane.WARNING_MESSAGE); + String MolcasOut = MolcasOutput( grp.getXYZ() ); + // write to a file now + boolean append = false; + try { + File f = new File( applicationDataDir + fileSeparator + + "tmp.txt" ); + FileWriter fw = new FileWriter( f, append ); + fw.write( MolcasOut ); + System.err.println( "MolcasOut = " ); + System.err.println( MolcasOut ); + fw.close(); + + exportedApplication = Settings.APP_NAME_MOLCAS; + + } catch (IOException ioe) { + System.err.println( "newNanocad:output MOLCAS:" + + "IOException" ); + System.err.println( ioe.toString() ); + ioe.printStackTrace(); + } + + // close molecular editor + // close the structure panel + if (t != null) { + t.setVisible( false ); + } + //this.setVisible(false); + Platform.runLater( () -> { + SEAGridEventBus.getInstance().post( new SEAGridEvent( SEAGridEvent.SEAGridEventType + .EXPORT_MOLCAS_EXP, MolcasOut ) ); + } ); + break; + } + + } + // lixh_4/27/05 + case 1: //open saved PDB/MOL2 + if (clearFlag) + break; + else { + JFileChooser chooser = new JFileChooser(); + chooser.addChoosableFileFilter(new PDBorMOL2FileFilter()); + chooser.setDialogTitle("Open pdb/mol2 file"); + int retVal = chooser.showOpenDialog(null); + if (retVal == JFileChooser.APPROVE_OPTION) { + String filename = chooser.getSelectedFile().getAbsolutePath(); + if (filename.endsWith("pdb") || filename.endsWith("mol2")) { + loadFile(filename, ""); + } + } + break; + /* + //runAsApplication + FileDialog f = new FileDialog((JFrame)this.getParent(),"Open PDB/MOL2 File", FileDialog.LOAD); + + f.setFile("*.pdb;*.mol2"); + f.setVisible(true); + + String filename = f.getFile(); + String dirname = f.getDirectory(); + if (filename.endsWith("pdb") || filename.endsWith("mol2") ) + { + loadFile(filename,dirname); + } + break; + */ + } + // + + case 2: //Saving files; + if (clearFlag) + break; + else if (!runAsApplication) { + tosave = new savewin("Save file", "", false, this); + tosave.setVisible(true); + String tosavefile = null; + String fileName = new String(); + } else { + JFileChooser chooser = new JFileChooser(); + chooser.setDialogTitle("Save as pdb file"); + int retVal = chooser.showSaveDialog(null); + if (retVal == JFileChooser.APPROVE_OPTION) { + String filename = chooser.getSelectedFile().getAbsolutePath(); + if (filename != null) { + if (filename.indexOf(".pdb") == -1) filename = filename + ".pdb"; + getSetStructure.select(0); + chooser.setSelectedFile(new File(filename)); + saveFile(filename); + } + + } + + /* + FileDialog f = new FileDialog((Frame)this.getParent(), "Save PDB File", FileDialog.SAVE); + f.setVisible(true); + String filename = f.getFile(); + String dirname = f.getDirectory(); + if (filename != null) + { + if (filename.indexOf(".pdb") == -1) + filename = filename + ".pdb"; + getSetStructure.select(0); + saveFile(dirname+filename); + } + */ + } + getSetStructure.select(0); + break; + + case 3: //View with chime + if (clearFlag) break; + + else if (!runAsApplication) { + String urlis = null; + try { + urlis = "http://chemviz.ncsa.uiuc.edu/cgi-bin/chimepdb.cgi"; + + sendFile(urlis, grp.getPDB(true), "chimepdb.cgi"); + String output_url = "http://pine.ncsa.uiuc.edu/csd/temp/" + getParameter("username") + "/chime.pdb"; + + callWaltz(e, output_url); + } catch (Exception e1) { + System.err.println(e1); + } + } else { + String URL = applicationDataDir + sepStr + "chimeout.pdb"; + saveFile(URL); + + try { + + //Runtime.getRuntime().exec(new String[] {"C:\\Program Files\\Internet Explorer\\IEXPLORE", URL}); + + openURL(URL); + } + //catch (java.io.IOException excep) + // { System.err.println( excep.toString() ); } + catch (SecurityException exceps) { + System.err.println(exceps.toString()); + } + } + break; + + } + return true; + } else if (e.target instanceof TextField) { + repaint(); + return true; + } else if (e.target == help) { + + if (!runAsApplication) { + try { + URL helpURL = new URL("http://pine.ncsa.uiuc.edu/nanocad/NanocadHelp.html"); + getAppletContext().showDocument(helpURL, "_blank"); + } catch (Exception roar) { + System.err.println(roar); + } + + return true; + } else { + //lixh_4/30/05 + /* + try + { + String osName = System.getProperty("os.name" ); + if (osName.equals("Windows NT")||osName.equals("Windows 2000")||osName.equals("Windows XP")) + Runtime.getRuntime().exec(new String[] {"cmd /w /q start", + pathvar+sepStr+"NanocadHelp.html"}); + else Runtime.getRuntime().exec(new String[] {"start", pathvar+sepStr+"NanocadHelp.html"}); + + } + catch (java.io.IOException excep) + { System.out.println( excep.toString() ); } + catch (java.lang.SecurityException exceps) + { System.out.println( exceps.toString() ); } + */ + + try { + String osName = System.getProperty("os.name"); + if (osName.equals("Windows NT") || osName.equals("Windows 2000") || osName.equals("Windows XP")) + Runtime.getRuntime().exec(new String[]{"\"C:\\Program Files\\Internet Explorer\\iexplore.exe\"", + "http://chemviz.ncsa.uiuc.edu/content/doc-nanocad.html"}); + else Runtime.getRuntime().exec(new String[]{"start", pathvar + sepStr + "NanocadHelp.html"}); + + } catch (IOException excep) { + System.out.println(excep.toString()); + } catch (SecurityException exceps) { + System.out.println(exceps.toString()); + } + /* + JDialog helpDialog = new JDialog(); + JEditorPane editorPane = new JEditorPane(); + editorPane.setEditable(false); + try + { + URL url = new URL("http://chemviz.ncsa.uiuc.edu/content/doc-nanocad.html"); + editorPane.setPage(url); + helpDialog.add(editorPane); + helpDialog.setSize(800,800); + helpDialog.setVisible(true); + } + catch (Exception roar) + { System.err.println(roar); } + */ + } + } else if (e.target == about) { + aboutWin = new textwin("About Nanocad", "", false); + aboutWin.setVisible(true); + aboutWin.setText(instructions); + return true; + } + return false; + } + + /** + * redirect to waltz + */ + public void callWaltz(Event event, String redirUrl) { + URL newUrl = null; + try { + newUrl = new URL(redirUrl); + getAppletContext().showDocument(newUrl); + } catch (Exception e) { + System.err.println(e); + } + } + + public void getFilesInDirectory(java.awt.List filelist, String directory) { + if (runAsApplication && (directory.charAt(directory.length() - 1) != sepChar)) + directory = directory + sepStr; + else if (directory.charAt(directory.length() - 1) != '/') + directory = directory + "/"; + String encodedDirName = URLEncoder.encode(directory); + + try { + URL url = new URL("http://chemviz.ncsa.uiuc.edu/cgi-bin/openpdbfromdir.cgi"); + + URLConnection conn = url.openConnection(); + conn.setDoOutput(true); + PrintWriter out = new PrintWriter(conn.getOutputStream()); + out.println(directory); + out.close(); + + BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line = null; + while ((line = in.readLine()) != null) { + //System.out.println("stretch Line is "+line); + filelist.add(line); + } + in.close(); + } catch (IOException e1) { + } + } + + /** + * reload new structure + * Notice: if "Clear" is pressed, then it will be a completely new + * structure, otherwise, it will be a combined one for functional group use + */ + public class VMDClass { + Timer timer; + + public VMDClass(int milliseconds) { + timer = new Timer(); + timer.schedule(new RemindTask(), milliseconds * 1); + } + + class RemindTask extends TimerTask { + public void run() { + viewVMDJob(); + System.out.println("Time's up!"); + timer.cancel(); //Terminate the timer thread + } + } + + + } + + public void viewVMDJob() { + String VMD = ""; + String VMD_mac_linux = ""; + VMDPathFileLoc = Settings.getApplicationDataDir() + File.separator + "nanocad" + File.separator + "VMDPathFile.inp"; + System.out.println("VMDpathfile: " + VMDPathFileLoc); + File VMDF = new File(VMDPathFileLoc); + try { + + if (!VMDF.exists()) { + int result = JOptionPane.showConfirmDialog( + null, + "It seems Nanocad editor does not know location of VMD binary file on your machine.\n" + + "Pressing 'OK' button will open a File Browser. Take browser to VMD directory.\n" + + "Select VMD executable (binary file) and then press open button.\n" + + "If you dont have VMD program, download and install it first.\n" + + "You can get it from 'http://www.ks.uiuc.edu/Research/vmd/'", + "VMD Path Locator", + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE); + if (result == 0) { + saveVMDPath(); + System.out.println("pressed OK"); + } + if (VMDF.exists()) { + FileReader VMDfile = new FileReader(VMDF); + + BufferedReader br = new BufferedReader(VMDfile); + VMD = br.readLine(); + VMD_mac_linux = VMD; + } + } else { + FileReader VMDfile = new FileReader(VMDF); + + BufferedReader br = new BufferedReader(VMDfile); + VMD = br.readLine(); + VMD_mac_linux = VMD; + } + } catch (IOException ie) { + System.err.println("error in reading molden location file"); + } + /* + String time = new SimpleDateFormat("yyMMdd").format(job.getCreated()); + + legacy.editors.commons.Settings.jobDir = legacy.editors.commons.Settings.defaultDirStr + File.separator + + job.getResearchProjectName() + File.separator + + job.getName() + "." + job.getSubmitMachine() + "." + + job.getLocalJobID() + "." + time; + jobName = job.getName(); + dataFileName = legacy.editors.commons.Settings.jobDir + File.separator + job.getName()+".out"; + String dataFileString = '"'+dataFileName+'"'; + File dataFile = new File(dataFileName); + */ + //String molden = Env.getApplicationDataDir() + File.separator + "molden"+File.separator+"molden.exe"; + //String molden_mac_linux = Env.getApplicationDataDir() + File.separator + "molden"+File.separator+"molden"; + + String VMDString = '"' + VMD + '"'; + File VMDfile = new File(VMD); + //if(dataFile.exists()){ + if (VMDfile.exists()) { + String osName = System.getProperty("os.name"); + try { + + if (osName.startsWith("Windows")) { + + //String windowsCommandStr = "cmd.exe /c "+VMDString + " " + dataFileString; + String windowsCommandStr = "cmd.exe /c " + VMDString + " vmd.pdb"; + //System.out.println("datafilestring: "+dataFileString); + //Runtime.getRuntime().exec("cmd.exe /c copy "+dataFileString+" vmd.out"); + + //Runtime.getRuntime().exec("cmd.exe /c cd "+moldenFolder); + System.out.println("Windows command str: " + windowsCommandStr); + InputStream in = Runtime.getRuntime().exec(windowsCommandStr).getInputStream(); + + StringBuffer sb = new StringBuffer(); + //System.out.println("Executed ipconfig on windows"); + + int c; + while ((c = in.read()) != -1) { + sb.append((char) c); + } + + String comOutput = sb.toString(); + + System.out.println("value of output form command prompt after running molden is: " + comOutput); + /* + if (comOutput.equals("")){ + JOptionPane.showMessageDialog(null, "Perhaps X-server (e.g. Exceed) on this machine is not running.\n"+ + "If this is the case, please go ahead and start it first and then try again.", + "X Server Problem!!", JOptionPane.WARNING_MESSAGE); + } + */ + //Runtime.getRuntime().exec(windowsCommandStr); + } else if (osName.startsWith("Mac")) { +// copying output file to a file with common name molden.out. This file is deleted when client is closed. + //Runtime.getRuntime().exec("cp "+dataFileName+" ./molden.out"); + //exporting display for bash shell, for running xterm + Runtime.getRuntime().exec("export DISPLAY=:0.0"); + + //launching molden output file using molden binary executable + //System.out.println("/usr/X11R6/bin/xterm -e "+ VMD_mac_linux+" "+dataFileName); + InputStream in = Runtime.getRuntime().exec("/usr/X11R6/bin/xterm -e " + VMD_mac_linux + " vmd.pdb").getInputStream(); + + //following peice of code prompts user to run x-server before launching molden + StringBuffer sb = new StringBuffer(); + //System.out.println("Executed ipconfig on windows"); + + int c; + while ((c = in.read()) != -1) { + sb.append((char) c); + } + + String comOutput = sb.toString(); + + System.out.println("value of output form command prompt after running molden is: " + comOutput); + /* + if (comOutput.equals("")){ + JOptionPane.showMessageDialog(null, "Perhaps X-server (e.g. Exceed) on this machine is not running.\n"+ + "If this is the case, please go ahead and start it first and then try again.", + "X Server Problem!!", JOptionPane.WARNING_MESSAGE); + } + */ + + } else { + //Runtime.getRuntime().exec("cp "+dataFileName+" ./molden.out"); + //System.out.println("cp "+dataFileName+" "+dataFileName); + Runtime.getRuntime().exec("xterm -e " + VMD_mac_linux + " vmd.pdb"); + System.out.println("xterm -e " + VMD_mac_linux + " vmd.pdb"); + } + + } catch (Exception e) { + System.out.println("problem in running VMD"); + } + } else { + JOptionPane.showMessageDialog(null, "Client cannot find VMD binary file on this machine\n" + + "It seems recently you have deleted or changed location of molden binary file.\n" + + "Please first varify it and then come back.", + "Problem reading file", JOptionPane.WARNING_MESSAGE); + VMDF.delete(); + //System.out.println("Program Molden does not exist on this machine"); + } + /* + }else{ + try{ + System.out.println("Ouput File does not exist on local machine hence downloading it..."); + int result = JOptionPane.showConfirmDialog( + null, + "Ouput File does not exist on local machine.\n" + + "Kindly press 'OK' to download from server first. Downloading file takes a while. \n"+ + "Remember if you press 'Cancel' button, this option wont do anything.\n", + "File Download Confirm", + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE); + if (result==0){ + doMolden=1; + GETOUTPUTCommand getOutputCommand = new GETOUTPUTCommand(gms,this); + getOutputCommand.getArguments().put("job", job); + statusChanged(new StatusEvent(getOutputCommand,Status.START)); + System.out.println("Downloaded output file. Launching VMD"); + } + }catch (Exception ig){ + System.err.println("error in thread sleep"); + } + } + */ + } + + public void saveVMDPath() { + JFileChooser chooser = new JFileChooser(); + + int result = chooser.showOpenDialog(this); + String inp = new String(); + if (result == JFileChooser.CANCEL_OPTION) return; + try { + File file = chooser.getSelectedFile(); + VMDPath = file.getAbsolutePath(); + System.out.println("this is path of VMD file: " + VMDPath); + + FileWriter VMDfile = new FileWriter(VMDPathFileLoc); + VMDfile.write(VMDPath); + VMDfile.close(); + + } catch (Exception e) { + JOptionPane.showMessageDialog(null, "Reading error", + "Problem reading file", JOptionPane.INFORMATION_MESSAGE); + } + + } + + public void saveFile(String filename) { + File toSave = new File(filename); + try { + PrintWriter out1 = new PrintWriter((OutputStream) new FileOutputStream(toSave)); + out1.println(grp.getPDB(true)); + out1.close(); + + } catch (IOException f) { + System.out.println("You can't see me"); + } + } + + public void loadFile(String filename, String directory) { + if (!runAsApplication) { + if ((!directory.equals("")) && (directory.charAt(directory.length() - 1) != '/')) + directory = directory + "/"; + } else { + if ((!directory.equals("")) && (directory.charAt(directory.length() - 1) != sepChar)) + directory = directory + sepStr; + } + int pos = filename.indexOf("pdb"); + String tryfile, data; + + if ((pos = filename.indexOf("pdb")) != -1) { + //System.out.println("pdb"); + //System.out.println(directory+filename); + String ext = filename.substring(pos, filename.length()); + data = receiveFile(filename, ext, directory); + //drawFile(data,ext); + drawFile(directory + filename, data, ext); + } else if ((pos = filename.indexOf("mol2")) != -1) { + //System.out.println("mol2"); + //System.out.println(directory+filename); + String ext = filename.substring(pos, filename.length()); + data = receiveFile(filename, ext, directory); + drawFile(directory + filename, data, ext); + } else { + pos = (filename.length() + 1); + tryfile = new String(filename + ".pdb"); + //System.out.println("try1:" + tryfile); + data = receiveFile(tryfile, "pdb", directory); + //System.out.println(data); + if (!((String) data.substring(0, 4)).equals("

") && !data.equals("error")) + //drawFile(data,"pdb"); + drawFile(directory + tryfile, data, "pdb"); + else { + tryfile = new String(filename + ".mol2"); + //System.out.println("try2:" + tryfile); + data = receiveFile(tryfile, "mol2", directory); + drawFile(directory + tryfile, data, "mol2"); + } + } + clearFlag = false; + return; + } + + // Wrapper so Jason's code likes Andrew's (stenhous 11/14/02) + public void drawFile(String filedata) { + drawFile(filedata, "pdb"); + } + + public void drawFile(String Filedata, String ext) { + if (ext.equals("mol2")) + par = new Parser(Filedata); // why the need to parse? + //par = new mol2parser(filename,Filedata); + else + //par = new PDBParser(filedata); + par = new PDBParser(Filedata); + + try { + par.process(); + } catch (IOException ioe) { + System.err.println(ioe); + } + drawstructure(); + + } + + public void drawFile(String fileName, String filedata, String ext) { + if (ext.equals("mol2")) { + par = new mol2parser(fileName, filedata); // why the need to parse? + } else { + //par = new PDBParser(filedata); + par = new PDBParsernew(fileName, filedata); + } + try { + par.process(); + } catch (IOException ioe) { + System.err.println(ioe); + } + + drawstructure(); + + } + + public void drawstructure() { + atomV = addAtoms(par.sym, par.atomX, par.atomY, par.atomZ); + bondV = addBonds(par.bAtom1, par.bAtom2, par.bOrder); + + if (!clearFlag) { + for (int i = 0; i < grp.atomList.size(); i++) { + atom oldatom = (atom) grp.atomList.elementAt(i); + atomV.addElement(oldatom); // update atom vector by taking atoms from atomList...diff b/w atomList and vector? + } + + for (int i = 0; i < grp.bondList.size(); i++) { + bond oldbond = (bond) grp.bondList.elementAt(i); + bondV.addElement(oldbond); + } + } + + grp = new MolTemplate(atomV, bondV, drawingArea); //just for drawing/display + drawingArea.setGroupToPaint(grp); + grp.centerAtoms(); + newFF = true; + + for (int j = 0; j < grp.atomList.size(); j++) + //System.out.println( ((atom)grp.atomList.elementAt(j)).getTypeNum(true) ); + + repaint(); + if (callDatabase == 2) { + atomInfo("Structure may have many sub-structures from unit cell"); + } else { + // This sets the empty space (width) for the bottom panel. + atomInfo(spaces + spaces + spaces + spaces + spaces + spaces + spaces + " "); + clearFlag = false; + } + } + + + public group getGroup() { + return grp; + } + + /** + * overload atom information + */ + public void atomInfo() { + atomInfoBlab.setBackground(this.getBackground()); + blabs.setBackground(this.getBackground()); + atomInfoBlab.setText(""); + } + + public void atomInfo(String s) { + atomInfoBlab.setBackground(this.getBackground()); + blabs.setBackground(this.getBackground()); + atomInfoBlab.setText(s); + instrucaba.setWarning(false); + } + + public void atomInfo(atom a) // see whr atomInfo used + { + if (a == null) return; + blabs.setBackground(this.getBackground()); + atomInfo(a.toString()); + } + + public void atomInfoWarning(String s) { + atomInfoWarning(s, Color.orange); + } + + public void atomInfoWarning(String s, Color theColor) { + blabs.setBackground(theColor); + atomInfoBlab.setBackground(theColor); + atomInfoBlab.setText(atomInfoBlab.getText() + " Warning: " + s); + instrucaba.setWarning(true); + } + + /** + * two GridBagConstrains + */ + private void constrain(Container container, Component component, + int gridX, int gridY, int gridW, int gridH) { + constrain(container, component, gridX, gridY, gridW, gridH, + GridBagConstraints.NONE, GridBagConstraints.NORTHWEST, + 0.0, 0.0, 0, 0, 0, 0); + } + + private void constrain(Container container, Component component, + int gridX, int gridY, int gridW, int gridH, + int fill, int anchor, double weightX, + double weightY, int top, int left, int bottom, + int right) { + GridBagConstraints c = new GridBagConstraints(); + c.gridx = gridX; + c.gridy = gridY; + c.gridwidth = gridW; + c.gridheight = gridH; + c.fill = fill; + c.anchor = anchor; + c.weightx = weightX; + c.weighty = weightY; + if (top + bottom + left + right > 0) + c.insets = new Insets(top, left, bottom, right); + ((GridBagLayout) container.getLayout()).setConstraints(component, c); + } + + /** + * paint the periodic table + */ + public void drawPTable(Graphics g) { + int boxWidth = (ptableHSize - 17) / 18; + int boxHeight = (ptableVSize - 9) / 10; + int fontHeight = boxHeight - 2; + Font font = new Font("Helvetica", Font.BOLD, boxHeight - 2); + g.setFont(font); + while (g.getFontMetrics().stringWidth("HHH") > boxWidth - 2) { + fontHeight--; + font = new Font("Helvetica", Font.BOLD, fontHeight); + g.setFont(font); + } + FontMetrics fm = g.getFontMetrics(); + if ((boxWidth > 2) && (boxHeight > 2)) { + try { + +// NOTE! I'm cheating. Leave it to me to abuse classes :) stenhous 1/16/03 +// eData.txt is not an AtomDataFile, but it's just easier to call it one +// because AtomDataFile supports everything needed and takes care of permissions. + AtomDataFile eDataFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "eData.txt"); + //AtomDataFile eDataFile = new AtomDataFile("eData.txt"); + for (int j = 0; j < 10; j++) { + for (int i = 0; i < 18; i++) { + String symbol = eDataFile.getLine(); + eDataFile.skipLines(1); + if (!symbol.equals("")) { + if ((i > 1 && i < 11 + j) || j > 7) + g.setColor(Color.cyan); + else g.setColor(Color.green); + g.fillRect(i * (boxWidth + 1) + ptableHOffset, j * (boxHeight + 1) + ptableVOffset, boxWidth, boxHeight); + g.setColor(Color.black); + int Hoffset = (boxWidth - fm.stringWidth(symbol)) / 2; + int Voffset = (boxHeight - fontHeight) / 2; + g.drawString(symbol, i * (boxWidth + 1) + Hoffset + ptableHOffset, (j + 1) * (boxHeight + 1) - (1 + Voffset) + ptableVOffset); + } + } + } + } catch (Exception e) { + System.err.println("Error reading ptable data file."); + System.err.println(e.toString()); + atomInfo(e.toString()); + e.printStackTrace(); + } + } + } + + /** + * energy minimize + */ + private void energyMinimize(boolean useCG) { + atomInfo("Initializing... (This could take a minute)"); + if (newFF) { + if (isUFF) energyMinimizer = new uffMinimizeAlgorythm(grp, this); + else energyMinimizer = new mm3MinimizeAlgorythm(grp, this); + currentPotential = energyMinimizer.potentialOnly(this); + newFF = false; + } + if (!energyMinimizer.minimizeGroup(this, useCG)) + atomInfoWarning("Data missing- form may be incorrect."); +/* This code was meant to check to see if minimizations were doing any good. + It "works" but you need to add some specific code in the if statement. + if(currentPotential - energyMinimizer.potentialOnly(this) < 0.0001) + { + ; + } + currentPotential = energyMinimizer.potentialOnly(this); +*/ + repaint(); + } + + + /** + * Insert the method's description here. + * Creation date: (7/25/2000 3:16:55 PM) + * + * @return energyMinimizeAlgorythm + */ + public energyMinimizeAlgorythm getEnergyMinimizer() { + return energyMinimizer; + } + + /** + * Gets and displays potential. + */ + private void getPotential() { + atomInfo("Initializing... (This could take a minute)"); + if (newFF) { + if (isUFF) energyMinimizer = new uffMinimizeAlgorythm(grp, this); + else energyMinimizer = new mm3MinimizeAlgorythm(grp, this); + newFF = false; + } + energyMinimizer.potentialOnly(this); + repaint(); + } + + /** + * constructor initialization + */ + public void init() { + //setting default atom type + currentAtomType = new GeneralAtom(); + currentAtomType.setName("Hydrogen"); + currentAtomType.setSymbol("H"); + currentAtomType.setAtomicNumber(1); + currentAtomType.setMass(1.007); + currentAtomType.setColor(new Color(255, 255, 255)); + currentAtomType.setCovalentRadius(.3); + currentAtomType.setVdwEnergy(.382); + currentAtomType.setVdwRadius(1.2); + currentAtomType.setCorrectNumBonds(1); + + int p = 200; + this.setBackground(new Color(p, p, p)); + Panel coorAxis = new Panel(); + drawingArea = new drawPanel(); + + //debugWindow = new textwin("Debug window", "", false); + //debugWindow.setVisible(false); + GridBagLayout gridbag = new GridBagLayout(); + this.setLayout(gridbag); + + instrucaba = new InstPanel(new FlowLayout(FlowLayout.RIGHT)); + instrucaba.setSize(500, 50); + about = new Button("About"); + instrucaba.add(about); + + constrain(this, instrucaba, 0, 0, 1, 1, GridBagConstraints.BOTH, GridBagConstraints.NORTH, .155, .155, 0, 0, 0, 0); + + constrain(this, drawingArea, 0, 1, 1, 1, + GridBagConstraints.BOTH, + GridBagConstraints.NORTH, + 1.0, 1.0, 0, 0, 0, 0); + + groupMode = new Checkbox("Group"); + groupMode.setState(false); + showForces = new Checkbox("Forces"); + showForces.setState(false); + + geometry = new Checkbox("Geometry"); + geometry.setState(false); + + emin = new Choice(); + emin.addItem("--Minimize--"); + emin.addItem("Conj. Grad."); + emin.addItem("Stp. Desc."); + + ffSelect = new Choice(); + ffSelect.addItem("--Force Field--"); + ffSelect.addItem("UFF"); + ffSelect.addItem("MM3"); + + knownStructure = new Button("Structure"); + clear = new Button("Clear"); + help = new Button("Help"); + undo = new Button("Undo"); + addHydro = new Button("Add H"); + getPotential = new Button("Get Potential"); + String osName = System.getProperty("os.name"); + getSetStructure = new Choice(); + getSetStructure.addItem("--Input/Output Menu--"); + getSetStructure.addItem("Open saved PDB/Mol2"); //lixh_add + getSetStructure.addItem("Save as PDB"); + + if (osName.startsWith("Windows")) + getSetStructure.addItem("View with Chime"); + else + getSetStructure.addItem("View with RasMol"); + getSetStructure.addItem("View XYZ"); + getSetStructure.addItem("View Native"); + getSetStructure.addItem("Gaussian Input"); + getSetStructure.addItem("GAMESS Input"); + +// FIXME-SEAGrid + getSetStructure.addItem("NWChem Input"); + getSetStructure.addItem( "PSI4 Input" ); + getSetStructure.addItem( "Molcas Input" ); +// getSetStructure.addItem("Molpro Input"); + +// getSetStructure.addItem("View PDB"); +// getSetStructure.addItem("View with VMD"); + + grp = new group(drawingArea); + grp1 = new group(drawingArea); + drawingArea.setGroupToPaint(grp); + + //if (debugWindow.isVisible()) + // debugWindow.clear(); + grp.setTextwin(debugWindow); + grp.v.zoomFactor = 25; + + tmpGroup = new group(grp); + tmpGroup.v.zoomFactor = 25; + + chgGroup = new group(grp); + chgGroup.v.zoomFactor = 25; + + undoGroup = new group(grp); + updateUndo(); + + controls.add(groupMode); + controls.add(geometry); + controls.add(showForces); + controls.add(help); + controls.add(knownStructure); + controls.add(clear); + controls.add(undo); + controls.add(addHydro); + + controls2.add(getPotential); + controls2.add(emin); + controls2.add(ffSelect); + controls2.add(getSetStructure); + + constrain(this, controls, 0, 2, 1, 1, GridBagConstraints.BOTH, + GridBagConstraints.NORTH, 0.0, 0.0, 0, 0, 0, 0); + constrain(this, controls2, 0, 3, 1, 1, GridBagConstraints.BOTH, + GridBagConstraints.NORTH, 0.0, 0.0, 0, 0, 0, 0); + + ((FlowLayout) controls.getLayout()).setAlignment(FlowLayout.CENTER); + ((FlowLayout) controls2.getLayout()).setAlignment(FlowLayout.CENTER); + + atomInfoBlab = new Label(""); + blabs = new Panel(); + blabs.add(atomInfoBlab); + + constrain(this, blabs, 0, 4, 1, 1, GridBagConstraints.BOTH, + GridBagConstraints.NORTH, 0.0, 0.0, 0, 0, 0, 0); + ((FlowLayout) blabs.getLayout()).setAlignment(FlowLayout.CENTER); + + this.add(instrucaba); + this.add(drawingArea); + this.add(controls); + this.add(controls2); + this.add(blabs); + + drawingArea.addMouseListener(this); + addMouseListener(this); + drawingArea.addMouseMotionListener(this); + addMouseMotionListener(this); + + grp.v.updateSize(600, 300); + tmpGroup.v.updateSize(600, 300); + chgGroup.v.updateSize(600, 300); + + // This code puts the molecule in the center for the local version. + // Probably doesn't hurt the web one really :) + if (runAsApplication) drawingArea.setSize(692, 366); + grp.centerAtoms(); + + initFlag = true; + + } + + public static void openURL(String url) { + String osName = System.getProperty("os.name"); + String errMsg = "For more information, visit www.gridchem.org"; + //System.out.println("OS name is: "+osName); + try { + if (osName.startsWith("Mac OS")) { + String currentDir = applicationDataDir; + String sep_str = System.getProperty("file.separator"); + if (!(currentDir.endsWith(sep_str))) + currentDir = currentDir + sep_str; + System.out.println("in OpenURL: applicationDatadir: " + currentDir); + String ras_dir = currentDir + "rasmol" + sep_str; + String rasmol = ras_dir + "RasMac_PPC_32BIT"; + System.out.println("1272: rasmol " + rasmol); + String rasmolBin = ras_dir + "RasMac_PPC_32BIT.bin"; + File browser = new File(rasmol); + if (browser.exists()) { + String run_ras = "open -a " + rasmol + " " + url; + Runtime.getRuntime().exec(run_ras); + System.out.println("1278: " + run_ras); + //System.out.println("1271"); + } else { + //System.out.println("1273"); + if (Runtime.getRuntime().exec("open " + rasmolBin).waitFor() == 0) { + JOptionPane.showMessageDialog(null, + "Press OK after Rasmol Installation is over", + "Installing Rasmol", + JOptionPane.INFORMATION_MESSAGE + ); + String run_ras = "open -a " + rasmol + " " + url; + Runtime.getRuntime().exec(run_ras); + System.out.println("1291: " + run_ras); + } + } + } else if (osName.startsWith("Windows")) {//System.out.println("test"); + Runtime.getRuntime().exec("cmd.exe /c start iexplore " + url); + } else { //assume Unix or Linux + String[] browsers = { + "mozilla", "netscape", "firefox", "konqueror", "opera"}; + String browser = null; + for (int count = 0; count < browsers.length && browser == null; count++) + if (Runtime.getRuntime().exec( + new String[]{"which", browsers[count]}).waitFor() == 0) + browser = browsers[count]; + if (browser == null) + throw new Exception("Could not find web browser."); + else + Runtime.getRuntime().exec("xterm -e " + browser + " " + url); + } + } catch (Exception e) { + JOptionPane.showMessageDialog(null, errMsg); + } + } + + public void start() { + /* + if(initFlag) + { + + if (!runAsApplication) + loadFile("ethanol.mol2", "/work/chemviz/mol2/Molecule/Organic/"); + else loadFile("aspirin.pdb", pathvar+sepStr+"common"+sepStr+ + "Molecule"+sepStr+"Organic"+sepStr); + initFlag = false; + //DemoWindow test = new DemoWindow(); + //test.setVisible(true); + t = new Template("Import Structure", this); + t.setVisible(false); + energyMinimizer = null; + grp.setShowForces (showForces.getState()); + grp.setTextwin(debugWindow); + needToRepaint = true; + atomInfo(" "+spaces+spaces+"Welcome to NCSA Nanocad!"+spaces+spaces+" "); + drawingArea.setGroupToPaint(grp); + grp.updateViewSize(); + getSetStructure.select(0); + grp.centerAtoms(); + this.repaint(); + } + */ + + //lixh_4/29/05 + if (initFlag == true) { + //String applicationDataDir = System.getProperty("user.dir"); + //String defaultFile; + defaultFile = applicationDataDir + fileSeparator + + "common" + fileSeparator + "Molecule" + fileSeparator + + "Inorganic" + fileSeparator + "water.pdb"; + try { + //System.out.println("Trying to check retrieved structure information in "+ legacy.editors.commons.Settings.jobDir); + //File f = new File(applicationDataDir + fileSeparator + "loadthis"); + File f = new File(Settings.jobDir + fileSeparator + "loadthis"); + if (f.exists()) { + BufferedReader br = new BufferedReader(new FileReader(f)); + String filetext; + while ((filetext = br.readLine()) != null) + defaultFile = filetext; + //System.out.println("newNanocad:Current Active File = " + defaultFile); + } + } catch (IOException ioe) { + System.err.println("newNanocad:start:IOException"); + System.err.println(ioe.toString()); + ioe.printStackTrace(); + } + //if (runAsApplication == false){ + //loadFile("aspirin.pdb", "/work/chemviz/mol2/Molecule/Organic"); + //} + //else { + + //lixh_4/27/05 + //File ftemp = new File(applicationDataDir + fileSeparator + defaultFile); + File ftemp = new File(defaultFile); + if (ftemp.exists()) { + //System.out.println("Trying to Load " + defaultFile); + //loadFile(defaultFile, applicationDataDir); + loadFile(defaultFile, ""); + //System.out.println(" Successfully loaded default input!"); + /* //****************** + //public static void openURL(String url) { + String url = defaultFile; + String errMsg = "For more information, visit www.gridchem.org"; + String osName = System.getProperty("os.name"); + System.out.println("OS name is: "+osName); + try { + if (osName.startsWith("Mac OS")) { + Class macUtils = Class.forName("com.apple.mrj.MRJFileUtils"); + Method openURL = macUtils.getDeclaredMethod("openURL", + new Class[] {String.class}); + openURL.invoke(null, new Object[] {url}); + } + else if (osName.startsWith("Windows")) + {System.out.println("test"); + Runtime.getRuntime().exec("cmd.exe /c start iexplore " + url);} + + else { //assume Unix or Linux + String[] browsers = { + "firefox", "opera", "konqueror", "mozilla", "netscape" }; + String browser = null; + for (int count = 0; count < browsers.length && browser == null; count++) + if (Runtime.getRuntime().exec( + new String[] {"which", browsers[count]}).waitFor() == 0) + browser = browsers[count]; + if (browser == null) + throw new Exception("Could not find web browser."); + else + Runtime.getRuntime().exec("xterm -e " + browser + " " + url); + } + } + catch (Exception e) { + JOptionPane.showMessageDialog(null, errMsg); + } +// ******************** } */ + //} + initFlag = false; + //DemoWindow test = new DemoWindow(); + //test.setVisible(true); + // Center atoms + needToRepaint = true; + atomInfo(); + grp.updateViewSize(); + grp.centerAtoms(); + + //lixh_4/30/05 + atomInfoBlab.setBackground(this.getBackground()); + blabs.setBackground(this.getBackground()); + atomInfoBlab.setText("Show atom information here "); + instrucaba.setWarning(false); + // + + this.repaint(); + + } else { + System.err.println("file " + defaultFile + " does not exist"); + } + } + // + + } + + + /** + * Display only .pdb and .mol2 files + */ + class PDBorMOL2FileFilter extends FileFilter { + + /** + * Accept only .pdb or .mol2 files. + * + * @param fileOrDirectory The file to be checked. + * @return true if the file is a directory, a .pdb or .mol2 file. + */ + public boolean accept(File fileOrDirectory) { + if (fileOrDirectory.isDirectory()) { + return true; + } + + String fileOrDirectoryName = fileOrDirectory.getName(); + int dotIndex = fileOrDirectoryName.lastIndexOf('.'); + if (dotIndex == -1) { + return false; + } + String extension = + fileOrDirectoryName + .substring(dotIndex); + + if (extension != null) { + if (extension.equalsIgnoreCase(".pdb") + || extension.equalsIgnoreCase(".mol2")) { + return true; + } else { + return false; + } + } + return false; + } + + /** + * The description of this filter + */ + public String getDescription() { + return ".pdb and .mol2 files"; + } + } + + + /** + * here we have the mouse functions. Only 3 are needed, but definitions have to + * be given for them all, since we are using an interface. If nanocad is ever + * made to use swing, mouseInputAdapter should be used instead of mouseListener + * and mouseMotionListener + */ + + public void mouseClicked(MouseEvent e) { + ;//do nothing, since we are dealing with the mouse being pressed and released + } + + public void mouseEntered(MouseEvent e) { + ;//do squat + } + + public void mouseExited(MouseEvent e) { + ;//you get the idea + } + + public void mouseMoved(MouseEvent e) { + ; + } + + public void mousePressed(MouseEvent e) { + int x = e.getX(); + int y = e.getY(); + int ourFlag = InputEvent.SHIFT_MASK | InputEvent.CTRL_MASK | + InputEvent.ALT_MASK | InputEvent.META_MASK; + Rectangle r = drawingArea.bounds(); + inDrawingArea = y < r.height; + needToRepaint = false; + double[] scrPos = {x, y, 0}; + mouseModifiers = e.getModifiers(); + mouseModifiers = mouseModifiers & ourFlag; + atom1 = grp.selectedAtom(scrPos, true); + + dragFlag = false; + + if (atom1 != null) { + double[] atomScrPos = grp.v.xyzToScreen(atom1.x); + atom1z = atomScrPos[2]; + + if (geometryFlag) //Andrew Knox 06/01/01 + { + int size = selectedAtomList.size(); + int i = selectedAtomList.indexOf(atom1); + + if (size == 0) { + atom1.setSelected(true); + selectedAtomList.addElement(atom1); + size++; + } else if (i != -1) { + while (selectedAtomList.size() > i) { + ((atom) selectedAtomList.elementAt(size - 1)).setSelected(false); + selectedAtomList.removeElementAt(size - 1); + size--; + } + } else { + //only add if it is next to the last atom + for (i = 0; i < ((atom) selectedAtomList.elementAt(size - 1)).bonds.size(); i++) { + if (((bond) ((atom) selectedAtomList.elementAt(size - 1)).bonds.elementAt(i)).a1 == atom1) { + if ((size == 1) || (atom1 != selectedAtomList.elementAt(size - 2))) { + atom1.setSelected(true); + selectedAtomList.addElement(atom1); + size++; + break; + } + } else if (((bond) ((atom) selectedAtomList.elementAt(size - 1)).bonds.elementAt(i)).a2 == atom1) { + if ((size == 1) || (atom1 != selectedAtomList.elementAt(size - 2))) { + atom1.setSelected(true); + selectedAtomList.addElement(atom1); + size++; + break; + } + } + } + } + + //now find appropriate information + if (size == 2) //bond length + { + geomValue = calculateBondLength(); + } else if (size == 3) //bond angle + { + geomValue = calculateBondAngle(); + } else if (size == 4) //dihedral + { + geomValue = calculateDihedral(); + } else ; //default + drawingArea.setGeometryValue(size, geomValue); + updateUndo(); + } + + //Andrew Knox 5/24/01 get a group of all atoms connected to one atom + else if (e.isAltDown() && e.isControlDown()) { + selectedAtomList.removeAllElements(); + selectedAtomList.addElement(atom1); + + boolean dontAdd = false; + boolean elementAdded = true; + int firstToCheck = selectedAtomList.size(); //the position of the first atom we need to check in the next step + int i, j, k; + + for (i = 0; i < atom1.bonds.size(); i++) //get atoms bonded to that atom + { + if (atom1 == ((bond) atom1.bonds.elementAt(i)).a1) + selectedAtomList.addElement(((bond) atom1.bonds.elementAt(i)).a2); + else + selectedAtomList.addElement(((bond) atom1.bonds.elementAt(i)).a1); + } + + while (elementAdded) //get atoms bonded to those atoms, etc. + { + elementAdded = false; + + for (i = firstToCheck; i < selectedAtomList.size(); i++) { + atom1 = (atom) selectedAtomList.elementAt(i); + for (j = 0; j < atom1.bonds.size(); j++) { + if (atom1 == ((bond) atom1.bonds.elementAt(j)).a1) { + for (k = 0; k < firstToCheck; k++) + if (((bond) atom1.bonds.elementAt(j)).a2 == selectedAtomList.elementAt(k)) + dontAdd = true; + + if (!dontAdd) { + selectedAtomList.addElement(((bond) atom1.bonds.elementAt(j)).a2); + elementAdded = true; + } + } else { + for (k = 0; k < firstToCheck; k++) + if (((bond) atom1.bonds.elementAt(j)).a1 == selectedAtomList.elementAt(k)) + dontAdd = true; + + if (!dontAdd) { + selectedAtomList.addElement(((bond) atom1.bonds.elementAt(j)).a1); + elementAdded = true; + } + } + dontAdd = false; + } + firstToCheck = selectedAtomList.size(); + } + } + + for (i = 0; i < selectedAtomList.size(); i++) { + ((atom) selectedAtomList.elementAt(i)).setSelected(true); + } + } else if (e.isAltDown() && !e.isControlDown() && !e.isShiftDown()) { //alt + + if (!(atom1.isSelected())) { + atom1.setSelected(true); + + //04/12 mark the atom directly not index + for (int i = 0; i < (grp.atomList).size(); i++) { + if (((atom) (grp.atomList.elementAt(i))) == atom1) { + selectedAtomList.addElement(atom1); + + } + } + } else //if atom is already selected, unselect it + { + atom1.setSelected(false); + + for (int i = 0; i < (grp.atomList).size(); i++) + if (((atom) (grp.atomList.elementAt(i))) == atom1) + selectedAtomList.removeElement(atom1); + } + } else + updateUndo(); + } else { + atom1z = 0; + } + + atomInfo(atom1); + xxx = x; + yyy = y; + x0 = x; + y0 = y; + } + + /** + * mouse drag operation handler + */ + + public void mouseDragged(MouseEvent e) { + //don't move molecule if choosing element + if (seePTable) return; + + int x = e.getX(); + int y = e.getY(); + //mouseModifiers = e.getModifiers(); + + // if moving atom, no need for extra line + boolean movingAtom = false; + + if (!dragFlag && !geometryFlag) + if (x < x0 - 2 || x > x0 + 2 || y < y0 - 2 || y > y0 + 2) + dragFlag = true; + if (!clearFlag) { + needToRepaint = true; + if (atom1 == null) { + //keep normal mode + switch (mouseModifiers) { + default: //no specific atom, in blank area for drag, so rotate + + if (grpFlag) //group rotation + { + + tmpGroup = new group(grp); + chgGroup = new group(grp); + + for (int j = 0; j < tmpGroup.atomList.size(); j++) { + atom tmpAtom = (atom) tmpGroup.atomList.elementAt(j); + if (belongTo(tmpAtom, selectedAtomList)) { + //this keeps the bond very important!!! + tmpGroup.atomList.removeElement(tmpAtom); + j--; + } + } + + for (int k = 0; k < chgGroup.atomList.size(); k++) { + atom tmpAtom = (atom) chgGroup.atomList.elementAt(k); + if (!belongTo(tmpAtom, selectedAtomList)) { + chgGroup.atomList.removeElement(tmpAtom); + k--; + } + } + + chgGroup.rotate(0.01 * (x - xxx), -0.01 * (y - yyy)); + grp = new group(tmpGroup, chgGroup, drawingArea); + drawingArea.setGroupToPaint(grp); + } else //molecule rotation + { + grp.rotate(0.01 * (x - xxx), -0.01 * (y - yyy)); + } + break; + + + case Event.SHIFT_MASK: + if (grpFlag) //group translation + { + tmpGroup = new group(grp); + chgGroup = new group(grp); + + for (int j = 0; j < tmpGroup.atomList.size(); j++) { + atom tmpAtom = (atom) tmpGroup.atomList.elementAt(j); + if (belongTo(tmpAtom, selectedAtomList)) { + //still keep the bondList + tmpGroup.atomList.removeElement(tmpAtom); + j--; + } + } + + for (int k = 0; k < chgGroup.atomList.size(); k++) { + atom tmpAtom = (atom) chgGroup.atomList.elementAt(k); + if (!belongTo(tmpAtom, selectedAtomList)) { + chgGroup.atomList.removeElement(tmpAtom); + k--; + } + } + + chgGroup.pan((x - xxx), (y - yyy)); + grp = new group(tmpGroup, chgGroup, drawingArea); + drawingArea.setGroupToPaint(grp); + } else grp.v.pan(x - xxx, y - yyy); //molecule translation + break; + + case Event.CTRL_MASK: + grp.v.zoomFactor *= Math.exp(0.01 * (x - xxx)); + //grp.v.perspDist *= Math.exp (0.01 * (y - yyy)); + break; + + case Event.META_MASK: + grp.v.zoomFactor *= Math.exp(0.01 * (x - xxx)); + //grp.v.perspDist *= Math.exp (0.01 * (y - yyy)); + break; + + } + drawingArea.clear(); + grp.wireframePaint(); + + } else if (geometryFlag) return; + else + //select atom or click on the atom + { + switch (mouseModifiers) { + default: //==0; drag without alt , shift or ctrl + double[] scrPos = {x, y, atom1z}; + atom1.x = grp.v.screenToXyz(scrPos); + movingAtom = true; + drawingArea.clear(); + grp.wireframePaint(); + break; + + case Event.SHIFT_MASK: //==1 + drawingArea.clear(); + grp.bubblePaint(); + break; + + case Event.CTRL_MASK: //==2 + drawingArea.clear(); + grp.bubblePaint(); + break; + + case Event.META_MASK: + drawingArea.clear(); + grp.bubblePaint(); + break; + + case Event.ALT_MASK: //==8, do nothing except marked already + break; + } + } + + xxx = x; + yyy = y; + if (atom1 != null && !movingAtom) grp.drawLineToAtom(atom1, x, y); + } + } + + /** + * determine whether an atom belongs to an atom vector or not + */ + public boolean belongTo(atom a, Vector b) { + boolean contain = false; + + for (int i = 0; i < b.size(); i++) { + atom c = (atom) b.elementAt(i); + if (a == c) { + contain = true; + break; + } + } + + return contain; + } + + /** + * mouse up operation handler + */ + + public void mouseReleased(MouseEvent e) { + int x = e.getX(); + int y = e.getY(); + int selectCount = 0; + + //if periodic table is up, select appropiate atom + if (seePTable) { + int pTableX = (x - ptableHOffset) / ((ptableHSize - 17) / 18 + 1); + int pTableY = (y - ptableVOffset) / ((ptableVSize - 9) / 10 + 1); + + try { + if ((pTableX >= 0) && (pTableY >= 0)) { + AtomDataFile dFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "pdata.txt"); + //AtomDataFile dFile = new AtomDataFile("pdata.txt"); + if (dFile.findData(pTableY, pTableX, 1, 2)) { + GeneralAtom selected = new GeneralAtom(); + selected.setName(dFile.parseString(3)); + selected.setSymbol(dFile.parseString(4)); + selected.setAtomicNumber(dFile.parseInt(0)); + selected.setMass(dFile.parseDouble(5)); + selected.setColor(new Color(dFile.parseInt(6), dFile.parseInt(7), dFile.parseInt(8))); + selected.setCovalentRadius(dFile.parseDouble(9)); + selected.setVdwEnergy(dFile.parseDouble(10)); + selected.setVdwRadius(dFile.parseDouble(11)); + selected.setCorrectNumBonds(dFile.parseInt(12)); + currentAtomType = selected; + t.currentElement.setText("Current Element: " + dFile.parseString(4)); + seePTable = false; + } + } + } catch (IOException ex) { + ex.printStackTrace(); + } + repaint(); + return; + } + + double[] scrPos = {x, y, atom1z}; + Graphics g = this.getGraphics(); + atom atom2 = grp.selectedAtom(scrPos, false); + + if ((atom1 != null) && !geometryFlag) { + if (dragFlag) { + //drag on an atom + switch (mouseModifiers) { + default: //copy the dragged atom + atom1.x = grp.v.screenToXyz(scrPos); + atom2 = atom1; + break; + + case Event.SHIFT_MASK: + if (atom1 != atom2 && atom1 != null && atom2 != null) { + updateUndo(); + grp.addBond(atom1, atom2); + } + break; + + case Event.CTRL_MASK: + if (atom1 != atom2 && atom1 != null && atom2 != null) { + updateUndo(); + grp.deleteBond(atom1, atom2); + } + atomInfo(atom2); + break; + } + } + //not drag, but click when up is detected + else { + //click on an atom + switch (mouseModifiers) { + case Event.SHIFT_MASK: + if (atom1 != null) { + updateUndo(); + grp.deleteAtom(atom1); + } else + atomInfo(); + + needToRepaint = true; + atomInfo(); + break; + + case Event.ALT_MASK: + needToRepaint = true; + } + } + } + //no atom + else { + //no atom and no drag + if (!dragFlag && !geometryFlag) { + //click on empty space + switch (mouseModifiers) { + case Event.SHIFT_MASK: + int sp; // What is this? + atom a = null; + needToRepaint = true; + + a = (atom) currentAtomType.copy(); + if (a != null) { + updateUndo(); + grp.addAtom(a, scrPos); + atomInfo(a); + clearFlag = false; //we know there is at least one atom + } + break; + + case Event.CTRL_MASK: + needToRepaint = true; + atomInfo(); + grp.updateViewSize(); + grp.centerAtoms(); + break; + + case Event.META_MASK: + needToRepaint = true; + atomInfo(); + grp.updateViewSize(); + grp.centerAtoms(); + break; + + case Event.ALT_MASK: + needToRepaint = false; + break; + } + } + } + + this.repaint(); + } + + /** + * paint + */ + public void paint(Graphics g) { + super.paint(g); + + drawingArea.clear(); + drawingArea.repaint(); + + drawingArea.clear(); + drawingArea.repaint(); + + if (seePTable) { + drawingArea.clear(); + drawPTable(drawingArea.getGraphics()); + + drawingArea.clear(); + drawPTable(drawingArea.getGraphics()); + } + needToRepaint = false; + } + + public final synchronized void update(Graphics g) { + paint(g); + } + + + /** + * main function for loading structure through socket, no use anymore, + */ + protected String receiveFile() { + try { + /* + NanoDataPacket pkt = new NanoDataPacket(); + pkt.setStatus(NanoDataPacket.readPacket); + pkt.setName(getParameter("fname")); + byte[] data = pkt.byteArray(); + */ + + byte[] data = new byte[50000]; + InetAddress addr = InetAddress.getByName(getCodeBase().getHost()); + //give read command to server; + String comm = "r"; + byte cData[] = comm.getBytes(); + + DatagramPacket spack = new DatagramPacket(cData, cData.length, addr, Integer.parseInt(getParameter("myPort"))); + DatagramSocket ds = new DatagramSocket(); + ds.send(spack); + + DatagramPacket rpack = new DatagramPacket(new byte[50000], 50000); + + ds.receive(rpack); + ds.close(); + + return new String(rpack.getData()); + + /*pkt = new NanoDataPacket(rpack.getData()); + return new String(pkt.getData()); + */ + + } catch (IOException e) { + System.out.println(e); + return new String(e.toString()); + } + } + + /** + * send file to specific url + */ + protected void sendFile(String urlname, String filedata, String filename) { // to send file frm Nanocad to Waltz, u can use sendFile?? + String username = getParameter("username"); + String encodedUsername = URLEncoder.encode(username); + String encodedFilename = URLEncoder.encode(filename); + String encodedData = URLEncoder.encode(filedata); + + try { + URL url1 = new URL(urlname); + //System.out.println("URL savepdb.cgi assigned to"+urlname); + + URLConnection conn1 = url1.openConnection(); + System.out.println("in sendFile: url connection opened"); + + conn1.setDoOutput(true); + PrintWriter out1 = new PrintWriter(conn1.getOutputStream()); + + out1.println("userid=" + encodedUsername + "&"); + //System.out.println("id=" + encodedUsername); + out1.println("filename=" + encodedFilename + "&"); + //System.out.println("filename=" + encodedFilename); + out1.println("data=" + encodedData); + //System.out.println("data=" + encodedData); + out1.close(); + + //System.out.println("now the molecule data is sent out to server....\n"); + + //read conformation from the URL ; // Anupama What data are we reading here?? Is it the sent file or smthin else + String line = null; + BufferedReader inStr1 = new BufferedReader(new InputStreamReader(conn1.getInputStream())); + while ((line = inStr1.readLine()) != null) { + //System.out.println(line); + } + + inStr1.close(); + } catch (MalformedURLException mx) { + saveWin = new textwin("URL Exception", "", false); + saveWin.setVisible(true); + saveWin.setText("Exception : " + mx.toString()); + } catch (IOException e) { + saveWin = new textwin("IO Exception", "", false); + saveWin.setVisible(true); + saveWin.setText("Exception : " + e.toString()); + System.out.println(e.getMessage()); + } + } + + + /** + * main function for reloading structure through url + */ + protected String receiveFile(String filename, String type, String directory) { + try { + URL url; + StringBuffer b = new StringBuffer(); + String encodedFilename = null; + + encodedFilename = URLEncoder.encode(filename); + if (type.equals("mol2")) + url = new URL("http://pine.ncsa.uiuc.edu/cgi-bin/openpdb-II.cgi"); // what r we doing here? + else if (callDatabase == 1) + url = new URL(" http://chemviz.ncsa.uiuc.edu/cgi-bin/reloadpdbIndiana.cgi"); + else if (callDatabase == 2) + url = new URL(" http://chemviz.ncsa.uiuc.edu/cgi-bin/reloadCsd.cgi"); + else + url = new URL("http://pine.ncsa.uiuc.edu/cgi-bin/openpdb-II.cgi"); + + + if (!runAsApplication) { + URLConnection conn = url.openConnection(); + conn.setDoOutput(true); + + PrintWriter out = new PrintWriter(conn.getOutputStream()); + out.print("filename=" + encodedFilename); + out.print("&" + "directory=" + directory); + out.close(); + + //read result mol2 file back through the URL again; + BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line = null; + while ((line = in.readLine()) != null) { + b.append(line); + } + + in.close(); + } else { + File toOpen = new File(directory + filename); + BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(toOpen))); + String line = null; + while ((line = in.readLine()) != null) + b.append(line); + + in.close(); + } + return new String(b); + + } catch (MalformedURLException mx) { + System.out.println(mx); + return new String(mx.toString()); + } catch (IOException e) { + System.out.println(e.getMessage()); + return new String("error"); + } + } + + /** + * Insert the method's description here. + * Creation date: (7/25/2000 3:16:55 PM) + * + * @param newEnergyMinimizer energyMinimizeAlgorythm + */ + public void setEnergyMinimizer(energyMinimizeAlgorythm newEnergyMinimizer) { + energyMinimizer = newEnergyMinimizer; + } + + /** + * add atoms by cooridates + */ + public Vector addAtoms(Vector aSym, Vector aX, Vector aY, Vector aZ) { + + Vector atomL = new Vector(); + atom a = null; + double x, y, z; + for (int i = 0; i < aSym.size(); i++) { + //cast first + x = ((Double) aX.elementAt(i)).doubleValue(); + y = ((Double) aY.elementAt(i)).doubleValue(); + z = ((Double) aZ.elementAt(i)).doubleValue(); + //determine atom type first; + a = determineAtom((String) aSym.elementAt(i), x, y, z); + //System.out.println(a.name()); + atomL.addElement(a); + } + return atomL; + } + + /** + * determine atom type and coordinates + */ + public atom determineAtom(String sym, double x0, double y0, double z0) { + atom a = null; + + try { + AtomDataFile dFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "pdata.txt"); + //AtomDataFile dFile = new AtomDataFile("pdata.txt"); + + if (dFile.determineData(sym)) { + GeneralAtom selected = new GeneralAtom(); + selected.setName(dFile.name); + selected.setSymbol(dFile.symbol); //may be commented out; + selected.setAtomicNumber(dFile.atomicNum); + selected.setMass(dFile.mass); + selected.setColor(new Color(dFile.color1, dFile.color2, dFile.color3)); + selected.setCovalentRadius(dFile.covalentRadius); + selected.setVdwEnergy(dFile.vdwEnergy); + selected.setVdwRadius(dFile.vdwRadius); + selected.setCorrectNumBonds(dFile.correctNumBonds); + a = (atom) selected; + a.x[0] = x0; + a.x[1] = y0; + a.x[2] = z0; + } + } catch (Exception e) { + + System.err.println(e); + return null; + } + return a; + } + + /** + * add bonds with correct order + */ + public Vector addBonds(Vector bA1, Vector bA2, Vector bO) { + Vector bondL = new Vector(); + bond b = null; + + int order; + atom atom1 = null; + atom atom2 = null; + int index1, index2; + System.out.println("bA1.size: " + bA1.size()); + for (int i = 0; i < bA1.size(); i++) { + order = ((Double) bO.elementAt(i)).intValue(); + index1 = ((Double) bA1.elementAt(i)).intValue(); + index2 = ((Double) bA2.elementAt(i)).intValue(); + int atomVsize = atomV.size(); + int ba2size = bA2.size(); + int ba1size = bA1.size(); + System.out.println("ba1size: " + ba1size + ",bA2size: " + ba2size + ",atomVsize: " + atomVsize + " i: " + i + " order: " + order + " index1: " + index1 + " index2: " + index2); + atom1 = (atom) atomV.elementAt(index1 - 1); + atom2 = (atom) atomV.elementAt(index2 - 1); + + b = new bond(atom1, atom2, order); + bondL.addElement(b); + } + return bondL; + } + + public void getDirectoriesInDirectory(java.awt.List dirlist, String directory) { + if (runAsApplication && (directory.charAt(directory.length() - 1) != sepChar)) + directory = directory + sepStr; + else if (directory.charAt(directory.length() - 1) != '/') + directory = directory + "/"; + String encodedDirName = URLEncoder.encode(directory); + + try { + URL url = new URL("http://pine.ncsa.uiuc.edu/cgi-bin/readdirfromdir.cgi"); + + URLConnection conn = url.openConnection(); + conn.setDoOutput(true); + PrintWriter out = new PrintWriter(conn.getOutputStream()); + out.println(directory); + out.close(); + + BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line = null; + while ((line = in.readLine()) != null) { + dirlist.add(line); + } + in.close(); + } catch (IOException e1) { + System.out.println("Doh!"); + } + } + + public NcadMenuBar CreateMenu(NcadMenuBar bar, Template t) { + NcadMenu temp; + NcadMenu[] toadd; + MenuItem tempItem; + int idc = 0; + java.awt.List dirl = new java.awt.List(50, false); + + if (!runAsApplication) + getDirectoriesInDirectory(dirl, "/work/chemviz/mol2/"); + /** + else + { + File directoryFile = new File(pathvar+sepStr+"common"+sepStr); + String[] directoryStrings = directoryFile.list(); + File[] directories = directoryFile.listFiles(); + + for (int i = 0; i < directories.length; i++) + { + if (directories[i].isDirectory()) + { idc++; + dir.add(directories[i].getName()); + } + } + } + + int items; + if (runAsApplication) items = idc + 3; + else items = dir.getItemCount() + 3; + toadd = new NcadMenu[items]; + + toadd[0] = new NcadMenu("Atom"); + tempItem = new MenuItem("Select element..."); + tempItem.addActionListener(t); + toadd[0].add(tempItem); + + toadd[1] = new NcadMenu("Database"); + // Indiana is commented out because it's worthless. :) + // tempItem = new MenuItem("Indiana Database"); + // tempItem.addActionListener(t); + // toadd[1].add(tempItem); + tempItem = new MenuItem("CSD"); + tempItem.addActionListener(t); + toadd[1].add(tempItem); + if (runAsApplication) + { + tempItem = new MenuItem("CSD/Chime setup"); + tempItem.addActionListener(t); + toadd[1].add(tempItem); + } + + toadd[2] = new NcadMenu("My Files"); + tempItem = new MenuItem("Load saved file"); + tempItem.addActionListener(t); + toadd[2].add(tempItem); + + for (int i = 3; i < items; i++) + { + String nospace = removeSpace(dir.getItem(i-3)); + temp = new NcadMenu(nospace); + if (!runAsApplication) + CreateMenu((Menu)temp.getMenu(), "/work/chemviz/mol2/" + ((Menu)temp.getMenu()).getLabel(), t); + else + CreateMenu((Menu)temp.getMenu(), pathvar+sepStr+"common"+sepStr+ + ((Menu)temp.getMenu()).getLabel(), t); + toadd[i] = temp; + } + + bar = new NcadMenuBar(toadd, items); + return bar; + */ + + //lixh_3_4_05 + else { +// File directoryFile = new File("C:\\nanocad\\common"); + // if it doesn't exist, download from mss and unzip it! + if (!((new File(applicationDataDir + fileSeparator + "common")).exists())) { + String zipFileName = applicationDataDir + fileSeparator + "nanocaddata.zip"; + if (!((new File(zipFileName)).exists())) { + GetDataFile gf = new GetDataFile(zipFileName); + } + //Unzip uz = new Unzip("nanocad" + fileSeparator + zipFileName); + ZipExtractor uz = new ZipExtractor(zipFileName); + System.err.println("Done with unzipping stuff"); + } + File directoryFile = new File(applicationDataDir + fileSeparator + + "common"); + String[] directoryStrings = directoryFile.list(); + //File[] directories = new File[directoryStrings.length]; + File[] directories = directoryFile.listFiles(); + + //for (int i = 0; i < directoryStrings.length; i++) + //directories[i] = new File(directoryStrings[i]); + + for (int i = 0; i < directories.length; i++) { + if (directories[i].isDirectory() == true) { + idc++; + dirl.add(directories[i].getName()); + //System.out.println(dirl.getItemCount()+ idc +" Directory "+directories[i].getName()+" found"); + } + } + + } + + //int items = 3 + dirl.getItemCount(); + int items = 3 + idc; + //System.out.println("Found "+items+" less 3 directories in local data base"); + toadd = new NcadMenu[items]; + + toadd[0] = new NcadMenu("Atom"); + tempItem = new MenuItem("Select element..."); + tempItem.addActionListener(t); + toadd[0].add(tempItem); + + toadd[1] = new NcadMenu("Database"); + //tempItem = new MenuItem("Indiana Database"); + //tempItem.addActionListener(t); + //toadd[1].add(tempItem); + tempItem = new MenuItem("CSD"); + tempItem.addActionListener(t); + toadd[1].add(tempItem); + + toadd[2] = new NcadMenu("My Files"); + tempItem = new MenuItem("Load saved file"); + tempItem.addActionListener(t); + toadd[2].add(tempItem); + + for (int i = 3; i < items; i++) { + String nospace = removeSpace(dirl.getItem(i - 3)); + temp = new NcadMenu(nospace); + if (runAsApplication == false) { + CreateMenu((Menu) temp.getMenu(), "/work/chemviz/mol2/" + ((Menu) temp.getMenu()).getLabel(), t); + } else { +// CreateMenu( (Menu)temp.getMenu(), "C:\\nanocad\\common\\" + ((Menu)temp.getMenu()).getLabel(), t); + CreateMenu((Menu) temp.getMenu(), applicationDataDir + + fileSeparator + "common" + fileSeparator + + ((Menu) temp.getMenu()).getLabel(), t); + System.err.println("Where am I now?"); + } + toadd[i] = temp; + } + + bar = new NcadMenuBar(toadd, items); + return bar; + } + + + public String removeSpace(String s) { + if (s.charAt(0) == ' ') + s = s.substring(1, s.length()); + if (s.charAt(s.length() - 1) == ' ') + s = s.substring(0, s.length() - 1); + return s; + } + + public Menu CreateMenu(Menu m, String directory, Template t) { + MenuItem temp; + Menu tempMenu = null; + java.awt.List files = new java.awt.List(50, false); + java.awt.List dir = new java.awt.List(50, false); + + if (!runAsApplication) { + getDirectoriesInDirectory(dir, directory); + getFilesInDirectory(files, directory); + } else { + File directoryFile = new File(directory); + String[] directoryStrings = directoryFile.list(); + File[] directories = directoryFile.listFiles(); + for (int i = 0; i < directories.length; i++) { + if (directories[i].isDirectory()) + dir.add(directories[i].getName()); + } + + directoryFile = new File(directory); + directoryStrings = directoryFile.list(); + File[] fileList = directoryFile.listFiles(); + for (int i = 0; i < fileList.length; i++) { + if (!fileList[i].isDirectory()) + files.add(fileList[i].getName()); + } + } + + int numfiles = files.getItemCount(); + + for (int i = 0; i < numfiles; i++) { + String name = removeSpace(files.getItem(i)); + int pos = name.indexOf(".pdb"); + if (pos != -1) { + name = name.substring(0, pos); + temp = new MenuItem(name); + temp.addActionListener(t); + m.add(temp); + } else if ((pos = name.indexOf(".mol2")) != -1) { + name = name.substring(0, pos); + temp = new MenuItem(name); + temp.addActionListener(t); + m.add(temp); + } + } + + for (int i = 0; i < dir.getItemCount(); i++) { + tempMenu = new Menu(removeSpace(dir.getItem(i))); + if (!runAsApplication) CreateMenu(tempMenu, directory + "/" + removeSpace(tempMenu.getLabel()), t); + else CreateMenu(tempMenu, directory + sepStr + removeSpace(tempMenu.getLabel()), t); + if (tempMenu != null) + m.add(tempMenu); + } + return m; + } + + /** + * inner class "Template" for structure reloading //Anupama use this code while making menu dynamic! + */ + public class Template extends Frame implements ActionListener { + private NcadMenuBar myMenuBar; + private NcadMenu[] m; + private Menu[] molSubMenu, molSubMenu_1; + private MenuItem atomItem, myfilesItem; + private MenuItem[] databaseItem; + private MenuItem[] orgItem, inorgItem, aminItem, ionsItem, funcGrpItem, bioItem; + private Panel templatecontrols; + private Label currentElement, elementLabel; + private NcadMenu test1, test2; + private TextField elementField; + private Button select; + private String openMenu; + + public Template(String name, newNanocad n1) { + super(name); + nano = n1; + setLayout(new GridBagLayout()); + + templatecontrols = new Panel(); + elementLabel = new Label("Change current element to:"); + elementField = new TextField("H", 3); + select = new Button("Select"); + select.addActionListener(this); + + myMenuBar = CreateMenu(myMenuBar, this); + myMenuBar.setParent(this); + + currentElement = new Label("Current Element: " + currentAtomType.symbol()); + templatecontrols.add(elementLabel); + templatecontrols.add(elementField); + templatecontrols.add(select); + templatecontrols.add(currentElement); + + constrain(this, myMenuBar, 0, 0, 1, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.NORTHWEST, 1.0, 0.0, 0, 0, 0, 0); + constrain(this, templatecontrols, 0, 1, 1, 1, GridBagConstraints.BOTH, GridBagConstraints.NORTHWEST, 0.0, 1.0, 0, 0, 0, 0); + + +//***************ANU TRYING*******************/ + structure = new Panel(); + //write applet code for popping up a window + CompoundName = new TextField(7); + Formula = new TextField(7); + Label lCompoundName = new Label("Compound Name: ", Label.RIGHT); + Label lFormula = new Label("Formula: ", Label.RIGHT); + Button okbutt = new Button("OK"); + structure.add(lCompoundName); + structure.add(CompoundName); + structure.add(lFormula); + structure.add(Formula); + structure.add(okbutt); + constrain(this, structure, 0, 3, 3, 3, GridBagConstraints.BOTH, GridBagConstraints.NORTHWEST, 0.0, 3.0, 3, 3, 3, 3); + +//***************ANU TRYING*******************/ + setLocationRelativeTo(null); + setAlwaysOnTop(true); + setVisible(true); + add(myMenuBar); + add(templatecontrols); + + pack(); + setResizable(true); + setSize(475, 105); + + addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + setVisible(false); + //System.exit(0); + } + }); + templatecontrols.paint(templatecontrols.getGraphics()); + } + + /** + * template handler + */ + public void actionPerformed(ActionEvent e) { + String s = e.getActionCommand(); + selectedItem = s; + //System.out.println( s.toString() ); + if (s.equals("Select element...")) { + drawingArea.clear(); + drawPTable(drawingArea.getGraphics()); + seePTable = true; + } //Actual code for INDIANA thing! + + else if (s.equals("Indiana Database")) { + callDatabase = 1; //this variable is used directly by indianaWindow.class + indiana = new indianaWindow(nano); + indiana.setVisible(true); + + //Now indianaWindow calls a cgi script which will put the appropriate pdb file in fileFromIndiana.pdb so we need toload that file. + + this.setVisible(false); + + // Check if foll code needed ! + addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + setVisible(false); + //System.exit(0); + } + }); + structure.paint(structure.getGraphics()); + pack(); + } + + // This gives you the ability to get the place where other people's executables + // are stored for CSD and Chime. I never had a chance to implement loading either of them + // because we don't have them on density (as far as I know). Good luck with that! -- Jeff + else if (s.equals("CSD/Chime setup")) { + define = new defineWindow(nano); + define.setVisible(true); + + this.setVisible(false); + + addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + setVisible(false); + //System.exit(0); + } + }); + structure.paint(structure.getGraphics()); + pack(); + } else if (s.equals("CSD")) { + // TO ADD ACTION CORR TO CSD! + callDatabase = 2; //this variable is used directly by the indianawindow class + + + //System.out.println("*** I am in CSD ***"); + +// indiana = new indianaWindow(nano); +// indiana.setVisible(true); +// //Now indianaWindow calls a cgi script which will put the appropriate pdb file in /work/csd/temp/csdsearch-.mol2 so we need toload that file. +// +// this.setVisible(false); +// // Check if foll code needed ! +// addWindowListener(new WindowAdapter() { +// public void windowClosing(WindowEvent e) { +// setVisible(false); +// } +// }); +// structure.paint(structure.getGraphics()); +// pack(); + + CSDSearch csdSearch = new CSDSearch(new JFrame(), true, nano); + csdSearch.setLocationRelativeTo(null); + this.dispose(); + csdSearch.setVisible(true); + } else if (s.equals("Load saved file")) { + if (!runAsApplication) { + browser = new java.awt.List(50, false); + String dirName = "/work/csd/temp/" + getParameter("username") + "/"; + getFilesInDirectory(browser, dirName); + + try { + String username = getParameter("username"); + String dirname = "http://pine.ncsa.uiuc.edu/csd/temp/" + username + "/"; + //System.out.println("Creating display."); + dis = new display(nano, browser, dirname, username); + dis.setVisible(true); + //System.out.println("Sending List."); + + // Now the above code whn repainted will produce file browser window + } catch (Exception e1) { + System.err.println(e1); + } + + browser.setVisible(true); + } else { + FileDialog f = new FileDialog(this, "Load File", FileDialog.LOAD); + f.show(); + String file = f.getFile(); + String directory = f.getDirectory(); + loadFile(file, directory); + + //lixh_4/30/05 + atomInfoBlab.setText("Show atom information here "); + instrucaba.setWarning(false); + + this.repaint(); + // + } + } else if (s.equals("Select")) { + //popup.show(elementLabel, 0, 0); + try { + AtomDataFile dFile = new AtomDataFile(newNanocad.txtDir + + newNanocad.fileSeparator + "pdata.txt"); + //AtomDataFile dFile = new AtomDataFile("pdata.txt"); + String symbol = elementField.getText(); + if (symbol.length() == 1) + symbol.toUpperCase(); + if (dFile.findData(symbol, 4)) { + GeneralAtom selected = new GeneralAtom(); + selected.setName(dFile.parseString(3)); + selected.setSymbol(dFile.parseString(4)); + selected.setAtomicNumber(dFile.parseInt(0)); + selected.setMass(dFile.parseDouble(5)); + selected.setColor(new Color(dFile.parseInt(6), dFile.parseInt(7), dFile.parseInt(8))); + selected.setCovalentRadius(dFile.parseDouble(9)); + selected.setVdwEnergy(dFile.parseDouble(10)); + selected.setVdwRadius(dFile.parseDouble(11)); + selected.setCorrectNumBonds(dFile.parseInt(12)); + currentAtomType = selected; + currentElement.setText("Current Element: " + symbol); + } + } catch (IOException er) { + er.printStackTrace(); + } + } else { + //for url only + if (s.charAt(0) == ' ') s = s.substring(1, s.length()); + String name = s; + MenuItem temp = (MenuItem) ((MenuItem) e.getSource()).getParent(); + + do { + if (runAsApplication) name = temp.getLabel() + sepStr + name; + else name = temp.getLabel() + "/" + name; + if ((((Object) temp.getParent()).toString()).equals("NcadMenu")) + break; + //System.out.println(((Object)temp.getParent()).toString()); + temp = (MenuItem) temp.getParent(); + } while (true); + + if (!runAsApplication) + loadFile(name, "/work/chemviz/mol2/"); + else { + //lixh_4/27/05 + //loadFile(pathvar+sepStr+"common"+sepStr+name, ""); + loadFile(applicationDataDir + fileSeparator + "common" + fileSeparator + name, ""); + //lixh_4/30/05 + atomInfoBlab.setText("Show atom information here "); + instrucaba.setWarning(false); + + this.repaint(); + } + } + } + } + + //Andrew Knox 06/01/01 + public double calculateBondLength() { + double p[] = {0.0, 0.0, 0.0}; + double q[] = {0.0, 0.0, 0.0}; + double length; + + for (int i = 0; i < 3; i++) { + p[i] = ((atom) selectedAtomList.elementAt(0)).x[i]; + q[i] = ((atom) selectedAtomList.elementAt(1)).x[i]; + } + + length = Math.sqrt(Math.pow(q[0] - p[0], 2) + Math.pow(q[1] - p[1], 2) + Math.pow(q[2] - p[2], 2)); + return length; + } + + //Andrew Knox 06/01/01 + public double calculateBondAngle() { + double angle, dotproduct, normpq, normqr; + double p[] = {0.0, 0.0, 0.0}; + double q[] = {0.0, 0.0, 0.0}; + double r[] = {0.0, 0.0, 0.0}; + double pq[] = {0.0, 0.0, 0.0}; + double qr[] = {0.0, 0.0, 0.0}; + + for (int i = 0; i < 3; i++) { + p[i] = ((atom) selectedAtomList.elementAt(0)).x[i]; + q[i] = ((atom) selectedAtomList.elementAt(1)).x[i]; + r[i] = ((atom) selectedAtomList.elementAt(2)).x[i]; + + pq[i] = p[i] - q[i]; //this order might not be right + qr[i] = r[i] - q[i]; + } + + dotproduct = pq[0] * qr[0] + pq[1] * qr[1] + pq[2] * qr[2]; + normpq = Math.sqrt(Math.pow(pq[0], 2) + Math.pow(pq[1], 2) + Math.pow(pq[2], 2)); + normqr = Math.sqrt(Math.pow(qr[0], 2) + Math.pow(qr[1], 2) + Math.pow(qr[2], 2)); + + angle = Math.acos(dotproduct / (normpq * normqr)); + angle = angle / Math.PI * 180; //convert to degrees + return angle; + } + + protected double[] crossProduct(double[] x, double[] y) { + double[] z = new double[3]; + z[0] = x[1] * y[2] - x[2] * y[1]; + z[1] = x[2] * y[0] - x[0] * y[2]; + z[2] = x[0] * y[1] - x[1] * y[0]; + return z; + } + + protected double dotProduct(double[] x, double[] y) { + return x[0] * y[0] + x[1] * y[1] + x[2] * y[2]; + } + + // Jeff Stenhouse 02/03/03 + public double calculateDihedral() { + double dihedral, dp2, dotProduct; + double pq[] = {0.0, 0.0, 0.0}; + double qr[] = {0.0, 0.0, 0.0}; + double rs[] = {0.0, 0.0, 0.0}; + double normal[] = {0.0, 0.0, 0.0}; + double normal2[] = {0.0, 0.0, 0.0}; + + for (int i = 0; i < 3; i++) { + pq[i] = ((atom) selectedAtomList.elementAt(0)).x[i] - ((atom) selectedAtomList.elementAt(1)).x[i]; + qr[i] = ((atom) selectedAtomList.elementAt(1)).x[i] - ((atom) selectedAtomList.elementAt(2)).x[i]; + rs[i] = ((atom) selectedAtomList.elementAt(2)).x[i] - ((atom) selectedAtomList.elementAt(3)).x[i]; + } + + normal = crossProduct(pq, qr); + normal2 = crossProduct(qr, rs); + dotProduct = dotProduct(normal, normal); // length^2 of normal + dp2 = dotProduct(normal2, normal2); // length^2 of normal2 + dihedral = dotProduct(normal, normal2); // |normal|*|normal2|*cos(theta) + dihedral = dihedral / (Math.sqrt(dotProduct * dp2)); // normalizing + dihedral = Math.acos(dihedral); + double direction = dotProduct(crossProduct(normal, normal2), ((atom) selectedAtomList.elementAt(1)).x); + if (direction < 0) dihedral = -dihedral; + return 180 * dihedral / Math.PI; + } + + // Written by Jeff Stenhouse on 13 Jan 02 + // Adds hydrogens based on valences. For the lazy people :) + public void addHydrogens() { + updateUndo(); +/* isUFF = false; + ffSelect.select(1); + newFF = true; +*/ + for (int i = 0; i < grp.atomList.size(); i++) { + atom currAtom = ((atom) grp.atomList.elementAt(i)); + int atomNumber = currAtom.atomicNumber(); +/* if(atomNumber == 13 || (atomNumber > 20 && atomNumber < 33) || + (atomNumber > 38 && atomNumber < 52) || + (atomNumber > 56 && atomNumber < 85) || atomNumber > 88) + { isUFF = true; + ffSelect.select(2); + } +*/ + if ((currAtom.correctNumBonds() > currAtom.currentNumBonds()) && + atomNumber != 1) { + int numHydro = currAtom.correctNumBonds() - currAtom.currentNumBonds(); + for (int k = 0; k < numHydro; k++) { + GeneralAtom newAtom = new GeneralAtom(); + newAtom.setName("Hydrogen"); + newAtom.setSymbol("H"); + newAtom.setAtomicNumber(1); + newAtom.setMass(1.007); + newAtom.setColor(new Color(255, 255, 255)); + newAtom.setCovalentRadius(.3); + newAtom.setVdwEnergy(.382); + newAtom.setVdwRadius(1.2); + newAtom.setCorrectNumBonds(1); + double pos[] = new double[numHydro * 3]; + Random rn = new Random(System.currentTimeMillis() * (currAtom.atomicNumber() + (k * i * i * i + (k + 1)))); + pos[3 * k + 0] = rn.nextGaussian(); + pos[3 * k + 1] = rn.nextGaussian(); + pos[3 * k + 2] = rn.nextGaussian(); + double length = Math.sqrt(pos[3 * k + 0] * pos[3 * k + 0] + + pos[3 * k + 1] * pos[3 * k + 1] + pos[3 * k + 2] * pos[3 * k + 2]); + pos[3 * k + 0] = pos[3 * k + 0] * 1.1 / length + currAtom.x[0]; + pos[3 * k + 1] = pos[3 * k + 1] * 1.1 / length + currAtom.x[1]; + pos[3 * k + 2] = pos[3 * k + 2] * 1.1 / length + currAtom.x[2]; + grp.addAtom(newAtom, pos[3 * k + 0], pos[3 * k + 1], pos[3 * k + 2]); + grp.addBond(newAtom, currAtom); + } + } + } + energyMinimize(false); + } + + public void updateUndo() { + undoGroup.copy(grp); + } + + //lixh_3_4_05 + public String GaussianOutput(String molInfo) { + String templateTop = "%nprocshared=1\n" + + "#P RHF/6-31g* Opt gfinput gfprint iop(6/7=3)" + + " scf=conventional\n" + " \n" + + "Gaussian Template from GridChem\n" + + "Molecule Built by NCSA-Nanocad \n" + " \n" + + "0 1\n"; + //ArrayList molInfsplit = (ArrayList) Arrays.asList(molInfo.split("\n")); + + //added by Shashank and Sandeep@ CCS,UKY +// FIXME-SEAGrid +// if(stuffInside.selectedGUI==1) +// { // G03InputGUI selected.. default template should be null + templateTop = ""; +// } + + + String text = templateTop; + StringTokenizer molTok = new StringTokenizer(molInfo, "\n"); + //int n = molInfsplit.size(); + //int i; + // ignore first line of molInfo + String line = molTok.nextToken(); + int i = 0; + while (molTok.hasMoreTokens()) { + line = molTok.nextToken(); + if ((line.length() > 0) && (i > 0)) { + text = text + line + "\n"; + System.err.println(line); + } + i++; + } + return text; + } + + public String NWchemOutput(String molInfo) { + String templateTop = "start \n" + "\n"; + String templateBottom = "task scf optimize \n" + "\n"; + + String text = templateTop; + text = text + "geometry units angstroms \n"; + StringTokenizer molTok = new StringTokenizer(molInfo, "\n"); + //int n = molInfsplit.size(); + //int i; + // ignore first line of molInfo + String line = molTok.nextToken(); + int i = 0; + while (molTok.hasMoreTokens()) { + line = molTok.nextToken(); + if ((line.length() > 0) && (i > 0)) { + text = text + line + "\n"; + System.err.println(line); + } + i++; + } + text = text + "end \n" + "\n"; + text = text + templateBottom; + + return text; + } + + public String PSI4Output(String molInfo) { + String text; + String templateTop = "#SEAGrid PSI4 Template Title\n" + + "memory 2gb \n"; + //+ "set basis cc-pVDZ \n" + "gprint,basis,orbital,civector; \n"; + + + text = templateTop; + text = text + "molecule { \n"; + StringTokenizer molTok = new StringTokenizer(molInfo, "\n"); + //int n = molInfsplit.size(); + //int i; + // ignore first line of molInfo + String line = molTok.nextToken(); + int i = 0; + while (molTok.hasMoreTokens()) { + line = molTok.nextToken(); + if ((line.length() > 0) && (i > 0)) { + text = text + line + "\n"; + System.err.println(line); + } + i++; + } + text = text + " } \n"; + String templateSettings; + templateSettings = "set {\n" + + "basis cc-pVDZ \n" + + "e_convergence 10 \n" + + "d_convergence 10 \n"; + //text = "It has not been supported yet. \n" + //+ "Please type input by yourself"; + text = text + templateSettings; + text = text + " } \n"; + String templateRun; + templateRun = "set qc_module detci \n" + + "thisenergy = optimize('cisd', dertype = 0) \n"; + text = text + templateRun; + + return text; + } + + public String MolcasOutput(String molInfo) { + String text; + String templateTop = "*SEAGrid Molcas Template Title\n" + + "&gateway \n" + + //"TITLE Molcas Run \n" + + " "; + //+ "set basis cc-pVDZ \n" + "gprint,basis,orbital,civector; \n"; + + + text = templateTop; + text = text + "Coord \n"; + StringTokenizer molTok = new StringTokenizer(molInfo, "\n"); + //int n = molInfsplit.size(); + //int i; + // ignore first line of molInfo + String line = molTok.nextToken(); + int i = 0; + String coords = ""; + while (molTok.hasMoreTokens()) { + line = molTok.nextToken(); + if ((line.length() > 0) && (i > 0)) { + coords = coords + line + "\n"; + System.err.println(line); + } + i++; + } + i=i-1; + text = text + i +" \n"; + text = text + " Angstroms \n"; + text = text + coords +" \n"; + String templateSettings; + templateSettings = "Basis=cc-pVDZ \n" + + "Group=Nosym \n" + + "\n"; + //text = "It has not been supported yet. \n" + //+ "Please type input by yourself"; + text = text + templateSettings; + text = text + ">> Do While \n"; + String templateRun; + templateRun = " \n" + + "&seward \n" + + "&scf \n" + + "Charge=0 \n" + + "Spin=1 \n" + + "\n" + + "&mp2 \n" + + "&slapaf \n" + + " \n"+ + ">>> EndDo"; + text = text + templateRun; + + return text; + } + + public String MolproOutput(String molInfo) { + String text; + String templateTop = "***,GridChem Molpro (SCF,MP2,CASSCF and properties) Template Title\n" + + "memory,500,m \n" + + "basis=aug-cc-pVDZ \n" + + "gprint,basis,orbital,civector; \n"; + + + text = templateTop; + text = text + "geometry={ \n"; + StringTokenizer molTok = new StringTokenizer(molInfo, "\n"); + //int n = molInfsplit.size(); + //int i; + // ignore first line of molInfo + String line = molTok.nextToken(); + int i = 0; + while (molTok.hasMoreTokens()) { + line = molTok.nextToken(); + if ((line.length() > 0) && (i > 0)) { + text = text + line + "\n"; + System.err.println(line); + } + i++; + } + text = text + " } \n"; + String templateBottom; + templateBottom = "hf \n" + + "optg \n" + + "method,diis !Optimization method: Geometry DIIS \n" + + "mp2 !mp2 calculation \n" + + "forces !mp2 gradients \n" + + "property { !call property program \n" + + "orbital !read mp2 orbitals \n" + + "density !read mp2 density \n " + + "dm !compute dipole moments and print orbital contributions \n" + + "qm } !compute quadrupole moments and print orbital contributions \n" + + "{multi;state,2;dm !do full-valence CASSCF \n" + + "natorb,state=1.1 !compute natural orbitals for state 1.1 \n" + + "natorb,state=2.1} !compute natural orbitals for state 2.1 \n" + + "{property !call property program \n" + + "orbital,state=1.1 !read casscf natural orbitals for state 1.1 \n" + + "density,state=1.1 !read casscf density matrix for state 1.1 \n" + + "dm !compute dipole moments and print orbital contributions \n" + + "qm} !compute quadrupole moments and print orbital contributions \n" + + "forces !casscf gradient \n"; + //text = "It has not been supported yet. \n" + //+ "Please type input by yourself"; + text = text + templateBottom; + return text; + } + + public String GamessOutput(String molInfo) { + String templateTop = + " $CONTRL SCFTYP=RHF RUNTYP=OPTIMIZE NZVAR=5 $END\n" + + " $SYSTEM TIMLIM=20 MEMORY=500000 $END\n" + + " $DFT DFTTYP=SVWN $END\n" + + " $BASIS GBASIS=N31 NGAUSS=6 NDFUNC=1 $END\n" + + " $GUESS GUESS=HUCKEL $END\n" + + " $STATPT OPTTOL=0.00001 $END\n" + + " $DATA\n" + + "Acetylene geometry optimization in internal coordinates\n" + + "Dnh 4\n"; + + String templateBottom = + " $END\n" + + " $ZMAT IZMAT(1)=1,1,2, 1,1,3, 1,2,4,\n" + + " 5,1,2,4, 5,2,1,3 $END\n" + + "------- XZ is 1st plane for both bends -------\n" + + " $LIBE APTS(1)=1.0,0.0,0.0,1.0,0.0,0.0 $END\n"; + +// FIXME-SEAGrid +// if(stuffInside.selectedGUI == 1) +// { +// templateTop = templateBottom = ""; +// } + String text = templateTop; + String text1 = ""; + StringTokenizer molTok = new StringTokenizer(molInfo, "\n"); + // ignore first line of molInfo + String line = molTok.nextToken(); + int i = 0; + while (molTok.hasMoreTokens()) { + line = molTok.nextToken(); + if ((line.length() > 0) && (i > 0)) { + StringTokenizer lineTok = new StringTokenizer(line); + int j = 0; + while (lineTok.hasMoreTokens()) { + String word = lineTok.nextToken(); + text = text + " " + word; + text1 = text1 + " " + word; + System.err.println(word); + if (j == 0) { + int atomnum = lookupAtomNum(word); + text = text + " " + atomnum; + text1 = text1 + " " + atomnum; + System.err.println(atomnum); + } + j++; + } + text = text + "\n"; + text1 = text1 + "\n"; + System.err.println(line); + } + i++; + } + text = text + templateBottom; + return text; + } + + public String GamessCoordOutput(String molInfo) { + +// FIXME-SEAGrid +// if(stuffInside.selectedGUI == 1) +// { +// templateTop = templateBottom = ""; +// } + //String text = templateTop; + String text1 = ""; + StringTokenizer molTok = new StringTokenizer(molInfo, "\n"); + // ignore first line of molInfo + String line = molTok.nextToken(); + int i = 0; + while (molTok.hasMoreTokens()) { + line = molTok.nextToken(); + if ((line.length() > 0) && (i > 0)) { + StringTokenizer lineTok = new StringTokenizer(line); + int j = 0; + while (lineTok.hasMoreTokens()) { + String word = lineTok.nextToken(); + //text = text + " " + word; + text1 = text1 + " " + word; + System.err.println(word); + if (j == 0) { + int atomnum = lookupAtomNum(word); + //text = text + " " + atomnum; + text1 = text1 + " " + atomnum; + System.err.println(atomnum); + } + j++; + } + //text = text + "\n"; + text1 = text1 + "\n"; + System.err.println(line); + } + i++; + } + //text = text + templateBottom; + return text1; + } + + public int lookupAtomNum(String atomname) { + int ressnum = 0; + if (atomname.equals("H")) { + ressnum = 1; + } else if (atomname.equals("HE")) { + ressnum = 2; + } else if (atomname.equals("LI")) { + ressnum = 3; + } else if (atomname.equals("BE")) { + ressnum = 4; + } else if (atomname.equals("B")) { + ressnum = 5; + } else if (atomname.equals("C")) { + ressnum = 6; + } else if (atomname.equals("N")) { + ressnum = 7; + } else if (atomname.equals("O")) { + ressnum = 8; + } else if (atomname.equals("F")) { + ressnum = 9; + } else if (atomname.equals("NE")) { + ressnum = 10; + } else if (atomname.equals("NA")) { + ressnum = 11; + } else if (atomname.equals("MG")) { + ressnum = 12; + } else if (atomname.equals("AL")) { + ressnum = 13; + } else if (atomname.equals("SI")) { + ressnum = 14; + } else if (atomname.equals("P")) { + ressnum = 15; + } else if (atomname.equals("S")) { + ressnum = 16; + } else if (atomname.equals("CL")) { + ressnum = 17; + } else if (atomname.equals("AR")) { + ressnum = 18; + } else if (atomname.equals("K")) { + ressnum = 19; + } else if (atomname.equals("CA")) { + ressnum = 20; + } else if (atomname.equals("SC")) { + ressnum = 21; + } else if (atomname.equals("TI")) { + ressnum = 22; + } else if (atomname.equals("V")) { + ressnum = 23; + } else if (atomname.equals("CR")) { + ressnum = 24; + } else if (atomname.equals("MN")) { + ressnum = 25; + } else if (atomname.equals("FE")) { + ressnum = 26; + } else if (atomname.equals("CO")) { + ressnum = 27; + } else if (atomname.equals("NI")) { + ressnum = 28; + } else if (atomname.equals("CU")) { + ressnum = 29; + } else if (atomname.equals("ZN")) { + ressnum = 30; + } else if (atomname.equals("GA")) { + ressnum = 31; + } else if (atomname.equals("GE")) { + ressnum = 32; + } else if (atomname.equals("AS")) { + ressnum = 33; + } else if (atomname.equals("SE")) { + ressnum = 34; + } else if (atomname.equals("BR")) { + ressnum = 35; + } else if (atomname.equals("KR")) { + ressnum = 36; + } else if (atomname.equals("RB")) { + ressnum = 37; + } else if (atomname.equals("SR")) { + ressnum = 38; + } else if (atomname.equals("Y")) { + ressnum = 39; + } else if (atomname.equals("ZR")) { + ressnum = 40; + } else if (atomname.equals("NB")) { + ressnum = 41; + } else if (atomname.equals("MO")) { + ressnum = 42; + } else if (atomname.equals("TC")) { + ressnum = 43; + } else if (atomname.equals("RU")) { + ressnum = 44; + } else if (atomname.equals("RH")) { + ressnum = 45; + } else if (atomname.equals("PD")) { + ressnum = 46; + } else if (atomname.equals("AG")) { + ressnum = 47; + } else if (atomname.equals("CD")) { + ressnum = 48; + } else if (atomname.equals("IN")) { + ressnum = 49; + } else if (atomname.equals("SN")) { + ressnum = 50; + } else if (atomname.equals("SB")) { + ressnum = 51; + } else if (atomname.equals("TE")) { + ressnum = 52; + } else if (atomname.equals("I")) { + ressnum = 53; + } else if (atomname.equals("XE")) { + ressnum = 54; + } else if (atomname.equals("CS")) { + ressnum = 55; + } else if (atomname.equals("BA")) { + ressnum = 56; + } else if (atomname.equals("LA")) { + ressnum = 57; + } else if (atomname.equals("CE")) { + ressnum = 58; + } else if (atomname.equals("PR")) { + ressnum = 59; + } else if (atomname.equals("ND")) { + ressnum = 60; + } else if (atomname.equals("PM")) { + ressnum = 61; + } else if (atomname.equals("SM")) { + ressnum = 62; + } else if (atomname.equals("EU")) { + ressnum = 63; + } else if (atomname.equals("GD")) { + ressnum = 64; + } else if (atomname.equals("TB")) { + ressnum = 65; + } else if (atomname.equals("DY")) { + ressnum = 66; + } else if (atomname.equals("HO")) { + ressnum = 67; + } else if (atomname.equals("ER")) { + ressnum = 68; + } else if (atomname.equals("TM")) { + ressnum = 69; + } else if (atomname.equals("YB")) { + ressnum = 70; + } else if (atomname.equals("LU")) { + ressnum = 71; + } else if (atomname.equals("HF")) { + ressnum = 72; + } else if (atomname.equals("TA")) { + ressnum = 73; + } else if (atomname.equals("W")) { + ressnum = 74; + } else if (atomname.equals("RE")) { + ressnum = 75; + } else if (atomname.equals("OS")) { + ressnum = 76; + } else if (atomname.equals("IR")) { + ressnum = 77; + } else if (atomname.equals("PT")) { + ressnum = 78; + } else if (atomname.equals("AU")) { + ressnum = 79; + } else if (atomname.equals("HG")) { + ressnum = 80; + } else if (atomname.equals("TI")) { + ressnum = 81; + } else if (atomname.equals("PB")) { + ressnum = 82; + } else if (atomname.equals("BI")) { + ressnum = 83; + } else if (atomname.equals("PO")) { + ressnum = 84; + } else if (atomname.equals("AT")) { + ressnum = 85; + } else if (atomname.equals("RN")) { + ressnum = 86; + } else if (atomname.equals("FR")) { + ressnum = 87; + } else if (atomname.equals("RA")) { + ressnum = 88; + } else if (atomname.equals("AC")) { + ressnum = 89; + } else if (atomname.equals("TH")) { + ressnum = 90; + } else if (atomname.equals("PA")) { + ressnum = 91; + } else if (atomname.equals("U")) { + ressnum = 92; + } else if (atomname.equals("NP")) { + ressnum = 93; + } else if (atomname.equals("PU")) { + ressnum = 94; + } else if (atomname.equals("AM")) { + ressnum = 95; + } else if (atomname.equals("CM")) { + ressnum = 96; + } else if (atomname.equals("BK")) { + ressnum = 97; + } else if (atomname.equals("CF")) { + ressnum = 98; + } else if (atomname.equals("ES")) { + ressnum = 99; + } else if (atomname.equals("FM")) { + ressnum = 100; + } else if (atomname.equals("MD")) { + ressnum = 101; + } else if (atomname.equals("NO")) { + ressnum = 102; + } else if (atomname.equals("LR")) { + ressnum = 103; + } else if (atomname.equals("RF")) { + ressnum = 104; + } else if (atomname.equals("DB")) { + ressnum = 105; + } else if (atomname.equals("SG")) { + ressnum = 106; + } else if (atomname.equals("BH")) { + ressnum = 107; + } else if (atomname.equals("HS")) { + ressnum = 108; + } else if (atomname.equals("MT")) { + ressnum = 109; + } + return ressnum; + } + +} + diff --git a/src/main/java/nanocad/nitrogen.java b/src/main/java/nanocad/nitrogen.java new file mode 100644 index 0000000..7d7f5f0 --- /dev/null +++ b/src/main/java/nanocad/nitrogen.java @@ -0,0 +1,87 @@ +package nanocad; + +/** + * nitrogen.java + * Copyright (c) 1997 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * or its derived works must display the following acknowledgement: + * This product includes software developed by Will Ware. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.awt.Color; + +public class nitrogen extends atom +{ + public static final String rcsid = + "$Id: nitrogen.java,v 1.2 2005/05/14 23:51:01 xli16 Exp $"; + public nitrogen () + { + double newx[] = { 0.0, 0.0, 0.0 }; + x = newx; + hybridization = SP3; + } + public nitrogen (double x0, double x1, double x2) + { + double newx[] = { x0, x1, x2 }; + x = newx; + hybridization = SP3; + } + public nitrogen (int h, double x0, double x1, double x2) + { + double newx[] = { x0, x1, x2 }; + x = newx; + hybridization = h; + } + public int atomicNumber () { return 7; } + public Color color () { return Color.blue; } + public int correctNumBonds () { return 3; } + public double covalentRadius () + { + switch (hybridization) + { + default: + case SP3: return 0.74; + case SP2: return 0.62; + case SP: return 0.55; + } + } + public double mass () { return 14.0; } + public String name () { return "Nitrogen"; } + public void rehybridize () // based on number of bonds + { + switch (currentSigmaBonds ()) + { + default: + case 3: hybridization = SP3; break; + case 2: hybridization = SP2; break; + case 1: hybridization = SP; break; + } + } + public void rehybridize (int hybrid) + { + hybridization = hybrid; + } + public String symbol () { return "N"; } + public double vdwEnergy () { return 0.447; } + public double vdwRadius () { return 1.5; } +} diff --git a/src/main/java/nanocad/opensavedPDB.java b/src/main/java/nanocad/opensavedPDB.java new file mode 100644 index 0000000..124a426 --- /dev/null +++ b/src/main/java/nanocad/opensavedPDB.java @@ -0,0 +1,166 @@ +//can be deleted if display.java works +package nanocad; +import java.awt.event.*; +import java.awt.*; +import java.io.*; +import java.lang.*; +import java.net.*; + +public class opensavedPDB extends Frame { + Panel plMain = new Panel(); + TextField Formula = new TextField(7); + TextField CompoundName = new TextField(7); + Label lCompoundName = new Label("Compound Name: ",Label.RIGHT); + Label lFormula = new Label("Formula: ",Label.RIGHT); + Button okbutt = new Button("OK"); + Button close = new Button("Close"); + textwin saveWin; + private Indiana ind; + private newNanocad nano; + + public opensavedPDB(newNanocad n1) { + + nano = n1; + + + enableEvents(AWTEvent.WINDOW_EVENT_MASK); + try { + jbInit(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + private void jbInit() throws Exception { +// this.setTitle("indianadata"); + if(nano.callDatabase == 1) + this.setTitle("Indiana Database Search"); + if(nano.callDatabase == 2) + this.setTitle("CSD Search"); + + this.add(plMain,null);//.getContentPane().add(plMain, null); +// this.getContentPane().setLayout(null); + this.setSize(new Dimension(400,250)); + plMain.setLayout(null); + plMain.add(CompoundName,null); + plMain.add(Formula,null); + plMain.add(lCompoundName,null); + plMain.add(lFormula,null); + plMain.add(okbutt, null); + plMain.add(close,null); + lFormula.setBounds(new Rectangle(34, 22, 60, 20)); + Formula.setBounds(new Rectangle(174, 22, 70, 20)); + lCompoundName.setBounds(new Rectangle(34, 52, 110, 20)); + CompoundName.setBounds(new Rectangle(174, 52, 70, 20)); + okbutt.setFont(new Font("SansSerif", 1, 12)); + okbutt.setBounds(new Rectangle(86, 100, 81, 25)); + okbutt.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + okbutt_actionPerformed(e); + } + }); + + close.setFont(new Font("SansSerif", 1, 12)); + close.setBounds(new Rectangle(166, 100, 81, 25)); + close.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + close_actionPerformed(e); + } + }); + } + + void close_actionPerformed(ActionEvent e) +{ + this.dispose(); +} + void okbutt_actionPerformed(ActionEvent e) + { + String formu = Formula.getText(); + String comp = CompoundName.getText(); + + String chk = "5"; + String encodedchk = null; + + /*Generate query as required by Indiana Database and pass it to them, + obtain PDB file and reload PDB in nanocad interface */ + + + // if(CompoundName.getText() != "") + if( comp.length() > 1) + chk = "0"; + else if(Formula.getText() != "") + { + chk = "1"; + //Process formula string + } + + + // To use CGI script to call Indiana.java and also to pass values of + // compound name and formula + + String encodedCompoundName = URLEncoder.encode(CompoundName.getText()); + String encodedFormula = URLEncoder.encode(Formula.getText()); + encodedchk = URLEncoder.encode(chk); + String databasecgi = null; + try{ + if(nano.callDatabase == 1) + databasecgi= "http://chemviz.ncsa.uiuc.edu/cgi-bin/nanocad/indiana.cgi"; + + System.out.println("Before calling csd.cgi"); + if(nano.callDatabase == 2) + databasecgi= "http://chemviz.ncsa.uiuc.edu/cgi-bin/nanocad/csd.cgi"; + + URL urlcgi = new URL(databasecgi); + URLConnection conn1 = urlcgi.openConnection(); + conn1.setDoOutput(true); + PrintWriter out1 = new PrintWriter(conn1.getOutputStream()); + if(chk.equals("0")) + out1.println(encodedCompoundName + "= 0"); + else + if(chk.equals("1")) + out1.println(encodedFormula + "= 1"); + +/* +//CHK if following needed I doubt! + if(Formula.getText() != "") + out1.println(encodedFormula + "= 1"); + if(CompoundName.getText() != "") + { + out1.println(encodedCompoundName + "= 0"); + } +//CHK if following needed I doubt! TILL HERE +*/ + out1.close(); + + + //Reading file from the cgi output + String line = null; + BufferedReader inStr1 = new BufferedReader (new InputStreamReader(conn1.getInputStream())); + String b = ""; + while ((line = inStr1.readLine()) !=null) + { + System.out.println(line); + b = b + line; + } + inStr1.close(); + + + + nano.drawFile(b); + + }catch(MalformedURLException mx){ + saveWin = new textwin("URL Exception","",false); + saveWin.setVisible(true); + saveWin.setText("Exception : "+ mx.toString()); + }catch ( IOException e1){ + saveWin = new textwin("IO Exception","",false); + saveWin.setVisible(true); + saveWin.setText("Exception : "+e1.toString()); + } + + this.dispose(); + } + +} + diff --git a/src/main/java/nanocad/oxygen.java b/src/main/java/nanocad/oxygen.java new file mode 100644 index 0000000..ca18509 --- /dev/null +++ b/src/main/java/nanocad/oxygen.java @@ -0,0 +1,99 @@ +package nanocad; + +/** + * oxygen.java + * Copyright (c) 1997 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * or its derived works must display the following acknowledgement: + * This product includes software developed by Will Ware. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.awt.Color; + +public class oxygen extends atom +{ + public static final String rcsid = + "$Id: oxygen.java,v 1.2 2005/05/14 23:51:01 xli16 Exp $"; + public static String ename = "Oxygen"; + public static String symbol = "O"; + public static int atomicNumber = 8; + public static double mass = 16.0; + public static Color color = Color.red; + public static double vdwRadius = 1.4; + public static int expectedNumBonds = 2; + public oxygen () + { + double newx[] = { 0.0, 0.0, 0.0 }; + x = newx; + hybridization = SP3; + } + public oxygen (double x0, double x1, double x2) + { + double newx[] = { x0, x1, x2 }; + x = newx; + hybridization = SP3; + } + public oxygen (int h, double x0, double x1, double x2) + { + double newx[] = { x0, x1, x2 }; + x = newx; + hybridization = h; + } + public int atomicNumber () { return 8; } + public Color color () { return Color.red; } + public int correctNumBonds () { return 2; } + public double covalentRadius () + { + switch (hybridization) + { + default: + case SP3: return 0.74; + case SP2: return 0.62; + case SP: return 0.55; + } + } + public double mass () { return 16.0; } + public String name () { return "Oxygen"; } + public void rehybridize () + { + switch (currentSigmaBonds ()) + { + default: + case 2: hybridization = SP3; break; + case 1: hybridization = SP2; break; + } + } + public void rehybridize (int hybrid) + { + hybridization = hybrid; + } + public String symbol () { return "O"; } + public double vdwEnergy () + { + if (hybridization == SP3) + return 0.406; + else + return 0.536; + } + public double vdwRadius () { return 1.4; } +} diff --git a/src/main/java/nanocad/partzip/nc112202.zip b/src/main/java/nanocad/partzip/nc112202.zip new file mode 100644 index 0000000..41fb17e Binary files /dev/null and b/src/main/java/nanocad/partzip/nc112202.zip differ diff --git a/src/main/java/nanocad/savewin.java b/src/main/java/nanocad/savewin.java new file mode 100644 index 0000000..5052137 --- /dev/null +++ b/src/main/java/nanocad/savewin.java @@ -0,0 +1,171 @@ +package nanocad; + +/** + * textwin.java - pop up a new frame to read or write text + * Copyright (c) 1998 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * or its derived works must display the following acknowledgement: + * This product includes software developed by Will Ware. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.awt.*; + +public class savewin extends Frame implements java.awt.event.ActionListener +{ + protected String contents = "Here's a debug window\n"; + protected TextField textWindow; + protected boolean editable, visible; + private Button cancel, save; + protected Label name; + private group grp; + public newNanocad nano; + public String urlname; + public boolean flag = false; + public savewin () + { + /* this one is only for inheritance purposes */ + } + + public savewin (String title, String initialContent, boolean edtbl, newNanocad n) + { + Panel p1 = new Panel(); + Panel p2 = new Panel(); + nano = n; + editable = edtbl; + visible = false; + setTitle (title); + contents = initialContent; + name = new Label("Enter the name of file to save"); + textWindow = new TextField ("", 8); + //textWindow.setText (contents); + //textWindow.setEditable (true); + p1.add("WEST",name); + p1.add ("North", textWindow); + cancel = new Button("Cancel"); + cancel.addActionListener(this); + + p2.add ("West", cancel); + save = new Button("Save"); + save.addActionListener(this); + + p2.add ("East", save); + add("North", p1); + add("South", p2); + resize (350, 150); + //setSize(600,600); + addWindowListener(new java.awt.event.WindowAdapter() { + public void windowClosing(java.awt.event.WindowEvent e){ + ((Window)e.getWindow()).dispose(); + } + }); + } + + //Ying, no, this is the one really invoked for handling the events; + public void actionPerformed(java.awt.event.ActionEvent e){ + String s = e.getActionCommand(); + if(s.equals("Cancel")) { + update(); + this.dispose(); + + if (grp != null) + grp.textWindowNotify(contents); + }else if (s.equals("Save")) { + update(); + urlname="http://pine.ncsa.uiuc.edu/cgi-bin/savepdb.cgi"; + nano.sendFile(urlname, ((group)nano.getGroup()).getPDB(true), (String)textWindow.getText() + ".pdb"); + this.dispose(); + } + } + + public void changeSize(int w, int h){ + resize(w,h); + } + + public void clear() + { + contents = ""; + textWindow.setText (contents); + } + + public String getText() + { + update(); + return contents; + } + + public boolean isEditable() + { + return editable; + } + public boolean isVisible() + { + return visible; + } + public void setEditable(boolean e) + { + editable = e; + textWindow.setEditable(editable); + } + + public void setGroup(group g) + { + grp = g; + } + + public void setText(String s) + { + clear(); + write(s); + } + public void setVisible(boolean v) + { + visible = v; + if (v) + show(); + else + hide(); + } + + public void update() + { + if (editable) //for SaveXYZ or PDB, this should be false; + contents = textWindow.getText(); + } + + public void write(double x) + { + contents = contents + (new Double(x)).toString(); + textWindow.setText (contents); + } + + public void write(int x) + { + contents = contents + (new Integer(x)).toString(); + textWindow.setText (contents); + } + public void write(String s) + { + contents = contents + s; + textWindow.setText (contents); + } +} diff --git a/src/main/java/nanocad/searchResult.java b/src/main/java/nanocad/searchResult.java new file mode 100644 index 0000000..351aeb7 --- /dev/null +++ b/src/main/java/nanocad/searchResult.java @@ -0,0 +1,139 @@ +package nanocad; + +import java.awt.event.*; +import java.awt.*; +import java.io.*; +import java.lang.*; +import java.util.*; +import java.awt.List; + +public class searchResult extends Frame { + public int newget; + public boolean flag = true; + public String smallad, get, header; + public String pdbfiles, outfile; + public BufferedReader in1; + public StringTokenizer l; + public newNanocad nano; + Panel plMain = new Panel(); + + List slist = new List(50, false); + Vector forstring = new Vector(); + + Label def = new Label("Following is the result of the CSD search: "); + Label inst = new Label("Select a molecule and click OK to continue."); + Button okbutt = new Button("OK"); + Button close = new Button("Close"); + private boolean tocheck, type; + + public searchResult(String infile, newNanocad n) { + + enableEvents(AWTEvent.WINDOW_EVENT_MASK); + try { + this.pdbfiles = infile; + nano = n; + jbInit(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void jbInit() throws Exception { + this.setTitle("Search Result"); + this.setVisible(true); + + close.setBackground(Color.red); + okbutt.setBackground(Color.red); + plMain.setBackground(Color.pink); + this.add(plMain, null); + //.getContentPane().add(plMain, null); + // this.getContentPane().setLayout(null); + this.setSize(new Dimension(400, 550)); + plMain.setLayout(null); + plMain.add(slist, null); + plMain.add(def, null); + plMain.add(inst, null); + plMain.add(close, null); + plMain.add(okbutt, null); + slist.setBounds(110, 90, 150, 140); + def.setBounds(new Rectangle(46, 7, 324, 20)); + inst.setBounds(new Rectangle(46, 37, 324, 20)); + try { + in1 = new BufferedReader(new StringReader(pdbfiles)); + get = in1.readLine(); + //while(!get.equals(null)) + { + l = new StringTokenizer(get, " "); + while (l.hasMoreTokens() == true) { + header = l.nextToken(); + //System.out.println("h:" + header); + if (header.equals("@MOLECULE")) { + //System.out.println("found file"); + smallad = l.nextToken(); + slist.add(smallad); + } + } + get = in1.readLine(); + } + in1.close(); + } catch (Exception e1) { + System.err.println(e1); + } + + def.setFont(new Font("SansSerif", 1, 16)); + okbutt.setFont(new Font("SansSerif", 1, 12)); + okbutt.setBounds(new Rectangle(80, 270, 81, 25)); + + okbutt.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + okbutt_actionPerformed(e); + } + }); + + close.setFont(new Font("SansSerif", 1, 12)); + close.setBounds(new Rectangle(197, 270, 81, 25)); + close.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + close_actionPerformed(e); + } + }); + } + + void close_actionPerformed(ActionEvent e) { + this.dispose(); + } + + void okbutt_actionPerformed(ActionEvent e) { + try { + in1 = new BufferedReader(new StringReader(pdbfiles)); + String item = slist.getSelectedItem(); + + //while(flag) + get = in1.readLine(); + StringTokenizer l = new StringTokenizer(get, " "); + System.out.println(item); + + while (l.hasMoreTokens() == true && !header.equals(item)) { + header = l.nextToken(); + } + outfile = new String(); + while (l.hasMoreTokens() == true && !header.equals("END")) { + outfile += header; + outfile += " "; + header = l.nextToken(); + } + + nano.drawFile(outfile, "pdb"); + this.dispose(); + } catch (Exception e1) { + System.err.println(e1); + } + } + +/* public static void main(String argv[]) + { + String filename = argv[0]; + searchResult obj = new searchResult(filename); + obj.setVisible(true); + }*/ +} diff --git a/src/main/java/nanocad/term.java b/src/main/java/nanocad/term.java new file mode 100644 index 0000000..84010c7 --- /dev/null +++ b/src/main/java/nanocad/term.java @@ -0,0 +1,190 @@ +package nanocad; + +/** + * term.java - MM2-style energy term, for computing interatomic forces + * Copyright (c) 1997 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.lang.Math; +import java.util.Vector; + +public abstract class term +{ + public atom[] myAtoms; + public group myGroup = null; // Used to determine when types need + // to be recomputed. See mm3/term.java + // for implementation details. + public static final double pi = 3.1415926; + + protected double potential; + protected boolean defaultsUsed = false; + + public double getpotential(){ + return potential; + } + + public term () + { + // needed for termList + } + protected double acos (double x) + { + //makes no sense - Mike Hewner 8/7/00 + if (x >= 1.0) return pi / 2; + if (x <= -1.0) return -pi / 2; + return Math.acos (x); + } + + private void bondChain (atom a, int n, Vector termList) + { + Vector v = new Vector(); + v.addElement(a); + nextBondChain(v, n-1, termList); + } + + protected abstract void buildTerm(Vector v, Vector termList); + + public abstract double computeForces(); + + // handy vector arithmetic + protected double[] crossProduct (double[] x, double[] y) + { + double[] z = new double[3]; + z[0] = x[1] * y[2] - x[2] * y[1]; + z[1] = x[2] * y[0] - x[0] * y[2]; + z[2] = x[0] * y[1] - x[1] * y[0]; + return z; + } +/** + * Insert the method's description here. + * Creation date: (7/17/2000 3:39:31 PM) + * @return boolean + */ +public boolean defaultsUsed() { + return defaultsUsed; +} + protected double dotProduct (double[] x, double[] y) + { + return x[0] * y[0] + x[1] * y[1] + x[2] * y[2]; + } + public void enumerate (Vector atomList, Vector termList) + { + int i; + for (i = 0; i < atomList.size (); i++) + bondChain ((atom) atomList.elementAt(i), termLength(), termList); + } + +protected double findAngle(atom a, atom b, atom c) +//returns the size of the angle abc in degrees +{ + double[] aCoordsRelativeToB = new double[3]; + double[] cCoordsRelativeToB = new double[3]; + double aLength = 0.0; + double cLength = 0.0; + for(int i = 0; i < 3; i++) + { + aCoordsRelativeToB[i] = a.x[i] - b.x[i]; + cCoordsRelativeToB[i] = c.x[i] - b.x[i]; + } + aLength = lengthBetween(a,b); + cLength = lengthBetween(b,c); + double cosTheta = dotProduct(aCoordsRelativeToB, cCoordsRelativeToB) / aLength / cLength; + return Math.acos(cosTheta); +} + +public double lengthBetween(atom a, atom b) { + double length = 0.0; + for(int i = 0; i < 3; i++) + { + double aCoordsRelativeToB = a.x[i] - b.x[i]; + length = length + aCoordsRelativeToB * aCoordsRelativeToB; + } + return Math.sqrt(length); +} + +private void nextBondChain (Vector v, int n, Vector termList) + { + int i; + atom a1, a2; + if (n == 0) + { + buildTerm (v, termList); + return; + } + a1 = (atom) v.elementAt(v.size()-1); + for (i = 0; i < a1.bonds.size(); i++) + { + a2 = ((bond) a1.bonds.elementAt(i)).otherAtom(a1); + if (!v.contains(a2)) + { + v.addElement(a2); + nextBondChain(v, n-1, termList); + v.removeElement(a2); + } + } + } + +public String repr() + { + int i; + if (myAtoms == null) + return ""; + + String s = ""; + } + protected String repr2() + { + return ""; + } + protected double[] scalevec (double m, double[] x) + { + double[] z = new double[3]; + int i; + for (i = 0; i < 3; i++) + z[i] = m * x[i]; + return z; + } +/** + * Insert the method's description here. + * Creation date: (6/15/00 1:34:52 PM) + */ +protected abstract void setCalculationValues(); + protected double sqrt (double x) + { + if (x <= 0.0) return 0.0; + return Math.sqrt (x); + } + protected abstract int termLength(); + protected String name() + { + return "default"; + } + protected double veclen (double[] x) + { + return Math.sqrt (dotProduct (x, x)); + } +} diff --git a/src/main/java/nanocad/test.java b/src/main/java/nanocad/test.java new file mode 100644 index 0000000..fb95999 --- /dev/null +++ b/src/main/java/nanocad/test.java @@ -0,0 +1,10 @@ +package nanocad; + +import java.lang.*; + +class test{ + public static void main(String[] args){ + int j=4; + System.out.println(j/3); + } +} diff --git a/src/main/java/nanocad/textwin.java b/src/main/java/nanocad/textwin.java new file mode 100644 index 0000000..6c2a98c --- /dev/null +++ b/src/main/java/nanocad/textwin.java @@ -0,0 +1,211 @@ +package nanocad; + +/** + * textwin.java - pop up a new frame to read or write text + * Copyright (c) 1998 Will Ware, all rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * or its derived works must display the following acknowledgement: + * This product includes software developed by Will Ware. + * + * This software is provided "as is" and any express or implied warranties, + * including, but not limited to, the implied warranties of merchantability + * or fitness for any particular purpose are disclaimed. In no event shall + * Will Ware be liable for any direct, indirect, incidental, special, + * exemplary, or consequential damages (including, but not limited to, + * procurement of substitute goods or services; loss of use, data, or + * profits; or business interruption) however caused and on any theory of + * liability, whether in contract, strict liability, or tort (including + * negligence or otherwise) arising in any way out of the use of this + * software, even if advised of the possibility of such damage. + */ + +import java.awt.*; +import javax.swing.*; + +import javax.swing.Box; +import javax.swing.JScrollPane; + +public class textwin extends Frame implements java.awt.event.ActionListener +{ + protected String contents = "Here's a debug window\n"; + protected TextArea textWindow; + protected boolean editable, visible; + private Button done, cancel; + private group grp; + + + public textwin () + { + /* this one is only for inheritance purposes */ + } + + public textwin (String title, String initialContent, boolean edtbl) + { + //lixh_4/27/05 + //Panel p1 = new Panel(); + Container p1 = Box.createVerticalBox(); + JPanel p2 = new JPanel(); + + editable = edtbl; + visible = false; + setTitle (title); + contents = initialContent; + textWindow = new TextArea (20, 75); + textWindow.setText (contents); + textWindow.setEditable (editable); + JScrollPane js = new JScrollPane(textWindow); + js.setWheelScrollingEnabled(true); + js.setBorder(BorderFactory.createEmptyBorder(15,15,15,15)); + p1.add(js); + //p1.add ("North", textWindow); + + done = new Button("Done"); + done.addActionListener(this); + p2.add ("West", done); + cancel = new Button("Cancel"); + cancel.addActionListener(this); + + p2.add ("East", cancel); + + setLayout(new BoxLayout(this,BoxLayout.Y_AXIS)); + add("North", p1); + add("South", p2); + //this.setPreferredSize(new Dimension(600,420)); + resize (600, 420); + //setSize(600,600); + addWindowListener(new java.awt.event.WindowAdapter() { + public void windowClosing(java.awt.event.WindowEvent e){ + visible = false; + setVisible(visible); + //System.exit(0); + } + }); + } + + //Ying, no, this is the one really invoked for handling the events; + public void actionPerformed(java.awt.event.ActionEvent e){ + String s = e.getActionCommand(); + if(s.equals("Done")) { + //visible = false; + //setVisible(visible); + update(); + setVisible(false); + + if (grp != null) + grp.textWindowNotify(contents); + }else if (s.equals("Cancel")) { + update(); + setVisible(false); + } + } + + public void changeSize(int w, int h){ + resize(w,h); + } + + public void clear() + { + contents = ""; + textWindow.setText (contents); + } + + public String getText() + { + update(); + return contents; + } + + + //Ying doubted that this function was never invoked; + public boolean handleEvent (Event e) + { + if (e.arg == "Done") + { + System.out.println("done is invoked*******1"); + + update(); + setVisible(false); + + System.out.println("done is invoked*******2"); + + if (grp != null) + grp.textWindowNotify(contents); + return true; + } + + if (e.arg == "Cancel") + { + update(); + setVisible(false); + return true; + } + return false; + } + + + + public boolean isEditable() + { + return editable; + } + public boolean isVisible() + { + return visible; + } + public void setEditable(boolean e) + { + editable = e; + textWindow.setEditable(editable); + } + + public void setGroup(group g) + { + grp = g; + } + + public void setText(String s) + { + clear(); + write(s); + } + public void setVisible(boolean v) + { + visible = v; + if (v) + show(); + else + hide(); + } + + public void update() + { + if (editable) //for SaveXYZ or PDB, this should be false; + contents = textWindow.getText(); + } + + public void write(double x) + { + contents = contents + (new Double(x)).toString(); + textWindow.setText (contents); + } + + public void write(int x) + { + contents = contents + (new Integer(x)).toString(); + textWindow.setText (contents); + } + public void write(String s) + { + contents = contents + s; + textWindow.setText (contents); + } +} diff --git a/src/main/java/nanocad/util/ATFInteg.java b/src/main/java/nanocad/util/ATFInteg.java new file mode 100644 index 0000000..8a6a6ff --- /dev/null +++ b/src/main/java/nanocad/util/ATFInteg.java @@ -0,0 +1,68 @@ +package nanocad.util; + +import java.io.*; + +import nanocad.newNanocad; + +class ATFInteg +{ + public static void main(String args[]) + { + String textLine = new String(""); + int i = 0; + try + { + System.out.println("aData1.dat integrity check."); + AtomTypeFile f = new AtomTypeFile(); + //BufferedReader text = new BufferedReader(new FileReader("p.txt")); + BufferedReader text = new BufferedReader(new FileReader(newNanocad.txtDir + + newNanocad.fileSeparator + "p.txt")); + + while(text.ready()) + { + textLine = text.readLine(); + String numText = textLine.substring(0, textLine.indexOf(" ")); + int TextAtomNum = Integer.parseInt(numText); + atomProperty curProp = f.getProperty(i); + //System.out.println(curProp.getANumber() + " " + textLine); + + if(curProp.getANumber() != TextAtomNum) + { + System.out.print("ANumber mismatch for " + textLine + " (" + i + ")"); + System.out.println(" - dat:" + curProp.getANumber() + " txt:" + TextAtomNum); + while(curProp.getANumber() != TextAtomNum) + { + int j = 0; + while(curProp.getANumber() > TextAtomNum) + { + textLine = text.readLine(); + numText = textLine.substring(0, textLine.indexOf(" ")); + TextAtomNum = Integer.parseInt(numText); + j++; + } + while(curProp.getANumber() < TextAtomNum) + { + i++; + curProp = f.getProperty(i); + j++; + } + System.out.println(j + " items skipped."); + } + } + i++; + } + } + catch(StringIndexOutOfBoundsException e) + { + System.out.println("Text parse error in line " + i + ": " + textLine); + e.printStackTrace(); + } + catch(Exception e) + { + System.out.println("ERROR"); + System.out.println(i + ": " + textLine); + e.printStackTrace(); + } + System.out.println("Integrity check concluded."); + } +} diff --git a/src/main/java/nanocad/util/AboutDialog.java b/src/main/java/nanocad/util/AboutDialog.java new file mode 100644 index 0000000..ecfc2bb --- /dev/null +++ b/src/main/java/nanocad/util/AboutDialog.java @@ -0,0 +1,121 @@ +package nanocad.util; + +/* + A basic extension of the java.awt.Dialog class + */ + +import java.awt.*; + +public class AboutDialog extends Dialog { + + //{{DECLARE_CONTROLS + Label label1; + Button okButton; + //}} + + // Used for addNotify redundency check. + boolean fComponentsAdjusted = false; + + class SymWindow extends java.awt.event.WindowAdapter + { + public void windowClosing(java.awt.event.WindowEvent event) + { + Object object = event.getSource(); + if (object == AboutDialog.this) + AboutDialog_WindowClosing(event); + } + } + + class SymAction implements java.awt.event.ActionListener + { + public void actionPerformed(java.awt.event.ActionEvent event) + { + Object object = event.getSource(); + if (object == okButton) + okButton_Clicked(event); + } + } + + public AboutDialog(Frame parent, String title, boolean modal) + { + this(parent, modal); + setTitle(title); + } + public AboutDialog(Frame parent, boolean modal) + { + super(parent, modal); + + // This code is automatically generated by Visual Cafe when you add + // components to the visual environment. It instantiates and initializes + // the components. To modify the code, only use code syntax that matches + // what Visual Cafe can generate, or Visual Cafe may be unable to back + // parse your Java file into its visual environment. + + //{{INIT_CONTROLS + setLayout(null); + setVisible(false); + setSize(insets().left + insets().right + 249,insets().top + insets().bottom + 150); + label1 = new Label("Michael Hewner, NCSA"); + label1.setBounds(insets().left + 36,insets().top + 12,166,72); + add(label1); + okButton = new Button(); + okButton.setLabel("OK"); + okButton.setBounds(insets().left + 84,insets().top + 108,66,27); + add(okButton); + setTitle("About"); + //}} + + //{{REGISTER_LISTENERS + SymWindow aSymWindow = new SymWindow(); + this.addWindowListener(aSymWindow); + SymAction lSymAction = new SymAction(); + okButton.addActionListener(lSymAction); + //}} + + } + void AboutDialog_WindowClosing(java.awt.event.WindowEvent event) + { + dispose(); + } + public void addNotify() + { + // Record the size of the window prior to calling parents addNotify. + Dimension d = getSize(); + + super.addNotify(); + + // Only do this once. + if (fComponentsAdjusted) + return; + + // Adjust components according to the insets + setSize(insets().left + insets().right + getSize().width, insets().top + insets().bottom + getSize().height); + Component components[] = getComponents(); + for (int i = 0; i < components.length; i++) + { + Point p = components[i].getLocation(); + p.translate(insets().left, insets().top); + components[i].setLocation(p); + } + + // Used for addNotify check. + fComponentsAdjusted = true; + } + void okButton_Clicked(java.awt.event.ActionEvent event) + { + //{{CONNECTION + // Clicked from okButton Hide the Dialog + dispose(); + //}} + } + public synchronized void show() + { + Rectangle bounds = getParent().bounds(); + Rectangle abounds = bounds(); + + move(bounds.x + (bounds.width - abounds.width)/ 2, + bounds.y + (bounds.height - abounds.height)/2); + + super.show(); + } +} diff --git a/src/main/java/nanocad/util/AtomReorderDialog.java b/src/main/java/nanocad/util/AtomReorderDialog.java new file mode 100644 index 0000000..6d92107 --- /dev/null +++ b/src/main/java/nanocad/util/AtomReorderDialog.java @@ -0,0 +1,510 @@ +package nanocad.util; + +import java.awt.*; +/** + * This type was generated by a SmartGuide. + */ +public class AtomReorderDialog extends Dialog { + private Panel ivjAtomReorderPane = null; + private Panel ivjContentsPane = null; + IvjEventHandler ivjEventHandler = new IvjEventHandler(); + private Button ivjCancelButton = null; + private Button ivjCommitButton = null; + private Button ivjDownButton = null; + private Button ivjUpButton = null; + private List ivjPropertyList = null; + private boolean wasCancelled = true; + +class IvjEventHandler implements java.awt.event.ActionListener, java.awt.event.WindowListener { + public void actionPerformed(java.awt.event.ActionEvent e) { + if (e.getSource() == AtomReorderDialog.this.getUpButton()) + connEtoC2(e); + if (e.getSource() == AtomReorderDialog.this.getDownButton()) + connEtoC3(e); + if (e.getSource() == AtomReorderDialog.this.getCancelButton()) + connEtoC1(e); + if (e.getSource() == AtomReorderDialog.this.getCommitButton()) + connEtoC5(e); + }; + public void windowActivated(java.awt.event.WindowEvent e) {}; + public void windowClosed(java.awt.event.WindowEvent e) {}; + public void windowClosing(java.awt.event.WindowEvent e) { + if (e.getSource() == AtomReorderDialog.this) + connEtoC6(e); + }; + public void windowDeactivated(java.awt.event.WindowEvent e) {}; + public void windowDeiconified(java.awt.event.WindowEvent e) {}; + public void windowIconified(java.awt.event.WindowEvent e) {}; + public void windowOpened(java.awt.event.WindowEvent e) {}; + }; +/** + * Constructor + * @param parent Symbol + */ +/* WARNING: THIS METHOD WILL BE REGENERATED. */ +public AtomReorderDialog(Frame parent) { + super(parent); + initialize(); +} + public void addItem(String item) + { + int i = -1 ; + boolean itemFound = false; + int val = atomicNumberOf(item); + while(i+1 AtomReorderDialog.atomReorder_WindowClosing(Ljava.awt.event.WindowEvent;)V) + * @param arg1 java.awt.event.ActionEvent + */ +/* WARNING: THIS METHOD WILL BE REGENERATED. */ +private void connEtoC1(java.awt.event.ActionEvent arg1) { + try { + // user code begin {1} + // user code end + this.atomReorder_WindowClosing(null); + // user code begin {2} + // user code end + } catch (Throwable ivjExc) { + // user code begin {3} + // user code end + handleException(ivjExc); + } +} +/** + * connEtoC2: (UpButton.action.actionPerformed(java.awt.event.ActionEvent) --> AtomReorder.upButton_ActionPerformed(Ljava.awt.event.ActionEvent;)V) + * @param arg1 java.awt.event.ActionEvent + */ +/* WARNING: THIS METHOD WILL BE REGENERATED. */ +private void connEtoC2(java.awt.event.ActionEvent arg1) { + try { + // user code begin {1} + // user code end + this.upButton_ActionPerformed(arg1); + // user code begin {2} + // user code end + } catch (Throwable ivjExc) { + // user code begin {3} + // user code end + handleException(ivjExc); + } +} +/** + * connEtoC3: (DownButton.action.actionPerformed(java.awt.event.ActionEvent) --> AtomReorder.downButton_ActionPerformed(Ljava.awt.event.ActionEvent;)V) + * @param arg1 java.awt.event.ActionEvent + */ +/* WARNING: THIS METHOD WILL BE REGENERATED. */ +private void connEtoC3(java.awt.event.ActionEvent arg1) { + try { + // user code begin {1} + // user code end + this.downButton_ActionPerformed(arg1); + // user code begin {2} + // user code end + } catch (Throwable ivjExc) { + // user code begin {3} + // user code end + handleException(ivjExc); + } +} +/** + * connEtoC5: (CommitButton.action.actionPerformed(java.awt.event.ActionEvent) --> AtomReorderDialog.commitButton_ActionPerformed(Ljava.awt.event.ActionEvent;)V) + * @param arg1 java.awt.event.ActionEvent + */ +/* WARNING: THIS METHOD WILL BE REGENERATED. */ +private void connEtoC5(java.awt.event.ActionEvent arg1) { + try { + // user code begin {1} + // user code end + this.commitButton_ActionPerformed(arg1); + // user code begin {2} + // user code end + } catch (Throwable ivjExc) { + // user code begin {3} + // user code end + handleException(ivjExc); + } +} +/** + * connEtoC6: (AtomReorder.window.windowClosing(java.awt.event.WindowEvent) --> AtomReorderDialog.atomReorder_WindowClosing(Ljava.awt.event.WindowEvent;)V) + * @param arg1 java.awt.event.WindowEvent + */ +/* WARNING: THIS METHOD WILL BE REGENERATED. */ +private void connEtoC6(java.awt.event.WindowEvent arg1) { + try { + // user code begin {1} + // user code end + this.atomReorder_WindowClosing(arg1); + // user code begin {2} + // user code end + } catch (Throwable ivjExc) { + // user code begin {3} + // user code end + handleException(ivjExc); + } +} +/** + * Insert the method's description here. + * Creation date: (6/21/00 11:51:39 AM) + * @return boolean + */ +public boolean dialogWasCancelled() { + return wasCancelled; +} +/** + * Comment + */ +public void downButton_ActionPerformed(java.awt.event.ActionEvent actionEvent) { + List list = getPropertyList(); + String itemToMove = getSelectedItem(); + int currentIndex = getSelectedIndex(); + if (currentIndex == (list.getItemCount() -1 )) return; + if (atomicNumberOf(list.getItem(currentIndex + 1 )) != atomicNumberOf(itemToMove)) + return; + ((Frame1) getParent()).getFile().demoteProperty(currentIndex); + list.delItem(currentIndex); + list.addItem(itemToMove, currentIndex+1); + list.select(currentIndex+1); + return; +} +/** + * Return the AtomReorderPane property value. + * @return java.awt.Panel + */ +/* WARNING: THIS METHOD WILL BE REGENERATED. */ +private Panel getAtomReorderPane() { + if (ivjAtomReorderPane == null) { + try { + ivjAtomReorderPane = new Panel(); + ivjAtomReorderPane.setName("AtomReorderPane"); + ivjAtomReorderPane.setLayout(null); + getAtomReorderPane().add(getPropertyList(), getPropertyList().getName()); + getAtomReorderPane().add(getUpButton(), getUpButton().getName()); + getAtomReorderPane().add(getDownButton(), getDownButton().getName()); + getAtomReorderPane().add(getCommitButton(), getCommitButton().getName()); + getAtomReorderPane().add(getCancelButton(), getCancelButton().getName()); + // user code begin {1} + // user code end + } catch (Throwable ivjExc) { + // user code begin {2} + // user code end + handleException(ivjExc); + } + } + return ivjAtomReorderPane; +} +/** + * Return the CancelButton property value. + * @return java.awt.Button + */ +/* WARNING: THIS METHOD WILL BE REGENERATED. */ +private Button getCancelButton() { + if (ivjCancelButton == null) { + try { + ivjCancelButton = new Button(); + ivjCancelButton.setName("CancelButton"); + ivjCancelButton.setBounds(258, 209, 56, 23); + ivjCancelButton.setLabel("Cancel"); + // user code begin {1} + // user code end + } catch (Throwable ivjExc) { + // user code begin {2} + // user code end + handleException(ivjExc); + } + } + return ivjCancelButton; +} +/** + * Return the CommitButton property value. + * @return java.awt.Button + */ +/* WARNING: THIS METHOD WILL BE REGENERATED. */ +private Button getCommitButton() { + if (ivjCommitButton == null) { + try { + ivjCommitButton = new Button(); + ivjCommitButton.setName("CommitButton"); + ivjCommitButton.setBounds(258, 181, 56, 23); + ivjCommitButton.setLabel("Commit"); + // user code begin {1} + // user code end + } catch (Throwable ivjExc) { + // user code begin {2} + // user code end + handleException(ivjExc); + } + } + return ivjCommitButton; +} +/** + * Return the ContentsPane property value. + * @return java.awt.Panel + */ +/* WARNING: THIS METHOD WILL BE REGENERATED. */ +private Panel getContentsPane() { + if (ivjContentsPane == null) { + try { + ivjContentsPane = new Panel(); + ivjContentsPane.setName("ContentsPane"); + ivjContentsPane.setLayout(new BorderLayout()); + getContentsPane().add(getAtomReorderPane(), "Center"); + // user code begin {1} + // user code end + } catch (Throwable ivjExc) { + // user code begin {2} + // user code end + handleException(ivjExc); + } + } + return ivjContentsPane; +} +/** + * Return the DownButton property value. + * @return java.awt.Button + */ +/* WARNING: THIS METHOD WILL BE REGENERATED. */ +private Button getDownButton() { + if (ivjDownButton == null) { + try { + ivjDownButton = new Button(); + ivjDownButton.setName("DownButton"); + ivjDownButton.setBounds(258, 36, 56, 23); + ivjDownButton.setEnabled(true); + ivjDownButton.setLabel("Down"); + // user code begin {1} + // user code end + } catch (Throwable ivjExc) { + // user code begin {2} + // user code end + handleException(ivjExc); + } + } + return ivjDownButton; +} +/** + * Insert the method's description here. + * Creation date: (6/21/00 12:02:08 PM) + * @return int + */ +public String getItem(int index) { + return getPropertyList().getItem(index); +} +/** + * Insert the method's description here. + * Creation date: (6/21/00 12:02:08 PM) + * @return int + */ +public int getItemCount() { + return getPropertyList().getItemCount(); +} +/** + * Return the List1 property value. + * @return java.awt.List + */ +/* WARNING: THIS METHOD WILL BE REGENERATED. */ +private List getPropertyList() { + if (ivjPropertyList == null) { + try { + ivjPropertyList = new List(); + ivjPropertyList.setName("PropertyList"); + ivjPropertyList.setBounds(10, 10, 245, 224); + // user code begin {1} + // user code end + } catch (Throwable ivjExc) { + // user code begin {2} + // user code end + handleException(ivjExc); + } + } + return ivjPropertyList; +} +/** + * Insert the method's description here. + * Creation date: (6/21/00 11:26:13 AM) + * @return int + */ +public int getSelectedIndex() { + return getPropertyList().getSelectedIndex(); +} +/** + * Insert the method's description here. + * Creation date: (6/21/00 11:26:13 AM) + * @return int + */ +public String getSelectedItem() { + return getPropertyList().getSelectedItem(); +} +/** + * Return the UpButton property value. + * @return java.awt.Button + */ +/* WARNING: THIS METHOD WILL BE REGENERATED. */ +private Button getUpButton() { + if (ivjUpButton == null) { + try { + ivjUpButton = new Button(); + ivjUpButton.setName("UpButton"); + ivjUpButton.setBounds(258, 8, 56, 23); + ivjUpButton.setEnabled(true); + ivjUpButton.setLabel("Up"); + // user code begin {1} + // user code end + } catch (Throwable ivjExc) { + // user code begin {2} + // user code end + handleException(ivjExc); + } + } + return ivjUpButton; +} +/** + * Called whenever the part throws an exception. + * @param exception java.lang.Throwable + */ +private void handleException(Throwable exception) { + + /* Uncomment the following lines to print uncaught exceptions to stdout */ + // System.out.println("--------- UNCAUGHT EXCEPTION ---------"); + // exception.printStackTrace(System.out); +} +/** + * Initializes connections + * @exception Exception The exception description. + */ +/* WARNING: THIS METHOD WILL BE REGENERATED. */ +private void initConnections() throws Exception { + // user code begin {1} + // user code end + getUpButton().addActionListener(ivjEventHandler); + getDownButton().addActionListener(ivjEventHandler); + this.addWindowListener(ivjEventHandler); + getCancelButton().addActionListener(ivjEventHandler); + getCommitButton().addActionListener(ivjEventHandler); +} +/** + * Initialize the class. + */ +/* WARNING: THIS METHOD WILL BE REGENERATED. */ +private void initialize() { + try { + // user code begin {1} + // user code end + setName("AtomReorder"); + setLayout(new BorderLayout()); + setSize(337, 288); + setTitle("atomReorder"); + add(getContentsPane(), "Center"); + initConnections(); + } catch (Throwable ivjExc) { + handleException(ivjExc); + } + // user code begin {2} + // user code end +} +/** + * Starts the application. + * @param args an array of command-line arguments + */ +public static void main(String[] args) { + try { + /* Create the frame */ + AtomReorderDialog aAtomReorder = new AtomReorderDialog(null); + /* Add a windowListener for the windowClosedEvent */ + aAtomReorder.addWindowListener(new java.awt.event.WindowAdapter() { + public void windowClosed(java.awt.event.WindowEvent e) { + System.exit(0); + }; + }); + aAtomReorder.setVisible(true); + } catch (Throwable exception) { + System.err.println("Exception occurred in main() of AtomReorder"); + exception.printStackTrace(System.out); + } +} +/** + * Insert the method's description here. + * Creation date: (6/23/00 1:47:28 PM) + */ +public void openForReorder() { + getUpButton().setVisible(true); + getDownButton().setVisible(true); + getCancelButton().setVisible(false); + setVisible(true); + } +/** + * Insert the method's description here. + * Creation date: (6/23/00 1:47:28 PM) + */ +public void openForSelect() { + getUpButton().setVisible(false); + getDownButton().setVisible(false); + getCancelButton().setVisible(true); + setVisible(true); + } +public List PropertyList() { + return getPropertyList(); +} +/** + * Insert the method's description here. + * Creation date: (6/21/00 12:05:12 PM) + * @param index int + */ +public void removeItem(int index) { + getPropertyList().delItem(index); +} +/** + * Comment + */ +public void upButton_ActionPerformed(java.awt.event.ActionEvent actionEvent) { + List list = getPropertyList(); + String itemToMove = getSelectedItem(); + int currentIndex = getSelectedIndex(); + if (currentIndex == 0) return; + if (atomicNumberOf(list.getItem(currentIndex - 1 )) != atomicNumberOf(itemToMove)) + return; + ((Frame1) getParent()).getFile().promoteProperty(currentIndex); + list.delItem(currentIndex); + list.addItem(itemToMove, currentIndex - 1); + list.select(currentIndex -1); + return; +} +} diff --git a/src/main/java/nanocad/util/AtomTypeFile.java b/src/main/java/nanocad/util/AtomTypeFile.java new file mode 100644 index 0000000..ecf01e8 --- /dev/null +++ b/src/main/java/nanocad/util/AtomTypeFile.java @@ -0,0 +1,295 @@ +package nanocad.util; + +import java.io.*; +import java.util.*; + +import nanocad.AtomTypeTest; +import nanocad.atom; +import nanocad.group; +import nanocad.newNanocad; + +public class AtomTypeFile implements Serializable +{ + //Data + protected String filename; + private Vector atomList; + + public AtomTypeFile() + { + atomList = new Vector(256); + } + public void addProperty(atomProperty prop) + { + try + { + Vector propList = (Vector) atomList.elementAt(prop.getANumber()); + propList.addElement(prop.toByteArray()); + } + catch (Exception e) + { + e.printStackTrace(); + } + + } + public void demoteProperty(int pNum) + //moves the property one step backward (that is, evaluated later) + { + int sizeSoFar = 0; + int i = 0; + Vector currentAtom = (Vector) atomList.elementAt(0); + while(pNum >= (sizeSoFar + currentAtom.size())) + { + i++; + sizeSoFar = sizeSoFar + currentAtom.size(); + currentAtom = (Vector) atomList.elementAt(i); + } + int startIndex = pNum-sizeSoFar; + Object selectedItem = currentAtom.elementAt(startIndex); + currentAtom.removeElementAt(startIndex); + currentAtom.insertElementAt(selectedItem, startIndex + 1); + } + public atomProperty getProperty(int pNum) + { + int sizeSoFar = 0; + int i = 0; + Vector currentAtom = (Vector) atomList.elementAt(0); + while(pNum >= (sizeSoFar + currentAtom.size())) + { + i++; + sizeSoFar = sizeSoFar + currentAtom.size(); + currentAtom = (Vector) atomList.elementAt(i); + } + byte[] barray = (byte[]) currentAtom.elementAt(pNum-sizeSoFar); + return new atomProperty(i, barray); + } + public int getType(group g, atom atomToType) + { + int total = 0; + int aNumber = atomToType.atomicNumber(); + for(int i = 0; i < aNumber; i++) + total = total + ((Vector) atomList.elementAt(i)).size(); + + Vector pList = (Vector) atomList.elementAt(aNumber); + AtomTypeTest tester = new AtomTypeTest(atomToType, g); + for(int i = 0; i < pList.size(); i++) + { + if((i+total) == 32) tester.verbose(); + if(tester.propertyWithoutPopups(new atomProperty(255, (byte[]) pList.elementAt(i)))) + return i+total; + } + return -1; + } + public int getTypeWithoutPopups(group g, atom atomToType) + { + int total = 0; + int aNumber = atomToType.atomicNumber(); + for(int i = 0; i < aNumber; i++) + total = total + ((Vector) atomList.elementAt(i)).size(); + + Vector pList = (Vector) atomList.elementAt(aNumber); + AtomTypeTest tester = new AtomTypeTest(atomToType, g); + for(int i = 0; i < pList.size(); i++) + { + if((i+total) == 32) tester.verbose(); + if(tester.propertyWithoutPopups(new atomProperty(255, (byte[]) pList.elementAt(i)))) + return i+total; + } + return -1; + } + public void promoteProperty(int pNum) + //moves the property one step forward (that is, evaluated sooner) + { + int sizeSoFar = 0; + int i = 0; + Vector currentAtom = (Vector) atomList.elementAt(0); + while(pNum >= (sizeSoFar + currentAtom.size())) + { + i++; + sizeSoFar = sizeSoFar + currentAtom.size(); + currentAtom = (Vector) atomList.elementAt(i); + } + int startIndex = pNum-sizeSoFar; + Object selectedItem = currentAtom.elementAt(startIndex); + currentAtom.removeElementAt(startIndex); + currentAtom.insertElementAt(selectedItem, startIndex - 1); + } + public void readFile(String newFilename) + { + readFileFromObject(newFilename); + } + public void readFileFromData(String newFilename) + { + filename = newFilename; + try + { + //RandomAccessFile f = new RandomAccessFile(filename + ".data.txt","r"); + RandomAccessFile f = new RandomAccessFile(newNanocad.txtDir + + newNanocad.fileSeparator + filename + ".data.txt","r"); + long data; + for(int i =0; i < 256; i++) + { + Vector propList = new Vector(); + data = f.readLong(); + if(data > 0) + { //System.out.println("Nonzero data item dected."); + long returnPoint = f.getFilePointer(); + f.seek(data); + int xx = ubyteToInt(f.readByte()); + while( xx == i) + { int x = ubyteToInt(f.readByte()); + //System.out.print(i + "/" + x + ":"); + byte[] barray = new byte[x]; + f.readFully(barray); + //for(int q = 0; q < x; q++) System.out.print(ubyteToInt(barray[q]) + " "); + //System.out.println(""); + propList.addElement(barray); + xx = ubyteToInt(f.readByte()); + //xx = 300; + //System.out.println(data + " - IN:"+i+"["+barray.length+"]"+xx); + } + f.seek(returnPoint); + } + atomList.addElement(propList); + } + } + catch (IOException e) + { + System.out.println("File read error! : " + e.getMessage()); + e.printStackTrace(); + return; + } + System.out.println("Data read sucessful." + filename + ".data"); + } + public void readFileFromObject(String newFileName) + { + filename = newFileName; + System.out.println("filename = " + filename); + try + { + //InputStream inputStream = getClass().getResourceAsStream("/" + filename + ".object.txt"); + FileInputStream inputStream = new FileInputStream(new File(newNanocad.txtDir + + newNanocad.fileSeparator + filename + ".object.txt")); + ObjectInputStream test = new ObjectInputStream(inputStream); + AtomTypeFile newTypeFile = (AtomTypeFile) test.readObject(); + atomList = newTypeFile.atomList; + } + catch (Exception e) + { + System.err.println("File read error! : " + e.getMessage()); + e.printStackTrace(); + return; + } + //System.out.println("Data read sucessful. " + atomList.size() + " elements loaded."); + } + public void removeProperty(int pNum) + { + int sizeSoFar = 0; + int i = 0; + Vector currentAtom = (Vector) atomList.elementAt(0); + while(pNum >= (sizeSoFar + currentAtom.size())) + { + i++; + sizeSoFar = sizeSoFar + currentAtom.size(); + currentAtom = (Vector) atomList.elementAt(i); + } + currentAtom.removeElementAt(pNum-sizeSoFar); + } + public void replaceProperty(int pNum, atomProperty newProperty) + { + int sizeSoFar = 0; + int i = 0; + Vector currentAtom = (Vector) atomList.elementAt(0); + while(pNum >= (sizeSoFar + currentAtom.size())) + { + i++; + sizeSoFar = sizeSoFar + currentAtom.size(); + currentAtom = (Vector) atomList.elementAt(i); + } + currentAtom.setElementAt((Object) newProperty.toByteArray(), pNum-sizeSoFar); + } + public static int ubyteToInt(byte b) + { + if (b >= 0) return (int) b; + return ((int)b + 256); + } +protected void writeDataFile() + { + try + { + //backup old file + //String dataFilename = filename + ".data.txt"; + String dataFilename = newNanocad.txtDir + newNanocad.fileSeparator + + filename + ".data.txt"; + File oldFile = new File(dataFilename + ".old"); + if(oldFile.exists()) oldFile.delete(); + File currentFile = new File(dataFilename); + currentFile.renameTo(oldFile); + + long fileEnd = 2048; //length of atom directory + + RandomAccessFile f = new RandomAccessFile(new File(dataFilename),"rw"); + for(int i =0; i < 256; i++) + { + Vector propList = (Vector) atomList.elementAt(i); + f.seek(i*8); //go to appropaite place in file directory + if (propList.size() == 0) + { + f.writeLong((long) 0); //zero indicates no entry + } + else + { + //System.out.println("Outputing " + propList.size() + "bytes for " + i); + f.writeLong(fileEnd); + + f.seek(fileEnd); + + for(int j = 0; j < propList.size(); j++) + { + f.writeByte(i); + byte[] barray = (byte[]) propList.elementAt(j); + f.writeByte((byte) barray.length); + f.write(barray); + //System.out.println(fileEnd+ " - OUT:"+i+"["+barray.length+"]"); + fileEnd = fileEnd + barray.length + 2; + } + } + } + f.seek(fileEnd); + f.writeByte((byte)254); + f.close(); + System.out.println("data write completed: " + dataFilename); + } + catch (IOException e) + { + System.out.println("File write error! : " + e.toString()); + } + } + public void writeFile() + { + writeDataFile(); + writeObjectFile(); + } + protected void writeObjectFile() + { + try + { + //String objectFileName = filename + ".object.txt"; + String objectFileName = newNanocad.txtDir + newNanocad.fileSeparator + + filename + ".object.txt"; + //backup old file + File oldFile = new File(objectFileName +".old"); + if(oldFile.exists()) oldFile.delete(); + File currentFile = new File(objectFileName); + if(currentFile.exists()) currentFile.renameTo(oldFile); + + ObjectOutputStream test = new ObjectOutputStream(new FileOutputStream(objectFileName)); + test.writeObject(this); + test.close(); + System.out.println("object write completed: " + objectFileName); + } + catch (Exception e) + { + System.out.println("File write error! : " + e.toString()); + } + } +} diff --git a/src/main/java/nanocad/util/Frame1.java b/src/main/java/nanocad/util/Frame1.java new file mode 100644 index 0000000..c789120 --- /dev/null +++ b/src/main/java/nanocad/util/Frame1.java @@ -0,0 +1,762 @@ +package nanocad.util; + +/* + This simple extension of the java.awt.Frame class + contains all the elements necessary to act as the + main window of an application. + */ + +import java.awt.*; +import java.io.*; +import java.util.*; + +import nanocad.newNanocad; + +public class Frame1 extends Frame +{ + public newDialog pDialog; + public atomProperty currentProperty; + public AtomTypeFile aFile= new AtomTypeFile(); + public Vector bipVector = new Vector(); + public Vector pVector = new Vector(); + // Used for addNotify check. + boolean fComponentsAdjusted = false; + + //{{DECLARE_CONTROLS + TextField textField1; + Label label1; + Label label2; + TextField aNumberField; + Label label3; + Checkbox checkbox1; + Button button1; + Button button2; + java.awt.List pdlist; + Button button3; + Label label4; + Button database_add; + java.awt.List biplist; + //}} + + //{{DECLARE_MENUS + MenuBar mainMenuBar; + Menu menu1; + MenuItem miOpen; + MenuItem miSaveAs; + MenuItem miExit; + Menu menu2; + MenuItem menuItem1; + MenuItem menuItem2; + MenuItem menuItem3; + Menu menu3; + MenuItem miAbout; + //}} + + class SymWindow extends java.awt.event.WindowAdapter + { + public void windowClosing(java.awt.event.WindowEvent event) + { + Object object = event.getSource(); + if (object == Frame1.this) + Frame1_WindowClosing(event); + } + } + + class SymAction implements java.awt.event.ActionListener + { + public void actionPerformed(java.awt.event.ActionEvent event) + { + Object object = event.getSource(); + if (object == miOpen) + miOpen_Action(event); + if (object == miReorder) + miReorder_Action(event); + else if (object == miAbout) + miAbout_Action(event); + else if (object == miExit) + miExit_Action(event); + else if (object == menuItem3) + removeProperty_Action(event ); + else if (object == biplist) + biplist_Action(); + else if (object == button3) + button3_Action(event); + else if (object == button2) + addUserDef_Action(); + else if (object == button1) + button1_Action(event); + else if (object == database_add) + database_add_Action(event); + else if (object == menuItem1) + menuItem1_Action(event); + else if (object == miSaveAs) + miSaveAs_Action(event); + else if (object == menuItem2) + menuItem2_Action(event); + } + } + + class SymItem implements java.awt.event.ItemListener + { + public void itemStateChanged(java.awt.event.ItemEvent event) + { + Object object = event.getSource(); + if (object == checkbox1) + checkbox1_ItemStateChanged(event); + } + } + + class SymText implements java.awt.event.TextListener + { + public void textValueChanged(java.awt.event.TextEvent event) + { + Object object = event.getSource(); + if (object == aNumberField) + aNumberField_TextValueChanged(event); + else if (object == textField1) + textField1_TextValueChanged(event); + } + } + + protected final static String propertySeperator = ">>"; + protected int currentPropertyIndex = -1; + protected MenuItem miReorder; + public Frame1() + { + //begin data readin + aFile.readFileFromData("aData2.dat"); + currentProperty = new atomProperty(); + try + { + + BufferedReader in = new BufferedReader(new FileReader(newNanocad.txtDir + + newNanocad.fileSeparator + "bip.txt")); +// //BufferedReader in = new BufferedReader(new FileReader("bip.txt")); + while(in.ready()) + { + bipVector.addElement((Object) in.readLine()); + } + in.close(); + + in = new BufferedReader(new FileReader(newNanocad.txtDir + + newNanocad.fileSeparator + "p.txt")); + //in = new BufferedReader(new FileReader("p.txt")); + while(in.ready()) + { + pVector.addElement((Object) in.readLine()); + } + in.close(); + + } + catch(IOException e) + { + System.err.println("ptable data read exception"); + } + + + // This code is automatically generated by Visual Cafe when you add + // components to the visual environment. It instantiates and initializes + // the components. To modify the code, only use code syntax that matches + // what Visual Cafe can generate, or Visual Cafe may be unable to back + // parse your Java file into its visual environment. + + //{{INIT_CONTROLS + setLayout(null); + setVisible(false); + setSize(insets().left + insets().right + 707,insets().top + insets().bottom + 407); + textField1 = new TextField(); + textField1.setBounds(insets().left + 24,insets().top + 48,372,36); + add(textField1); + label1 = new Label("Property Name"); + label1.setBounds(insets().left + 24,insets().top + 24,132,24); + add(label1); + label2 = new Label("Associated Atomic Number"); + label2.setBounds(insets().left + 24,insets().top + 96,156,22); + add(label2); + aNumberField = new TextField(); + aNumberField.setBounds(insets().left + 24,insets().top + 120,156,36); + add(aNumberField); + label3 = new Label("Built in Properties"); + label3.setBounds(insets().left + 408,insets().top + 24,108,18); + add(label3); + checkbox1 = new Checkbox("Temporary"); + checkbox1.setBounds(insets().left + 240,insets().top + 132,84,22); + add(checkbox1); + button1 = new Button(); + button1.setLabel("<< Add Built In"); + button1.setBounds(insets().left + 264,insets().top + 252,132,25); + button1.setBackground(new Color(12632256)); + add(button1); + button2 = new Button(); + button2.setLabel("<< Add User Defined"); + button2.setBounds(insets().left + 264,insets().top + 288,132,26); + button2.setBackground(new Color(12632256)); + add(button2); + pdlist = new java.awt.List(0,false); + add(pdlist); + pdlist.setBounds(insets().left + 24,insets().top + 192,229,160); + button3 = new Button(); + button3.setLabel("Remove"); + button3.setBounds(insets().left + 264,insets().top + 324,132,27); + button3.setBackground(new Color(12632256)); + add(button3); + label4 = new Label("Property Definition"); + label4.setBounds(insets().left + 24,insets().top + 168,108,19); + add(label4); + database_add = new Button(); + database_add.setLabel("Add to Database"); + database_add.setBounds(insets().left + 24,insets().top + 360,374,23); + database_add.setBackground(new Color(12632256)); + add(database_add); + biplist = new java.awt.List(0,false); + add(biplist); + biplist.setBounds(insets().left + 408,insets().top + 48,276,336); + setTitle("Atom Property Definition"); + //}} + + //add built in properties to the list box + for (int i = 0 ; i < bipVector.size(); i++) + biplist.add((String) bipVector.elementAt(i)); + add(biplist); + + //add user-defined properties to the property dialog + pDialog = new newDialog(this); + for (int i = 0; i < pVector.size(); i++) + pDialog.addItem((String) pVector.elementAt(i)); + + //{{INIT_MENUS + mainMenuBar = new MenuBar(); + menu1 = new Menu("File"); + miOpen = new MenuItem("Edit Property"); + menu1.add(miOpen); + miReorder = new MenuItem("Reorder properties"); + menu1.add(miReorder); + miSaveAs = new MenuItem("Save Database"); + menu1.add(miSaveAs); + menu1.addSeparator(); + miExit = new MenuItem("Exit"); + menu1.add(miExit); + mainMenuBar.add(menu1); + menu2 = new Menu("Property"); + menuItem1 = new MenuItem("New Property"); + menu2.add(menuItem1); + menuItem2 = new MenuItem("Commit Property"); + menu2.add(menuItem2); + menuItem3 = new MenuItem("Remove Property"); + menu2.add(menuItem3); + mainMenuBar.add(menu2); + menu3 = new Menu("Help"); + mainMenuBar.setHelpMenu(menu3); + miAbout = new MenuItem("About.."); + menu3.add(miAbout); + mainMenuBar.add(menu3); + setMenuBar(mainMenuBar); + //$$ mainMenuBar.move(156,24); + //}} + + //{{REGISTER_LISTENERS + SymWindow aSymWindow = new SymWindow(); + this.addWindowListener(aSymWindow); + SymAction lSymAction = new SymAction(); + miOpen.addActionListener(lSymAction); + miReorder.addActionListener(lSymAction); + miAbout.addActionListener(lSymAction); + miExit.addActionListener(lSymAction); + menuItem3.addActionListener(lSymAction); + button3.addActionListener(lSymAction); + button2.addActionListener(lSymAction); + button1.addActionListener(lSymAction); + SymItem lSymItem = new SymItem(); + checkbox1.addItemListener(lSymItem); + SymText lSymText = new SymText(); + aNumberField.addTextListener(lSymText); + textField1.addTextListener(lSymText); + database_add.addActionListener(lSymAction); + menuItem1.addActionListener(lSymAction); + miSaveAs.addActionListener(lSymAction); + menuItem2.addActionListener(lSymAction); + //}} + biplist.addActionListener(lSymAction); + } + public Frame1(String title) + { + this(); + setTitle(title); + } + public void addNotify() + { + // Record the size of the window prior to calling parents addNotify. + Dimension d = getSize(); + + super.addNotify(); + + if (fComponentsAdjusted) + return; + + // Adjust components according to the insets + setSize(insets().left + insets().right + d.width, insets().top + insets().bottom + d.height); + Component components[] = getComponents(); + for (int i = 0; i < components.length; i++) + { + Point p = components[i].getLocation(); + p.translate(insets().left, insets().top); + components[i].setLocation(p); + } + fComponentsAdjusted = true; + } +/** + * Insert the method's description here. + * Creation date: (6/20/00 10:04:15 AM) + * @param v java.util.Vector + */ +protected void addPropertiesToList(atomProperty propertyToView) +{ + addPropertiesToList(propertyToView, ""); +} +/** + * Insert the method's description here. + * Creation date: (6/20/00 10:04:15 AM) + * @param v java.util.Vector + */ +protected void addPropertiesToList(atomProperty propertyToList, String prefix) { + String propertyName; + for (int i = 0; i < propertyToList.numberOfProperties(); i++) { + propertyName = biplist.getItem(propertyToList.getPropertyType(i)); + if (propertyName.endsWith("I")) + propertyName = propertyName + ": " + propertyToList.getParameterAsInt(i); + pdlist.add(prefix + i + " " + propertyName); + if (propertyName.endsWith("P")) + addPropertiesToList(propertyToList.getParameterAsProperty(i), prefix + i + " " + propertyName + propertySeperator); + + } +} + void addUserDef_Action() + { + pDialog.openForSelect(); + int selectedIndex = pDialog.getSelectedIndex(); + if (pDialog.dialogWasCancelled()) + return; + atomProperty p = aFile.getProperty(selectedIndex); + p = getSelectedSubPropertyOwner(); + p.addProperty(p); + replaceSelectedSubPropertyOwnerWith(p); + refreshPropertyDefinitionList(); + } + void aNumberField_TextValueChanged(java.awt.event.TextEvent event) + { + int val; + try + { + if (aNumberField.getText().equals("")) + val = 255; + else + val = Integer.parseInt(aNumberField.getText()); + } + catch(Exception e) + { + val = 256; + } + if (val > 255) //negative numbers not possible - "-" not a vaild integer + { + aNumberField.setText("255"); + currentProperty.setANumber(255); + return; + } + currentProperty.setANumber(val); + } + void biplist_Action() + { + atomProperty newProperty = getSelectedSubPropertyOwner(); + String param = new String(""); + String s = new String(biplist.getSelectedItem()); + int index = s.indexOf(" "); + if( index > 0) + { + if(s.substring(index,s.length()).indexOf("F") >= 0) + { + + paramDialog p = new paramDialog(this, true); + p.show(); + param = p.textField1.getText(); + + try + { + + float fParam = Float.valueOf(param).floatValue(); + newProperty.addProperty((byte)biplist.getSelectedIndex(), fParam); + } + catch (NumberFormatException e) + { + biplist_Action(); //let the user try to enter the data again + return; + } + + } + if(s.substring(index,s.length()).indexOf("P") >= 0) + { + + pDialog.openForSelect(); + param = pDialog.getItem(pDialog.getSelectedIndex()); + if (param == null) return; + newProperty.addProperty((byte)biplist.getSelectedIndex(),aFile.getProperty(pDialog.getSelectedIndex())); + } + else + { + if(s.substring(index,s.length()).indexOf("I") >= 0) + { + paramDialog p = new paramDialog(this, true); + p.show(); + param = p.textField1.getText(); + + try + { + + int iParam = Integer.parseInt(param); + newProperty.addProperty((byte)biplist.getSelectedIndex(), iParam); + } + catch (NumberFormatException e) + { + biplist_Action(); //let the user try to enter the data again + return; + } + + }//end if(s.substring(index,s.length()).indexOf("I") >= 0) + }//end else + }//end if (index > 0) + else //occurs if there are not parameters + { + newProperty.addProperty((byte)biplist.getSelectedIndex()); + } + replaceSelectedSubPropertyOwnerWith(newProperty); + refreshPropertyDefinitionList(); + return; + } + void button1_Action(java.awt.event.ActionEvent event) + { + // to do: code goes here. + + //{{CONNECTION + // Add a string to the List... Get the current item text + biplist_Action(); + //}} + } + //remove property + void button3_Action(java.awt.event.ActionEvent event) + { + atomProperty owner = getSelectedSubPropertyOwner(); + int index = getSelectedIndexInOwner(); + if (index == -1) return; + owner.removeProperty(index); + replaceSelectedSubPropertyOwnerWith(owner); + refreshPropertyDefinitionList(); + } + void checkbox1_ItemStateChanged(java.awt.event.ItemEvent event) + { + // to do: code goes here. + + //{{CONNECTION + // Disable the TextField on condition... Is Checkbox On? + aNumberField.setText("255"); + aNumberField.setEnabled(! checkbox1.getState()); + //}} + if(!checkbox1.getState()) + { + currentProperty.setANumber(255); + } + } + void database_add_Action(java.awt.event.ActionEvent event) + { + if(currentPropertyIndex == -1) + { + aFile.addProperty(currentProperty); + pDialog.addItem(currentProperty.getANumber() +" "+textField1.getText()); + } + else + aFile.replaceProperty(currentPropertyIndex, currentProperty); + //clear all values + menuItem1_Action(event); + + } + void Frame1_WindowClosing(java.awt.event.WindowEvent event) + { + hide(); // hide the Frame + dispose(); // free the system resources + System.exit(0); // close the application + } +/** + * Insert the method's description here. + * Creation date: (6/23/00 1:40:52 PM) + * @return AtomTypeFile + */ +public AtomTypeFile getFile() { + return aFile; +} +/** + * Insert the method's description here. + * Creation date: (6/22/00 4:38:28 PM) + * @return atomProperty + */ +protected int getSelectedIndexInOwner() { + String selectedItem = pdlist.getSelectedItem(); + if (selectedItem == null) return -1; + int startIndex = selectedItem.lastIndexOf(propertySeperator) + propertySeperator.length(); + if(startIndex < propertySeperator.length()) startIndex = 0; + return Integer.parseInt(selectedItem.substring(startIndex, selectedItem.indexOf(" ", startIndex))); +} +/** + * Insert the method's description here. + * Creation date: (6/22/00 4:38:28 PM) + * @return atomProperty + */ +protected atomProperty getSelectedSubPropertyOwner() { + String selectedItem = pdlist.getSelectedItem(); + if (selectedItem == null) return currentProperty; + return getSelectedSubPropertyOwner(selectedItem, currentProperty); +} +/** + * Insert the method's description here. + * Creation date: (6/22/00 4:38:28 PM) + * @return atomProperty + */ +private atomProperty getSelectedSubPropertyOwner(String listingToParse, atomProperty propertyRoot) { + int indexOfSeperator = listingToParse.indexOf(propertySeperator); + if (indexOfSeperator < 0) return propertyRoot; + int subpropertyIndex = Integer.parseInt(listingToParse.substring(0, listingToParse.indexOf(" "))); + String newListing = listingToParse.substring(indexOfSeperator + propertySeperator.length(), listingToParse.length()); + return getSelectedSubPropertyOwner(newListing, propertyRoot.getParameterAsProperty(subpropertyIndex)); +} + static public void main(String args[]) + { + (new Frame1()).show(); + } + //new Property menu action + void menuItem1_Action(java.awt.event.ActionEvent event) + { + currentPropertyIndex = -1; + currentProperty = new atomProperty(); + + //{{CONNECTION + // Enable the TextField + textField1.setEnabled(true); + //}} + + //{{CONNECTION + // Enable the TextField + aNumberField.setEnabled(true); + //}} + + //{{CONNECTION + // Clear the Checkbox + checkbox1.setState(false); + //}} + + //{{CONNECTION + // Enable the Checkbox + checkbox1.setEnabled(true); + //}} + + //{{CONNECTION + // Enable the Button + button1.setEnabled(true); + //}} + + //{{CONNECTION + // Enable the Button + button2.setEnabled(true); + //}} + + //{{CONNECTION + // Enable the List + pdlist.setEnabled(true); + //}} + + //{{CONNECTION + // Enable the Button + button3.setEnabled(true); + //}} + + //{{CONNECTION + // Enable the Button + database_add.setEnabled(true); + //}} + + //{{CONNECTION + // Enable the List + biplist.setEnabled(true); + //}} + + //{{CONNECTION + // Clear the text for TextField + textField1.setText(""); + //}} + + //{{CONNECTION + // Clear the text for TextField + aNumberField.setText(""); + //}} + + //{{CONNECTION + // Clear the List + pdlist.removeAll(); + //}} + + //{{CONNECTION + // Enable the MenuItem + menuItem2.setEnabled(true); + //}} + + //{{CONNECTION + // Disable the MenuItem + //menuItem3.disable(); + //}} + } + void menuItem2_Action(java.awt.event.ActionEvent event) + { + database_add_Action(event); + } + void miAbout_Action(java.awt.event.ActionEvent event) + { + //{{CONNECTION + // Action from About Create and show as modal + (new AboutDialog(this, true)).show(); + //}} + } + void miExit_Action(java.awt.event.ActionEvent event) + { + //{{CONNECTION + // Action from Exit Create and show as modal + (new QuitDialog(this, true)).show(); + //}} + } + //edit property + void miOpen_Action(java.awt.event.ActionEvent event) + { + pDialog.openForSelect(); + currentPropertyIndex = pDialog.getSelectedIndex(); + if (pDialog.dialogWasCancelled()) + return; + currentProperty = aFile.getProperty(currentPropertyIndex); + currentProperty.setName(pDialog.getItem(pDialog.getSelectedIndex())); + refreshPropertyDefinitionList(); + textField1.setText(currentProperty.getName()); + if(currentProperty.getANumber() == 255) + { + aNumberField.setEnabled(false); + checkbox1.setState(true); + } + else + { + checkbox1.setState(false); + aNumberField.setText(Integer.toString(currentProperty.getANumber())); + } + + //{{CONNECTION + // Disable the TextField + textField1.setEnabled(false); + //}} + + //{{CONNECTION + // Disable the TextField + aNumberField.setEnabled(false); + //}} + + //{{CONNECTION + // Disable the Checkbox + checkbox1.setEnabled(false); + //}} + + + //{{CONNECTION + // Disable the MenuItem + menuItem2.setEnabled(false); + //}} + + //{{CONNECTION + // Enable the MenuItem + menuItem3.setEnabled(true); + //}} + } + void miReorder_Action(java.awt.event.ActionEvent event) + { + pDialog.openForReorder(); + } + //Save Database menu item + void miSaveAs_Action(java.awt.event.ActionEvent event) + { + try + { + PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(newNanocad.txtDir + + newNanocad.fileSeparator + "p.txt"))); + //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("p.txt"))); + for(int i = 0; i < pDialog.getItemCount(); i++) + out.println(pDialog.getItem(i)); + out.close(); + } + catch(IOException e) + { + System.out.println("File write error: " + e.toString()); + e.printStackTrace(); + } + + aFile.writeFile(); + + } +/** + * Insert the method's description here. + * Creation date: (6/22/00 5:33:28 PM) + */ +public void refreshPropertyDefinitionList() +{ + pdlist.removeAll(); + addPropertiesToList(currentProperty); +} + //remove property + void removeProperty_Action(java.awt.event.ActionEvent event) + { + pDialog.openForSelect(); + int index = pDialog.getSelectedIndex(); + if (pDialog.dialogWasCancelled()) + return; + aFile.removeProperty(index); + pDialog.removeItem(index); + menuItem1_Action(event); + + } +/** + * Insert the method's description here. + * Creation date: (6/22/00 4:38:28 PM) + * @return atomProperty + */ +private atomProperty replaceSelectedSubPropertyOwnerWith(String listingToParse, atomProperty propertyRoot ,atomProperty newOwner) { + int indexOfSeperator = listingToParse.indexOf(propertySeperator); + if (indexOfSeperator < 0) return newOwner; + int subpropertyIndex = Integer.parseInt(listingToParse.substring(0, listingToParse.indexOf(" "))); + String newListing = listingToParse.substring(indexOfSeperator + propertySeperator.length(), listingToParse.length()); + newOwner = replaceSelectedSubPropertyOwnerWith(newListing, propertyRoot.getParameterAsProperty(subpropertyIndex), newOwner); + propertyRoot.replacePropertyParameter(subpropertyIndex, newOwner); + return propertyRoot; +} +/** + * Insert the method's description here. + * Creation date: (6/22/00 4:38:28 PM) + * @return atomProperty + */ +protected void replaceSelectedSubPropertyOwnerWith(atomProperty newOwner) { + String selectedItem = pdlist.getSelectedItem(); + if (selectedItem == null) + { + currentProperty = newOwner; + return; + } + currentProperty = replaceSelectedSubPropertyOwnerWith(selectedItem, currentProperty, newOwner); +} + public synchronized void show() + { + move(50, 50); + super.show(); + } + void textField1_TextValueChanged(java.awt.event.TextEvent event) + { + currentProperty.setName(textField1.getText()); + } +} diff --git a/src/main/java/nanocad/util/QuitDialog.java b/src/main/java/nanocad/util/QuitDialog.java new file mode 100644 index 0000000..86145b8 --- /dev/null +++ b/src/main/java/nanocad/util/QuitDialog.java @@ -0,0 +1,132 @@ +package nanocad.util; + +/* + A basic extension of the java.awt.Dialog class + */ + +import java.awt.*; +import java.awt.event.*; + +public class QuitDialog extends Dialog +{ + // Used for addNotify check. + boolean fComponentsAdjusted = false; + + //{{DECLARE_CONTROLS + Button yesButton; + Button noButton; + Label label1; + Label label2; + //}} + + class SymWindow extends WindowAdapter + { + public void windowClosing(WindowEvent event) + { + Object object = event.getSource(); + if (object == QuitDialog.this) + QuitDialog_WindowClosing(event); + } + } + + class SymAction implements ActionListener + { + public void actionPerformed(ActionEvent event) + { + Object object = event.getSource(); + if (object == noButton) + noButton_Clicked(event); + else if (object == yesButton) + yesButton_Clicked(event); + } + } + + public QuitDialog(Frame parent, String title, boolean modal) + { + this(parent, modal); + setTitle(title); + } + public QuitDialog(Frame parent, boolean modal) + { + super(parent, modal); + + // This code is automatically generated by Visual Cafe when you add + // components to the visual environment. It instantiates and initializes + // the components. To modify the code, only use code syntax that matches + // what Visual Cafe can generate, or Visual Cafe may be unable to back + // parse your Java file into its visual environment. + //{{INIT_CONTROLS + setLayout(null); + setVisible(false); + setSize(insets().left + insets().right + 337,insets().top + insets().bottom + 135); + yesButton = new Button(); + yesButton.setLabel(" Yes "); + yesButton.setBounds(insets().left + 72,insets().top + 96,79,22); + yesButton.setFont(new Font("Dialog", Font.BOLD, 12)); + add(yesButton); + noButton = new Button(); + noButton.setLabel(" No "); + noButton.setBounds(insets().left + 192,insets().top + 96,79,22); + noButton.setFont(new Font("Dialog", Font.BOLD, 12)); + add(noButton); + label1 = new Label("If you have not saved file, changes will be lost.",Label.CENTER); + label1.setBounds(insets().left + 12,insets().top + 12,312,23); + add(label1); + label2 = new Label("Really quit?",Label.CENTER); + label2.setBounds(insets().left + 72,insets().top + 48,203,22); + add(label2); + setTitle("A Basic Application - Quit"); + //}} + + //{{REGISTER_LISTENERS + SymWindow aSymWindow = new SymWindow(); + this.addWindowListener(aSymWindow); + SymAction lSymAction = new SymAction(); + noButton.addActionListener(lSymAction); + yesButton.addActionListener(lSymAction); + //}} + } + public void addNotify() + { + // Record the size of the window prior to calling parents addNotify. + Dimension d = getSize(); + + super.addNotify(); + + if (fComponentsAdjusted) + return; + + // Adjust components according to the insets + setSize(insets().left + insets().right + d.width, insets().top + insets().bottom + d.height); + Component components[] = getComponents(); + for (int i = 0; i < components.length; i++) + { + Point p = components[i].getLocation(); + p.translate(insets().left, insets().top); + components[i].setLocation(p); + } + fComponentsAdjusted = true; + } + void noButton_Clicked(ActionEvent event) + { + dispose(); + } + void QuitDialog_WindowClosing(WindowEvent event) + { + dispose(); + } + public synchronized void show() + { + Rectangle bounds = getParent().bounds(); + Rectangle abounds = bounds(); + + move(bounds.x + (bounds.width - abounds.width)/ 2, + bounds.y + (bounds.height - abounds.height)/2); + + super.show(); + } + void yesButton_Clicked(ActionEvent event) + { + Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(new WindowEvent((Window)getParent(), WindowEvent.WINDOW_CLOSING)); + } +} diff --git a/src/main/java/nanocad/util/YesNoDialog.java b/src/main/java/nanocad/util/YesNoDialog.java new file mode 100644 index 0000000..035e435 --- /dev/null +++ b/src/main/java/nanocad/util/YesNoDialog.java @@ -0,0 +1,75 @@ +package nanocad.util; + +import java.awt.*; + +/** + * Insert the type's description here. + * Creation date: (7/14/2000 12:25:34 PM) + * @author: + */ +public class YesNoDialog extends Dialog implements java.awt.event.ActionListener { + private Button yesButton = new Button("Yes"); + private Button noButton = new Button("No"); + private boolean answeredYes; +/** + * Insert the method's description here. + * Creation date: (7/14/2000 12:26:13 PM) + */ +public YesNoDialog(String question) +{ + super(new Frame(), "", true); + addComponents(question); + addActionListeners(); +} +/** + * Insert the method's description here. + * Creation date: (7/14/2000 12:40:09 PM) + * @param e java.awt.event.ActionEvent + */ +public void actionPerformed(java.awt.event.ActionEvent e) +{ + if(e.getSource() == yesButton) + closeWithYes(); + if(e.getSource() == noButton) + closeWithNo(); +} + +private void addActionListeners() +{ + yesButton.addActionListener(this); + noButton.addActionListener(this); +} + +private void addComponents(String question) +{ + setBounds(100,100,200,100); + setLayout(new FlowLayout()); + add(new Label(question)); + add(yesButton); + add(noButton); +} +public void ask() +{ + setVisible(true); +} + +private void closeWithNo() +{ + answeredYes = false; + setVisible(false); +} + +private void closeWithYes() +{ + answeredYes = true; + setVisible(false); +} + +public boolean userAnsweredNo() { + return !answeredYes; +} + +public boolean userAnsweredYes() { + return answeredYes; +} +} diff --git a/src/main/java/nanocad/util/atomProperty.java b/src/main/java/nanocad/util/atomProperty.java new file mode 100644 index 0000000..94e009b --- /dev/null +++ b/src/main/java/nanocad/util/atomProperty.java @@ -0,0 +1,207 @@ +package nanocad.util; + +import java.util.*; + +public class atomProperty +{ + //data + private Vector pList = new Vector(); + private int size; + private int anumber; + private String name = new String(""); + + + public atomProperty() + { + size = 0; + anumber = 255; + return; + } + public atomProperty(int number, byte[] data) + { + anumber = 255; + setANumber(number); + size = data.length; + //for(int q = 0; q < size; q++) System.out.println(data[q]); + int i = 0; + while(i < size) + { + Vector v = new Vector();//make vector for next property in the list + v.addElement(new Byte(data[i]));//get property number + i++; + byte pLength = data[i]; //get property length + v.addElement(new Byte(pLength)); + i++; + for(int j = 0; j < pLength; j++) + { + v.addElement(new Byte(data[i])); + i++; + } + pList.addElement(v); + } + } + //add property with no parameter + public void addProperty(byte iNum) + { + Vector data = new Vector(2); + data.addElement(new Byte(iNum)); + data.addElement(new Byte((byte) 0)); + size = size + 2; + pList.addElement(data); + } + //add property with float parameter + public void addProperty(byte iNum, float param) + { + //done using cheezy to String conversion, should be reimplemented by someone who isn't lazy + byte[] barray = (Float.toString(param)).getBytes(); + int aSize = barray.length; + Vector data = new Vector(aSize+2); + data.addElement(new Byte(iNum)); + data.addElement(new Byte((byte) aSize)); + for(int i = 0; i < aSize; i++) + { + data.addElement(new Byte(barray[i])); + } + pList.addElement(data); + } + //add property with integer parameter + public void addProperty(byte iNum, int param) + { + Vector data = new Vector(6); + data.addElement(new Byte(iNum)); + data.addElement(new Byte((byte) 4)); + //encode integer + int posParam = Math.abs(param); + data.addElement(new Byte((byte) (posParam % 256))); + data.addElement(new Byte((byte) (posParam/256 % 256))); + data.addElement(new Byte((byte) (posParam/65536 % 256))); + data.addElement(new Byte((byte) (param/16777216 % 256))); + size = size + 6; + try + { + pList.addElement(data); + } + catch(Exception e) + { + e.printStackTrace(); + + } + } + //add property with property parameter + public void addProperty(byte iNum, atomProperty param) + { + byte[] paramArray = param.toByteArray(); + Vector data = new Vector(3 + paramArray.length); + data.addElement(new Byte(iNum)); + data.addElement(new Byte((byte) paramArray.length)); + for(int i = 0; i < paramArray.length; i++) + data.addElement(new Byte(paramArray[i])); + size = size + 2 + paramArray.length; + pList.addElement(data); + } + //add property + public void addProperty(atomProperty param) + { + for (int i = 0; i < param.pList.size(); i++) + pList.addElement(((Vector) param.pList.elementAt(i)).clone()); + size = size + param.size; + } + public int getANumber() + { + return anumber; + } + public String getName() + { + return new String(name); + } + public byte[] getParameter(int propertyNum) + { + Vector property = (Vector) pList.elementAt(propertyNum); + byte[] returnVal = new byte[property.size() - 2]; + for(int i = 2; i < property.size(); i++) + returnVal[i-2] = ((Byte) property.elementAt(i)).byteValue(); + return returnVal; + } + public int getParameterAsInt(int propertyNum) + { + return paramToInt(getParameter(propertyNum)); + } + public atomProperty getParameterAsProperty(int propertyNum) + { + return new atomProperty(255, getParameter(propertyNum)); + } + public byte getPropertyType(int propertyNum) + { + Vector property = (Vector) pList.elementAt(propertyNum); + return ((Byte) property.elementAt(0)).byteValue(); + } +/** + * Insert the method's description here. + * Creation date: (6/20/00 11:20:19 AM) + * @return int + */ +public int numberOfProperties() { + return pList.size(); +} + //utility functions + + protected static int paramToInt(byte[] b) + { + return (unsignedByte(b[0]) +256*unsignedByte(b[1]) + 65536*unsignedByte(b[2]) + 16777216*b[3]); + } + protected void removeProperty(int i) + { + size = size - ((Vector) pList.elementAt(i)).size(); + pList.removeElementAt(i); + } + //add property with property parameter + public void replacePropertyParameter(int indexOfPropertyToReplace, atomProperty param) + { + byte[] paramArray = param.toByteArray(); + Vector data = new Vector(3 + paramArray.length); + Vector oldArray = (Vector) pList.elementAt(indexOfPropertyToReplace); + data.addElement(oldArray.elementAt(0)); + data.addElement(new Byte((byte) paramArray.length)); + for(int i = 0; i < paramArray.length; i++) + data.addElement(new Byte(paramArray[i])); + size = size + 2 + paramArray.length - oldArray.size(); + pList.setElementAt(data, indexOfPropertyToReplace); + } + public void setANumber(int num) + { + if ((num > -1) && (num < 256)) + anumber = num; + return; + } + public void setName(String n) + { + name = new String(n); + } + public byte[] toByteArray() + { + System.out.println("********SIZE************: "+ size); + byte[] output = new byte[size]; + int place = 0; + for(int i = 0; i < pList.size(); i++) + { + Vector v = (Vector) pList.elementAt(i); + for(int j = 0; j < v.size(); j++) + { + output[place] = ((Byte) v.elementAt(j)).byteValue(); + place++; + } + } + return output; + } + public String toString() + { + return new String("atomProperty to String NYI"); + + } + protected static int unsignedByte(byte b) + { + if(b < 0) + return 256 + (int) b; + return (int) b; + } +} diff --git a/src/main/java/nanocad/util/newDialog.java b/src/main/java/nanocad/util/newDialog.java new file mode 100644 index 0000000..71c645e --- /dev/null +++ b/src/main/java/nanocad/util/newDialog.java @@ -0,0 +1,181 @@ +package nanocad.util; + +import java.awt.*; + +public class newDialog extends Dialog implements java.awt.event.ActionListener +{ + private List propertyList = new List(); + private Button upButton = new Button("Up"); + private Button downButton = new Button("Down"); + private Button okButton = new Button("OK"); + private Button cancelButton = new Button("Cancel"); + private boolean wasCancelled; + + public newDialog(Frame owner) + { + super(owner, true); + setSize(400,400); + setInternalComponentLayout(); + setActionListeners(); + } + public void actionPerformed(java.awt.event.ActionEvent e) + { + if (e.getSource() == upButton) + reorderUp(); + if (e.getSource() == downButton) + reorderDown(); + if (e.getSource() == okButton) + closeWithOK(); + if (e.getSource() == cancelButton) + closeWithCancel(); + } + public void addItem(String item) + { + if(item == null) + return; + int i = -1 ; + int val = atomicNumberOf(item); + while(i+1 { + Platform.exit(); + System.exit(0); + }); + } + }else{ + SEAGridDialogHelper.showExceptionDialogAndWait(new Exception("Application Data Dir Does Not Exists"), + "Application Data Dir Does Not Exists", null, "Application Data Dir Does Not Exists"); + System.exit(0); + } + } + + @Subscribe + public void handleSEAGridEvents(SEAGridEvent event){ + if(event.getEventType().equals(SEAGridEvent.SEAGridEventType.LOGOUT)){ + try { + start(new Stage()); + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); + } + } + } + + public static void main(String[] args) throws IOException { + initApplicationDirs(); + launch(args); + } + + public static void initApplicationDirs() throws IOException { + createTrustStoreFileIfNotExists(); + File appDataRoot = new File(applicationDataDir()); + if(!appDataRoot.exists()){ + appDataRoot.mkdirs(); + } + if(!appDataRoot.canWrite()){ + SEAGridDialogHelper.showExceptionDialogAndWait(new Exception("Cannot Write to Application Data Dir"), + "Cannot Write to Application Data Dir", null, "Cannot Write to Application Data Dir " + applicationDataDir()); + } + + //Legacy editors use stdout and stderr instead of loggers. This is a workaround to append them to a file + System.setProperty("app.data.dir", applicationDataDir() + "logs"); + logger = LoggerFactory.getLogger(SEAGridDesktop.class); + File logParent = new File(applicationDataDir() + "logs"); + if(!logParent.exists()) + logParent.mkdirs(); + PrintStream outPs = new PrintStream(applicationDataDir() + "logs/seagrid.std.out"); + PrintStream errPs = new PrintStream(applicationDataDir() + "logs/seagrid.std.err"); + System.setOut(outPs); + System.setErr(errPs); + Runtime.getRuntime().addShutdownHook(new Thread() { + public void run() { + outPs.close(); + errPs.close(); + SEAGridContext.getInstance().saveUserPrefs(); + } + }); + + extractLegacyEditorResources(); + } + + public static void createTrustStoreFileIfNotExists() throws IOException { + File parentDir = new File(applicationDataDir()); + if(!parentDir.exists()) + parentDir.mkdirs(); + File targetFile = new File(applicationDataDir() + "client_truststore.jks"); + if(!targetFile.exists()) { + InputStream initialStream = SEAGridContext.class.getResourceAsStream("/client_truststore.jks"); + byte[] buffer = new byte[initialStream.available()]; + initialStream.read(buffer); + OutputStream outStream = new FileOutputStream(targetFile); + outStream.write(buffer); + } + } + + public static void extractLegacyEditorResources() { + try { + String destParent = applicationDataDir() + ".ApplicationData" + File.separator; + File appHome = new File(destParent); + if(!appHome.exists()){ + if(!appHome.mkdirs()){ + SEAGridDialogHelper.showExceptionDialogAndWait(new Exception("Cannot Create Application Data Dir"), + "Cannot Create Application Data Dir", null, "Cannot Create Application Data Dir"); + } + } + byte[] buf = new byte[1024]; + ZipInputStream zipinputstream; + ZipEntry zipentry; + zipinputstream = new ZipInputStream(SEAGridDesktop.class.getClassLoader().getResourceAsStream("legacy.editors.zip")); + + zipentry = zipinputstream.getNextEntry(); + if(zipentry == null){ + SEAGridDialogHelper.showExceptionDialogAndWait(new Exception("Cannot Read Application Resources"), + "Cannot Read Application Resources", null, "Cannot Read Application Resources"); + }else { + while (zipentry != null) { + //for each entry to be extracted + String entryName = destParent + zipentry.getName(); + entryName = entryName.replace('/', File.separatorChar); + entryName = entryName.replace('\\', File.separatorChar); + logger.info("entryname " + entryName); + int n; + FileOutputStream fileoutputstream; + File newFile = new File(entryName); + if (zipentry.isDirectory()) { + if (!newFile.mkdirs()) { + break; + } + zipentry = zipinputstream.getNextEntry(); + continue; + } + fileoutputstream = new FileOutputStream(entryName); + while ((n = zipinputstream.read(buf, 0, 1024)) > -1) { + fileoutputstream.write(buf, 0, n); + } + fileoutputstream.close(); + zipinputstream.closeEntry(); + zipentry = zipinputstream.getNextEntry(); + } + zipinputstream.close(); + } + } catch (Exception e) { + e.printStackTrace(); + logger.error(e.getMessage(), e); + } + } + + private static String applicationDataDir() + { + return System.getProperty("user.home") + File.separator + "SEAGrid" + File.separator; + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/connectors/.DS_Store b/src/main/java/org/seagrid/desktop/connectors/.DS_Store new file mode 100644 index 0000000..d2f8391 Binary files /dev/null and b/src/main/java/org/seagrid/desktop/connectors/.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/.DS_Store b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/.DS_Store new file mode 100644 index 0000000..31db881 Binary files /dev/null and b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/._.DS_Store b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/._.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/Exception/NextcloudApiException.java b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/Exception/NextcloudApiException.java new file mode 100644 index 0000000..3b95c92 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/Exception/NextcloudApiException.java @@ -0,0 +1,13 @@ +package org.seagrid.desktop.connectors.NextcloudStorage.Exception; + +public class NextcloudApiException extends RuntimeException { + private static final long serialVersionUID = 8088239559973590632L; + + public NextcloudApiException(Throwable cause) { + super(cause); + } + + public NextcloudApiException(String message) { + super(message); + } +} diff --git a/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextCloudFolderdownloadtask.java b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextCloudFolderdownloadtask.java new file mode 100644 index 0000000..c45a44e --- /dev/null +++ b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextCloudFolderdownloadtask.java @@ -0,0 +1,126 @@ +package org.seagrid.desktop.connectors.NextcloudStorage; + +import com.github.sardine.DavResource; +import com.jcraft.jsch.SftpException; +import org.seagrid.desktop.connectors.NextcloudStorage.Exception.NextcloudApiException; +import org.seagrid.desktop.util.SEAGridContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; +import java.util.LinkedList; +import java.util.List; + +public class NextCloudFolderdownloadtask extends NextcloudFileTask { + + private final static Logger logger = LoggerFactory.getLogger(NextCloudFolderdownloadtask.class); + + private String rootpath; + private String remoteDirPath, localDirPath; + private double totalBytesRead = 0, totalSize = 0; + + public NextCloudFolderdownloadtask(String remoteDirPath, String localDirPath) throws IOException { + super(); + rootpath = (isusehttps ? "https" : "http") +"://"+servername+"/"+basepath+ "/" + SEAGridContext.getInstance().getUserName(); + this.remoteDirPath = remoteDirPath; + this.localDirPath = localDirPath; + } + + @Override + protected Boolean call() throws Exception { + calculateNextcloudTotalSize(remoteDirPath); + boolean status = downloadFolder(remoteDirPath, localDirPath); + return status; + } + + /** + * Downloads the folder at the specified remotepath to the rootdownloadirpath + * + * @param remotepath the path in the nextcloud server with respect to the specific folder + * @param rootdownloadirpath the local path in the system where the folder needs be saved + * @return + * @throws IOException + */ + + public boolean downloadFolder(String remotepath, String rootdownloadirpath) throws IOException { + int depth=1; + String newdownloadir = rootdownloadirpath; + File localDir = new File(newdownloadir); + + if(!localDir.exists()){ + localDir.mkdirs(); + } + + String rootpathnew = rootpath + remotepath ; + + int count = 0; + String filepath; + + List retVal= new LinkedList<>(); + List resources; + try { + resources = sardine.list(rootpathnew, depth); + } catch (IOException e) { + throw new NextcloudApiException(e); + } + + for (DavResource res : resources) + { + if(count != 0) { + if(res.equals(".") || res.equals("..")){ + continue; + } + + else if(res.isDirectory()) { + String subFoldername = res.getName(); + String downloadDirtosend = newdownloadir + "/" + subFoldername; + String pathToSend = remotepath + "/" + subFoldername; + downloadFolder(pathToSend,downloadDirtosend); + } + + else { + String filename = res.getName(); + filepath = rootpathnew + "/" + filename; + retVal.add(res.getName()); + InputStream in = null; + if (sardine.exists(filepath)) { + in = sardine.get(filepath); + byte[] buffer = new byte[in.available()]; + File targetFile = new File(newdownloadir + "/" + filename); + OutputStream outStream = new FileOutputStream(targetFile); + int bytesRead = -1; + while ((bytesRead = in.read(buffer)) != -1) { + outStream.write(buffer); + totalBytesRead += bytesRead; + updateMessage("Downloaded " + totalBytesRead + " bytes"); + updateProgress(totalBytesRead, totalSize); + } + in.close(); + outStream.close(); + } + } + } + count ++; + } + return true; + } + + private void calculateNextcloudTotalSize(String remoteDirPath) throws SftpException, IOException { + List davResource = listDirectories(remoteDirPath); + int count = 0; + for (DavResource res : davResource) { + if(count != 0) { + if (res.getName().equals(".") || res.getName().equals("..")) { + continue; + } + if (res.isDirectory()) { + String tempRemoteDir = remoteDirPath + "/" + res.getName(); + calculateNextcloudTotalSize(tempRemoteDir); + } else { + totalSize += res.getContentLength().intValue(); + } + } + count++; + } + } +} diff --git a/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextcloudFileDownloadTask.java b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextcloudFileDownloadTask.java new file mode 100644 index 0000000..12e018d --- /dev/null +++ b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextcloudFileDownloadTask.java @@ -0,0 +1,49 @@ +package org.seagrid.desktop.connectors.NextcloudStorage; + +import org.seagrid.desktop.connectors.NextcloudStorage.Exception.NextcloudApiException; +import org.seagrid.desktop.util.SEAGridContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; + +public class NextcloudFileDownloadTask extends NextcloudFileTask { + + private final static Logger logger = LoggerFactory.getLogger(NextcloudFileDownloadTask.class); + + private String remoteFilePath, localFilePath; + private String remoterootpath; + + public NextcloudFileDownloadTask(String remoteFilePath, String localFilePath) throws IOException { + super(); + this.remoteFilePath = remoteFilePath; + this.localFilePath = localFilePath; + remoterootpath = (isusehttps ? "https" : "http") + "://" + servername + "/" + basepath + "/" + SEAGridContext.getInstance().getUserName(); + } + + @Override + protected Boolean call() throws Exception { + return downloadFile(localFilePath, remoteFilePath); + } + + public boolean downloadFile(String sourceFile, String destFile) { + String path = remoterootpath + destFile; + File downloadFilepath = new File(sourceFile); + if(!downloadFilepath.getParentFile().exists()) { + downloadFilepath.getParentFile().mkdirs(); + } + try { + InputStream in = sardine.get(path); + byte[] buffer = new byte[in.available()]; + in.read(buffer); + File targetFile = new File(sourceFile); + OutputStream outStream = new FileOutputStream(targetFile); + outStream.write(buffer); + outStream.close(); + in.close(); + return true; + } catch (IOException e) { + throw new NextcloudApiException(e); + } + } +} diff --git a/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextcloudFileTask.java b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextcloudFileTask.java new file mode 100644 index 0000000..50f7a03 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextcloudFileTask.java @@ -0,0 +1,64 @@ +package org.seagrid.desktop.connectors.NextcloudStorage; + +import com.github.sardine.DavResource; +import com.github.sardine.Sardine; +import com.github.sardine.SardineFactory; +import javafx.concurrent.Task; +import org.seagrid.desktop.connectors.NextcloudStorage.Exception.NextcloudApiException; +import org.seagrid.desktop.util.SEAGridContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.List; + +public abstract class NextcloudFileTask extends Task { + private final static Logger logger = LoggerFactory.getLogger(org.seagrid.desktop.connectors.NextcloudStorage.NextcloudFileTask.class); + + protected Sardine sardine = SardineFactory.begin(); + + protected String servername; + protected String basepath; + protected boolean isusehttps; + private String token; + private String rootremotepath; + + public NextcloudFileTask() throws IOException { + servername = SEAGridContext.getInstance().getNextcloudServername(); + basepath = SEAGridContext.getInstance().getDavBasepath(); + isusehttps = SEAGridContext.getInstance().isUseHttps(); + rootremotepath = (isusehttps ? "https" : "http") + "://" + servername + "/" + basepath + "/" + SEAGridContext.getInstance().getUserName(); + token = SEAGridContext.getInstance().getOAuthToken(); + sardine.setCredentials(SEAGridContext.getInstance().getUserName(), SEAGridContext.getInstance().getClientID()); + sardine.enablePreemptiveAuthentication(SEAGridContext.getInstance().getNextcloudServername()); + } + + /** + * Create the folder at the specified path + * @param remotepath + */ + public void createFolder(String remotepath){ + String path = rootremotepath+remotepath; + try { + sardine.createDirectory(path); + } catch (IOException e) { + throw new NextcloudApiException(e); + } + } + + public List listDirectories(String remotepath) throws IOException { + String path = rootremotepath + remotepath; + List resources; + if(sardine.exists(path)) { + try { + resources = sardine.list(path, 1); + return resources; + } catch (IOException e) { + e.printStackTrace(); + } + } + return null; + } +} + + diff --git a/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextcloudFileUploadTask.java b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextcloudFileUploadTask.java new file mode 100644 index 0000000..e0a0052 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextcloudFileUploadTask.java @@ -0,0 +1,73 @@ +package org.seagrid.desktop.connectors.NextcloudStorage; + +import org.seagrid.desktop.connectors.NextcloudStorage.Exception.NextcloudApiException; +import org.seagrid.desktop.util.SEAGridContext; + +import java.io.*; +import java.util.Map; + +public class NextcloudFileUploadTask extends NextcloudFileTask { + + private String remoterootpath; + private Map uploadFiles; + /** + * Constructor + */ + public NextcloudFileUploadTask(Map uploadFiles) throws IOException { + super(); + this.uploadFiles = uploadFiles; + remoterootpath = (isusehttps ? "https" : "http") + "://" + servername + "/" + basepath + "/" + SEAGridContext.getInstance().getUserName(); + } + + @Override + protected Boolean call() throws Exception { + return uploadToNextcloud(); + } + + public boolean uploadToNextcloud() throws IOException { + for(String remoteFilePath : uploadFiles.keySet()){ + int numberOfFiles = uploadFiles.size(); + int index = 1; + remoteFilePath = remoteFilePath.replace("\\","/"); + File localFile = uploadFiles.get(remoteFilePath); + String localpath = localFile.getPath(); + String remotepath = remoteFilePath; + boolean status = false; + InputStream inputStream = new FileInputStream(localpath); + String path; + try { + //createpath if not exists + String[] segments = remotepath.split("/"); + String appendpath=""; + for(int i = 1; i < segments.length - 1 ; i++) + { + appendpath = appendpath + "/" + segments[i]; + if(!sardine.exists(remoterootpath + "/" + appendpath)) { + createFolder(appendpath); + } + } + path = remoterootpath + remotepath; + long fileSize = localFile.length(); + byte[] buffer = new byte[inputStream.available()]; + int bytesRead = -1; + int totalBytesRead = 0; + double percentCompleted = 0; + while ((bytesRead = inputStream.read(buffer)) != -1) { + totalBytesRead += bytesRead; + sardine.put(path, buffer); + percentCompleted = ((double)totalBytesRead) / fileSize * index / numberOfFiles; + updateMessage("Uploaded " + totalBytesRead + " bytes"); + updateProgress(percentCompleted, 1); + } + status = true; + } catch (IOException e) { + throw new NextcloudApiException(e); + } finally { + inputStream.close(); + return status; + } + } + return true; + } + +} diff --git a/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextcloudFolderUploadTask.java b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextcloudFolderUploadTask.java new file mode 100644 index 0000000..c09b182 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextcloudFolderUploadTask.java @@ -0,0 +1,77 @@ +package org.seagrid.desktop.connectors.NextcloudStorage; + +import org.seagrid.desktop.connectors.NextcloudStorage.Exception.NextcloudApiException; +import org.seagrid.desktop.util.SEAGridContext; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; + +public class NextcloudFolderUploadTask extends NextcloudFileTask { + + private String remoterootpath; + private String remoteDirPath, localDirPath; + + public NextcloudFolderUploadTask(String remoteDirPath, String localDirPath) throws IOException { + super(); + this.remoteDirPath = remoteDirPath; + this.localDirPath = localDirPath; + remoterootpath = (isusehttps ? "https" : "http") + "://" + servername + "/" + basepath + "/" + SEAGridContext.getInstance().getUserName(); + } + + @Override + protected Boolean call() throws Exception { + return uploadFolder(localDirPath, remoteDirPath); + } + + /** + * Upload the folder at the specified path, if the folder doesn't exist a new folder with + * the specific foldername is created + * + * @param localpath + * @param remotepath + * @throws IOException + */ + public Boolean uploadFolder(String localpath, String remotepath) throws IOException { + String path; + path = remoterootpath + remotepath; + String ip = localpath; + File f = new File(ip); + try { + if (f.exists() && f.isDirectory()) { + //Extract the Foldername from the path + String[] segments = ip.split("/"); + String foldername = segments[segments.length - 1]; + String folderemotepath = remotepath + "/" + foldername; + String checkpath = remoterootpath + "/" + folderemotepath; + + //if the folder doesn't exist in the remote server then create the folder + if (!sardine.exists(checkpath)) { + createFolder(folderemotepath); + } + + File[] listfil = f.listFiles(); + if (listfil != null) { + for (File child : listfil) { + if(child.isDirectory()) { + String childfoldername = child.getName(); + String newremotepath = folderemotepath; + String newlocalpath = localpath + "/" + childfoldername; + uploadFolder(newlocalpath, newremotepath); + } else { + String filename = child.getName(); + String newpath = path + "/" + foldername + "/" + filename; + InputStream input = new FileInputStream(child.getAbsolutePath()); + sardine.put(newpath, input); + input.close(); + } + } + } + } + } catch (IOException e) { + throw new NextcloudApiException(e); + } + return true; + } +} diff --git a/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextcloudSingleFileUploadTask.java b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextcloudSingleFileUploadTask.java new file mode 100644 index 0000000..e24026f --- /dev/null +++ b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextcloudSingleFileUploadTask.java @@ -0,0 +1,63 @@ +package org.seagrid.desktop.connectors.NextcloudStorage; + +import org.seagrid.desktop.connectors.NextcloudStorage.Exception.NextcloudApiException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; + +public class NextcloudSingleFileUploadTask extends NextcloudFileTask{ + + private final static Logger logger = LoggerFactory.getLogger(NextcloudSingleFileUploadTask.class); + + private String remoteFilePath, localFilePath; + private String remoterootpath; + + public NextcloudSingleFileUploadTask(String remoteFilePath, String localFilePath) throws IOException { + super(); + this.remoteFilePath = remoteFilePath; + this.localFilePath = localFilePath; + } + + + @Override + protected Boolean call() throws Exception { + return uploadFile(remoteFilePath, localFilePath); + } + + /** + * Upload the inputstream to the remote file path as specified to the nextcloud server + * + * @param localpath + * @param remotepath + * @throws IOException + * + */ + protected boolean uploadFile(String localpath, String remotepath) throws IOException { + boolean status = false; + InputStream inputStream = new FileInputStream(localpath); + String path; + try { + //createpath if not exists + String[] segments = remotepath.split("/"); + String appendpath=""; + for(int i = 1; i < segments.length - 1 ; i++) + { + appendpath = appendpath + "/" + segments[i]; + if(!sardine.exists(remoterootpath + "/" + appendpath)) { + createFolder(appendpath); + } + } + path = remoterootpath + remotepath; + sardine.put(path, inputStream); + status = true; + } catch (IOException e) { + throw new NextcloudApiException(e); + } finally { + inputStream.close(); + return status; + } + } +} diff --git a/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextcloudStorageManager.java b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextcloudStorageManager.java new file mode 100644 index 0000000..81f7a49 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/connectors/NextcloudStorage/NextcloudStorageManager.java @@ -0,0 +1,95 @@ +package org.seagrid.desktop.connectors.NextcloudStorage; + +import com.github.sardine.DavResource; +import com.github.sardine.Sardine; +import com.github.sardine.SardineFactory; +import com.jcraft.jsch.JSchException; +import org.seagrid.desktop.connectors.NextcloudStorage.Exception.NextcloudApiException; +import org.seagrid.desktop.util.SEAGridContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.List; + +public class NextcloudStorageManager { + private final static Logger logger = LoggerFactory.getLogger(NextcloudStorageManager.class); + + private static NextcloudStorageManager instance; + + protected Sardine sardine = SardineFactory.begin(); + + private String servername; + private String basepath; + private boolean isusehttps; + private String token; + private String rootremotepath; + + public NextcloudStorageManager() throws IOException, JSchException { + connect(); + } + + private void connect() throws JSchException, IOException { + servername = SEAGridContext.getInstance().getNextcloudServername(); + basepath = SEAGridContext.getInstance().getDavBasepath(); + isusehttps = SEAGridContext.getInstance().isUseHttps(); + rootremotepath = (isusehttps ? "https" : "http") + "://" + servername + "/" + basepath + "/" + SEAGridContext.getInstance().getUserName(); + token = SEAGridContext.getInstance().getOAuthToken(); + sardine.setCredentials(SEAGridContext.getInstance().getUserName(), SEAGridContext.getInstance().getClientID()); + sardine.enablePreemptiveAuthentication(SEAGridContext.getInstance().getNextcloudServername()); + } + + public static NextcloudStorageManager getInstance() throws JSchException, IOException { + if(instance==null) { + instance = new NextcloudStorageManager(); + } + return instance; + } + + public List listDirectories(String remotepath) throws IOException { + String path = rootremotepath + remotepath; + List resources; + if(sardine.exists(path)) { + try { + resources = sardine.list(path, 1); + return resources; + } catch (IOException e) { + e.printStackTrace(); + } + } + return null; + } + + /** + * Creates the folder if the folder is not present at the remote path of the nextcloud storage + * @param remotepath + * @throws IOException + */ + public void createFolderifNotExist(String remotepath) throws IOException { + String[] segments = remotepath.split("/"); + + String tempath = ""; + for (int i = 1; i < segments.length; i++) { + tempath = tempath + "/" + segments[i]; + String path = rootremotepath + tempath; + if (!sardine.exists(path)) { + createFolder(tempath); + } + } + } + + /** + * Create the folder at the specified path + * @param remotepath + */ + public void createFolder(String remotepath) + { + String path= rootremotepath+remotepath; + + try { + sardine.createDirectory(path); + } catch (IOException e) { + throw new NextcloudApiException(e); + } + } +} diff --git a/src/main/java/org/seagrid/desktop/connectors/airavata/.DS_Store b/src/main/java/org/seagrid/desktop/connectors/airavata/.DS_Store new file mode 100644 index 0000000..5a1f574 Binary files /dev/null and b/src/main/java/org/seagrid/desktop/connectors/airavata/.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/connectors/airavata/AiravataCache.java b/src/main/java/org/seagrid/desktop/connectors/airavata/AiravataCache.java new file mode 100644 index 0000000..8a18ea2 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/connectors/airavata/AiravataCache.java @@ -0,0 +1,129 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.connectors.airavata; + +import java.util.ArrayList; +import org.apache.commons.collections.MapIterator; +import org.apache.commons.collections.map.LRUMap; + + +public class AiravataCache { + + private long timeToLive; + private LRUMap crunchifyCacheMap; + + protected class AiravataCacheObject { + public long lastAccessed = System.currentTimeMillis(); + public T value; + + protected AiravataCacheObject(T value) { + this.value = value; + } + } + + public AiravataCache(long crunchifyTimeToLive, final long crunchifyTimerInterval, int maxItems) { + this.timeToLive = crunchifyTimeToLive * 1000; + + crunchifyCacheMap = new LRUMap(maxItems); + + if (timeToLive > 0 && crunchifyTimerInterval > 0) { + + Thread t = new Thread(new Runnable() { + public void run() { + while (true) { + try { + Thread.sleep(crunchifyTimerInterval * 1000); + } catch (InterruptedException ex) { + } + cleanup(); + } + } + }); + + t.setDaemon(true); + t.start(); + } + } + + public void put(K key, T value) { + synchronized (crunchifyCacheMap) { + crunchifyCacheMap.put(key, new AiravataCacheObject(value)); + } + } + + @SuppressWarnings("unchecked") + public T get(K key) { + synchronized (crunchifyCacheMap) { + AiravataCacheObject c = (AiravataCacheObject) crunchifyCacheMap.get(key); + + if (c == null) + return null; + else { + c.lastAccessed = System.currentTimeMillis(); + return c.value; + } + } + } + + public void remove(K key) { + synchronized (crunchifyCacheMap) { + crunchifyCacheMap.remove(key); + } + } + + public int size() { + synchronized (crunchifyCacheMap) { + return crunchifyCacheMap.size(); + } + } + + @SuppressWarnings("unchecked") + public void cleanup() { + + long now = System.currentTimeMillis(); + ArrayList deleteKey = null; + + synchronized (crunchifyCacheMap) { + MapIterator itr = crunchifyCacheMap.mapIterator(); + + deleteKey = new ArrayList((crunchifyCacheMap.size() / 2) + 1); + K key = null; + AiravataCacheObject c = null; + + while (itr.hasNext()) { + key = (K) itr.next(); + c = (AiravataCacheObject) itr.getValue(); + + if (c != null && (now > (timeToLive + c.lastAccessed))) { + deleteKey.add(key); + } + } + } + + for (K key : deleteKey) { + synchronized (crunchifyCacheMap) { + crunchifyCacheMap.remove(key); + } + + Thread.yield(); + } + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/connectors/airavata/AiravataManager.java b/src/main/java/org/seagrid/desktop/connectors/airavata/AiravataManager.java new file mode 100644 index 0000000..55e23c4 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/connectors/airavata/AiravataManager.java @@ -0,0 +1,269 @@ +package org.seagrid.desktop.connectors.airavata; + +import org.apache.airavata.api.Airavata; +import org.apache.airavata.model.appcatalog.appinterface.ApplicationInterfaceDescription; +import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription; +import org.apache.airavata.model.appcatalog.userresourceprofile.UserComputeResourcePreference; +import org.apache.airavata.model.data.replica.DataProductModel; +import org.apache.airavata.model.data.replica.DataReplicaLocationModel; +import org.apache.airavata.model.error.*; +import org.apache.airavata.model.experiment.ExperimentModel; +import org.apache.airavata.model.experiment.ExperimentSearchFields; +import org.apache.airavata.model.experiment.ExperimentSummaryModel; +import org.apache.airavata.model.security.AuthzToken; +import org.apache.airavata.model.status.JobStatus; +import org.apache.airavata.model.workspace.Notification; +import org.apache.airavata.model.workspace.Project; +import org.apache.thrift.TException; +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TProtocol; +import org.apache.thrift.transport.TSSLTransportFactory; +import org.apache.thrift.transport.TTransport; +import org.apache.thrift.transport.TTransportException; +import org.seagrid.desktop.util.SEAGridContext; +import org.seagrid.desktop.util.messaging.SEAGridEvent; +import org.seagrid.desktop.util.messaging.SEAGridEventBus; + +import java.io.File; +import java.util.*; +import java.util.stream.Collectors; + +public class AiravataManager { + + private static AiravataManager instance; + + private Airavata.Client airavataClient; + + private AiravataCache airavataCache; + + private AiravataManager() throws AiravataClientException { + try { + this.airavataClient = createAiravataClient(); + this.airavataCache = new AiravataCache<>(200, 500, 50); + } catch (Exception e) { + e.printStackTrace(); + throw new AiravataClientException(AiravataErrorType.UNKNOWN); + } + } + + public static AiravataManager getInstance() throws AiravataClientException { + if (AiravataManager.instance == null) { + AiravataManager.instance = new AiravataManager(); + } + return AiravataManager.instance; + } + + private Airavata.Client createAiravataClient() throws TTransportException { + String host = SEAGridContext.getInstance().getAiravataHost(); + int port = SEAGridContext.getInstance().getAiravataPort(); + String applicationDataDir = System.getProperty("user.home") + File.separator + "SEAGrid" + File.separator; + TSSLTransportFactory.TSSLTransportParameters params = new TSSLTransportFactory.TSSLTransportParameters(); + params.setTrustStore(applicationDataDir + "client_truststore.jks", "password"); + TTransport transport = TSSLTransportFactory.getClientSocket(host, port, 10000, params); + TProtocol protocol = new TBinaryProtocol(transport); + return new Airavata.Client(protocol); + } + + private Airavata.Client getClient() throws AiravataClientException, TTransportException { + try{ + airavataClient.getAPIVersion(getAuthzToken()); + } catch (Exception e) { + try{ + airavataClient = createAiravataClient(); + airavataClient.getAPIVersion(getAuthzToken()); + } catch (Exception e1) { + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.LOGOUT, null)); + } + } + return airavataClient; + } + + private AuthzToken getAuthzToken() { + AuthzToken authzToken = new AuthzToken(SEAGridContext.getInstance().getOAuthToken()); + authzToken.setClaimsMap(new HashMap<>()); + authzToken.getClaimsMap().put("gatewayID", SEAGridContext.getInstance().getAiravataGatewayId()); + authzToken.getClaimsMap().put("userName", SEAGridContext.getInstance().getUserName()); + return authzToken; + } + + private String getGatewayId() { + return SEAGridContext.getInstance().getAiravataGatewayId(); + } + + private String getUserName() { + return SEAGridContext.getInstance().getUserName(); + } + + public synchronized List getExperimentSummaries(Map filters, + int limit, int offset) throws TException { + List exp = getClient().searchExperiments( + getAuthzToken(), getGatewayId(), getUserName(), filters, limit, offset); + return exp; + } + + public synchronized List getExperimentSummariesInProject(String projectId) throws TException { + List exp; + Map filters = new HashMap<>(); + filters.put(ExperimentSearchFields.PROJECT_ID, projectId); + exp = getClient().searchExperiments( + getAuthzToken(), getGatewayId(), getUserName(), filters, -1, 0); + return exp; + } + + public synchronized List getRecentExperimentSummaries(int limit) throws TException { + List exp; + + Map filters = new HashMap<>(); + exp = getClient().searchExperiments( + getAuthzToken(), getGatewayId(), getUserName(), filters, limit, 0); + return exp; + } + + public synchronized List getProjects() throws TException { + List projects; + try{ + projects = getClient().getUserProjects( + getAuthzToken(), getGatewayId(), getUserName(), -1, 0); + }catch (Exception ex){ + //FIXME If the user is new getProjects will fail + getClient().createProject(getAuthzToken(),getGatewayId(),new Project("", getUserName(), + SEAGridContext.getInstance().getAiravataGatewayId(), "Default Project")); + projects = getClient().getUserProjects( + getAuthzToken(), getGatewayId(), getUserName(), -1, 0); + } + return projects; + } + + public synchronized Project createProject(String projectName, String projectDescription) throws TException { + Project project; + project = new Project("no-id", getUserName(), SEAGridContext.getInstance().getAiravataGatewayId(), projectName); + if (projectDescription != null) + project.setDescription(projectDescription); + String projectId = getClient().createProject( + getAuthzToken(), getGatewayId(), project); + project.setProjectID(projectId); + + return project; + } + + public synchronized ExperimentModel getExperiment(String experimentId) throws TException { + return getClient().getExperiment(getAuthzToken(), experimentId); + } + + public synchronized ComputeResourceDescription getComputeResource(String resourceId) throws TException { + ComputeResourceDescription computeResourceDescription; + + if (airavataCache.get(resourceId) != null) { + computeResourceDescription = (ComputeResourceDescription) airavataCache.get(resourceId); + } else { + computeResourceDescription = getClient().getComputeResource(getAuthzToken(), resourceId); + airavataCache.put(resourceId, computeResourceDescription); + } + return computeResourceDescription; + } + + public synchronized ApplicationInterfaceDescription getApplicationInterface(String interfaceId) throws TException { + ApplicationInterfaceDescription applicationInterfaceDescription = null; + + if (airavataCache.get(interfaceId) != null) { + applicationInterfaceDescription = (ApplicationInterfaceDescription) airavataCache.get(interfaceId); + } else { + applicationInterfaceDescription = getClient().getApplicationInterface(getAuthzToken(), interfaceId); + airavataCache.put(interfaceId, applicationInterfaceDescription); + } + + return applicationInterfaceDescription; + } + + public synchronized Project getProject(String projectId) throws TException { + Project project; + if (airavataCache.get(projectId) != null) { + project = (Project) airavataCache.get(projectId); + } else { + project = getClient().getProject(getAuthzToken(), projectId); + airavataCache.put(projectId, project); + } + return project; + } + + public synchronized Map getJobStatuses(String expId) throws TException { + Map jobStatuses; + jobStatuses = getClient().getJobStatuses(getAuthzToken(), expId); + return jobStatuses; + } + + public synchronized List getAllApplicationInterfaces() throws TException { + List allApplicationInterfaces; + allApplicationInterfaces = getClient().getAllApplicationInterfaces(getAuthzToken(), getGatewayId()); + Collections.sort(allApplicationInterfaces, (o1, o2) -> o1.getApplicationName().compareTo(o2.getApplicationName())); + return allApplicationInterfaces; + } + + public synchronized List getAvailableComputeResourcesForApp(String applicationInterfaceId) + throws TException { + List availableComputeResources; + Map temp = getClient().getAvailableAppInterfaceComputeResources(getAuthzToken(), applicationInterfaceId); + availableComputeResources = new ArrayList<>(); + for (String resourceId : temp.keySet()) { + availableComputeResources.add(getComputeResource(resourceId)); + } + return availableComputeResources; + } + + public synchronized String createExperiment(ExperimentModel experimentModel) throws TException { + return getClient().createExperiment(getAuthzToken(), getGatewayId(), experimentModel); + } + + public synchronized void updateExperiment(ExperimentModel experimentModel) throws TException { + getClient().updateExperiment(getAuthzToken(), experimentModel.getExperimentId(), experimentModel); + } + + public synchronized void launchExperiment(String experimentId) throws TException { + getClient().launchExperiment(getAuthzToken(), experimentId, getGatewayId()); + } + + public synchronized void deleteExperiment(String experimentId) throws TException { + getClient().deleteExperiment(getAuthzToken(), experimentId); + } + + public synchronized void cancelExperiment(String experimentId) throws TException { + getClient().terminateExperiment(getAuthzToken(),experimentId, getGatewayId()); + } + + public synchronized String cloneExperiment(String experimentId, String newExpName, String projectId) throws TException { + return getClient().cloneExperiment(getAuthzToken(), experimentId, newExpName, projectId); + } + + public String registerDataProduct(DataProductModel dpModel) throws TException { + return getClient().registerDataProduct(getAuthzToken(), dpModel); + } + + public List getDataReplicas(String uri) throws TException { + return getClient().getDataProduct(getAuthzToken(), uri).getReplicaLocations(); + } + + public List getNotifications() throws TException { + //We don't need security token for calling getNotifications API method + java.util.List temp = (createAiravataClient()).getAllNotifications(new AuthzToken("dummy-token"), + SEAGridContext.getInstance().getAiravataGatewayId()); + java.util.List messages = new ArrayList<>(); + if(temp != null){ + messages.addAll(temp.stream().filter(m -> m.getExpirationTime() > System.currentTimeMillis() + || m.getExpirationTime() == 0).collect(Collectors.toList())); + } + return messages; + } + + public UserComputeResourcePreference getUserComputeResourcePrefs(String computeResourceId) throws TException { + UserComputeResourcePreference userComputeResourcePreference = null; + try{ + userComputeResourcePreference = getClient().getUserComputeResourcePreference(getAuthzToken(), + SEAGridContext.getInstance().getUserName(), SEAGridContext.getInstance().getAiravataGatewayId(), + computeResourceId); + return userComputeResourcePreference; + }catch (Exception ex) { + //User compute resource pref does not exists + return null; + } + } +} diff --git a/src/main/java/org/seagrid/desktop/connectors/storage/GuiBulkFileUploadTask.java b/src/main/java/org/seagrid/desktop/connectors/storage/GuiBulkFileUploadTask.java new file mode 100644 index 0000000..f2e0edb --- /dev/null +++ b/src/main/java/org/seagrid/desktop/connectors/storage/GuiBulkFileUploadTask.java @@ -0,0 +1,146 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.connectors.storage; + +import com.jcraft.jsch.JSchException; +import com.jcraft.jsch.SftpException; +import javafx.scene.control.Alert; +import javafx.scene.control.ButtonType; +import org.seagrid.desktop.util.SEAGridContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; +import java.nio.file.Paths; +import java.util.Map; +import java.util.logging.FileHandler; +import java.util.logging.SimpleFormatter; + + +public class GuiBulkFileUploadTask extends GuiFileTask { + private final static Logger logger = LoggerFactory.getLogger(GuiBulkFileUploadTask.class); + + private Map uploadFiles; + + public GuiBulkFileUploadTask(Map uploadFiles) throws JSchException { + super(); + this.uploadFiles = uploadFiles; + } + + @Override + protected Boolean call() throws Exception { + //return uploadFiles(this.uploadFiles); + //next.UploadFile(uploadFiles.get()) + return uploadtonextcloud(); + } + + public boolean uploadFiles(Map uploadFiles) throws IOException, SftpException { + int numberOfFiles = uploadFiles.size(); + int index = 1; + for(String remoteFilePath : uploadFiles.keySet()) { + remoteFilePath = remoteFilePath.replace("\\","/"); + //System.out.println(entry.getKey() + ":" + entry.getValue().toString()); + //Alert alert = new Alert(Alert.AlertType.CONFIRMATION, remoteFilePath, ButtonType.YES, ButtonType.NO, ButtonType.CANCEL); + //alert.show(); + + //System.out.println(remoteFilePath); + //My code + /* + String str = "Hello"; + String fileName="create.txt"; + BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); + writer.write(""+remoteFilePath+"\n"); + */ + createRemoteParentDirsIfNotExists(Paths.get(remoteFilePath).getParent().toString()); + + OutputStream remoteOutputStream = new BufferedOutputStream(channelSftp.put(remoteFilePath)); + File localFile = uploadFiles.get(remoteFilePath); + String localpath = localFile.getPath(); + String remotepath = "Documents" + remoteFilePath; + //writer.write(""+next.UploadFile("/Users/kkotabag/Desktop/test/Fileupload/third.txt","/Documents/third.txt")+""); + InputStream localInputStream = new FileInputStream(localFile); + //writer.close(); + long fileSize = localFile.length(); + byte[] buffer = new byte[BUFFER_SIZE]; + int bytesRead = -1; + int totalBytesRead = 0; + double percentCompleted = 0; + + while ((bytesRead = localInputStream.read(buffer)) != -1) { + remoteOutputStream.write(buffer, 0, bytesRead); + totalBytesRead += bytesRead; + percentCompleted = ((double)totalBytesRead) / fileSize * index / numberOfFiles; + updateMessage("Uploaded " + totalBytesRead + " bytes"); + updateProgress(percentCompleted, 1); + } + + remoteOutputStream.close(); + localInputStream.close(); + index++; + } + return true; + } + + + public boolean uploadtonextcloud() throws IOException { + for(String remoteFilePath : uploadFiles.keySet()){ + remoteFilePath = remoteFilePath.replace("\\","/"); + //System.out.println(entry.getKey() + ":" + entry.getValue().toString()); + //Alert alert = new Alert(Alert.AlertType.CONFIRMATION, remoteFilePath, ButtonType.YES, ButtonType.NO, ButtonType.CANCEL); + //alert.show(); + //System.out.println(remoteFilePath); + //My code + String str = "Hello"; + String fileName="create.txt"; + BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); + writer.write(""+remoteFilePath+"\n"); + File localFile = uploadFiles.get(remoteFilePath); + String localpath = localFile.getPath(); + writer.write(localpath); + + String remotepath = remoteFilePath; + + writer.write(""+next.UploadFile(localpath,remotepath)+""); + //writer.write(SEAGridContext.getInstance().getOAuthToken()); + InputStream localInputStream = new FileInputStream(localFile); + writer.close(); + } + return true; + } + + private void createRemoteParentDirsIfNotExists(String parentDirPath) throws SftpException { + parentDirPath = parentDirPath.replace("\\","/"); + channelSftp.cd("/"); + String[] folders = parentDirPath.split( "/" ); + for ( String folder : folders ) { + if ( folder.length() > 0 ) { + try { + channelSftp.cd(folder); + } + catch ( SftpException e ) { + channelSftp.mkdir( folder ); + channelSftp.chmod(Integer.parseInt("777",8), folder); + channelSftp.cd( folder ); + } + } + } + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/connectors/storage/GuiDirDownloadTask.java b/src/main/java/org/seagrid/desktop/connectors/storage/GuiDirDownloadTask.java new file mode 100644 index 0000000..3a230a9 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/connectors/storage/GuiDirDownloadTask.java @@ -0,0 +1,157 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.connectors.storage; + +import com.github.sardine.DavResource; +import com.jcraft.jsch.*; +import javafx.scene.control.ProgressIndicator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; +import java.util.List; +import java.util.Vector; + + +public class GuiDirDownloadTask extends GuiFileTask { + private final static Logger logger = LoggerFactory.getLogger(GuiDirDownloadTask.class); + + private String remoteDirPath, localDirPath; + private double totalBytesRead = 0, totalSize = 0; + + public GuiDirDownloadTask(String remoteDirPath, String localDirPath) throws JSchException { + super(); + this.remoteDirPath = remoteDirPath; + this.localDirPath = localDirPath; + } + + @Override + protected Boolean call() throws Exception { + String fileName="CalculateSizeDownloadFolderLog.txt"; + BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); + + String fileName2="CalculateSizeNextcloudDownloadFolderLog.txt"; + BufferedWriter writer2 = new BufferedWriter(new FileWriter(fileName2)); + calculateNextcloudTotalSize(remoteDirPath, writer2); + calculateTotalSize(remoteDirPath, writer); + writer.close(); + writer2.close(); + return downloadDir(remoteDirPath, localDirPath); + //return nextcloudDownloadDir(remoteDirPath, localDirPath); + } + + public Boolean downloadDir(String remoteDirPath, String localDirPath) throws SftpException, IOException { + + String fileName="DirDownloadLog.txt"; + BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); + writer.write("\nRemotepath ---> "+remoteDirPath); + writer.write("\nLocalpath--->"+localDirPath); + writer.close(); + + //Creating the local directory if the path doesn't exist + File localDir = new File(localDirPath); + if(!localDir.exists()){ + localDir.mkdirs(); + } + + Vector lsEntries = channelSftp.ls(remoteDirPath); + for(ChannelSftp.LsEntry lsEntry : lsEntries){ + if(lsEntry.getFilename().equals(".") || lsEntry.getFilename().equals("..")){ + continue; + } + if(lsEntry.getAttrs().isDir()){ + String tempLocalDir = localDirPath + File.separator + lsEntry.getFilename(); + String tempRemoteDir = remoteDirPath + "/" + lsEntry.getFilename(); + downloadDir(tempRemoteDir, tempLocalDir); + }else{ + File localFile = new File(localDirPath + File.separator + lsEntry.getFilename()); + OutputStream localOutputStream = new FileOutputStream(localFile); + BufferedInputStream remoteInputStream = new BufferedInputStream(channelSftp.get(remoteDirPath + + "/" + lsEntry.getFilename())); + byte[] buffer = new byte[BUFFER_SIZE]; + int bytesRead = -1; + while ((bytesRead = remoteInputStream.read(buffer)) != -1) { + localOutputStream.write(buffer, 0, bytesRead); + totalBytesRead += bytesRead; + updateMessage("Downloaded " + totalBytesRead + " bytes"); + updateProgress(totalBytesRead, totalSize); + } + remoteInputStream.close(); + localOutputStream.close(); + } + } + return true; + } + + + + private void calculateTotalSize(String remoteDirPath, BufferedWriter writer) throws SftpException, IOException { + Vector lsEntries = channelSftp.ls(remoteDirPath); + + for(ChannelSftp.LsEntry lsEntry : lsEntries){ + if(lsEntry.getFilename().equals(".") || lsEntry.getFilename().equals("..")){ + continue; + } + if(lsEntry.getAttrs().isDir()){ + String tempRemoteDir = remoteDirPath + "/" + lsEntry.getFilename(); + calculateTotalSize(tempRemoteDir, writer); + }else { + totalSize += lsEntry.getAttrs().getSize(); + writer.write("\n Total Size"+totalSize); + } + } + } + + private void calculateNextcloudTotalSize(String remoteDirPath, BufferedWriter writer2) throws SftpException, IOException { + //Vector lsEntries = channelSftp.ls(remoteDirPath); + List davResource = next.listDirectories(remoteDirPath); + // for(ChannelSftp.LsEntry lsEntry : lsEntries){ + int count = 0; + for (DavResource res : davResource) { + if(count != 0) { + if (res.getName().equals(".") || res.getName().equals("..")) { + continue; + } + if (res.isDirectory()) { + String tempRemoteDir = remoteDirPath + "/" + res.getName(); + calculateNextcloudTotalSize(tempRemoteDir, writer2); + } else { + totalSize += res.getContentLength().intValue(); + writer2.write("\n TotalSize" + totalSize); + } + } + count++; + } + } + + + public boolean nextcloudDownloadDir(String remoteDirPath, String localDirPath) throws IOException { + + String downlfile="DownloadDirNextcloudEntry.txt"; + BufferedWriter writer1 = new BufferedWriter(new FileWriter(downlfile)); + if(next.downloadFolder(remoteDirPath, localDirPath, writer1)) { + writer1.close(); + return true; + } + return false; + } + +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/connectors/storage/GuiDirUploadTask.java b/src/main/java/org/seagrid/desktop/connectors/storage/GuiDirUploadTask.java new file mode 100644 index 0000000..622592e --- /dev/null +++ b/src/main/java/org/seagrid/desktop/connectors/storage/GuiDirUploadTask.java @@ -0,0 +1,106 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.connectors.storage; + +import com.jcraft.jsch.JSchException; +import com.jcraft.jsch.SftpException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; + + +public class GuiDirUploadTask extends GuiFileTask { + private final static Logger logger = LoggerFactory.getLogger(GuiDirUploadTask.class); + + private String remoteDirPath, localDirPath; + private double totalBytesRead = 0, totalSize = 0; + + public GuiDirUploadTask(String remoteDirPath, String localDirPath) throws JSchException { + super(); + this.remoteDirPath = remoteDirPath; + this.localDirPath = localDirPath; + } + + @Override + protected Boolean call() throws Exception { + calculateTotalSize(localDirPath); + return downloadDir(remoteDirPath, localDirPath); + } + + public Boolean downloadDir(String remoteDirPath, String localDirPath) throws SftpException, IOException { + createRemoteDirsIfNotExists(remoteDirPath); + File localDir = new File(localDirPath); + for(File file : localDir.listFiles()){ + if(file.getName().equals(".") || file.getName().equals("..")){ + continue; + } + if(file.isDirectory()){ + String tempLocalDir = file.getAbsolutePath(); + String tempRemoteDir = remoteDirPath + "/" + file.getName(); + downloadDir(tempRemoteDir, tempLocalDir); + }else{ + FileInputStream localInputStream = new FileInputStream(file); + BufferedOutputStream remoteOutputStream = new BufferedOutputStream(channelSftp.put(remoteDirPath + + "/" + file.getName())); + byte[] buffer = new byte[BUFFER_SIZE]; + int bytesRead = -1; + while ((bytesRead = localInputStream.read(buffer)) != -1) { + remoteOutputStream.write(buffer, 0, bytesRead); + totalBytesRead += bytesRead; + updateMessage("Uploaded " + totalBytesRead + " bytes"); + updateProgress(totalBytesRead, totalSize); + } + remoteOutputStream.close(); + localInputStream.close(); + } + } + return true; + } + + private void calculateTotalSize(String localDirPath) throws SftpException, IOException { + for (File file : (new File(localDirPath)).listFiles()) { + if (file.isFile()) + totalSize += file.length(); + else + calculateTotalSize(file.getPath().toString()); + } + } + + private void createRemoteDirsIfNotExists(String parentDirPath) throws SftpException { + String[] folders = parentDirPath.split( "/" ); + for ( String folder : folders ) { + if ( folder.length() > 0 ) { + try { + channelSftp.cd(folder); + } + catch ( SftpException e ) { + channelSftp.mkdir( folder ); + channelSftp.chmod(Integer.parseInt("777",8), folder); + channelSftp.cd( folder ); + } + } + } + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/connectors/storage/GuiFileDownloadTask.java b/src/main/java/org/seagrid/desktop/connectors/storage/GuiFileDownloadTask.java new file mode 100644 index 0000000..929a853 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/connectors/storage/GuiFileDownloadTask.java @@ -0,0 +1,120 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.connectors.storage; + +import com.jcraft.jsch.JSchException; +import com.jcraft.jsch.SftpATTRS; +import com.jcraft.jsch.SftpException; +import org.seagrid.desktop.util.SEAGridContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; + + +public class GuiFileDownloadTask extends GuiFileTask { + private final static Logger logger = LoggerFactory.getLogger(GuiFileDownloadTask.class); + + private String remoteFilePath, localFilePath; + + public GuiFileDownloadTask(String remoteFilePath, String localFilePath) throws JSchException { + super(); + this.remoteFilePath = remoteFilePath; + this.localFilePath = localFilePath; + } + + @Override + protected Boolean call() throws Exception { + String downlfile="DownloadFile.txt"; + BufferedWriter writer1 = new BufferedWriter(new FileWriter(downlfile)); + writer1.write("Downloading file : \n"); + writer1.write("\nDownload File Remote path:--->"+remoteFilePath); + writer1.write("\nDownload File Local path:--->"+localFilePath); + writer1.close(); + //return downloadFile(remoteFilePath, localFilePath); + return nextcloudDownloadFile(remoteFilePath, localFilePath); + } + + public Boolean downloadFile(String remoteFilePath, String localFilePath) throws SftpException, IOException { + String downlfile="DownloadFile2.txt"; + BufferedWriter writer2 = new BufferedWriter(new FileWriter(downlfile)); + writer2.write("\nDownload File Remote path:--->"+remoteFilePath); + writer2.write("\nDownload File Local path:--->"+localFilePath); + + remoteFilePath = remoteFilePath.replace("\\","/"); + writer2.write("\nDownload File Remote path after replacement:--->"+remoteFilePath); + writer2.close(); + + remoteFilePath = remoteFilePath.replaceAll(SEAGridContext.getInstance().getUserName(), ""); + InputStream remoteInputStream = new BufferedInputStream(channelSftp.get(remoteFilePath)); + File localFile = new File(localFilePath); + if(!localFile.getParentFile().exists()){ + localFile.getParentFile().mkdirs(); + } + + OutputStream localOutputStream = new FileOutputStream(localFile); + SftpATTRS attrs = channelSftp.lstat(remoteFilePath); + long fileSize = attrs.getSize(); + byte[] buffer = new byte[BUFFER_SIZE]; + int bytesRead = -1; + long totalBytesRead = 0; + double percentCompleted = 0; + + while ((bytesRead = remoteInputStream.read(buffer)) != -1) { + localOutputStream.write(buffer, 0, bytesRead); + totalBytesRead += bytesRead; + percentCompleted = ((double)totalBytesRead)/ fileSize; + updateMessage("Downloaded " + totalBytesRead + " bytes"); + updateProgress(percentCompleted, 1); + } + + remoteInputStream.close(); + localOutputStream.close(); + + return true; + } +/* + public boolean nextcloudDownloadFile(String remoteFilePath, String localFilePath) throws IOException { + String downlfile="DownloadFile3.txt"; + BufferedWriter writer3 = new BufferedWriter(new FileWriter(downlfile)); + writer3.write("\nDownload File Remote path:--->"+remoteFilePath); + writer3.write("\nDownload File Local path:--->"+localFilePath); + + remoteFilePath = remoteFilePath.replace("\\","/"); + writer3.write("\nDownload File Remote path after replacement:--->"+remoteFilePath); + + remoteFilePath = remoteFilePath.replaceAll(SEAGridContext.getInstance().getUserName(), ""); + File localFile = new File(localFilePath); + if(!localFile.getParentFile().exists()){ + localFile.getParentFile().mkdirs(); + writer3.write("\nCreated the directory"); + } + if(next.downloadFile(remoteFilePath,localFilePath)) { + writer3.write("Returning true"); + writer3.close(); + return true; + } + writer3.close(); + return false; + } + */ + +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/connectors/storage/GuiFileTask.java b/src/main/java/org/seagrid/desktop/connectors/storage/GuiFileTask.java new file mode 100644 index 0000000..5a12877 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/connectors/storage/GuiFileTask.java @@ -0,0 +1,55 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.connectors.storage; + +import com.jcraft.jsch.*; +import javafx.concurrent.Task; +import org.seagrid.desktop.util.SEAGridContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public abstract class GuiFileTask extends Task { + private final static Logger logger = LoggerFactory.getLogger(GuiFileTask.class); + + protected static final int BUFFER_SIZE = 512000; + + protected Session session = null; + protected Channel channel = null; + protected ChannelSftp channelSftp = null; + + protected NextcloudAdapter next = new NextcloudAdapter(); + + public GuiFileTask() throws JSchException { + JSch jsch = new JSch(); + session = jsch.getSession(SEAGridContext.getInstance().getUserName(), + SEAGridContext.getInstance().getSFTPHost(), SEAGridContext.getInstance().getSFTPPort()); + session.setPassword(SEAGridContext.getInstance().getOAuthToken()); + java.util.Properties config = new java.util.Properties(); + config.put("StrictHostKeyChecking", "no"); + session.setConfig(config); + session.connect(); + channel = session.openChannel("sftp"); + channel.connect(); + channelSftp = (ChannelSftp) channel; + } + +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/connectors/storage/GuiFileUploadTask.java b/src/main/java/org/seagrid/desktop/connectors/storage/GuiFileUploadTask.java new file mode 100644 index 0000000..b40fbe9 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/connectors/storage/GuiFileUploadTask.java @@ -0,0 +1,89 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.connectors.storage; + +import com.jcraft.jsch.JSchException; +import com.jcraft.jsch.SftpException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; +import java.nio.file.Paths; + + +public class GuiFileUploadTask extends GuiFileTask { + private final static Logger logger = LoggerFactory.getLogger(GuiFileUploadTask.class); + + private String remoteFilePath, localFilePath; + + public GuiFileUploadTask(String remoteFilePath, String localFilePath) throws JSchException { + super(); + this.remoteFilePath = remoteFilePath; + this.localFilePath = localFilePath; + } + + @Override + protected Boolean call() throws Exception { + return uploadFile(remoteFilePath, localFilePath); + } + + public Boolean uploadFile(String remoteFilePath, String localFilePath) throws IOException, SftpException { + createRemoteDirsIfNotExists(Paths.get(remoteFilePath).getParent().toString()); + remoteFilePath = remoteFilePath.replace("\\","/"); + OutputStream remoteOutputStream = new BufferedOutputStream(channelSftp.put(remoteFilePath)); + File localFile = new File(localFilePath); + InputStream localInputStream = new FileInputStream(localFile); + long fileSize = localFile.length(); + byte[] buffer = new byte[BUFFER_SIZE]; + int bytesRead = -1; + int totalBytesRead = 0; + double percentCompleted = 0; + + while ((bytesRead = localInputStream.read(buffer)) != -1) { + remoteOutputStream.write(buffer, 0, bytesRead); + totalBytesRead += bytesRead; + percentCompleted = ((double)totalBytesRead) / fileSize; + updateMessage("Uploaded " + totalBytesRead + " bytes"); + updateProgress(percentCompleted, 1); + } + + remoteOutputStream.close(); + localInputStream.close(); + return true; + } + + private void createRemoteDirsIfNotExists(String parentDirPath) throws SftpException { + parentDirPath = parentDirPath.replace("\\","/"); + String[] folders = parentDirPath.split( "/" ); + for ( String folder : folders ) { + if ( folder.length() > 0 ) { + try { + channelSftp.cd(folder); + } + catch ( SftpException e ) { + channelSftp.mkdir( folder ); + channelSftp.chmod(Integer.parseInt("777",8), folder); + channelSftp.cd( folder ); + } + } + } + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/connectors/storage/StorageManager.java b/src/main/java/org/seagrid/desktop/connectors/storage/StorageManager.java new file mode 100644 index 0000000..6809165 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/connectors/storage/StorageManager.java @@ -0,0 +1,132 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.connectors.storage; + +import com.jcraft.jsch.*; +import org.seagrid.desktop.util.SEAGridContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Vector; + +public class StorageManager { + private final static Logger logger = LoggerFactory.getLogger(StorageManager.class); + + private static StorageManager instance; + + private Session session = null; + private Channel channel = null; + private ChannelSftp channelSftp = null; + + private StorageManager() throws JSchException { + connect(); + } + + private void connect() throws JSchException { + JSch jsch = new JSch(); + session = jsch.getSession( + SEAGridContext.getInstance().getUserName(), SEAGridContext.getInstance().getSFTPHost(), + SEAGridContext.getInstance().getSFTPPort() + ); + session.setPassword(SEAGridContext.getInstance().getOAuthToken()); + java.util.Properties config = new java.util.Properties(); + config.put("StrictHostKeyChecking", "no"); + session.setConfig(config); + session.connect(); + channel = session.openChannel("sftp"); + channel.connect(); + channelSftp = (ChannelSftp) channel; + } + + public static StorageManager getInstance() throws JSchException { + if(instance==null){ + instance = new StorageManager(); + } + return instance; + } + + public Vector getDirectoryListing(String path) throws SftpException, JSchException, IOException { + //channel may get timeout + String DirectoryListings ="DirectoryListings2.txt"; + BufferedWriter writ = new BufferedWriter(new FileWriter(DirectoryListings)); + writ.write("\nPath to query and get the listings:--->"+path); + if(channelSftp.isClosed()){ + connect(); + } + channelSftp.cd(path); + writ.write("\nDirectory Listing names as that are part of the file path:--->"+channelSftp.ls(path)); + writ.close(); + return channelSftp.ls(path); + } + + public void createSymLink(String oldPath, String newPath) throws JSchException, SftpException, IOException { + if(channelSftp.isClosed()){ + connect(); + } + createRemoteParentDirsIfNotExists((new File(newPath)).getParentFile().getPath()); + channelSftp.symlink(oldPath, newPath); + } + + private void createRemoteParentDirsIfNotExists(String parentDirPath) throws SftpException, IOException { + String createremotedir="CreateRemoteDirectory.txt"; + BufferedWriter writ = new BufferedWriter(new FileWriter(createremotedir)); + writ.write("Parent Directory Path to be added"+ parentDirPath); + String pwd = channelSftp.pwd(); + String[] folders = parentDirPath.split( "/" ); + for ( String folder : folders ) { + if ( folder.length() > 0 ) { + try { + channelSftp.cd(folder); + writ.write("Folder name"+folder); + } + catch ( SftpException e ) { + writ.write("Folder Name"+folder); + channelSftp.mkdir( folder ); + channelSftp.cd( folder ); + } + } + } + writ.close(); + channelSftp.cd(pwd); + } + + public void createDirIfNotExists(String dirPath) throws SftpException { + String pwd = channelSftp.pwd(); + channelSftp.cd("/"); + String[] folders = dirPath.split( "/" ); + for ( String folder : folders ) { + if ( folder.length() > 0 ) { + try { + channelSftp.cd(folder); + } + catch ( SftpException e ) { + channelSftp.mkdir( folder ); + channelSftp.cd( folder ); + } + } + } + channelSftp.cd(pwd); + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/ui/.DS_Store b/src/main/java/org/seagrid/desktop/ui/.DS_Store new file mode 100644 index 0000000..7f44685 Binary files /dev/null and b/src/main/java/org/seagrid/desktop/ui/.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/ui/commons/ImageButton.java b/src/main/java/org/seagrid/desktop/ui/commons/ImageButton.java new file mode 100644 index 0000000..7a3e982 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/ui/commons/ImageButton.java @@ -0,0 +1,33 @@ +package org.seagrid.desktop.ui.commons; + +import javafx.event.EventHandler; +import javafx.scene.control.Button; +import javafx.scene.image.Image; +import javafx.scene.image.ImageView; +import javafx.scene.input.MouseEvent; + +public class ImageButton extends Button { + + private final String STYLE_NORMAL = "-fx-background-color: transparent; -fx-padding: 5, 5, 5, 5;"; + private final String STYLE_PRESSED = "-fx-background-color: transparent; -fx-padding: 6 4 4 6;"; + + public ImageButton(String imageurl) { + setGraphic(new ImageView(new Image(getClass().getResourceAsStream(imageurl)))); + setStyle(STYLE_NORMAL); + + setOnMousePressed(new EventHandler() { + @Override + public void handle(MouseEvent event) { + setStyle(STYLE_PRESSED); + } + }); + + setOnMouseReleased(new EventHandler() { + @Override + public void handle(MouseEvent event) { + setStyle(STYLE_NORMAL); + } + }); + } + +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/ui/commons/SEAGridDialogHelper.java b/src/main/java/org/seagrid/desktop/ui/commons/SEAGridDialogHelper.java new file mode 100644 index 0000000..f0f0439 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/ui/commons/SEAGridDialogHelper.java @@ -0,0 +1,128 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.ui.commons; + +import javafx.concurrent.Service; +import javafx.geometry.Pos; +import javafx.scene.control.Alert; +import javafx.scene.control.Button; +import javafx.scene.control.ButtonBar; +import javafx.scene.control.ButtonType; +import javafx.scene.web.WebView; +import javafx.stage.Modality; +import javafx.stage.Window; +import javafx.util.Duration; +import org.controlsfx.control.Notifications; +import org.controlsfx.dialog.ExceptionDialog; +import org.controlsfx.dialog.ProgressDialog; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Optional; + +public class SEAGridDialogHelper { + private final static Logger logger = LoggerFactory.getLogger(SEAGridDialogHelper.class); + + public static void showProgressDialog(Service service, String title, Window parentWindow, String message){ + ProgressDialog progressDialog = new ProgressDialog(service); + progressDialog.setTitle(title); + progressDialog.initOwner(parentWindow); + progressDialog.setHeaderText(message); + ButtonBar buttonBar = (ButtonBar)progressDialog.getDialogPane().getChildren().get(2); + Button cancelButton = new Button("Cancel"); + cancelButton.setOnAction(event -> { + if(showConfirmDialog("Confirm Action", "Do you want cancel", "The transferred data will be lost")) + service.cancel(); + }); + buttonBar.getButtons().add(cancelButton); + progressDialog.initModality(Modality.WINDOW_MODAL); + } + + public static void showExceptionDialogAndWait(Throwable e, String title, Window parentWindow, String message){ + ExceptionDialog exceptionDialog = new ExceptionDialog(e); + exceptionDialog.setTitle(title); + exceptionDialog.initOwner(parentWindow); + exceptionDialog.setHeaderText(message); + exceptionDialog.initModality(Modality.WINDOW_MODAL); + exceptionDialog.getDialogPane().setMaxWidth(800); + exceptionDialog.showAndWait(); + } + + public static void showExceptionDialog(Throwable e, String title, Window parentWindow, String message){ + ExceptionDialog exceptionDialog = new ExceptionDialog(e); + exceptionDialog.setTitle(title); + exceptionDialog.initOwner(parentWindow); + exceptionDialog.setHeaderText(message); + exceptionDialog.initModality(Modality.WINDOW_MODAL); + exceptionDialog.getDialogPane().setMaxWidth(800); + exceptionDialog.show(); + } + + public static void showWarningDialog(String title, String headerText, String contentText){ + Alert alert = new Alert(Alert.AlertType.WARNING); + alert.setTitle(title); + alert.setHeaderText(headerText); + alert.setContentText(contentText); + alert.showAndWait(); + } + + public static void showInformationNotification(String title, String message, Window parentWindow) { + Notifications notification = Notifications.create(); + notification.hideAfter(new Duration(3000)); + notification.position(Pos.TOP_RIGHT); + notification.owner(parentWindow); + notification.text(message); + notification.title(title); + notification.showInformation(); + } + + public static boolean showConfirmDialog(String title, String headerText, String contentText){ + Alert alert = new Alert(Alert.AlertType.CONFIRMATION); + alert.setTitle(title); + alert.setHeaderText(headerText); + alert.setContentText(contentText); + + Optional result = alert.showAndWait(); + if (result.get() == ButtonType.OK){ + return true; + } else { + return false; + } + } + + public static void showInformationDialog(String title, String headerText, String contentText, Window parent){ + Alert alert = new Alert(Alert.AlertType.INFORMATION); + alert.setTitle(title); + alert.setHeaderText(headerText); + alert.initOwner(parent); + alert.setContentText(contentText); + alert.showAndWait(); + } + + public static void showInformationDialog(String title, String headerText, WebView webView, Window parent){ + Alert alert = new Alert(Alert.AlertType.INFORMATION); + alert.setTitle(title); + alert.setHeaderText(headerText); + alert.initOwner(parent); + alert.getDialogPane().setContent(webView); + alert.showAndWait(); + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/ui/experiment/.DS_Store b/src/main/java/org/seagrid/desktop/ui/experiment/.DS_Store new file mode 100644 index 0000000..4637912 Binary files /dev/null and b/src/main/java/org/seagrid/desktop/ui/experiment/.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/ui/experiment/._.DS_Store b/src/main/java/org/seagrid/desktop/ui/experiment/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/org/seagrid/desktop/ui/experiment/._.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/ui/experiment/create/.DS_Store b/src/main/java/org/seagrid/desktop/ui/experiment/create/.DS_Store new file mode 100644 index 0000000..36510fe Binary files /dev/null and b/src/main/java/org/seagrid/desktop/ui/experiment/create/.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/ui/experiment/create/._.DS_Store b/src/main/java/org/seagrid/desktop/ui/experiment/create/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/org/seagrid/desktop/ui/experiment/create/._.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/ui/experiment/create/ExperimentCreateWindow.java b/src/main/java/org/seagrid/desktop/ui/experiment/create/ExperimentCreateWindow.java new file mode 100644 index 0000000..b75134f --- /dev/null +++ b/src/main/java/org/seagrid/desktop/ui/experiment/create/ExperimentCreateWindow.java @@ -0,0 +1,163 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.ui.experiment.create; + +import javafx.application.Application; +import javafx.fxml.FXMLLoader; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.stage.Modality; +import javafx.stage.Stage; +import org.apache.airavata.model.experiment.ExperimentModel; +import org.apache.thrift.TException; +import org.seagrid.desktop.ui.experiment.create.controller.ExperimentCreateController; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.net.URISyntaxException; + +public class ExperimentCreateWindow extends Application{ + private final static Logger logger = LoggerFactory.getLogger(ExperimentCreateWindow.class); + + private static Stage createPrimaryStage; + + @Override + public void start(Stage primaryStage) throws Exception { + Parent root = FXMLLoader.load(getClass().getResource("/views/experiment/create/experiment-create.fxml")); + primaryStage.setTitle("SEAGrid Desktop Client - Create Experiment"); + primaryStage.setScene(new Scene(root, 800, 600)); + primaryStage.show(); + } + + public static void displayCreateExperiment() throws IOException { + if(createPrimaryStage == null || !createPrimaryStage.isShowing()) { + createPrimaryStage = new Stage(); + Parent root = FXMLLoader.load(ExperimentCreateWindow.class.getResource("/views/experiment/create/experiment-create.fxml")); + createPrimaryStage.setTitle("SEAGrid Desktop Client - Create Experiment"); + createPrimaryStage.setScene(new Scene(root, 800, 600)); + createPrimaryStage.initModality(Modality.WINDOW_MODAL); + createPrimaryStage.show(); + } + createPrimaryStage.requestFocus(); + } + + public static void displayEditExperiment(ExperimentModel experimentModel) throws IOException, TException, URISyntaxException { + if(createPrimaryStage != null) { + createPrimaryStage.close(); + } + createPrimaryStage = new Stage(); + FXMLLoader loader = new FXMLLoader(ExperimentCreateWindow.class.getResource( + "/views/experiment/create/experiment-create.fxml")); + Parent root = loader.load(); + createPrimaryStage.setTitle("SEAGrid Desktop Client - Edit Experiment"); + createPrimaryStage.setScene(new Scene(root, 800, 600)); + ExperimentCreateController controller = loader.getController(); + controller.initExperimentEdit(experimentModel); + createPrimaryStage.initModality(Modality.WINDOW_MODAL); + createPrimaryStage.show(); + } + + public static void displayCreateGaussianExp(String gaussianInput) throws IOException, TException, URISyntaxException { + if(createPrimaryStage != null) { + createPrimaryStage.close(); + } + Stage primaryStage = new Stage(); + FXMLLoader loader = new FXMLLoader(ExperimentCreateWindow.class.getResource( + "/views/experiment/create/experiment-create.fxml")); + Parent root = loader.load(); + primaryStage.setTitle("SEAGrid Desktop Client - Create Gaussian Experiment"); + primaryStage.setScene(new Scene(root, 800, 600)); + ExperimentCreateController controller = loader.getController(); + controller.initGaussianExperiment(gaussianInput); + primaryStage.initModality(Modality.WINDOW_MODAL); + primaryStage.show(); + } + + public static void displayCreateGamessExp(String gamessInput) throws IOException, TException, URISyntaxException { + if(createPrimaryStage != null) { + createPrimaryStage.close(); + } + Stage primaryStage = new Stage(); + FXMLLoader loader = new FXMLLoader(ExperimentCreateWindow.class.getResource( + "/views/experiment/create/experiment-create.fxml")); + Parent root = loader.load(); + primaryStage.setTitle("SEAGrid Desktop Client - Create Gamess Experiment"); + primaryStage.setScene(new Scene(root, 800, 600)); + ExperimentCreateController controller = loader.getController(); + controller.initGamessExperiment(gamessInput); + primaryStage.initModality(Modality.WINDOW_MODAL); + primaryStage.show(); + } + + public static void displayCreateNwchemExp(String nwchemInput) throws IOException, TException, URISyntaxException { + if(createPrimaryStage != null) { + createPrimaryStage.close(); + } + Stage primaryStage = new Stage(); + FXMLLoader loader = new FXMLLoader(ExperimentCreateWindow.class.getResource( + "/views/experiment/create/experiment-create.fxml")); + Parent root = loader.load(); + primaryStage.setTitle("SEAGrid Desktop Client - Create NWChem Experiment"); + primaryStage.setScene(new Scene(root, 800, 600)); + ExperimentCreateController controller = loader.getController(); + controller.initNwchemExperiment(nwchemInput); + primaryStage.initModality(Modality.WINDOW_MODAL); + primaryStage.show(); + } + + public static void displayCreatePsi4Exp(String processors, String psi4Input) throws IOException, TException, URISyntaxException { + if(createPrimaryStage != null) { + createPrimaryStage.close(); + } + Stage primaryStage = new Stage(); + FXMLLoader loader = new FXMLLoader(ExperimentCreateWindow.class.getResource( + "/views/experiment/create/experiment-create.fxml")); + Parent root = loader.load(); + primaryStage.setTitle("SEAGrid Desktop Client - Create PSI4 Experiment"); + primaryStage.setScene(new Scene(root, 800, 600)); + ExperimentCreateController controller = loader.getController(); + controller.initPsi4Experiment(processors, psi4Input); + primaryStage.initModality(Modality.WINDOW_MODAL); + primaryStage.show(); + } + + public static void displayCreateMolcasExp(String processors, String molcasInput) throws IOException, TException, URISyntaxException { + if(createPrimaryStage != null) { + createPrimaryStage.close(); + } + Stage primaryStage = new Stage(); + FXMLLoader loader = new FXMLLoader(ExperimentCreateWindow.class.getResource( + "/views/experiment/create/experiment-create.fxml")); + Parent root = loader.load(); + primaryStage.setTitle("SEAGrid Desktop Client - Create Molcas Experiment"); + primaryStage.setScene(new Scene(root, 800, 600)); + ExperimentCreateController controller = loader.getController(); + controller.initMolcasExperiment(processors, molcasInput); + primaryStage.initModality(Modality.WINDOW_MODAL); + primaryStage.show(); + } + + public static void main(String[] args) { + launch(args); + } + +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/ui/experiment/create/controller/ExperimentCreateController.java b/src/main/java/org/seagrid/desktop/ui/experiment/create/controller/ExperimentCreateController.java new file mode 100644 index 0000000..9eb1c7a --- /dev/null +++ b/src/main/java/org/seagrid/desktop/ui/experiment/create/controller/ExperimentCreateController.java @@ -0,0 +1,1084 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.ui.experiment.create.controller; + +import javafx.concurrent.Service; +import javafx.concurrent.Task; +import javafx.concurrent.WorkerStateEvent; +import javafx.fxml.FXML; +import javafx.fxml.FXMLLoader; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.scene.control.Button; +import javafx.scene.control.*; +import javafx.scene.control.Label; +import javafx.scene.control.TextArea; +import javafx.scene.control.TextField; +import javafx.scene.layout.GridPane; +import javafx.scene.layout.HBox; +import javafx.scene.layout.RowConstraints; +import javafx.stage.FileChooser; +import javafx.stage.Modality; +import javafx.stage.Stage; +import javafx.util.StringConverter; +import org.apache.airavata.model.appcatalog.appinterface.ApplicationInterfaceDescription; +import org.apache.airavata.model.appcatalog.computeresource.BatchQueue; +import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription; +import org.apache.airavata.model.appcatalog.userresourceprofile.UserComputeResourcePreference; +import org.apache.airavata.model.application.io.DataType; +import org.apache.airavata.model.application.io.InputDataObjectType; +import org.apache.airavata.model.application.io.OutputDataObjectType; +import org.apache.airavata.model.data.replica.*; +import org.apache.airavata.model.experiment.ExperimentModel; +import org.apache.airavata.model.experiment.UserConfigurationDataModel; +import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel; +import org.apache.airavata.model.workspace.Project; +import org.apache.thrift.TException; +import org.seagrid.desktop.connectors.NextcloudStorage.NextcloudFileDownloadTask; +import org.seagrid.desktop.connectors.NextcloudStorage.NextcloudFileUploadTask; +import org.seagrid.desktop.connectors.airavata.AiravataManager; +import org.seagrid.desktop.ui.commons.ImageButton; +import org.seagrid.desktop.ui.commons.SEAGridDialogHelper; +import org.seagrid.desktop.util.SEAGridContext; +import org.seagrid.desktop.util.UserPrefs; +import org.seagrid.desktop.util.messaging.SEAGridEvent; +import org.seagrid.desktop.util.messaging.SEAGridEventBus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.awt.*; +import java.io.*; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.*; +import java.util.List; + +public class ExperimentCreateController { + private final static Logger logger = LoggerFactory.getLogger(ExperimentCreateController.class); + + //These attributes are used when edit experiment is called + private boolean isEditExperiment = false; + + private ExperimentModel editExperimentModel = null; + + + @FXML + public GridPane expCreateInputsGridPane; + + @FXML + public Label expCreateTitle; + + @FXML + private Label expCreateWallTimeLabel; + + @FXML + private Label expCreateCoreCountLabel; + + @FXML + private Label expCreateNodeCountLabel; + + @FXML + private TextField expCreateNameField; + + @FXML + private TextArea expCreateDescField; + + @FXML + private ComboBox expCreateProjField; + + @FXML + private ComboBox expCreateAppField; + + @FXML + private ComboBox expCreateResourceField; + + @FXML + private ComboBox expCreateQueueField; + + @FXML + private TextField expCreateNodeCountField; + + @FXML + private TextField expCreateTotalCoreCountField; + + @FXML + private TextField expCreateWallTimeField; + + @FXML + private TextField expCreatePhysicalMemField; + + @FXML + private Button expSaveButton; + + @FXML + private Button expSaveLaunchButton; + + @FXML + private RadioButton useMyCRAccount; + + private FileChooser fileChooser; + + private Map experimentInputs; + + private String remoteDataDirRoot = SEAGridContext.getInstance().getGatewayUserDataRoot(); + + private List outputDataObjectTypes; + + @SuppressWarnings("unused") + public void initialize() { + initElements(); + initFileChooser(); + } + + private void initElements(){ + try{ + List projects = AiravataManager.getInstance().getProjects(); + expCreateProjField.getItems().setAll(projects); + expCreateProjField.setConverter(new StringConverter() { + @Override + public String toString(Project project) { + return project.getName(); + } + + @Override + public Project fromString(String string) { + return null; + } + }); + expCreateProjField.getSelectionModel().selectFirst(); + + List applications = AiravataManager.getInstance().getAllApplicationInterfaces(); + expCreateAppField.getItems().setAll(applications); + + UserPrefs userPrefs = SEAGridContext.getInstance().getUserPrefs(); + ApplicationInterfaceDescription lastSelectedApplication = null; + if(userPrefs != null && userPrefs.getLastApplicationId() != null){ + Optional lastApplication = applications.stream() + .filter(application -> application.getApplicationInterfaceId().equals(userPrefs.getLastApplicationId())).findFirst(); + if(lastApplication.isPresent()){ + lastSelectedApplication = lastApplication.get(); + } + } + + expCreateAppField.setConverter(new StringConverter() { + @Override + public String toString(ApplicationInterfaceDescription application) { + return application.getApplicationName(); + } + + @Override + public ApplicationInterfaceDescription fromString(String string) { + return null; + } + }); + expCreateAppField.valueProperty().addListener((observable, oldValue, newValue) -> { + try { + loadAvailableComputeResources(); + ApplicationInterfaceDescription applicationInterfaceDescription = (ApplicationInterfaceDescription)expCreateAppField + .getSelectionModel().getSelectedItem(); + boolean hasOptionalFileInputs = applicationInterfaceDescription.isHasOptionalFileInputs(); + List inputDataObjectTypes = applicationInterfaceDescription.getApplicationInputs(); + this.outputDataObjectTypes = applicationInterfaceDescription.getApplicationOutputs(); + updateExperimentInputs(inputDataObjectTypes, hasOptionalFileInputs); + } catch (Exception e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", expCreateAppField.getScene().getWindow(), + "Failed to load experiment create dialog !"); + } + }); + + if(lastSelectedApplication != null){ + expCreateAppField.getSelectionModel().select(lastSelectedApplication); + }else{ + expCreateAppField.getSelectionModel().selectFirst(); + } + + //Won't allow characters to be entered + expCreateNodeCountField.textProperty().addListener((observable, oldValue, newValue) -> { + if (!newValue.matches("\\d*")) { + expCreateNodeCountField.setText(oldValue); + } + }); + expCreateTotalCoreCountField.textProperty().addListener((observable, oldValue, newValue) -> { + if (!newValue.matches("\\d*")) { + expCreateTotalCoreCountField.setText(oldValue); + } + }); + expCreateWallTimeField.textProperty().addListener((observable, oldValue, newValue) -> { + if (!newValue.matches("\\d*")) { + expCreateWallTimeField.setText(oldValue); + } + }); + expCreatePhysicalMemField.textProperty().addListener((observable, oldValue, newValue) -> { + if (!newValue.matches("\\d*")) { + expCreatePhysicalMemField.setText(oldValue); + } + }); + + expSaveButton.setOnAction(event -> { + try { + createExperiment(false); + } catch (TException e) { + SEAGridDialogHelper.showExceptionDialog(e,"Caught Exception",null, "Unable to create experiment"); + } catch (IOException e) { + e.printStackTrace(); + } + }); + + expSaveLaunchButton.setOnAction(event -> { + try { + createExperiment(true); + } catch (TException e) { + SEAGridDialogHelper.showExceptionDialog(e, "Caught Exception", null, "Unable to create experiment"); + } catch (IOException e) { + e.printStackTrace(); + } + }); + + }catch (Exception e){ + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", expCreateNameField.getScene().getWindow(), + "Failed To Load New Experiment Window !"); + } + } + + public void initExperimentEdit(ExperimentModel experimentModel) throws TException, URISyntaxException { + isEditExperiment = true; + editExperimentModel = experimentModel; + expCreateTitle.setText("Edit Experiment"); + + expCreateNameField.setText(experimentModel.getExperimentName()); + expCreateDescField.setText(experimentModel.getDescription()); + expCreateProjField.getItems().stream().filter(p->((Project)p).getProjectID().equals(experimentModel.getProjectId())) + .forEach(p -> expCreateProjField.getSelectionModel().select(p)); + expCreateAppField.getItems().stream().filter(p->((ApplicationInterfaceDescription)p).getApplicationInterfaceId() + .equals(experimentModel.getExecutionId())).forEach(p -> expCreateAppField.getSelectionModel().select(p)); + expCreateAppField.setDisable(true); + expCreateProjField.setDisable(true); + expCreateAppField.setStyle("-fx-opacity: 1;"); + expCreateResourceField.getItems().stream().filter(r -> ((ComputeResourceDescription) r).getComputeResourceId() + .equals(experimentModel.getUserConfigurationData().getComputationalResourceScheduling().getResourceHostId())) + .forEach(r -> expCreateResourceField.getSelectionModel().select(r)); + + UserComputeResourcePreference userComputeResourcePreference = AiravataManager.getInstance() + .getUserComputeResourcePrefs(editExperimentModel.getUserConfigurationData() + .getComputationalResourceScheduling().getResourceHostId()); + + if(userComputeResourcePreference != null){ + useMyCRAccount.setVisible(true); + if(editExperimentModel.getUserConfigurationData().isUseUserCRPref()){ + useMyCRAccount.setSelected(true); + } + }else{ + useMyCRAccount.setVisible(false); + } + + expCreateQueueField.getItems().stream().filter(q -> ((BatchQueue) q).getQueueName() + .equals(experimentModel.getUserConfigurationData().getComputationalResourceScheduling().getQueueName())) + .forEach(q -> expCreateQueueField.getSelectionModel().select(q)); + expCreateNodeCountField.setText(experimentModel.getUserConfigurationData().getComputationalResourceScheduling() + .getNodeCount()+""); + expCreateTotalCoreCountField.setText(experimentModel.getUserConfigurationData().getComputationalResourceScheduling() + .getTotalCPUCount()+""); + expCreateWallTimeField.setText(experimentModel.getUserConfigurationData().getComputationalResourceScheduling() + .getWallTimeLimit()+""); + expCreatePhysicalMemField.setText(experimentModel.getUserConfigurationData().getComputationalResourceScheduling() + .getTotalPhysicalMemory()+""); + + ApplicationInterfaceDescription applicationInterfaceDescription = AiravataManager.getInstance().getApplicationInterface(experimentModel.getExecutionId()); + boolean hasOptionalFileInputs = applicationInterfaceDescription.isHasOptionalFileInputs(); + updateExperimentInputs(experimentModel.getExperimentInputs(), hasOptionalFileInputs); + } + + //FIXME This is an application specific initialization method. It is nice if we can come up with a generalizable way to handle + //FIXME application specific initializer + public void initGaussianExperiment(String gaussianInput) throws FileNotFoundException, TException, URISyntaxException { + String tempFilePath = System.getProperty("java.io.tmpdir") + File.separator + "gaussian.in"; + PrintWriter out = new PrintWriter(tempFilePath); + out.println(gaussianInput); + out.close(); + int bcount=0; + String[] lines = gaussianInput.split("\n"); + String desc=""; + for(String temp : lines){ + //These properties are set in the input file we are reusing it. + if(temp.contains("%nproc=")){ + temp = temp.replace("%nproc=", ""); + expCreateNodeCountField.setText("1"); + expCreateTotalCoreCountField.setText(temp); + }else if(temp.contains("%nprocl=")){ + temp = temp.replace("%nprocl=", ""); + //expCreateTotalCoreCountField.setText(temp); + expCreateNodeCountField.setText(temp); + }else if(temp.contains("%mem=")){ + temp = temp.replace("%mem=", ""); + temp = temp.replace("MB", ""); + expCreatePhysicalMemField.setText(temp); + } + else if(temp.equals("")){ + //blank + bcount++; + if (bcount == 1) { + desc=""; + temp=""; + } + } + if (bcount < 2) { + desc=desc+temp; + } + + } + expCreateNameField.setText("Default_job" ); + expCreateDescField.setText(desc); + List applicationInterfaceDescriptions = AiravataManager.getInstance().getAllApplicationInterfaces(); + List gaussianApps = new ArrayList<>(); + for(ApplicationInterfaceDescription appInter : applicationInterfaceDescriptions){ + if(appInter.getApplicationName().toLowerCase().startsWith(SEAGridContext.getInstance().getGaussianAppName())){ + gaussianApps.add(appInter); + } + } + if(gaussianApps.size() > 0){ + expCreateAppField.getItems().setAll(gaussianApps); + expCreateAppField.getSelectionModel().select(0); + for(ApplicationInterfaceDescription app : gaussianApps){ + List gaussianInputs = app.getApplicationInputs(); + gaussianInputs.get(0).setValue(tempFilePath); + updateExperimentInputs(gaussianInputs, true); + } + } + } + + public void initGamessExperiment(String gamessInput) throws FileNotFoundException, TException, URISyntaxException { + String tempFilePath = System.getProperty("java.io.tmpdir") + File.separator + "gamess.inp"; + PrintWriter out = new PrintWriter(tempFilePath); + out.println(gamessInput); + out.close(); + List applicationInterfaceDescriptions = AiravataManager.getInstance().getAllApplicationInterfaces(); + List gamessApps = new ArrayList<>(); + for(ApplicationInterfaceDescription appInter : applicationInterfaceDescriptions){ + if(appInter.getApplicationName().toLowerCase().startsWith(SEAGridContext.getInstance().getGamessAppName())){ + gamessApps.add(appInter); + } + } + if(gamessApps.size() > 0){ + expCreateAppField.getItems().setAll(gamessApps); + expCreateAppField.getSelectionModel().select(0); + for(ApplicationInterfaceDescription app : gamessApps){ + List gaussianInputs = app.getApplicationInputs(); + gaussianInputs.get(0).setValue(tempFilePath); + updateExperimentInputs(gaussianInputs, true); + } + } + } + + public void initNwchemExperiment(String nwchemInput) throws FileNotFoundException, TException, URISyntaxException { + String tempFilePath = System.getProperty("java.io.tmpdir") + File.separator + "input.nw"; + PrintWriter out = new PrintWriter(tempFilePath); + out.println(nwchemInput); + out.close(); + List applicationInterfaceDescriptions = AiravataManager.getInstance().getAllApplicationInterfaces(); + List nwchemApps = new ArrayList<>(); + for(ApplicationInterfaceDescription appInter : applicationInterfaceDescriptions){ + if(appInter.getApplicationName().toLowerCase().startsWith(SEAGridContext.getInstance().getNwchemAppName())){ + nwchemApps.add(appInter); + } + } + if(nwchemApps.size() > 0){ + expCreateAppField.getItems().setAll(nwchemApps); + expCreateAppField.getSelectionModel().select(0); + for(ApplicationInterfaceDescription app : nwchemApps){ + List gaussianInputs = app.getApplicationInputs(); + gaussianInputs.get(0).setValue(tempFilePath); + updateExperimentInputs(gaussianInputs, true); + } + } + } + + public void initPsi4Experiment(String processors, String psi4Input) throws FileNotFoundException, TException, URISyntaxException { + String tempFilePath = System.getProperty("java.io.tmpdir") + File.separator + "input.dat"; + PrintWriter out = new PrintWriter(tempFilePath); + out.println(psi4Input); + out.close(); + List applicationInterfaceDescriptions = AiravataManager.getInstance().getAllApplicationInterfaces(); + List psi4Apps = new ArrayList<>(); + for(ApplicationInterfaceDescription appInter : applicationInterfaceDescriptions){ + if(appInter.getApplicationName().toLowerCase().startsWith(SEAGridContext.getInstance().getPsi4AppName())){ + psi4Apps.add(appInter); + } + } + if(psi4Apps.size() > 0){ + expCreateAppField.getItems().setAll(psi4Apps); + expCreateAppField.getSelectionModel().select(0); + for(ApplicationInterfaceDescription app : psi4Apps){ + List gaussianInputs = app.getApplicationInputs(); + gaussianInputs.get(0).setValue(processors); + gaussianInputs.get(1).setValue(tempFilePath); + updateExperimentInputs(gaussianInputs, true); + } + } + } + public void initMolcasExperiment(String processors, String molcasInput) throws FileNotFoundException, TException, URISyntaxException { + String tempFilePath = System.getProperty("java.io.tmpdir") + File.separator + "molcas.input"; + PrintWriter out = new PrintWriter(tempFilePath); + out.println(molcasInput); + out.close(); + List applicationInterfaceDescriptions = AiravataManager.getInstance().getAllApplicationInterfaces(); + List molcasApps = new ArrayList<>(); + for(ApplicationInterfaceDescription appInter : applicationInterfaceDescriptions){ + if(appInter.getApplicationName().toLowerCase().startsWith(SEAGridContext.getInstance().getMolcasAppName())){ + molcasApps.add(appInter); + } + } + if(molcasApps.size() > 0){ + expCreateAppField.getItems().setAll(molcasApps); + expCreateAppField.getSelectionModel().select(0); + for(ApplicationInterfaceDescription app : molcasApps){ + List gaussianInputs = app.getApplicationInputs(); + gaussianInputs.get(1).setValue(processors); + gaussianInputs.get(0).setValue(tempFilePath); + updateExperimentInputs(gaussianInputs, true); + } + } + } + + private void initFileChooser(){ + fileChooser = new FileChooser(); + fileChooser.setTitle("Open Resource File"); +// Todo Should add Science Specific Filters +// fileChooser.getExtensionFilters().addAll( +// new FileChooser.ExtensionFilter("Text Files", "*.txt"), +// new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"), +// new FileChooser.ExtensionFilter("Audio Files", "*.wav", "*.mp3", "*.aac"), +// new FileChooser.ExtensionFilter("All Files", "*.*")); + } + + private void loadAvailableComputeResources() throws TException { + ApplicationInterfaceDescription selectedApp = (ApplicationInterfaceDescription)expCreateAppField + .getSelectionModel().getSelectedItem(); + if(selectedApp != null){ + List computeResourceDescriptions = AiravataManager.getInstance() + .getAvailableComputeResourcesForApp(selectedApp.getApplicationInterfaceId()); + expCreateResourceField.getItems().setAll(computeResourceDescriptions); + expCreateResourceField.setConverter(new StringConverter() { + @Override + public String toString(ComputeResourceDescription resourceDescription) { + return resourceDescription.getHostName(); + } + + @Override + public ComputeResourceDescription fromString(String string) { + return null; + } + }); + expCreateResourceField.valueProperty().addListener((observable, oldValue, newValue) -> { + String computeResourceId = ((ComputeResourceDescription)newValue).getComputeResourceId(); + try{ + UserComputeResourcePreference userComputeResourcePreference = AiravataManager.getInstance() + .getUserComputeResourcePrefs(computeResourceId); + if(userComputeResourcePreference != null){ + useMyCRAccount.setSelected(true); + useMyCRAccount.setVisible(true); + }else{ + useMyCRAccount.setSelected(false); + useMyCRAccount.setVisible(false); + } + }catch (Exception ex){ + SEAGridDialogHelper.showExceptionDialog(ex, "Failed while retrieving user compute prefs", null, ex.getMessage()); + } + + loadAvailableBatchQueues(); + }); + expCreateResourceField.getSelectionModel().selectFirst(); + } + } + + private void loadAvailableBatchQueues(){ + ComputeResourceDescription selectedResource = (ComputeResourceDescription)expCreateResourceField + .getSelectionModel().getSelectedItem(); + if(selectedResource != null){ + List batchQueues = selectedResource.getBatchQueues(); + expCreateQueueField.getItems().setAll(batchQueues); + expCreateQueueField.setConverter(new StringConverter() { + @Override + public String toString(BatchQueue batchQueue) { + return batchQueue.getQueueName(); + } + + @Override + public BatchQueue fromString(String string) { + return null; + } + }); + expCreateQueueField.valueProperty().addListener((observable, oldValue, newValue) -> { + updateQueueSpecificLimitsInLabels(); + }); + expCreateQueueField.getSelectionModel().selectFirst(); + } + } + + private void updateQueueSpecificLimitsInLabels(){ + BatchQueue selectedQueue = (BatchQueue)expCreateQueueField.getSelectionModel().getSelectedItem(); + if(selectedQueue != null){ + expCreateNodeCountLabel.setText("Node Count ( max - " + selectedQueue.getMaxNodes() + + " )"); + expCreateCoreCountLabel.setText("Total Core Count ( max - " + selectedQueue.getMaxProcessors() + + " )"); + expCreateWallTimeLabel.setText("Wall Time Limit ( max - " + selectedQueue.getMaxRunTime() + + " )"); + } + } + + private void updateExperimentInputs(List inputDataObjectTypes, boolean hasOptionalFileInputs) throws TException, URISyntaxException { + if(hasOptionalFileInputs){ + if(!inputDataObjectTypes.stream().filter(p->p.getType().equals(DataType.URI_COLLECTION)).findFirst().isPresent()){ + InputDataObjectType inputDataObjectType = new InputDataObjectType(); + inputDataObjectType.setName("Optional-File-Inputs"); + inputDataObjectType.setType(DataType.URI_COLLECTION); + inputDataObjectType.setIsRequired(false); + inputDataObjectTypes.add(inputDataObjectType); + } + } + this.experimentInputs = new HashMap<>(); + expCreateInputsGridPane.getChildren().clear(); + expCreateInputsGridPane.getRowConstraints().clear(); + int index = 0; + for(InputDataObjectType inputDataObjectType : inputDataObjectTypes){ + String lable = inputDataObjectType.getName(); + String toolTip = ""; + if(inputDataObjectType.getUserFriendlyDescription() != null){ + toolTip = inputDataObjectType.getUserFriendlyDescription(); + } + Label labelObj = new Label(lable); + labelObj.setTooltip(new Tooltip(toolTip)); + if(inputDataObjectType.getType().equals(DataType.STRING)){ + expCreateInputsGridPane.add(labelObj, 0, index); + TextField stringField = new TextField(); + expCreateInputsGridPane.add( stringField, 1, index); + this.experimentInputs.put(inputDataObjectType,null); + stringField.textProperty().addListener((observable, oldValue, newValue) -> { + experimentInputs.put(inputDataObjectType,newValue); + }); + if(inputDataObjectType.getValue() != null) + stringField.setText(inputDataObjectType.getValue()); + }else if(inputDataObjectType.getType().equals(DataType.INTEGER)){ + expCreateInputsGridPane.add(labelObj, 0, index); + TextField numericField = new TextField(); + numericField.textProperty().addListener((observable, oldValue, newValue) -> { + if (!newValue.matches("\\d*")) { + numericField.setText(oldValue); + experimentInputs.put(inputDataObjectType, oldValue); + } else { + experimentInputs.put(inputDataObjectType, newValue); + } + }); + expCreateInputsGridPane.add(numericField, 1, index); + if(inputDataObjectType.getValue() != null) + numericField.setText(inputDataObjectType.getValue()); + }else if(inputDataObjectType.getType().equals(DataType.FLOAT)){ + expCreateInputsGridPane.add(labelObj, 0, index); + TextField floatField = new TextField(); + floatField.textProperty().addListener((observable, oldValue, newValue) -> { + if (!newValue.matches("\\f*")) { + floatField.setText(oldValue); + experimentInputs.put(inputDataObjectType, oldValue); + } else { + experimentInputs.put(inputDataObjectType, newValue); + } + }); + expCreateInputsGridPane.add(floatField, 1, index); + if(inputDataObjectType.getValue() != null) + floatField.setText(inputDataObjectType.getValue()); + }else if(inputDataObjectType.getType().equals(DataType.URI)){ + expCreateInputsGridPane.add(labelObj, 0, index); + HBox hBox = new HBox(2); + Button localFilePickBtn = new ImageButton("/images/local-storage.png"); + localFilePickBtn.setTooltip(new Tooltip("Select local file")); + hBox.getChildren().add(0, localFilePickBtn); + Button remoteFilePickBtn = new ImageButton("/images/remote-storage.png"); + remoteFilePickBtn.setTooltip(new Tooltip("Select remote file")); +// hBox.getChildren().add(1, remoteFilePickBtn); + expCreateInputsGridPane.add(hBox, 1, index); + localFilePickBtn.setOnAction(event -> { + File selectedFile = fileChooser.showOpenDialog(expCreateInputsGridPane.getScene().getWindow()); + handleExperimentFileSelect(inputDataObjectType, hBox, localFilePickBtn, remoteFilePickBtn, selectedFile); + }); + remoteFilePickBtn.setOnAction(event -> { + try { + String selectedRemoteFilePath = showSelectRemoteFile(); + if(selectedRemoteFilePath != null && !selectedRemoteFilePath.isEmpty()) { + selectedRemoteFilePath = remoteDataDirRoot + (selectedRemoteFilePath.startsWith("/") + ? selectedRemoteFilePath.substring(1) : selectedRemoteFilePath); + inputDataObjectType.setValue(selectedRemoteFilePath); + handleExperimentFileSelect(inputDataObjectType, hBox, localFilePickBtn, remoteFilePickBtn, new File(selectedRemoteFilePath)); + } + } catch (IOException e) { + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", remoteFilePickBtn.getScene().getWindow(), + "Failed to load remote file picker"); + } + }); + if(inputDataObjectType.getValue() != null && inputDataObjectType.getValue().startsWith("airavata-dp")){ + List replicas = AiravataManager.getInstance().getDataReplicas(inputDataObjectType.getValue()); + String fileUri = ""; + for(DataReplicaLocationModel rpModel : replicas){ + if(rpModel.getReplicaLocationCategory().equals(ReplicaLocationCategory.GATEWAY_DATA_STORE)) { + fileUri = rpModel.getFilePath(); + break; + } + } + String filePath = (new URI(fileUri)).getPath(); + handleExperimentFileSelect(inputDataObjectType, hBox, localFilePickBtn, remoteFilePickBtn, new File(filePath)); + }else{ + File file = new File(inputDataObjectType.getValue()); + if(file.exists()){ + handleExperimentFileSelect(inputDataObjectType, hBox, localFilePickBtn, remoteFilePickBtn, new File(inputDataObjectType.getValue())); + } + } + }else if(inputDataObjectType.getType().equals(DataType.URI_COLLECTION)){ + expCreateInputsGridPane.add(labelObj, 0, index); + HBox hBox = new HBox(2); + Button localFilePickBtn = new ImageButton("/images/local-storage.png"); + localFilePickBtn.setTooltip(new Tooltip("Select multiple local files")); + hBox.getChildren().add(0, localFilePickBtn); + expCreateInputsGridPane.add(hBox, 1, index); + + Button remoteFilePickBtn = new ImageButton("/images/remote-storage.png"); + remoteFilePickBtn.setTooltip(new Tooltip("Select remote file")); +// hBox.getChildren().add(1, remoteFilePickBtn); + + localFilePickBtn.setOnAction(event -> { + List selectedFiles = fileChooser.showOpenMultipleDialog(expCreateInputsGridPane.getScene().getWindow()); + handleMultipleExperimentFileSelect(inputDataObjectType, hBox, localFilePickBtn, remoteFilePickBtn, selectedFiles); + }); + + if(inputDataObjectType.getValue() != null && inputDataObjectType.getValue().contains("airavata-dp")){ + String[] replicaUris = inputDataObjectType.getValue().split(","); + ArrayList fileList = new ArrayList<>(); + for(String replicaUri : replicaUris) { + List replicas = AiravataManager.getInstance().getDataReplicas(replicaUri); + String fileUri = ""; + for (DataReplicaLocationModel rpModel : replicas) { + if (rpModel.getReplicaLocationCategory().equals(ReplicaLocationCategory.GATEWAY_DATA_STORE)) { + fileUri = rpModel.getFilePath(); + break; + } + } + String filePath = (new URI(fileUri)).getPath(); + fileList.add(new File(filePath)); + } + handleMultipleExperimentFileSelect(inputDataObjectType, hBox, localFilePickBtn, remoteFilePickBtn, fileList); + } + } + //maintaining the grid pane row height + expCreateInputsGridPane.getRowConstraints().add(index,new RowConstraints(25)); + index++; + } + } + + private void handleExperimentFileSelect(InputDataObjectType inputDataObjectType, HBox hBox, Button localFilePickBtn, + Button remoteFilePickBtn,File selectedFile){ + if (selectedFile != null) { + hBox.getChildren().clear(); + Hyperlink hyperlink = new Hyperlink(selectedFile.getName()); + hyperlink.setOnAction(hyperLinkEvent -> { + //FIXME Else it is a remote file. Cannot open locally without downloading it. + if(selectedFile.exists()){ + try { + Desktop.getDesktop().open(selectedFile); + } catch (IOException e) { + logger.error("Cannot open file. Opening parent directory"); + try { + Desktop.getDesktop().open(selectedFile.getParentFile()); + } catch (IOException e1) { + logger.error("Cannot open file. Opening parent directory"); + SEAGridDialogHelper.showExceptionDialog(e, "Exception Dialog", + expCreateInputsGridPane.getScene().getWindow(), "Failed Opening File"); + } + } + }else{ + boolean result = SEAGridDialogHelper.showConfirmDialog("Confirm Action", "Remote File Download", "You have selected a remote file." + + " Do you want to download it ?"); + if(result){ + try { + String filePath = selectedFile.getPath(); + String remotePath = filePath.replaceAll(remoteDataDirRoot, ""); + downloadFile(Paths.get(remotePath), System.getProperty("java.io.tmpdir")); + } catch (Exception e) { + SEAGridDialogHelper.showExceptionDialog(e, "Exception Dialog", + expCreateInputsGridPane.getScene().getWindow(), "Failed Downloading File"); + } + } + } + }); + hBox.getChildren().add(0, hyperlink); + hBox.getChildren().add(1, localFilePickBtn); +// hBox.getChildren().add(2, remoteFilePickBtn); + experimentInputs.put(inputDataObjectType, selectedFile); + } + } + + private void handleMultipleExperimentFileSelect(InputDataObjectType inputDataObjectType, HBox hBox, Button localFilePickBtn, + Button remoteFilePickBtn,List selectedFiles){ + List nonNullSelectedFiles = new ArrayList<>(); + int i = 0; + hBox.getChildren().clear(); + for (File selectedFile : selectedFiles){ + if (selectedFile != null) { + Hyperlink hyperlink = new Hyperlink(selectedFile.getName()); + hyperlink.setOnAction(hyperLinkEvent -> { + //FIXME Else it is a remote file. Cannot open locally without downloading it. + if (selectedFile.exists()) { + try { + Desktop.getDesktop().open(selectedFile); + } catch (IOException e) { + logger.error("Cannot open file. Opening parent directory"); + try { + Desktop.getDesktop().open(selectedFile.getParentFile()); + } catch (IOException e1) { + logger.error("Cannot open file. Opening parent directory"); + SEAGridDialogHelper.showExceptionDialog(e, "Exception Dialog", + expCreateInputsGridPane.getScene().getWindow(), "Failed Opening File"); + } + } + } else { + boolean result = SEAGridDialogHelper.showConfirmDialog("Confirm Action", "Remote File Download", "You have selected a remote file." + + " Do you want to download it ?"); + if (result) { + try { + String filePath = selectedFile.getPath(); + String remotePath = filePath.replaceAll(remoteDataDirRoot, ""); + downloadFile(Paths.get(remotePath), System.getProperty("java.io.tmpdir")); + } catch (Exception e) { + SEAGridDialogHelper.showExceptionDialog(e, "Exception Dialog", + expCreateInputsGridPane.getScene().getWindow(), "Failed Downloading File"); + } + } + } + }); + hBox.getChildren().add(i, hyperlink); + i++; + nonNullSelectedFiles.add(selectedFile); + } + } + hBox.getChildren().add(i, localFilePickBtn); + experimentInputs.put(inputDataObjectType, nonNullSelectedFiles); + + } + + private String showSelectRemoteFile() throws IOException { + Stage primaryStage = new Stage(); + FXMLLoader loader = new FXMLLoader(getClass().getResource( + "/views/experiment/create/remote-file-picker.fxml")); + Parent root = loader.load(); + primaryStage.setTitle("SEAGrid Desktop Client - Select Remote File"); + primaryStage.setScene(new Scene(root, 400, 600)); + RemoteFilePickerController controller = loader.getController(); + primaryStage.initModality(Modality.APPLICATION_MODAL); + primaryStage.showAndWait(); + return controller.getSelectedFilePath(); + } + + private void createExperiment(boolean launch) throws TException, IOException { + if(validateExperimentFields()){ + //FIXME Hardcoded value + String projectId = ((Project)expCreateProjField.getSelectionModel().getSelectedItem()).getProjectID(); + String randomString = projectId.substring(0,projectId.length()-37).replaceAll("[^A-Za-z0-9 ]", "_") + "/" + + expCreateNameField.getText().replaceAll("[^A-Za-z0-9]","_"); + String remoteDataDir = SEAGridContext.getInstance().getRemoteDataDirPrefix() + remoteDataDirRoot + randomString + "/"; + ExperimentModel experimentModel = assembleExperiment(remoteDataDir, randomString + "/"); + Map uploadFiles = new HashMap<>(); + for(Iterator> it = experimentInputs.entrySet().iterator(); it.hasNext(); ) { + Map.Entry entry = it.next(); + if(entry.getKey().getType().equals(DataType.URI)) { + File file = (File) entry.getValue(); + //FIXME - Otherwise the file is remote file. This is not a good way to handle this. Should find a better way to handle it + if(file.exists()) + uploadFiles.put("/Documents/" + randomString + "/" + file.getName(), file); + }else if(entry.getKey().getType().equals(DataType.URI_COLLECTION)){ + for(File file : (List)entry.getValue()){ + //FIXME - Otherwise the file is remote file. This is not a good way to handle this. Should find a better way to handle it + if(file.exists()) + uploadFiles.put("/Documents/" + randomString + "/" + file.getName(), file); + } + } + } + if(uploadFiles.size() > 0){ + Service fileUploadService = getFileUploadService(uploadFiles); + fileUploadService.setOnSucceeded(event -> { + createExperiment(experimentModel, launch); + }); + fileUploadService.start(); + }else{ + createExperiment(experimentModel, launch); + } + } + } + + private void createExperiment(ExperimentModel experimentModel, boolean launch){ + try { + if(!isEditExperiment) { + String expId = AiravataManager.getInstance().createExperiment(experimentModel); + experimentModel = AiravataManager.getInstance().getExperiment(expId); + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.EXPERIMENT_CREATED + , experimentModel)); + + }else{ + experimentModel.setExperimentId(editExperimentModel.getExperimentId()); + AiravataManager.getInstance().updateExperiment(experimentModel); + experimentModel = AiravataManager.getInstance().getExperiment(experimentModel.getExperimentId()); + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.EXPERIMENT_UPDATED + ,experimentModel)); + } + if(launch){ + try { + AiravataManager.getInstance().launchExperiment(experimentModel.getExperimentId()); + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.EXPERIMENT_LAUNCHED + ,experimentModel)); + }catch (TException e){ + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", expSaveLaunchButton.getScene().getWindow(), + "Experiment launch failed !"); + } + } + Stage stage = (Stage) expSaveButton.getScene().getWindow(); + stage.close(); + } catch (TException e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", expSaveButton.getScene().getWindow(), + "Experiment create failed !"); + } + } + + private ExperimentModel assembleExperiment(String remoteDataDir, String experimentDataDir) throws TException { + + ExperimentModel experimentModel = new ExperimentModel(); + experimentModel.setExperimentName(expCreateNameField.getText()); + experimentModel.setDescription(expCreateDescField.getText() == null ? "" : expCreateDescField.getText()); + experimentModel.setProjectId(((Project)expCreateProjField.getSelectionModel().getSelectedItem()).getProjectID()); + experimentModel.setExecutionId(((ApplicationInterfaceDescription)expCreateAppField.getSelectionModel() + .getSelectedItem()).getApplicationInterfaceId()); + + UserPrefs userPrefs = SEAGridContext.getInstance().getUserPrefs(); + userPrefs.setLastApplicationId(((ApplicationInterfaceDescription) expCreateAppField.getSelectionModel() + .getSelectedItem()).getApplicationInterfaceId()); + + experimentModel.setGatewayId(SEAGridContext.getInstance().getAiravataGatewayId()); + experimentModel.setUserName(SEAGridContext.getInstance().getUserName()); + + UserConfigurationDataModel userConfigurationDataModel = new UserConfigurationDataModel(); + + //FIXME Hard Coded Default Values + userConfigurationDataModel.setAiravataAutoSchedule(false); + userConfigurationDataModel.setOverrideManualScheduledParams(false); + userConfigurationDataModel.setStorageId(SEAGridContext.getInstance().getGatewayaStorageId()); + + userConfigurationDataModel.setExperimentDataDir(remoteDataDirRoot + experimentDataDir); + userConfigurationDataModel.setUseUserCRPref(useMyCRAccount.isSelected()); + + ComputationalResourceSchedulingModel resourceSchedulingModel = new ComputationalResourceSchedulingModel(); + resourceSchedulingModel.setResourceHostId(((ComputeResourceDescription)expCreateResourceField.getSelectionModel() + .getSelectedItem()).getComputeResourceId()); + resourceSchedulingModel.setQueueName(((BatchQueue)expCreateQueueField.getSelectionModel().getSelectedItem()) + .getQueueName()); + resourceSchedulingModel.setNodeCount(Integer.parseInt(expCreateNodeCountField.getText())); + resourceSchedulingModel.setTotalCPUCount(Integer.parseInt(expCreateTotalCoreCountField.getText())); + resourceSchedulingModel.setWallTimeLimit(Integer.parseInt(expCreateWallTimeField.getText())); + resourceSchedulingModel.setTotalPhysicalMemory(Integer.parseInt(expCreatePhysicalMemField.getText())); + userConfigurationDataModel.setComputationalResourceScheduling(resourceSchedulingModel); + experimentModel.setUserConfigurationData(userConfigurationDataModel); + + List temp = new ArrayList<>(); + for(InputDataObjectType inputDataObjectType : this.experimentInputs.keySet()){ + if(inputDataObjectType.getType().equals(DataType.URI)){ + //FIXME - Otherwise the file is remote file. This is not a good way to handle this. Should find a better way to handle it + if(((File) this.experimentInputs + .get(inputDataObjectType)).exists()) { + String fileName = ((File) this.experimentInputs.get(inputDataObjectType)).getName(); + String remoteFilePath = remoteDataDir + fileName; + DataProductModel dpModel = new DataProductModel(); + dpModel.setGatewayId(SEAGridContext.getInstance().getAiravataGatewayId()); + dpModel.setOwnerName(SEAGridContext.getInstance().getUserName()); + dpModel.setProductName(fileName); + dpModel.setDataProductType(DataProductType.FILE); + + DataReplicaLocationModel rpModel = new DataReplicaLocationModel(); + rpModel.setStorageResourceId(SEAGridContext.getInstance().getGatewayaStorageId()); + rpModel.setReplicaName(fileName + " gateway data store copy"); + rpModel.setReplicaLocationCategory(ReplicaLocationCategory.GATEWAY_DATA_STORE); + rpModel.setReplicaPersistentType(ReplicaPersistentType.TRANSIENT); + rpModel.setFilePath(remoteFilePath); + dpModel.addToReplicaLocations(rpModel); + String uri = AiravataManager.getInstance().registerDataProduct(dpModel); + inputDataObjectType.setValue(uri); + } + }else if(inputDataObjectType.getType().equals(DataType.URI_COLLECTION)){ + List files = (List) this.experimentInputs.get(inputDataObjectType); + //FIXME - Otherwise the files are remote file. This is not a good way to handle this. Should find a better way to handle it + if(files.get(0).exists()){ + String uriCollection = ""; + for(File file : files){ + if(file.exists()) { + String fileName = file.getName(); + String remoteFilePath = remoteDataDir + fileName; + DataProductModel dpModel = new DataProductModel(); + dpModel.setGatewayId(SEAGridContext.getInstance().getAiravataGatewayId()); + dpModel.setOwnerName(SEAGridContext.getInstance().getUserName()); + dpModel.setProductName(fileName); + dpModel.setDataProductType(DataProductType.FILE); + + DataReplicaLocationModel rpModel = new DataReplicaLocationModel(); + rpModel.setStorageResourceId(SEAGridContext.getInstance().getGatewayaStorageId()); + rpModel.setReplicaName(fileName + " gateway data store copy"); + rpModel.setReplicaLocationCategory(ReplicaLocationCategory.GATEWAY_DATA_STORE); + rpModel.setReplicaPersistentType(ReplicaPersistentType.TRANSIENT); + rpModel.setFilePath(remoteFilePath); + dpModel.addToReplicaLocations(rpModel); + String uri = AiravataManager.getInstance().registerDataProduct(dpModel); + uriCollection = uriCollection + uri + ","; + } + } + uriCollection = uriCollection.substring(0, uriCollection.length() -1); + inputDataObjectType.setValue(uriCollection); + } + }else{ + inputDataObjectType.setValue((String) this.experimentInputs.get(inputDataObjectType)); + } + temp.add(inputDataObjectType); + } + experimentModel.setExperimentInputs(temp); + experimentModel.setExperimentOutputs(outputDataObjectTypes); + return experimentModel; + } + + private boolean validateExperimentFields(){ + + String expName = expCreateNameField.getText(); + if(expName == null || expName.isEmpty()){ + SEAGridDialogHelper.showWarningDialog("Warning Dialog", "Experiment Validation Failed", "Experiment name should" + + " be non empty"); + return false; + } + + BatchQueue selectedQueue = (BatchQueue)expCreateQueueField.getSelectionModel().getSelectedItem(); + if(selectedQueue != null) { + try { + int nodeCount = Integer.parseInt(expCreateNodeCountField.getText().trim()); + if (nodeCount <= 0 || nodeCount > selectedQueue.getMaxNodes()){ + SEAGridDialogHelper.showWarningDialog("Warning Dialog", "Experiment Validation Failed", "Node count should" + + " be positive value less than " + selectedQueue.getMaxNodes()); + return false; + } + + int coreCount = Integer.parseInt(expCreateTotalCoreCountField.getText().trim()); + if (coreCount <= 0 || coreCount > selectedQueue.getMaxProcessors()){ + SEAGridDialogHelper.showWarningDialog("Warning Dialog", "Experiment Validation Failed", "Core count should" + + " be positive value less than " + selectedQueue.getMaxProcessors()); + return false; + } + + int wallTime = Integer.parseInt(expCreateWallTimeField.getText().trim()); + if (wallTime <= 0 || wallTime > selectedQueue.getMaxRunTime()){ + SEAGridDialogHelper.showWarningDialog("Warning Dialog", "Experiment Validation Failed", "Wall time should" + + " be positive value less than " + selectedQueue.getMaxRunTime()); + return false; + } + + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if(this.experimentInputs == null || this.experimentInputs.size()==0){ + SEAGridDialogHelper.showWarningDialog("Warning Dialog", "Experiment Validation Failed", "Experiment inputs" + + " not selected"); + return false; + }else{ + for(InputDataObjectType inputDataObjectType : this.experimentInputs.keySet()){ + Object object = this.experimentInputs.get(inputDataObjectType); + if(inputDataObjectType.isIsRequired() && (object == null || object.toString().equals(""))){ + SEAGridDialogHelper.showWarningDialog("Warning Dialog", "Experiment Validation Failed", "No value" + + " selected for input " + inputDataObjectType.getName()); + return false; + } + } + } + return true; + } + + private Service getFileUploadService(Map uploadFiles){ + Service service = new Service() { + @Override + protected Task createTask() { + try { + /*for (Map.Entry entry : uploadFiles.entrySet()) { + //System.out.println(entry.getKey() + ":" + entry.getValue().toString()); + Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Content of the keys" + entry.getKey() + " ?" +"Value of the key"+entry.getValue(), ButtonType.YES, ButtonType.NO, ButtonType.CANCEL); + alert.showAndWait(); + if (alert.getResult() == ButtonType.YES) { + //do stuff + } + }*/ + return new NextcloudFileUploadTask(uploadFiles); + } catch (Exception e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", expCreateInputsGridPane.getScene().getWindow(), + "Unable To Connect To File Server !"); + } + return null; + } + }; + SEAGridDialogHelper.showProgressDialog(service,"Progress Dialog",expCreateInputsGridPane.getScene().getWindow(), + "Uploading Experiment Input Files"); + service.setOnFailed((WorkerStateEvent t) -> { + SEAGridDialogHelper.showExceptionDialogAndWait(service.getException(), "Exception Dialog", + expCreateInputsGridPane.getScene().getWindow(), "File Upload Failed"); + }); + return service; + } + + private void downloadFile(Path remotePath, String destParentPath){ + String localPath = destParentPath + File.separator + remotePath.getFileName(); + Service service = new Service() { + @Override + protected Task createTask() { + try { + return new NextcloudFileDownloadTask(remotePath.toString(), localPath); + } catch (Exception e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", expCreateNameField.getScene().getWindow(), + "Unable To Connect To File Server !"); + } + return null; + } + }; + SEAGridDialogHelper.showProgressDialog(service,"Progress Dialog",expCreateNameField.getScene().getWindow(), + "Downloading File " + remotePath.getFileName()); + service.setOnFailed((WorkerStateEvent t) -> { + SEAGridDialogHelper.showExceptionDialogAndWait(service.getException(), "Exception Dialog", + expCreateNameField.getScene().getWindow(), "File Download Failed"); + }); + service.setOnSucceeded((WorkerStateEvent t)->{ + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.FILE_DOWNLOADED,localPath)); + }); + service.start(); + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/ui/experiment/create/controller/RemoteFilePickerController.java b/src/main/java/org/seagrid/desktop/ui/experiment/create/controller/RemoteFilePickerController.java new file mode 100644 index 0000000..6a00b9f --- /dev/null +++ b/src/main/java/org/seagrid/desktop/ui/experiment/create/controller/RemoteFilePickerController.java @@ -0,0 +1,237 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.ui.experiment.create.controller; + +import com.github.sardine.DavResource; +import com.jcraft.jsch.ChannelSftp; +import com.jcraft.jsch.JSchException; +import com.jcraft.jsch.SftpException; +import javafx.beans.property.SimpleObjectProperty; +import javafx.beans.property.SimpleStringProperty; +import javafx.collections.FXCollections; +import javafx.collections.ObservableList; +import javafx.fxml.FXML; +import javafx.geometry.Pos; +import javafx.scene.control.*; +import javafx.scene.image.Image; +import javafx.scene.input.ClipboardContent; +import javafx.scene.input.DataFormat; +import javafx.scene.input.Dragboard; +import javafx.scene.input.TransferMode; +import javafx.scene.layout.HBox; +import javafx.stage.Stage; +import org.seagrid.desktop.connectors.NextcloudStorage.NextcloudStorageManager; +import org.seagrid.desktop.ui.commons.SEAGridDialogHelper; +import org.seagrid.desktop.ui.storage.model.FileListModel; +import org.seagrid.desktop.util.SEAGridContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Vector; + +public class RemoteFilePickerController { + private final static Logger logger = LoggerFactory.getLogger(RemoteFilePickerController.class); + + @FXML + private TableView fbRemoteFileTable; + + @FXML + private TableColumn fbRemoteFileTblFileName; + + @FXML + private TableColumn fbRemoteFileTblFileSize; + + @FXML + public TableColumn fbRemoteFileTblLastMod; + + @FXML + private TextField fbRemotePath; + + @FXML + private Button selectRemoteFileBtn; + + private Path currentRemotePath; + + private ObservableList currentRemoteFileList; + + private String selectedFilePath = null; + + @SuppressWarnings("unused") + public void initialize(){ + try{ + initialiseColumnWidths(); + initializeRemoteFileTable(); + fbRemotePath.setAlignment(Pos.BASELINE_LEFT); + selectRemoteFileBtn.setOnAction(e->{ + if(selectedFilePath != null){ + ((Stage)selectRemoteFileBtn.getScene().getWindow()).close(); + } + }); + selectRemoteFileBtn.setDisable(true); + }catch (Exception e){ + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", null, + "Failed opening mass storage browser"); + if(fbRemotePath != null && fbRemotePath.getScene() != null && fbRemotePath.getScene().getWindow() != null) + ((Stage)fbRemotePath.getScene().getWindow()).close(); + } + } + + private void initialiseColumnWidths(){ + fbRemoteFileTblFileName.prefWidthProperty().bind(fbRemoteFileTable.widthProperty().divide(3)); + fbRemoteFileTblFileSize.prefWidthProperty().bind(fbRemoteFileTable.widthProperty().divide(3)); + fbRemoteFileTblLastMod.prefWidthProperty().bind(fbRemoteFileTable.widthProperty().divide(3)); + } + + private void initializeRemoteFileTable() throws SftpException, JSchException, IOException { + String remoteHome = "/"; + this.currentRemotePath = Paths.get(remoteHome); + + fbRemoteFileTblFileName.setCellValueFactory(cellData-> new SimpleObjectProperty(cellData.getValue())); + fbRemoteFileTblFileName.setCellFactory(param -> new TableCell(){ + @Override + public void updateItem(FileListModel item, boolean empty){ + if(item != null){ + HBox hBox = new HBox(2); + Image fileImage; + if(item.getFileListModelType().equals(FileListModel.FileListModelType.FILE)){ + fileImage = new Image(RemoteFilePickerController.class.getResourceAsStream("/images/file.png")); + }else{ + fileImage = new Image(RemoteFilePickerController.class.getResourceAsStream("/images/folder.png")); + } + hBox.getChildren().add(new javafx.scene.image.ImageView(fileImage)); + hBox.getChildren().add(new Label(item.getFileName())); + setGraphic(hBox); + }else{ + setGraphic(null); + } + } + }); + fbRemoteFileTblFileSize.setCellValueFactory(cellData -> cellData.getValue().getFileListModelType() + .equals(FileListModel.FileListModelType.FILE) ? new SimpleStringProperty(cellData.getValue().getSize()+" bytes") + : null); + fbRemoteFileTblFileSize.setCellFactory(param -> new TableCell(){ + @Override + public void updateItem(String item, boolean empty){ + setText(item); + setAlignment(Pos.CENTER_RIGHT); + } + }); + fbRemoteFileTblLastMod.setCellValueFactory(cellData -> cellData.getValue().getFileListModelType() + .equals(FileListModel.FileListModelType.PARENT_DIR) ? null + : new SimpleStringProperty(LocalDateTime.ofEpochSecond(cellData.getValue().getLastModifiedTime() / 1000, 0, + SEAGridContext.getInstance().getTimeZoneOffset()).toString())); + fbRemoteFileTblLastMod.setCellFactory(param -> new TableCell(){ + @Override + public void updateItem(String item, boolean empty){ + setText(item); + setAlignment(Pos.CENTER_RIGHT); + } + }); + + currentRemoteFileList = FXCollections.observableArrayList(); + fbRemoteFileTable.setItems(currentRemoteFileList); + + fbRemoteFileTable.setOnMouseClicked(event -> { + FileListModel fileListModel = fbRemoteFileTable.getSelectionModel().getSelectedItem(); + if(fileListModel != null) { + selectRemoteFileBtn.setDisable(true); + + //File Selected + if (event.getClickCount() == 1) { + if (fileListModel.getFileListModelType().equals(FileListModel.FileListModelType + .FILE)) { + selectedFilePath = fileListModel.getFilePath(); + selectRemoteFileBtn.setDisable(false); + } + } + if (event.getClickCount() == 2) { + if (fileListModel.getFileListModelType().equals(FileListModel.FileListModelType.DIR)) { + currentRemotePath = Paths.get(currentRemotePath.toString() + "/" + fileListModel.getFileName()); + } else if (fileListModel.getFileListModelType().equals(FileListModel.FileListModelType + .PARENT_DIR)) { + currentRemotePath = currentRemotePath.getParent(); + } + try { + populateRemoteFileTable(); + } catch (Exception e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", fbRemoteFileTable.getScene().getWindow(), + "Failed to load remote directory information"); + } + } + } + }); + + fbRemoteFileTable.setRowFactory(tv -> { + TableRow row = new TableRow<>(); + row.setOnDragDetected(event -> { + if (!row.isEmpty() && !currentRemoteFileList.get(row.getIndex()).getFileName().equals("..") + && currentRemoteFileList.get(row.getIndex()).getFileListModelType().equals(FileListModel + .FileListModelType.FILE)) { + FileListModel selectedFileListModel = fbRemoteFileTable.getSelectionModel().getSelectedItem(); + Dragboard db = row.startDragAndDrop(TransferMode.MOVE); + db.setDragView(row.snapshot(null, null)); + ClipboardContent cc = new ClipboardContent(); + cc.put(new DataFormat("application/x-java-serialized-object"), selectedFileListModel); + db.setContent(cc); + event.consume(); + } + }); + return row; + }); + + populateRemoteFileTable(); + } + + private void populateRemoteFileTable() throws JSchException, SftpException, IOException { + currentRemoteFileList.clear(); + int count = 0; + fbRemotePath.setText(SEAGridContext.getInstance().getUserName() + currentRemotePath.toString()); + FileListModel fileListModel; + if(currentRemotePath.getParent() != null){ + fileListModel = new FileListModel("..", FileListModel.FileListModelType.PARENT_DIR,0,0, FileListModel.FileLocation.REMOTE, + currentRemotePath.getParent().toString()); + currentRemoteFileList.add(fileListModel); + } + List resources = NextcloudStorageManager.getInstance().listDirectories(currentRemotePath.toString()); + + for (DavResource res : resources) { + if (count != 0) { + if (res.getName().equals(".") || res.getName().equals("..")) continue; + fileListModel = new FileListModel(res.getName(), res.isDirectory() == false + ? FileListModel.FileListModelType.FILE : FileListModel.FileListModelType.DIR, res.getContentLength().intValue(), + res.getModified().getTime(), FileListModel.FileLocation.REMOTE, currentRemotePath.toString() + + "/" + res.getName()); + currentRemoteFileList.add(fileListModel); + } + count++; + } + } + + public String getSelectedFilePath() { + return selectedFilePath; + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/ui/experiment/summary/.DS_Store b/src/main/java/org/seagrid/desktop/ui/experiment/summary/.DS_Store new file mode 100644 index 0000000..77dbdc7 Binary files /dev/null and b/src/main/java/org/seagrid/desktop/ui/experiment/summary/.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/ui/experiment/summary/._.DS_Store b/src/main/java/org/seagrid/desktop/ui/experiment/summary/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/org/seagrid/desktop/ui/experiment/summary/._.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/ui/experiment/summary/ExperimentSummaryWindow.java b/src/main/java/org/seagrid/desktop/ui/experiment/summary/ExperimentSummaryWindow.java new file mode 100644 index 0000000..9ed7f8c --- /dev/null +++ b/src/main/java/org/seagrid/desktop/ui/experiment/summary/ExperimentSummaryWindow.java @@ -0,0 +1,76 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.ui.experiment.summary; + +import javafx.application.Application; +import javafx.fxml.FXMLLoader; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.stage.Stage; +import org.apache.thrift.TException; +import org.seagrid.desktop.ui.commons.SEAGridDialogHelper; +import org.seagrid.desktop.ui.experiment.summary.controller.ExperimentSummaryController; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.net.URISyntaxException; + +public class ExperimentSummaryWindow extends Application { + private final static Logger logger = LoggerFactory.getLogger(ExperimentSummaryWindow.class); + + @Override + public void start(Stage primaryStage) throws Exception { + Parent root = FXMLLoader.load(getClass().getResource("/views/experiment/summary/experiment-summary.fxml")); + primaryStage.setTitle("SEAGrid Desktop Client - Experiment Summary"); + primaryStage.setScene(new Scene(root, 800, 600)); + primaryStage.show(); + } + + public Parent getExperimentInfoNode(String experimentId) throws IOException, TException { + FXMLLoader loader = new FXMLLoader(getClass().getResource( + "/views/experiment/summary/experiment-summary.fxml")); + Parent node = loader.load(); + ExperimentSummaryController controller = loader.getController(); + try { + controller.initExperimentInfo(experimentId); + } catch (URISyntaxException e) { + SEAGridDialogHelper.showExceptionDialog(e,"Exception caught", null, "Unable to open experiment"); + } + return node; + } + + public void showExperimentSummaryWindow(String experimentId) throws IOException, TException { + Stage primaryStage = new Stage(); + FXMLLoader loader = new FXMLLoader(getClass().getResource( + "/views/experiment/summary/experiment-summary.fxml")); + Parent root = loader.load(); + primaryStage.setTitle("SEAGrid Desktop Client - Experiment Summary"); + primaryStage.setScene(new Scene(root, 800, 600)); + ExperimentSummaryController controller = loader.getController(); + try { + controller.initExperimentInfo(experimentId); + } catch (URISyntaxException e) { + SEAGridDialogHelper.showExceptionDialog(e, "Exception caught", null, "Unable to open experiment"); + } + primaryStage.show(); + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/ui/experiment/summary/controller/ExperimentSummaryController.java b/src/main/java/org/seagrid/desktop/ui/experiment/summary/controller/ExperimentSummaryController.java new file mode 100644 index 0000000..1b899e9 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/ui/experiment/summary/controller/ExperimentSummaryController.java @@ -0,0 +1,588 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.ui.experiment.summary.controller; + +import com.google.common.eventbus.Subscribe; +import javafx.animation.KeyFrame; +import javafx.animation.Timeline; +import javafx.application.Platform; +import javafx.concurrent.Service; +import javafx.concurrent.Task; +import javafx.concurrent.WorkerStateEvent; +import javafx.fxml.FXML; +import javafx.scene.Node; +import javafx.scene.control.Button; +import javafx.scene.control.Hyperlink; +import javafx.scene.control.Label; +import javafx.scene.control.TextArea; +import javafx.scene.layout.GridPane; +import javafx.scene.layout.RowConstraints; +import javafx.scene.layout.VBox; +import javafx.scene.paint.Color; +import javafx.scene.text.Text; +import javafx.scene.text.TextFlow; +import javafx.util.Duration; +import org.apache.airavata.model.appcatalog.appinterface.ApplicationInterfaceDescription; +import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription; +import org.apache.airavata.model.application.io.InputDataObjectType; +import org.apache.airavata.model.application.io.OutputDataObjectType; +import org.apache.airavata.model.commons.ErrorModel; +import org.apache.airavata.model.data.replica.DataReplicaLocationModel; +import org.apache.airavata.model.data.replica.ReplicaLocationCategory; +import org.apache.airavata.model.error.AiravataClientException; +import org.apache.airavata.model.experiment.ExperimentModel; +import org.apache.airavata.model.status.ExperimentState; +import org.apache.airavata.model.status.JobStatus; +import org.apache.airavata.model.workspace.Project; +import org.apache.thrift.TException; +import org.seagrid.desktop.connectors.NextcloudStorage.NextcloudFileDownloadTask; +import org.seagrid.desktop.connectors.NextcloudStorage.NextcloudStorageManager; +import org.seagrid.desktop.connectors.airavata.AiravataManager; +import org.seagrid.desktop.ui.commons.SEAGridDialogHelper; +import org.seagrid.desktop.ui.home.model.ExperimentListModel; +import org.seagrid.desktop.ui.storage.MassStorageBrowserWindow; +import org.seagrid.desktop.util.SEAGridContext; +import org.seagrid.desktop.util.messaging.SEAGridEvent; +import org.seagrid.desktop.util.messaging.SEAGridEventBus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class ExperimentSummaryController { + private final static Logger logger = LoggerFactory.getLogger(ExperimentSummaryController.class); + + private static final double EXPERIMENT_UPDATE_INTERVAL = 10000; + + private ExperimentModel experimentModel; + + @FXML + private Button expStorageDir; + + @FXML + private Button expLaunchButton; + + @FXML + private Button expEditButton; + + @FXML + private Button expCancelButton; + + @FXML + private Button expCloneButton; + + @FXML + private Label experimentIdLabel; + + @FXML + private Label experimentNameLabel; + + @FXML + private Label experimentProjectLabel; + + @FXML + private Label experimentDescField; + + @FXML + private Label experimentApplicationLabel; + + @FXML + private Label experimentCRLabel; + + @FXML + private Label experimentJobStatusLabel; + + @FXML + private Label experimentStatusLabel; + + @FXML + private Label experimentCreationTimeLabel; + + @FXML + private Label experimentLastModifiedTimeLabel; + + @FXML + private Label experimentEnableAutoSchedLabel; + + @FXML + private Label experimentWallTimeLabel; + + @FXML + private Label experimentCPUCountLabel; + + @FXML + private Label experimentQueueLabel; + + @FXML + private Label experimentNodeCountLabel; + + @FXML + private GridPane experimentInfoGridPane; + + @FXML + private GridPane experimentErrorGridPane; + + @FXML + private TextArea errorTextArea; + + @FXML + private VBox experimentSummaryVBox; + + private Timeline expInfoUpdateTimer = null; + + + private String remoteDataDirRoot = SEAGridContext.getInstance().getGatewayUserDataRoot(); + + //This is the start row of experiment inputs in summary view + private int EXPERIMENT_INPUT_START_ROW = 15; + + public void initialize(){ + expLaunchButton.setOnAction(event -> { + try{ + AiravataManager.getInstance().launchExperiment(experimentModel.getExperimentId()); + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.EXPERIMENT_LAUNCHED,experimentModel)); + } catch (Exception e) { + SEAGridDialogHelper.showExceptionDialog(e, "Exception Dialog", experimentInfoGridPane.getScene().getWindow(), + "Failed launching experiment"); + } + }); + expCancelButton.setOnAction(event -> { + try{ + AiravataManager.getInstance().cancelExperiment(experimentModel.getExperimentId()); + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.EXPERIMENT_CANCELLED, experimentModel)); + } catch (Exception e) { + SEAGridDialogHelper.showExceptionDialog(e, "Exception Dialog", experimentInfoGridPane.getScene().getWindow(), + "Failed cancelling experiment"); + } + }); + expEditButton.setOnAction(event -> { + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.EXPERIMENT_EDIT_REQUEST, experimentModel)); + }); + expCloneButton.setOnAction(event -> { + try { + List inputDataObjectTypes = experimentModel.getExperimentInputs(); + String experimentDataDir = "/" + experimentModel.getProjectId().substring(0, experimentModel.getProjectId().length()-37).replaceAll("[^A-Za-z0-9 ]", "_") + "/" + + experimentNameLabel.getText().replaceAll("[^A-Za-z0-9]","_")+"."+System.currentTimeMillis(); + NextcloudStorageManager.getInstance().createFolderifNotExist(experimentDataDir); + String expId = AiravataManager.getInstance().cloneExperiment(experimentModel.getExperimentId(), + "Clone of " + experimentModel.getExperimentName(), experimentModel.getProjectId()); + ExperimentModel clonedExperimentModel = AiravataManager.getInstance().getExperiment(expId); + clonedExperimentModel.setExperimentInputs(inputDataObjectTypes); + clonedExperimentModel.getUserConfigurationData().setExperimentDataDir(experimentDataDir); + AiravataManager.getInstance().updateExperiment(clonedExperimentModel); + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.EXPERIMENT_CLONED, + clonedExperimentModel)); + } catch (Exception e) { + SEAGridDialogHelper.showExceptionDialog(e, "Exception Dialog", experimentInfoGridPane.getScene().getWindow(), + "Failed cloning experiment"); + } + }); + expStorageDir.setOnAction(event -> { + try { + String path = "Documents" + "/" + experimentModel.getUserConfigurationData().getExperimentDataDir(); + path = path.replaceAll(SEAGridContext.getInstance().getGatewayUserDataRoot(),""); + MassStorageBrowserWindow.displayFileBrowse(path); + } catch (Exception e) { + SEAGridDialogHelper.showExceptionDialog(e, "Exception Dialog", expStorageDir.getScene().getWindow(), + "Failed to open mass storage browser"); + } + }); + SEAGridEventBus.getInstance().register(this); + } + + public void initExperimentInfo(ExperimentModel experimentModel) throws TException, URISyntaxException, IOException { + if(experimentModel != null){ + experimentIdLabel.setText(experimentModel.getExperimentId()); + experimentNameLabel.setText(experimentModel.getExperimentName()); + experimentDescField.setText(experimentModel.getDescription()); + if(experimentModel.getProjectId() != null){ + Project project = AiravataManager.getInstance().getProject(experimentModel.getProjectId()); + if(project != null){ + experimentProjectLabel.setText(project.getName()); + } + } + if(experimentModel.getExecutionId() != null){ + ApplicationInterfaceDescription app = AiravataManager.getInstance().getApplicationInterface( + experimentModel.getExecutionId()); + if(app != null){ + experimentApplicationLabel.setText(app.getApplicationName()); + } + } + if(experimentModel.getUserConfigurationData().getComputationalResourceScheduling().getResourceHostId() != null){ + ComputeResourceDescription computeResourceDescription = AiravataManager.getInstance().getComputeResource( + experimentModel.getUserConfigurationData().getComputationalResourceScheduling().getResourceHostId() + ); + if(computeResourceDescription != null){ + String temp = " (using community account)"; + if(experimentModel.getUserConfigurationData().isUseUserCRPref()){ + temp = " (using user account)"; + } + experimentCRLabel.setText(computeResourceDescription.getHostName()+temp); + } + } + showStatus(experimentModel); + experimentCreationTimeLabel.setText(LocalDateTime.ofEpochSecond(experimentModel + .getCreationTime() / 1000, 0, SEAGridContext.getInstance().getTimeZoneOffset()).toString()); + experimentLastModifiedTimeLabel.setText(LocalDateTime.ofEpochSecond(experimentModel.getExperimentStatus().get(0) + .getTimeOfStateChange() / 1000, 0, SEAGridContext.getInstance().getTimeZoneOffset()).toString()); + experimentEnableAutoSchedLabel.setText("true"); + experimentWallTimeLabel.setText(experimentModel.getUserConfigurationData() + .getComputationalResourceScheduling().getWallTimeLimit()+""); + experimentCPUCountLabel.setText(experimentModel.getUserConfigurationData() + .getComputationalResourceScheduling().getTotalCPUCount()+""); + experimentQueueLabel.setText(experimentModel.getUserConfigurationData() + .getComputationalResourceScheduling().getQueueName()); + experimentNodeCountLabel.setText(experimentModel.getUserConfigurationData() + .getComputationalResourceScheduling().getNodeCount()+""); + + //This is to clear the current grid rows for experiment inputs, outputs and errors + //EXPERIMENT_INPUT_START_ROW is a hardcoded constant which the input row starts + List removingNodes = experimentInfoGridPane.getChildren().stream().filter(child -> + experimentInfoGridPane.getRowIndex(child) >= EXPERIMENT_INPUT_START_ROW).collect(Collectors.toList()); + experimentInfoGridPane.getChildren().removeAll(removingNodes); + experimentInfoGridPane.getRowConstraints().remove(EXPERIMENT_INPUT_START_ROW, experimentInfoGridPane + .getRowConstraints().size()); + showExperimentInputs(experimentModel); + updateButtonOptions(experimentModel); + if((experimentStatusLabel.getText().equals(ExperimentState.FAILED.toString()) || experimentStatusLabel.getText() + .equals(ExperimentState.COMPLETED.toString()) + || experimentStatusLabel.getText().equals(ExperimentState.CANCELED.toString()))) { + showExperimentOutputs(experimentModel); + }else{ + //TODO this should replace with a RabbitMQ Listener + expInfoUpdateTimer = new Timeline(new KeyFrame( + Duration.millis(EXPERIMENT_UPDATE_INTERVAL), + ae -> updateExperimentInfo())); + expInfoUpdateTimer.setCycleCount(Timeline.INDEFINITE); + expInfoUpdateTimer.play(); + } + + if(experimentStatusLabel.getText().equals(ExperimentState.FAILED.toString())){ + showExperimentErrors(experimentModel); + }else{ + experimentSummaryVBox.getChildren().remove(experimentErrorGridPane); + } + } + } + + public void initExperimentInfo(String experimentId) throws TException, URISyntaxException, IOException { + experimentModel = AiravataManager.getInstance().getExperiment(experimentId); + initExperimentInfo(experimentModel); + } + + //updates the experiment status and outputs in the background + public void updateExperimentInfo(){ + if(!(experimentStatusLabel.getText().equals("FAILED") || experimentStatusLabel.getText().equals("COMPLETED") + || experimentStatusLabel.getText().equals("CANCELLED"))) { + Platform.runLater(() -> { + String experimentId = experimentIdLabel.getText(); + try { + ExperimentModel experimentModel = AiravataManager.getInstance().getExperiment(experimentId); + showStatus(experimentModel); + updateButtonOptions(experimentModel); + String expState = experimentModel.getExperimentStatus().get(0).getState().toString(); + if(expState.equals("FAILED") || expState.equals("COMPLETED") || expState.equals("CANCELLED")){ + showExperimentOutputs(experimentModel); + expInfoUpdateTimer.stop(); + } + logger.debug("Updated Experiment :" + experimentId); + } catch (Exception e) { + e.printStackTrace(); + if(this.expInfoUpdateTimer != null) + this.expInfoUpdateTimer.stop(); + } + }); + }else{ + expInfoUpdateTimer.stop(); + } + } + + private void showStatus(ExperimentModel experimentModel) throws TException { + experimentStatusLabel.setText(experimentModel.getExperimentStatus().get(0).getState().toString()); + switch (experimentModel.getExperimentStatus().get(0).getState()){ + case COMPLETED : + experimentStatusLabel.setTextFill(Color.GREEN); + break; + case FAILED : + experimentStatusLabel.setTextFill(Color.RED); + break; + case CREATED : + experimentStatusLabel.setTextFill(Color.BLUE); + break; + default : + experimentStatusLabel.setTextFill(Color.ORANGE); + } + + Map jobStatusMap = null; + try { + jobStatusMap = AiravataManager.getInstance().getJobStatuses(experimentModel.getExperimentId()); + if(jobStatusMap != null && jobStatusMap.values().size()>0){ + JobStatus jobStatus = (JobStatus)jobStatusMap.values().toArray()[0]; + experimentJobStatusLabel.setText(jobStatus.getJobState().toString()); + switch (jobStatus.getJobState()){ + case COMPLETE : + experimentJobStatusLabel.setTextFill(Color.GREEN); + break; + case FAILED : + experimentJobStatusLabel.setTextFill(Color.RED); + break; + default : + experimentJobStatusLabel.setTextFill(Color.ORANGE); + } + }else{ + experimentJobStatusLabel.setText("NOT-AVAILABLE"); + } + } catch (AiravataClientException e) { + e.printStackTrace(); + } + } + + private void showExperimentInputs(ExperimentModel experimentModel) throws TException, URISyntaxException { + + List inputDataObjectTypes = experimentModel.getExperimentInputs(); + int rowIndex = EXPERIMENT_INPUT_START_ROW; + experimentInfoGridPane.add(new Label("Inputs"), 0, rowIndex); + String dataRoot = remoteDataDirRoot; + List replicas; + String fileUri; + Hyperlink hyperlink; + TextFlow uriOutputLabel; + + Collections.sort(inputDataObjectTypes, (o1, o2) -> { + if(o1.getName().startsWith("Optional-File-Inputs")) + return Integer.MAX_VALUE; + else if(o2.getName().startsWith("Optional-File-Inputs")) + return Integer.MIN_VALUE; + else + return o1.getName().compareTo(o2.getName()); + }); + + for(InputDataObjectType input : inputDataObjectTypes){ + switch (input.getType()){ + case URI : + case STDERR: + case STDOUT: + if(input.getValue() != null && !input.getValue().equals("")) { + replicas = AiravataManager.getInstance().getDataReplicas(input.getValue()); + fileUri = ""; + for (DataReplicaLocationModel rpModel : replicas) { + if (rpModel.getReplicaLocationCategory().equals(ReplicaLocationCategory.GATEWAY_DATA_STORE)) { + fileUri = rpModel.getFilePath(); + break; + } + } + String filePath1 = (new URI(fileUri)).getPath(); + hyperlink = new Hyperlink(Paths.get(filePath1).getFileName().toString()); + uriOutputLabel = new TextFlow(new Text(input.getName() + " : "), hyperlink); + + hyperlink.setOnAction(event -> { + downloadFile(Paths.get(filePath1.toString().replaceAll(dataRoot, "")), experimentModel); + }); + experimentInfoGridPane.add(uriOutputLabel, 1, rowIndex); + } + break; + case URI_COLLECTION: + if(input.getValue() != null && !input.getValue().equals("")) { + String uriCollection = input.getValue(); + String[] uris = uriCollection.split(","); + int i = 1; + for(String uri : uris){ + replicas = AiravataManager.getInstance().getDataReplicas(uri); + fileUri = ""; + for(DataReplicaLocationModel rpModel : replicas){ + if(rpModel.getReplicaLocationCategory().equals(ReplicaLocationCategory.GATEWAY_DATA_STORE)) { + fileUri = rpModel.getFilePath(); + break; + } + } + String filePath2 = (new URI(fileUri)).getPath(); + hyperlink = new Hyperlink(Paths.get(filePath2).getFileName().toString()); + uriOutputLabel = new TextFlow(new Text(input.getName()+" ("+ i +")" +" : "), hyperlink); + hyperlink.setOnAction(event -> { + downloadFile(Paths.get(filePath2.toString().replaceAll(dataRoot, "")), experimentModel); + }); + experimentInfoGridPane.add(uriOutputLabel, 1, rowIndex); + + experimentInfoGridPane.getRowConstraints().add(rowIndex-1,new RowConstraints(25)); + rowIndex++; + i++; + } + rowIndex--; + } + break; + default : + Label outputLabel = new Label(); + outputLabel.setText(input.getName() + " : " + input.getValue()); + experimentInfoGridPane.add(outputLabel, 1, rowIndex); + } + experimentInfoGridPane.getRowConstraints().add(rowIndex-1,new RowConstraints(25)); + rowIndex++; + } + } + + private void showExperimentErrors(ExperimentModel experimentModel) { + String error = ""; + if(experimentModel.getErrors() != null && !experimentModel.getErrors().isEmpty()) { + for (ErrorModel errorModel : experimentModel.getErrors()) { + error = error + errorModel.getUserFriendlyMessage() + " : "; + error = error + errorModel.getActualErrorMessage() + "\n"; + } + errorTextArea.setText(error); + errorTextArea.setWrapText(true); + } + } + + private void showExperimentOutputs(ExperimentModel experimentModel) throws TException, URISyntaxException, IOException { + int rowIndex = experimentInfoGridPane.getRowConstraints().size(); + experimentInfoGridPane.add(new Label("Outputs"), 0, rowIndex); + List outputDataObjectTypes = experimentModel.getExperimentOutputs(); + for(OutputDataObjectType output : outputDataObjectTypes){ + //not showing wildcard file names + if(!output.getValue().contains("*")){ + switch (output.getType()){ + case URI : + case STDERR: + case STDOUT: + String dataRoot = remoteDataDirRoot; + + try{ + List replicas = AiravataManager.getInstance().getDataReplicas(output.getValue()); + String fileUri = ""; + for(DataReplicaLocationModel rpModel : replicas){ + if(rpModel.getReplicaLocationCategory().equals(ReplicaLocationCategory.GATEWAY_DATA_STORE)) { + fileUri = rpModel.getFilePath(); + break; + } + } + String filePath = (new URI(fileUri)).getPath(); + Hyperlink hyperlink = new Hyperlink(Paths.get(filePath).getFileName().toString()); + TextFlow uriOutputLabel = new TextFlow(new Text(output.getName()+" : "), hyperlink); + hyperlink.setOnAction(event -> { + downloadFile(Paths.get(filePath.toString().replaceAll(dataRoot, "")), experimentModel); + }); + experimentInfoGridPane.add(uriOutputLabel, 1, rowIndex); + break; + }catch (Exception ex){ + logger.info("Failed to retrieve output data for experiment : " + experimentModel.getExperimentId() + + ". Output : " + output.getValue()); + } + + default : + Label outputLabel = new Label(); + outputLabel.setText(output.getName() + " : " + output.getValue()); + experimentInfoGridPane.add(outputLabel, 1, rowIndex); + } + experimentInfoGridPane.getRowConstraints().add(rowIndex - 1, new RowConstraints(25)); + rowIndex++; + } + } + } + + private void downloadFile(Path remotePath, ExperimentModel experimentModel){ + String localPath = SEAGridContext.getInstance() + .getFileDownloadLocation()+ File.separator + experimentModel.getProjectId().substring(0,experimentModel + .getProjectId().length() - 37) + File.separator + experimentModel.getExperimentId() +File.separator+remotePath.getFileName(); + Service service = new Service() { + @Override + protected Task createTask() { + try { + return new NextcloudFileDownloadTask("/Documents" + "/" + remotePath.toString(), localPath); + } catch (Exception e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", experimentInfoGridPane.getScene().getWindow(), + "Unable To Connect To File Server !"); + } + return null; + } + }; + SEAGridDialogHelper.showProgressDialog(service,"Progress Dialog",experimentInfoGridPane.getScene().getWindow(), + "Downloading File " + remotePath.getFileName()); + service.setOnFailed((WorkerStateEvent t) -> { + SEAGridDialogHelper.showExceptionDialogAndWait(service.getException(), "Exception Dialog", + experimentInfoGridPane.getScene().getWindow(), "File Download Failed"); + }); + service.setOnSucceeded((WorkerStateEvent t)->{ + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.FILE_DOWNLOADED,localPath)); + }); + service.start(); + } + + private void updateButtonOptions(ExperimentModel experimentModel){ + switch (experimentModel.getExperimentStatus().get(0).getState()){ + case CREATED: + expCancelButton.setDisable(true); + expStorageDir.setDisable(false); + break; + case EXECUTING: + expCancelButton.setDisable(false); + case CANCELING: + expLaunchButton.setDisable(true); + expEditButton.setDisable(true); + expCancelButton.setDisable(true); + break; + case FAILED: + case CANCELED: + case COMPLETED: + expCancelButton.setDisable(true); + expLaunchButton.setDisable(true); + expEditButton.setDisable(true); + } + } + + @SuppressWarnings("unused") + @Subscribe + public void listenSEAGridEvents(SEAGridEvent event) throws TException, IOException { + if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.EXPERIMENT_UPDATED)) { + ExperimentModel updatedExperimentModel = (ExperimentModel) event.getPayload(); + if(updatedExperimentModel.getExperimentId().equals(this.experimentModel.getExperimentId())){ + try { + initExperimentInfo(updatedExperimentModel); + } catch (URISyntaxException e) { + SEAGridDialogHelper.showExceptionDialog(e, "Exception caught", null, "Unable to open experiment"); + } + } + }else if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.EXPERIMENT_DELETED)) { + if(event.getPayload() instanceof ExperimentListModel){ + ExperimentListModel experimentListModel = (ExperimentListModel) event.getPayload(); + if(experimentModel.getExperimentId().equals(experimentListModel.getId())){ + expInfoUpdateTimer.stop(); + } + }else if(event.getPayload() instanceof ExperimentModel){ + ExperimentModel deletedExpModel = (ExperimentModel) event.getPayload(); + if(experimentModel.getExperimentId().equals(deletedExpModel.getExperimentId())){ + expInfoUpdateTimer.stop(); + } + } + } + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/ui/home/.DS_Store b/src/main/java/org/seagrid/desktop/ui/home/.DS_Store new file mode 100644 index 0000000..226bcd0 Binary files /dev/null and b/src/main/java/org/seagrid/desktop/ui/home/.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/ui/home/._.DS_Store b/src/main/java/org/seagrid/desktop/ui/home/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/org/seagrid/desktop/ui/home/._.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/ui/home/HomeWindow.java b/src/main/java/org/seagrid/desktop/ui/home/HomeWindow.java new file mode 100644 index 0000000..c45be2b --- /dev/null +++ b/src/main/java/org/seagrid/desktop/ui/home/HomeWindow.java @@ -0,0 +1,22 @@ +package org.seagrid.desktop.ui.home; + +import javafx.application.Application; +import javafx.fxml.FXMLLoader; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.stage.Stage; + +public class HomeWindow extends Application { + + @Override + public void start(Stage primaryStage) throws Exception{ + Parent root = FXMLLoader.load(getClass().getResource("/views/home/home.fxml")); + primaryStage.setTitle("SEAGrid Desktop Client"); + primaryStage.setScene(new Scene(root, 800, 600)); + primaryStage.show(); + } + + public static void main(String[] args) { + launch(args); + } +} diff --git a/src/main/java/org/seagrid/desktop/ui/home/controller/HomeController.java b/src/main/java/org/seagrid/desktop/ui/home/controller/HomeController.java new file mode 100644 index 0000000..ca58869 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/ui/home/controller/HomeController.java @@ -0,0 +1,1081 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.ui.home.controller; + + +import cct.JamberooMolecularEditor; +import com.google.common.eventbus.Subscribe; +import com.google.common.reflect.TypeToken; +import com.google.gson.Gson; +import g03input.G03MenuTree; +import gamess.GamessGUI; +import javafx.animation.Animation; +import javafx.animation.KeyFrame; +import javafx.animation.Timeline; +import javafx.beans.Observable; +import javafx.collections.FXCollections; +import javafx.collections.ObservableList; +import javafx.collections.transformation.FilteredList; +import javafx.collections.transformation.SortedList; +import javafx.fxml.FXML; +import javafx.scene.Node; +import javafx.scene.Parent; +import javafx.scene.control.Button; +import javafx.scene.control.*; +import javafx.scene.control.Label; +import javafx.scene.control.MenuItem; +import javafx.scene.control.TextField; +import javafx.scene.control.cell.CheckBoxTableCell; +import javafx.scene.control.cell.PropertyValueFactory; +import javafx.scene.image.Image; +import javafx.scene.image.ImageView; +import javafx.scene.input.MouseButton; +import javafx.scene.paint.Color; +import javafx.scene.web.WebView; +import javafx.stage.Stage; +import javafx.util.Callback; +import javafx.util.Duration; +import nanocad.nanocadMain; +import org.apache.airavata.model.experiment.ExperimentModel; +import org.apache.airavata.model.experiment.ExperimentSearchFields; +import org.apache.airavata.model.experiment.ExperimentSummaryModel; +import org.apache.airavata.model.status.ExperimentState; +import org.apache.airavata.model.workspace.Notification; +import org.apache.airavata.model.workspace.Project; +import org.apache.thrift.TException; +import org.seagrid.desktop.connectors.airavata.AiravataManager; +import org.seagrid.desktop.ui.commons.SEAGridDialogHelper; +import org.seagrid.desktop.ui.experiment.create.ExperimentCreateWindow; +import org.seagrid.desktop.ui.experiment.summary.ExperimentSummaryWindow; +import org.seagrid.desktop.ui.home.model.ExperimentListModel; +import org.seagrid.desktop.ui.home.model.ProjectTreeModel; +import org.seagrid.desktop.ui.home.model.TreeModel; +import org.seagrid.desktop.ui.project.ProjectWindow; +import org.seagrid.desktop.ui.storage.MassStorageBrowserWindow; +import org.seagrid.desktop.util.SEAGridConfig; +import org.seagrid.desktop.util.SEAGridContext; +import org.seagrid.desktop.util.messaging.SEAGridEvent; +import org.seagrid.desktop.util.messaging.SEAGridEventBus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.swing.*; +import java.awt.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.reflect.Type; +import java.net.URL; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Controls the home screen + */ +public class HomeController { + private final static Logger logger = LoggerFactory.getLogger(ExperimentListModel.class); + + private ObservableList observableExperimentList; + + @FXML + public Label notificationLabel; + + @FXML + private Button browseMassStorageBtn; + + @FXML + public Button createProjectButton; + + @FXML + private Button createExperimentButton; + + @FXML + private TreeView projectsTreeView; + + @FXML + private TableView expSummaryTable; + + @FXML + private TableColumn expCheckedColumn; + + @FXML + private TableColumn expApplicationColumn; + + @FXML + private TableColumn expHostColumn; + + @FXML + private TableColumn expStatusColumn; + + @FXML + private TableColumn expNameColumn; + + @FXML + private TableColumn ownerNameColumn; + + @FXML + private TableColumn expCreateTimeColumn; + + @FXML + private TextField filterField; + + @FXML + private TabPane tabbedPane; + + @FXML + private Button logoutBtn; + + @FXML + private Button nanocadBtn; + + @FXML + private Button jamberooBtn; + + @FXML + private MenuItem aboutMenuItem; + + @FXML + private MenuItem appExitMenuItem; + + @FXML + private MenuItem nanocadMenuBtn; + + @FXML + private MenuItem jamberooMenuBtn; + + @FXML + private MenuItem g03MenuBtn; + + @FXML + private MenuItem gamessMenuBtn; + + @FXML + private Button launchSelectedBtn; + + @FXML + private Button deleteSelectedBtn; + + @FXML + private Button gamessBtn; + + @FXML + private Button g03Btn; + + @FXML + public MenuItem projCreateMenuItem; + + @FXML + public MenuItem expCreateMenuItem; + + private Map previousExperimentListFilter; + + private ContextMenu contextMenu; + + //Dummy class used for storing notification list index + private class Index{ + int index; + } + + @SuppressWarnings("unused") + public void initialize() { + SEAGridEventBus.getInstance().register(this); + initMenuBar(); + initProjectTreeView(); + try { + initExperimentList(); + } catch (TException e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", null, + "Failed initialising experiment list !"); + } + initTokenUpdateDaemon(); + + //initializing notification messages + notificationLabel.setCursor(javafx.scene.Cursor.HAND); + notificationLabel.setStyle("-fx-border-color: white;"); + notificationLabel.setMaxWidth(Double.MAX_VALUE); + try{ + java.util.List messages = AiravataManager.getInstance().getNotifications(); + final Index index = new Index(); + index.index = 0; + if (messages != null && messages.size() > 0) { + notificationLabel.setText(messages.get(index.index).getTitle() + " : " + + messages.get(index.index).getNotificationMessage().split("\r|\n")[0]); + Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0), + event -> { + index.index++; + index.index = index.index % messages.size(); + switch (messages.get(index.index).getPriority()){ + case HIGH: + notificationLabel.setTextFill(Color.web("#ff0000")); + break; + case NORMAL: + notificationLabel.setTextFill(Color.web("#ffa500")); + break; + case LOW: + notificationLabel.setTextFill(Color.web("#808080")); + break; + } + notificationLabel.setText(messages.get(index.index).getTitle() + " : " + + messages.get(index.index).getNotificationMessage().split("\r|\n")[0]); + + notificationLabel.setOnMouseClicked(event1 -> { + SEAGridDialogHelper.showInformationDialog("Notification", messages.get(index.index).getTitle(), + messages.get(index.index).getNotificationMessage(), null); + }); + }), + new KeyFrame(Duration.seconds(5))); + timeline.setCycleCount(Animation.INDEFINITE); + timeline.play(); + } + }catch (Exception ex){ + //cannot connect to Airavata + ex.printStackTrace(); + } + } + + public void initMenuBar() { + expCreateMenuItem.setOnAction(event -> { + try { + ExperimentCreateWindow.displayCreateExperiment(); + } catch (IOException e) { + e.printStackTrace(); + } + }); + projCreateMenuItem.setOnAction(event -> { + try { + ProjectWindow.displayCreateProject(); + } catch (IOException e) { + e.printStackTrace(); + } + }); + createProjectButton.setOnMouseClicked(event -> { + try { + ProjectWindow.displayCreateProject(); + } catch (IOException e) { + e.printStackTrace(); + } + }); + createExperimentButton.setOnMouseClicked(event -> { + try { + ExperimentCreateWindow.displayCreateExperiment(); + } catch (IOException e) { + e.printStackTrace(); + } + }); + browseMassStorageBtn.setOnMouseClicked(event -> { + try { + MassStorageBrowserWindow.displayFileBrowse(null); + } catch (Exception e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", browseMassStorageBtn.getScene().getWindow(), + "Failed to open Storage Browser"); + } + }); + nanocadBtn.setOnAction(event -> + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + nanocadMain.showNanocad(); + } + })); + jamberooBtn.setOnAction(event -> { + try{ + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + JamberooMolecularEditor.showJamberoo(); + } + }); + + }catch (Exception ex){ + ex.printStackTrace(); + } + + }); + g03Btn.setOnAction(event1 -> SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + G03MenuTree.showG03MenuTree(); + } + })); + gamessBtn.setOnAction(event1 -> SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + GamessGUI.showGamesGUI(); + } + })); + logoutBtn.setOnAction(event -> { + java.net.CookieHandler.setDefault(new com.sun.webkit.network.CookieManager()); + ((Stage) logoutBtn.getScene().getWindow()).close(); + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.LOGOUT, null)); + }); + aboutMenuItem.setOnAction(event -> { + String imgtext = ""; + String textinfo1 = "
" + + "
" + + imgtext + " Welcome to SEAGrid !! - Science and Engineering Applications Grid" + + "" + + "
" + + "

You are running the " + + "SEAGrid Desktop Client " + + "Application.

"; + String textinfo2 = "

To use Web Portal and for more information, " + + " visit https://seagrid.org/

"; + String textinfo3 = "

If you do not have SEAGrid account, you may request one on the web portal." + + "

"; + + String textinfo4 = "

Note: This version is in active development and will" + + " be auto-updated automatically.

"; + + WebView webView = new WebView(); + webView.getEngine().loadContent(textinfo1 + textinfo2 + textinfo3 + textinfo4); + SEAGridDialogHelper.showInformationDialog( + "Information Dialog", + "SEAGrid Desktop Client", + webView, + logoutBtn.getScene().getWindow()); + }); + appExitMenuItem.setOnAction(event -> { + boolean result = SEAGridDialogHelper.showConfirmDialog("Confirmation Dialog", "Confirm your action", + "Are sure you want to exit the application?"); + if (result) { + System.exit(0); + } + }); + nanocadMenuBtn.setOnAction(event -> + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + nanocadMain.showNanocad(); + } + })); + jamberooMenuBtn.setOnAction(event -> + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + JamberooMolecularEditor.showJamberoo(); + } + })); + g03MenuBtn.setOnAction(event -> SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + G03MenuTree.showG03MenuTree(); + } + })); + gamessMenuBtn.setOnAction(event -> SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + GamessGUI.showGamesGUI(); + } + })); + launchSelectedBtn.setOnAction(event -> expSummaryTable.getItems().stream() + .filter(e -> e.getChecked() && e.getStatus().equals("CREATED")).forEach(e -> { + try { + AiravataManager.getInstance().launchExperiment(e.getId()); + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.EXPERIMENT_LAUNCHED, e)); + } catch (Exception ex) { + SEAGridDialogHelper.showExceptionDialog(ex, "Exception Dialog", launchSelectedBtn.getScene().getWindow(), + "Failed to launch experiment!"); + } + })); + deleteSelectedBtn.setOnAction(event -> { + List experimentListModels = FXCollections.observableArrayList(expSummaryTable.getItems()); + experimentListModels.stream() + .filter(e -> e.getChecked() && e.getStatus().equals("CREATED")).forEach(e -> { + try { + AiravataManager.getInstance().deleteExperiment(e.getId()); + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.EXPERIMENT_DELETED, e)); + } catch (Exception ex) { + SEAGridDialogHelper.showExceptionDialog(ex, "Exception Dialog", launchSelectedBtn.getScene().getWindow(), + "Failed to delete experiment!"); + } + }); + }); + } + + public void initProjectTreeView() { + projectsTreeView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE); + projectsTreeView.setCellFactory(param -> { + TreeCell cell = new TreeCell() { + @Override + public void updateItem(TreeModel item, boolean empty) { + super.updateItem(item, empty); + if (empty) { + setText(null); + setGraphic(null); + } else { + setText(item.getDisplayName()); + if (item.getItemType().equals(TreeModel.ITEM_TYPE.EXPERIMENT)) { + Node experimentIcon = new ImageView(new Image(HomeController.class + .getResourceAsStream("/images/file.png"))); + setGraphic(experimentIcon); + } else { + Node projectIcon = new ImageView(new Image(HomeController.class + .getResourceAsStream("/images/folder.png"))); + setGraphic(projectIcon); + } + } + } + }; + cell.setOnMouseClicked(event -> { + if (!cell.isEmpty() && cell.isSelected()) { + TreeItem treeItem = cell.getTreeItem(); + TreeModel treeModel = treeItem.getValue(); + Map filters = new HashMap<>(); + if (treeModel.getItemType().equals(TreeModel.ITEM_TYPE.PROJECT)) { + filters.put(ExperimentSearchFields.PROJECT_ID, treeModel.getItemId()); + tabbedPane.getTabs().get(0).setText(treeModel.getDisplayName()); + try { + updateExperimentList(filters, -1, 0); + } catch (TException e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", tabbedPane.getScene().getWindow(), + "Failed to update experiment list !"); + } + } else if (treeModel.getItemType().equals(TreeModel.ITEM_TYPE.RECENT_EXPERIMENTS)) { + tabbedPane.getTabs().get(0).setText(treeModel.getDisplayName()); + try { + updateExperimentList(filters, SEAGridContext.getInstance().getMaxRecentExpCount(), 0); + } catch (TException e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", tabbedPane.getScene().getWindow(), + "Failed to update experiment list !"); + } + } else if (event.getClickCount() == 2 && treeModel.getItemType().equals(TreeModel.ITEM_TYPE.EXPERIMENT)) { + try { + ExperimentSummaryWindow experimentSummaryWindow = new ExperimentSummaryWindow(); + Parent parentNode = experimentSummaryWindow.getExperimentInfoNode(treeModel.getItemId()); + Tab experimentTab = new Tab(treeModel.getDisplayName(), parentNode); + experimentTab.setClosable(true); + tabbedPane.getTabs().add(experimentTab); + tabbedPane.getSelectionModel().select(experimentTab); + } catch (Exception e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", tabbedPane.getScene().getWindow(), + "Cannot open experiment information"); + } + } + } + }); + return cell; + }); + + TreeItem root = createProjectTreeModel(); + root.setExpanded(true); + projectsTreeView.setRoot(root); + projectsTreeView.setShowRoot(false); + } + + //init the right pane with experiment list + public void initExperimentList() throws TException { + expSummaryTable.setEditable(true); + + expSummaryTable.setRowFactory(tv -> { + TableRow row = new TableRow<>(); + row.setOnMouseClicked(event -> { + if (event.getClickCount() == 2 && (!row.isEmpty())) { + ExperimentListModel rowData = row.getItem(); + try { + ExperimentSummaryWindow experimentSummaryWindow = new ExperimentSummaryWindow(); + Parent parentNode = experimentSummaryWindow.getExperimentInfoNode(rowData.getId()); + Tab experimentTab = new Tab(rowData.getName(), parentNode); + experimentTab.setClosable(true); + tabbedPane.getTabs().add(experimentTab); + tabbedPane.getSelectionModel().select(experimentTab); + } catch (Exception e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", tabbedPane.getScene().getWindow(), + "Cannot open experiment information"); + } + } + }); + return row; + }); + + expCheckedColumn.setCellValueFactory(new PropertyValueFactory<>("checked")); + expCheckedColumn.setCellFactory(CheckBoxTableCell.forTableColumn(expCheckedColumn)); + expCheckedColumn.setEditable(true); + expNameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty()); + ownerNameColumn.setCellValueFactory(cellData -> cellData.getValue().ownerNameProperty()); + expApplicationColumn.setCellValueFactory(cellData -> cellData.getValue().applicationProperty()); + expHostColumn.setCellValueFactory(cellData -> cellData.getValue().hostProperty()); + expStatusColumn.setCellValueFactory(cellData -> cellData.getValue().statusProperty()); + expStatusColumn.setCellFactory(new Callback, + TableCell>() { + @Override + public TableCell call(TableColumn param) { + return new TableCell() { + @Override + public void updateItem(String item, boolean empty) { + super.updateItem(item, empty); + setText(item); + if (!empty) { + if (item.equals(ExperimentState.COMPLETED.toString())) { + this.setTextFill(Color.GREEN); + } else if (item.equals(ExperimentState.FAILED.toString())) { + this.setTextFill(Color.RED); + } else if (item.equals(ExperimentState.CREATED.toString())) { + this.setTextFill(Color.BLUE); + } else { + this.setTextFill(Color.ORANGE); + } + } + } + }; + } + }); + expCreateTimeColumn.setCellValueFactory(cellData -> cellData.getValue().createdTimeProperty()); + + Map filters = new HashMap<>(); + tabbedPane.setTabClosingPolicy(TabPane.TabClosingPolicy.SELECTED_TAB); + tabbedPane.getTabs().get(0).setText("Recent Experiments"); + tabbedPane.getTabs().get(0).setClosable(false); + updateExperimentList(filters, SEAGridContext.getInstance().getMaxRecentExpCount(), 0); + + createContextMenuForExperimentSummaryTable(); + + if (expSummaryTable.getItems().size() > 0) { + expSummaryTable.setContextMenu(contextMenu); + } else { + expSummaryTable.setContextMenu(null); + } + } + + private void createContextMenuForExperimentSummaryTable() { + ContextMenu cm = new ContextMenu(); + MenuItem mi1 = new MenuItem("launch"); + mi1.setOnAction(event -> { + try { + ExperimentListModel experimentListModel = expSummaryTable.getSelectionModel().getSelectedItem(); + if (experimentListModel != null) { + AiravataManager.getInstance().launchExperiment(experimentListModel.getId()); + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType + .EXPERIMENT_LAUNCHED, experimentListModel)); + } + } catch (TException e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", expSummaryTable.getScene() + .getWindow(), "Experiment launch failed"); + } + }); + cm.getItems().add(mi1); + + MenuItem mi2 = new MenuItem("cancel"); + mi2.setOnAction(event -> { + try { + ExperimentListModel experimentListModel = expSummaryTable.getSelectionModel().getSelectedItem(); + if (experimentListModel != null) { + AiravataManager.getInstance().cancelExperiment(experimentListModel.getId()); + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType + .EXPERIMENT_CANCELLED, experimentListModel)); + } + } catch (TException e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", expSummaryTable.getScene() + .getWindow(), "Experiment cancel failed"); + } + }); + cm.getItems().add(mi2); + + MenuItem mi3 = new MenuItem("edit"); + mi3.setOnAction(event -> { + try { + ExperimentListModel experimentListModel = expSummaryTable.getSelectionModel().getSelectedItem(); + if (experimentListModel != null) { + ExperimentModel experimentModel = AiravataManager.getInstance().getExperiment(experimentListModel.getId()); + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType + .EXPERIMENT_EDIT_REQUEST, experimentModel)); + } + } catch (TException e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", expSummaryTable.getScene() + .getWindow(), "Experiment edit failed"); + } + }); + cm.getItems().add(mi3); + + MenuItem mi4 = new MenuItem("open in new tab"); + mi4.setOnAction(event -> { + try { + ExperimentListModel experimentListModel = expSummaryTable.getSelectionModel().getSelectedItem(); + if (experimentListModel != null) { + ExperimentSummaryWindow experimentSummaryWindow = new ExperimentSummaryWindow(); + Parent parentNode = experimentSummaryWindow.getExperimentInfoNode(experimentListModel.getId()); + Tab experimentTab = new Tab(experimentListModel.getName(), parentNode); + experimentTab.setId(experimentListModel.getId()); + experimentTab.setClosable(true); + tabbedPane.getTabs().add(experimentTab); + tabbedPane.getSelectionModel().select(experimentTab); + } + } catch (Exception e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", tabbedPane.getScene().getWindow(), + "Cannot open experiment information"); + } + }); + cm.getItems().add(mi4); + MenuItem mi5 = new MenuItem("open in new window"); + mi5.setOnAction(event -> { + try { + ExperimentListModel experimentListModel = expSummaryTable.getSelectionModel().getSelectedItem(); + if (experimentListModel != null) { + ExperimentSummaryWindow experimentSummaryWindow = new ExperimentSummaryWindow(); + experimentSummaryWindow.showExperimentSummaryWindow(experimentListModel.getId()); + } + } catch (Exception e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", tabbedPane.getScene().getWindow(), + "Cannot open experiment information"); + } + }); + cm.getItems().add(mi5); + MenuItem mi6 = new MenuItem("delete"); + mi6.setOnAction(event -> { + try { + ExperimentListModel experimentListModel = expSummaryTable.getSelectionModel().getSelectedItem(); + if (experimentListModel != null) { + if(SEAGridDialogHelper.showConfirmDialog("Confirmation Dialog", "Confirm your action", + "Are sure you want to delete the experiment?")){ + AiravataManager.getInstance().deleteExperiment(experimentListModel.getId()); + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType + .EXPERIMENT_DELETED, experimentListModel)); + } + } + } catch (TException e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", expSummaryTable.getScene() + .getWindow(), "Experiment delete failed"); + } + }); + cm.getItems().add(mi6); + + this.contextMenu = cm; + + expSummaryTable.setOnMouseClicked(event -> { + if (event.getButton() == MouseButton.SECONDARY) { + ExperimentListModel experimentListModel = expSummaryTable.getSelectionModel().getSelectedItem(); + if (experimentListModel != null) { + mi1.setDisable(true); + mi2.setDisable(true); + mi3.setDisable(true); + mi4.setDisable(false); + mi5.setDisable(false); + mi6.setDisable(true); + if (experimentListModel.getStatus().equals(ExperimentState.CREATED.toString())) { + mi1.setDisable(false); + mi3.setDisable(false); + mi6.setDisable(false); + } else if (experimentListModel.getStatus().equals(ExperimentState.EXECUTING.toString())) { + mi2.setDisable(false); + } + } + } + }); + } + + //update the right pane with experiment list + public void updateExperimentList(Map filters, int limit, int offset) throws TException { + + this.previousExperimentListFilter = filters; + + List experimentSummaryModelList = AiravataManager.getInstance() + .getExperimentSummaries(filters, limit, offset); + observableExperimentList = FXCollections.observableArrayList(new Callback() { + @Override + public Observable[] call(ExperimentListModel param) { + return new Observable[]{param.statusProperty()}; + } + }); + for (ExperimentSummaryModel expModel : experimentSummaryModelList) { + ExperimentListModel expFXModel = new ExperimentListModel(expModel); + observableExperimentList.add(expFXModel); + } + //Set the filter Predicate whenever the filter changes. + FilteredList filteredExpSummaryData = new FilteredList<>(observableExperimentList, p -> true); + filterField.textProperty().addListener((observable, oldValue, newValue) -> { + filteredExpSummaryData.setPredicate(experiment -> { + // If filter text is empty, display all persons. + if (newValue == null || newValue.isEmpty()) { + return true; + } + + // Compare first name and last name of every person with filter text. + String lowerCaseFilter = newValue.toLowerCase(); + + if (experiment.getName().toLowerCase().contains(lowerCaseFilter)) { + return true; // Filter matches first name. + } else if (experiment.getApplication().toLowerCase().contains(lowerCaseFilter)) { + return true; // Filter matches last name. + } else if (experiment.getHost().toLowerCase().contains(lowerCaseFilter)) { + return true; // Filter matches last name. + } else if (experiment.getStatus().toLowerCase().contains(lowerCaseFilter)) { + return true; // Filter matches last name. + } + return false; // Does not match. + }); + }); + SortedList sortedExperimentListData = new SortedList<>(filteredExpSummaryData); + sortedExperimentListData.comparatorProperty().bind(expSummaryTable.comparatorProperty()); + expSummaryTable.setItems(filteredExpSummaryData); + + filterField.setText(""); + tabbedPane.getSelectionModel().select(0); + + + if (expSummaryTable.getItems().size() > 0) { + expSummaryTable.setContextMenu(contextMenu); + } else { + expSummaryTable.setContextMenu(null); + } + } + + //Creates the project tree model + private TreeItem createProjectTreeModel() { + + TreeItem root = new TreeItem(); + TreeItem recentExps = new ProjectTreeModel( + new TreeModel(TreeModel.ITEM_TYPE.RECENT_EXPERIMENTS, "no-id", "Recent Experiments")); + root.getChildren().add(recentExps); + + TreeItem projectRoot = new TreeItem( + new TreeModel(TreeModel.ITEM_TYPE.PROJECT_ROOT_NODE, "no-id", "Projects")) { + { + SEAGridEventBus.getInstance().register(this); + } + + private boolean isFirstTimeChildren = true; + + @SuppressWarnings("unused") + @Subscribe + public void handleNewProjectEvent(SEAGridEvent event) { + if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.PROJECT_CREATED)) { + if (!isFirstTimeChildren) { + Project project = (Project) event.getPayload(); + getChildren().add(0, new ProjectTreeModel(new TreeModel(TreeModel.ITEM_TYPE.PROJECT, + project.getProjectID(), project.getName()))); + } + } + } + + @Override + public boolean isLeaf() { + return false; + } + + @Override + public ObservableList> getChildren() { + if (isFirstTimeChildren) { + isFirstTimeChildren = false; + ObservableList> projChildern = FXCollections.observableArrayList(); + List projects; + try { + projects = AiravataManager.getInstance().getProjects(); + projChildern.addAll(projects.stream().map(project -> new ProjectTreeModel( + new TreeModel( + TreeModel.ITEM_TYPE.PROJECT, project.getProjectID(), + project.getName() + ))).collect(Collectors.toList())); + } catch (Exception e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", projectsTreeView.getScene().getWindow(), + "Failed loading project list !"); + } + super.getChildren().setAll(projChildern); + } + return super.getChildren(); + } + }; + root.getChildren().add(projectRoot); + + return root; + } + + + private void initTokenUpdateDaemon() { + Timeline oauthTokenUpdateTimer = new Timeline(new KeyFrame( + //It seems the OAuthTokenExpiration time is in GMT + Duration.millis(60*60*1000), + ae -> { + try { + String url; + if(SEAGridConfig.DEV){ + url = "https://dev.seagrid.org/refreshed-token-desktop?refresh_code=" + + SEAGridContext.getInstance().getRefreshToken(); + }else{ + url = "https://seagrid.org/refreshed-token-desktop?refresh_code=" + + SEAGridContext.getInstance().getRefreshToken(); + } + String json = readUrl(url); + Gson gson = new Gson(); + Type type = new TypeToken>(){}.getType(); + Map params = gson.fromJson(json, type); + + if(!params.get("status").equals("ok")){ + throw new Exception("Token refresh failed."); + }else{ + SEAGridContext.getInstance().setOAuthToken(params.get("code")); + SEAGridContext.getInstance().setRefreshToken(params.get("refresh_code")); + SEAGridContext.getInstance().setTokenExpiaryTime(Integer.parseInt(params.get("valid_time").trim())); + } + } catch (Throwable e) { + e.printStackTrace(); + //Initiating a logout + SEAGridDialogHelper.showInformationDialog("Session Timed Out...", "Session Timed Out...", + "Your session has timed out. Please re-login to continue work.", null); + ((Stage) logoutBtn.getScene().getWindow()).close(); + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.LOGOUT, null)); + } + })); + oauthTokenUpdateTimer.setCycleCount(Timeline.INDEFINITE); + oauthTokenUpdateTimer.play(); + } + + + @SuppressWarnings("unused") + @Subscribe + public void listenSEAGridEvents(SEAGridEvent event) throws TException { + if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.PROJECT_CREATED)) { + Project project = (Project) event.getPayload(); + SEAGridDialogHelper.showInformationNotification("Success", "Project " + + project.getName() + " created successfully", createProjectButton.getScene().getWindow()); + } else if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.FILE_DOWNLOADED)) { + String localFilePath = (String) event.getPayload(); + SEAGridDialogHelper.showInformationNotification("Success", Paths.get(localFilePath).getFileName() + + " was downloaded successfully", createProjectButton.getScene().getWindow()); + //Opening the file in system proffered editor + try { + Desktop.getDesktop().open(new File(localFilePath)); + } catch (IOException e) { + logger.error("Cannot open file. Opening parent directory"); + try { + Desktop.getDesktop().open(new File(localFilePath).getParentFile()); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + } else if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.FILE_UPLOADED)) { + String localFilePath = (String) event.getPayload(); + SEAGridDialogHelper.showInformationNotification("Success", Paths.get(localFilePath).getFileName() + + " was uploaded successfully", createProjectButton.getScene().getWindow()); + } else if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.EXPERIMENT_CREATED)) { + ExperimentModel experiment = (ExperimentModel) event.getPayload(); + SEAGridDialogHelper.showInformationNotification("Success", "Experiment " + + experiment.getExperimentName() + " created successfully", createProjectButton.getScene().getWindow()); + ExperimentListModel experimentListModel = assembleExperimentListModel(experiment); + if (this.previousExperimentListFilter == null || + this.previousExperimentListFilter.get(ExperimentSearchFields.PROJECT_ID) == null || + this.previousExperimentListFilter.get(ExperimentSearchFields.PROJECT_ID).equals( + SEAGridContext.getInstance().getRecentExperimentsDummyId()) || + this.previousExperimentListFilter.get(ExperimentSearchFields.PROJECT_ID).equals(experiment.getProjectId())) { + observableExperimentList.add(0, experimentListModel); + } + if (expSummaryTable.getContextMenu() == null) { + expSummaryTable.setContextMenu(contextMenu); + } + } else if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.EXPERIMENT_LAUNCHED)) { + if (event.getPayload() instanceof ExperimentModel) { // This is coming from create and launch experiment + ExperimentModel experimentModel = (ExperimentModel) event.getPayload(); + SEAGridDialogHelper.showInformationNotification("Success", "Launched experiment " + experimentModel.getExperimentName(), + createProjectButton.getScene().getWindow()); + } else if (event.getPayload() instanceof ExperimentListModel) { // This is coming from experiment list in home + ExperimentListModel experimentListModel = (ExperimentListModel) event.getPayload(); + SEAGridDialogHelper.showInformationNotification("Success", "Launched experiment " + experimentListModel.getName(), + createProjectButton.getScene().getWindow()); + } + } else if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.EXPERIMENT_DELETED)) { + if (event.getPayload() instanceof ExperimentListModel) { + ExperimentListModel experimentListModel = (ExperimentListModel) event.getPayload(); + ExperimentListModel matchingModel = null; + for (ExperimentListModel temp : observableExperimentList) { + if (temp.getId().equals(experimentListModel.getId())) { + matchingModel = temp; + break; + } + } + if (matchingModel != null) { + observableExperimentList.remove(matchingModel); + } + if (expSummaryTable.getItems().size() == 0) { + expSummaryTable.setContextMenu(null); + } + SEAGridDialogHelper.showInformationNotification("Success", "Deleted experiment " + + experimentListModel.getName(), createProjectButton.getScene().getWindow()); + } + } else if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.EXPERIMENT_CANCELLED)) { + if (event.getPayload() instanceof ExperimentModel) { // This is coming from experiment summary + ExperimentModel experimentModel = (ExperimentModel) event.getPayload(); + SEAGridDialogHelper.showInformationNotification("Success", "Cancelled experiment " + + experimentModel.getExperimentName(), + createProjectButton.getScene().getWindow()); + } else if (event.getPayload() instanceof ExperimentListModel) { // This is coming from browse experiment + ExperimentListModel experimentListModel = (ExperimentListModel) event.getPayload(); + SEAGridDialogHelper.showInformationNotification("Success", "Cancelled experiment " + + experimentListModel.getName(), + createProjectButton.getScene().getWindow()); + } + } else if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.EXPERIMENT_EDIT_REQUEST)) { + if (event.getPayload() instanceof ExperimentModel) { // This is coming from experiment summary + ExperimentModel experimentModel = (ExperimentModel) event.getPayload(); + try { + ExperimentCreateWindow.displayEditExperiment(experimentModel); + } catch (Exception e) { + SEAGridDialogHelper.showExceptionDialog(e, "Exception Dialog", expSummaryTable.getScene().getWindow(), + "Failed to launch edit experiment dialog"); + } + } + } else if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.EXPERIMENT_UPDATED)) { + if (event.getPayload() instanceof ExperimentModel) { // This is coming from experiment edit + ExperimentModel experimentModel = (ExperimentModel) event.getPayload(); + SEAGridDialogHelper.showInformationNotification("Success", "Updated experiment " + + experimentModel.getExperimentName(), expSummaryTable.getScene().getWindow()); + tabbedPane.getTabs().stream().forEach(t->{ + String tabId = t.getId(); + if(experimentModel.getExperimentId().equals(tabId)){ + t.setText(experimentModel.getExperimentName()); + } + }); + } + } else if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.EXPERIMENT_CLONED)) { + if (event.getPayload() instanceof ExperimentModel) { // This is coming from experiment edit + ExperimentModel experimentModel = (ExperimentModel) event.getPayload(); + SEAGridDialogHelper.showInformationNotification("Success", "Cloned experiment " + + experimentModel.getExperimentName(), createProjectButton.getScene().getWindow()); + ExperimentListModel experimentListModel = assembleExperimentListModel(experimentModel); + if (this.previousExperimentListFilter == null || + this.previousExperimentListFilter.get(ExperimentSearchFields.PROJECT_ID) == null || + this.previousExperimentListFilter.get(ExperimentSearchFields.PROJECT_ID).equals( + SEAGridContext.getInstance().getRecentExperimentsDummyId()) || + this.previousExperimentListFilter.get(ExperimentSearchFields.PROJECT_ID).equals(experimentModel.getProjectId())) { + observableExperimentList.add(0, experimentListModel); + } + try { + ExperimentSummaryWindow experimentSummaryWindow = new ExperimentSummaryWindow(); + Parent parentNode = experimentSummaryWindow.getExperimentInfoNode(experimentListModel.getId()); + Tab experimentTab = new Tab(experimentModel.getExperimentName(), parentNode); + experimentTab.setId(experimentModel.getExperimentId()); + experimentTab.setClosable(true); + tabbedPane.getTabs().add(experimentTab); + tabbedPane.getSelectionModel().select(experimentTab); + + ExperimentCreateWindow.displayEditExperiment(experimentModel); + } catch (Exception e) { + SEAGridDialogHelper.showExceptionDialog(e, "Exception Dialog", expSummaryTable.getScene().getWindow(), + "Failed to launch edit experiment dialog"); + } + } + } else if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.EXPORT_GAUSSIAN_EXP)) { + if (event.getPayload() instanceof String) { + String gaussianInput = (String) event.getPayload(); + try { + ExperimentCreateWindow.displayCreateGaussianExp(gaussianInput); + } catch (Exception e) { + SEAGridDialogHelper.showExceptionDialog(e, "Exception Dialog", expSummaryTable.getScene().getWindow(), + "Failed to launch gaussian experiment dialog"); + } + } + } else if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.EXPORT_GAMESS_EXP)) { + if (event.getPayload() instanceof String) { + String gamessInput = (String) event.getPayload(); + try { + ExperimentCreateWindow.displayCreateGamessExp(gamessInput); + } catch (Exception e) { + SEAGridDialogHelper.showExceptionDialog(e, "Exception Dialog", expSummaryTable.getScene().getWindow(), + "Failed to launch gamess experiment dialog"); + } + } + } else if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.EXPORT_NWCHEM_EXP)) { + if (event.getPayload() instanceof String) { + String nwchemInput = (String) event.getPayload(); + try { + ExperimentCreateWindow.displayCreateNwchemExp( nwchemInput ); + } catch (Exception e) { + SEAGridDialogHelper.showExceptionDialog( e, "Exception Dialog", expSummaryTable.getScene().getWindow(), + "Failed to launch nwchem experiment dialog" ); + } + } + } else if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.EXPORT_PSI4_EXP)) { + if (event.getPayload() instanceof String) { + String psi4Input = (String) event.getPayload(); + String processors = "$SLURM_NPROCS"; + try { + ExperimentCreateWindow.displayCreatePsi4Exp(processors, psi4Input); + } catch (Exception e) { + SEAGridDialogHelper.showExceptionDialog(e, "Exception Dialog", expSummaryTable.getScene().getWindow(), + "Failed to launch PSI4 experiment dialog"); + } + } + } else if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.EXPORT_MOLCAS_EXP)) { + if (event.getPayload() instanceof String) { + String molcasInput = (String) event.getPayload(); + String processors = "$SLURM_NPROCS"; + try { + ExperimentCreateWindow.displayCreateMolcasExp(processors, molcasInput); + } catch (Exception e) { + SEAGridDialogHelper.showExceptionDialog(e, "Exception Dialog", expSummaryTable.getScene().getWindow(), + "Failed to launch Molcas experiment dialog"); + } + } + } + + } + + private String readUrl(String urlString) throws Exception { + BufferedReader reader = null; + try { + URL url = new URL(urlString); + reader = new BufferedReader(new InputStreamReader(url.openStream())); + StringBuffer buffer = new StringBuffer(); + int read; + char[] chars = new char[1024]; + while ((read = reader.read(chars)) != -1) + buffer.append(chars, 0, read); + + return buffer.toString(); + } finally { + if (reader != null) + reader.close(); + } + } + + private ExperimentListModel assembleExperimentListModel(ExperimentModel experiment) throws TException { + ExperimentSummaryModel experimentSummaryModel = new ExperimentSummaryModel(); + experimentSummaryModel.setExperimentId(experiment.getExperimentId()); + experimentSummaryModel.setName(experiment.getExperimentName()); + experimentSummaryModel.setExecutionId(experiment.getExecutionId()); + experimentSummaryModel.setResourceHostId(experiment.getUserConfigurationData() + .getComputationalResourceScheduling().getResourceHostId()); + experimentSummaryModel.setProjectId(experiment.getProjectId()); + experimentSummaryModel.setGatewayId(experiment.getGatewayId()); + experimentSummaryModel.setUserName(experiment.getUserName()); + experimentSummaryModel.setDescription(experiment.getDescription()); + experimentSummaryModel.setExperimentStatus(experiment.getExperimentStatus().get(0).getState().toString()); + long time = System.currentTimeMillis(); + experimentSummaryModel.setCreationTime(time); + experimentSummaryModel.setStatusUpdateTime(time); + return new ExperimentListModel(experimentSummaryModel); + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/ui/home/model/ExperimentListModel.java b/src/main/java/org/seagrid/desktop/ui/home/model/ExperimentListModel.java new file mode 100644 index 0000000..246b927 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/ui/home/model/ExperimentListModel.java @@ -0,0 +1,296 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.ui.home.model; + +import com.google.common.eventbus.Subscribe; +import javafx.animation.KeyFrame; +import javafx.animation.Timeline; +import javafx.application.Platform; +import javafx.beans.property.*; +import javafx.util.Duration; +import org.apache.airavata.model.appcatalog.appinterface.ApplicationInterfaceDescription; +import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription; +import org.apache.airavata.model.error.AiravataClientException; +import org.apache.airavata.model.experiment.ExperimentModel; +import org.apache.airavata.model.experiment.ExperimentSummaryModel; +import org.apache.thrift.TException; +import org.seagrid.desktop.connectors.airavata.AiravataManager; +import org.seagrid.desktop.ui.commons.SEAGridDialogHelper; +import org.seagrid.desktop.util.SEAGridContext; +import org.seagrid.desktop.util.messaging.SEAGridEvent; +import org.seagrid.desktop.util.messaging.SEAGridEventBus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.time.LocalDateTime; + +public class ExperimentListModel { + private final static Logger logger = LoggerFactory.getLogger(ExperimentListModel.class); + private static final double EXPERIMENT_LIST_UPDATE_INTERVAL = 10000; + + private StringProperty id; + private StringProperty projectId; + private BooleanProperty checked; + private StringProperty name; + private StringProperty ownerName; + private StringProperty application; + private StringProperty host; + private StringProperty status; + private ObjectProperty createdTime; + + private Timeline expStatusUpdateTimer = null; + + public ExperimentListModel(StringProperty id, StringProperty projectId, BooleanProperty checked, StringProperty name, StringProperty ownerName, + StringProperty application, StringProperty host, + StringProperty status, ObjectProperty createdTime) { + this.id = id; + this.projectId = projectId; + this.checked = checked; + this.name = name; + this.ownerName = ownerName; + this.application = application; + this.host = host; + this.status = status; + this.createdTime = createdTime; + } + + public ExperimentListModel(){ + this.checked = new SimpleBooleanProperty(false); + this.id = new SimpleStringProperty("test-id"); + this.projectId = new SimpleStringProperty("test-proj-id"); + this.name = new SimpleStringProperty("test-name"); + this.ownerName = new SimpleStringProperty("owner-name"); + this.application = new SimpleStringProperty("test-application"); + this.host = new SimpleStringProperty("test-host"); + this.status = new SimpleStringProperty("test-status"); + this.createdTime = new SimpleObjectProperty<>(LocalDateTime.now()); + } + + public ExperimentListModel(ExperimentSummaryModel experimentSummaryModel) throws TException { + this.id = new SimpleStringProperty(experimentSummaryModel.getExperimentId()); + this.projectId = new SimpleStringProperty(experimentSummaryModel.getProjectId()); + this.checked = new SimpleBooleanProperty(); + this.name = new SimpleStringProperty(experimentSummaryModel.getName()); + this.ownerName = new SimpleStringProperty(experimentSummaryModel.getUserName()); + if(experimentSummaryModel.getResourceHostId()!=null){ + ComputeResourceDescription resourceDescription = null; + try { + resourceDescription = AiravataManager.getInstance().getComputeResource(experimentSummaryModel.getResourceHostId()); + if(resourceDescription != null){ + this.host = new SimpleStringProperty(resourceDescription.getHostName()); + } + } catch (AiravataClientException e) { + e.printStackTrace(); + } + } + if(experimentSummaryModel.getExecutionId()!=null){ + ApplicationInterfaceDescription interfaceDescription = null; + try { + interfaceDescription = AiravataManager.getInstance().getApplicationInterface(experimentSummaryModel.getExecutionId()); + if(interfaceDescription != null){ + this.application = new SimpleStringProperty(interfaceDescription.getApplicationName()); + } + } catch (Exception e) { + logger.error("Failed to load application interface for id: "+ experimentSummaryModel.getExecutionId()); + } + } + this.status = new SimpleStringProperty(experimentSummaryModel.getExperimentStatus()); + this.createdTime = new SimpleObjectProperty<>(LocalDateTime.ofEpochSecond(experimentSummaryModel + .getCreationTime() / 1000, 0, SEAGridContext.getInstance().getTimeZoneOffset())); + + //TODO this should replace with a RabbitMQ Listener + if(!(status.equals("FAILED") || getStatus().equals("COMPLETED") || getStatus().equals("CANCELLED"))) { + expStatusUpdateTimer = new Timeline(new KeyFrame( + Duration.millis(EXPERIMENT_LIST_UPDATE_INTERVAL), + ae -> updateExperimentStatuses())); + expStatusUpdateTimer.setCycleCount(Timeline.INDEFINITE); + expStatusUpdateTimer.play(); + } + + SEAGridEventBus.getInstance().register(this); + } + + public String getId() { + return id.get(); + } + + public StringProperty idProperty() { + return id; + } + + public void setId(String id) { + this.id.set(id); + } + + public String getProjectId() { + return projectId.get(); + } + + public StringProperty projectIdProperty() { + return projectId; + } + + public void setProjectId(String projectId) { + this.projectId.set(projectId); + } + + public boolean getChecked() { + return checked.get(); + } + + public BooleanProperty checkedProperty() { + return checked; + } + + public void setChecked(boolean checked) { + this.checked.set(checked); + } + + public String getName() { + return name.get(); + } + + public StringProperty nameProperty() { + return name; + } + + public void setName(String name) { + this.name.set(name); + } + + public String getOwnerName() { + return ownerName.get(); + } + + public StringProperty ownerNameProperty() { + return ownerName; + } + + public void setOwnerName(String ownerName) { + this.ownerName.set(ownerName); + } + + public String getApplication() { + return application.get(); + } + + public StringProperty applicationProperty() { + return application; + } + + public void setApplication(String application) { + this.application.set(application); + } + + public String getHost() { + return host.get(); + } + + public StringProperty hostProperty() { + return host; + } + + public void setHost(String host) { + this.host.set(host); + } + + public String getStatus() { + return status.get(); + } + + public StringProperty statusProperty() { + return status; + } + + public void setStatus(String status) { + this.status.set(status); + } + + public LocalDateTime getCreatedTime() { + return createdTime.get(); + } + + public ObjectProperty createdTimeProperty() { + return createdTime; + } + + public void setCreatedTime(LocalDateTime createdTime) { + this.createdTime.set(createdTime); + } + + @SuppressWarnings("unused") + @Subscribe + public void listenSEAGridEvents(SEAGridEvent event){ + if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.EXPERIMENT_DELETED)) { + if(event.getPayload() instanceof ExperimentListModel){ + ExperimentListModel experimentListModel = (ExperimentListModel) event.getPayload(); + if(getId().equals(experimentListModel.getId())){ + this.expStatusUpdateTimer.stop(); + } + }else if(event.getPayload() instanceof ExperimentModel){ + ExperimentModel deletedExpModel = (ExperimentModel) event.getPayload(); + if(getId().equals(deletedExpModel.getExperimentId())){ + this.expStatusUpdateTimer.stop(); + } + } + }else if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.EXPERIMENT_UPDATED)) { + if(event.getPayload() instanceof ExperimentModel){ + ExperimentModel updatedExperimentModel = (ExperimentModel) event.getPayload(); + if(getId().equals(updatedExperimentModel.getExperimentId())){ + try{ + this.setProjectId(updatedExperimentModel.getProjectId()); + this.setName(updatedExperimentModel.getExperimentName()); + ComputeResourceDescription host = AiravataManager.getInstance() + .getComputeResource(updatedExperimentModel.getUserConfigurationData() + .getComputationalResourceScheduling().getResourceHostId()); + this.setHost(host.getHostName()); + }catch (Exception e){ + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialog(e,"Exception Dialog", null, "Failed updating experiment" + + " information in ExperimentListModel"); + } + } + } + } + } + + //updates the experiment status in the background + private void updateExperimentStatuses(){ + if(!(status.equals("FAILED") || getStatus().equals("COMPLETED") || getStatus().equals("CANCELLED"))) { + Platform.runLater(() -> { + String experimentId = id.getValue(); + try { + ExperimentModel experimentModel = AiravataManager.getInstance().getExperiment(experimentId); + if(experimentModel.getExperimentStatus() != null) { + this.setStatus(experimentModel.getExperimentStatus().get(0).getState().toString()); + } + logger.debug("Updated Experiment Status for :" + experimentId); + } catch (Exception e) { + e.printStackTrace(); + if(this.expStatusUpdateTimer != null) + expStatusUpdateTimer.stop(); + } + }); + }else{ + expStatusUpdateTimer.stop(); + } + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/ui/home/model/ProjectTreeModel.java b/src/main/java/org/seagrid/desktop/ui/home/model/ProjectTreeModel.java new file mode 100644 index 0000000..a03af44 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/ui/home/model/ProjectTreeModel.java @@ -0,0 +1,115 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.ui.home.model; + +import com.google.common.eventbus.Subscribe; +import javafx.collections.FXCollections; +import javafx.collections.ObservableList; +import javafx.scene.control.TreeItem; +import org.apache.airavata.model.error.AiravataClientException; +import org.apache.airavata.model.experiment.ExperimentModel; +import org.apache.airavata.model.experiment.ExperimentSummaryModel; +import org.apache.thrift.TException; +import org.seagrid.desktop.connectors.airavata.AiravataManager; +import org.seagrid.desktop.ui.commons.SEAGridDialogHelper; +import org.seagrid.desktop.util.SEAGridContext; +import org.seagrid.desktop.util.messaging.SEAGridEvent; +import org.seagrid.desktop.util.messaging.SEAGridEventBus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class ProjectTreeModel extends TreeItem { + private final static Logger logger = LoggerFactory.getLogger(ProjectTreeModel.class); + + private boolean isFirstTimeChildren = true; + + public ProjectTreeModel(TreeModel treeModel) { + super(treeModel); + SEAGridEventBus.getInstance().register(this); + } + + @SuppressWarnings("unused") + @Subscribe + public void handleSEAGridEvents(SEAGridEvent event) { + if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.EXPERIMENT_CREATED)) { + ExperimentModel experiment = (ExperimentModel) event.getPayload(); + if (!isFirstTimeChildren && (((getValue().getItemType().equals(TreeModel.ITEM_TYPE.PROJECT)) + && getValue().getItemId().equals(experiment.getProjectId())) || (getValue().getItemType() + .equals(TreeModel.ITEM_TYPE.RECENT_EXPERIMENTS)))) { + getChildren().add(0, new TreeItem<>(new TreeModel(TreeModel.ITEM_TYPE.EXPERIMENT, experiment.getExperimentId(), + experiment.getExperimentName()))); + } + } else if (event.getEventType().equals(SEAGridEvent.SEAGridEventType.EXPERIMENT_DELETED)) { + if (event.getPayload() instanceof ExperimentListModel) { + ExperimentListModel experimentListModel = (ExperimentListModel) event.getPayload(); + if (!isFirstTimeChildren && (((getValue().getItemType().equals(TreeModel.ITEM_TYPE.PROJECT)) + && getValue().getItemId().equals(experimentListModel.getProjectId())) || (getValue().getItemType() + .equals(TreeModel.ITEM_TYPE.RECENT_EXPERIMENTS)))) { + TreeItem matchingTreeItem = null; + for (TreeItem temp : getChildren()) { + if (temp.getValue().getItemId().equals(experimentListModel.getId())) { + matchingTreeItem = temp; + break; + } + } + getChildren().remove(matchingTreeItem); + } + } + } + } + + @Override + public boolean isLeaf() { + return false; + } + + @Override + public ObservableList> getChildren() { + if (isFirstTimeChildren) { + isFirstTimeChildren = false; + ObservableList> expChildren = FXCollections.observableArrayList(); + List experiments = new ArrayList<>(); + try { + if (getValue().getItemType().equals(TreeModel.ITEM_TYPE.PROJECT)) { + experiments = AiravataManager.getInstance() + .getExperimentSummariesInProject(this.getValue().getItemId()); + } else if (getValue().getItemType().equals(TreeModel.ITEM_TYPE.RECENT_EXPERIMENTS)) { + experiments = AiravataManager.getInstance().getRecentExperimentSummaries(SEAGridContext + .getInstance().getMaxRecentExpCount()); + } + expChildren.addAll(experiments.stream().map(experimentModel -> new TreeItem( + new TreeModel( + TreeModel.ITEM_TYPE.EXPERIMENT, experimentModel.getExperimentId(), + experimentModel.getName() + )) { + }).collect(Collectors.toList())); + } catch (Exception e) { + e.printStackTrace(); + } + super.getChildren().setAll(expChildren); + } + return super.getChildren(); + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/ui/home/model/TreeModel.java b/src/main/java/org/seagrid/desktop/ui/home/model/TreeModel.java new file mode 100644 index 0000000..80ad171 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/ui/home/model/TreeModel.java @@ -0,0 +1,68 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.ui.home.model; + +import javafx.scene.control.TreeItem; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TreeModel extends TreeItem { + private final static Logger logger = LoggerFactory.getLogger(TreeModel.class); + + public enum ITEM_TYPE { + PROJECT_ROOT_NODE, PROJECT, RECENT_EXPERIMENTS, EXPERIMENT + } + + private ITEM_TYPE itemType; + private String itemId; + private String displayName; + + public TreeModel(ITEM_TYPE itemType, String itemId, String displayName){ + this.itemType = itemType; + this.itemId = itemId; + this.displayName = displayName; + } + + public ITEM_TYPE getItemType() { + return itemType; + } + + public void setItemType(ITEM_TYPE itemType) { + this.itemType = itemType; + } + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/ui/login/.DS_Store b/src/main/java/org/seagrid/desktop/ui/login/.DS_Store new file mode 100644 index 0000000..0221708 Binary files /dev/null and b/src/main/java/org/seagrid/desktop/ui/login/.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/ui/login/._.DS_Store b/src/main/java/org/seagrid/desktop/ui/login/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/org/seagrid/desktop/ui/login/._.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/ui/login/LoginWindow.java b/src/main/java/org/seagrid/desktop/ui/login/LoginWindow.java new file mode 100644 index 0000000..fa50aa5 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/ui/login/LoginWindow.java @@ -0,0 +1,44 @@ +package org.seagrid.desktop.ui.login; + +import javafx.application.Application; +import javafx.application.Platform; +import javafx.fxml.FXMLLoader; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.stage.Stage; + +import java.io.IOException; + +public class LoginWindow extends Application { + + @Override + public void start(Stage primaryStage) throws Exception{ + Parent root = FXMLLoader.load(getClass().getResource("/views/login/login.fxml")); + primaryStage.setTitle("SEAGrid Desktop Client - Login"); + primaryStage.setScene(new Scene(root)); + primaryStage.setResizable(true); + primaryStage.setOnCloseRequest(t -> { + Platform.exit(); + System.exit(0); + }); + primaryStage.show(); + } + + public void displayLoginAndWait() throws IOException { + Stage primaryStage = new Stage(); + Parent root = FXMLLoader.load(getClass().getResource("/views/login/login.fxml")); + primaryStage.setTitle("SEAGrid Desktop Client - Login"); + primaryStage.setScene(new Scene(root)); + primaryStage.setResizable(true); +// primaryStage.setAlwaysOnTop(true); + primaryStage.setOnCloseRequest(t -> { + Platform.exit(); + System.exit(0); + }); + primaryStage.showAndWait(); + } + + public static void main(String[] args) { + launch(args); + } +} diff --git a/src/main/java/org/seagrid/desktop/ui/login/controller/LoginController.java b/src/main/java/org/seagrid/desktop/ui/login/controller/LoginController.java new file mode 100644 index 0000000..03d9233 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/ui/login/controller/LoginController.java @@ -0,0 +1,260 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.ui.login.controller; + +import javafx.animation.Animation; +import javafx.animation.KeyFrame; +import javafx.animation.Timeline; +import javafx.concurrent.Worker; +import javafx.fxml.FXML; +import javafx.scene.Cursor; +import javafx.scene.control.Button; +import javafx.scene.control.Hyperlink; +import javafx.scene.control.Label; +import javafx.scene.paint.Color; +import javafx.scene.web.WebEngine; +import javafx.scene.web.WebView; +import javafx.stage.Stage; +import javafx.util.Duration; +import org.apache.airavata.model.workspace.Notification; +import org.seagrid.desktop.connectors.airavata.AiravataManager; +import org.seagrid.desktop.ui.commons.SEAGridDialogHelper; +import org.seagrid.desktop.util.SEAGridConfig; +import org.seagrid.desktop.util.SEAGridContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.net.ssl.*; +import java.awt.*; +import java.net.URI; +import java.security.cert.X509Certificate; +import java.util.HashMap; +import java.util.Map; + + +public class LoginController { + private final static Logger logger = LoggerFactory.getLogger(LoginController.class); + + @FXML + public Label notificationLabel; + + + @FXML + private Button loginButton; + + @FXML + private Hyperlink dontHaveAccountLink; + + @FXML + private WebView loginWebView; + + //Dummy class used for storing notification list index + private class Index{ + int index; + } + + public void initialize() { + // Create a trust manager that does not validate certificate chains + TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + public void checkClientTrusted(X509Certificate[] certs, String authType) { + } + public void checkServerTrusted(X509Certificate[] certs, String authType) { + } + } + }; + + try{ + // Install the all-trusting trust manager + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + + // Create all-trusting host name verifier + HostnameVerifier allHostsValid = new HostnameVerifier() { + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + + // Install the all-trusting host verifier + HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); + }catch (Exception ex){ + ex.printStackTrace(); + } + + loginButton.setOnMouseClicked(event -> { + handleSEAGridWebLogin(); + }); + + dontHaveAccountLink.setOnAction(event -> { + try { + String url; + if(SEAGridConfig.DEV){ + url = "https://dev.seagrid.org/create"; + }else{ + url = "https://seagrid.org/create"; + } + Desktop.getDesktop().browse(new URI(url)); + } catch (Exception e1) { + e1.printStackTrace(); + } + }); + + String imgtext = ""; + String textinfo1 = "
" + + "
" + + imgtext + " Welcome to SEAGrid !! - Science and Engineering Applications Grid" + + "" + + "
" + + "

You are running the " + + "SEAGrid Desktop Client " + + "Application.

"; + String textinfo2 = "

To use Web Portal and for more information, " + + " visit https://seagrid.org/

"; + String textinfo3 = "

If you do not have SEAGrid account, you may request one on the web portal." + + "

"; + + String textinfo4 = "

Note: This version is in active development and will" + + " be auto-updated automatically.

"; + + loginWebView.getEngine().loadContent(textinfo1 + textinfo2 + textinfo3 + textinfo4); + + //initializing notification messages + notificationLabel.setCursor(Cursor.HAND); + notificationLabel.setStyle("-fx-border-color: white;"); + notificationLabel.setMaxWidth(Double.MAX_VALUE); + try{ + java.util.List messages = AiravataManager.getInstance().getNotifications(); + final Index index = new Index(); + index.index = 0; + if (messages != null && messages.size() > 0) { + notificationLabel.setText(messages.get(index.index).getTitle() + " : " + + messages.get(index.index).getNotificationMessage().split("\r|\n")[0]); + Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0), + event -> { + index.index++; + index.index = index.index % messages.size(); + switch (messages.get(index.index).getPriority()){ + case HIGH: + notificationLabel.setTextFill(Color.web("#ff0000")); + break; + case NORMAL: + notificationLabel.setTextFill(Color.web("#ffa500")); + break; + case LOW: + notificationLabel.setTextFill(Color.web("#808080")); + break; + } + notificationLabel.setText(messages.get(index.index).getTitle() + " : " + + messages.get(index.index).getNotificationMessage().split("\r|\n")[0]); + + notificationLabel.setOnMouseClicked(event1 -> { + SEAGridDialogHelper.showInformationDialog("Notification", messages.get(index.index).getTitle(), + messages.get(index.index).getNotificationMessage(), null); + }); + }), + new KeyFrame(Duration.seconds(5))); + timeline.setCycleCount(Animation.INDEFINITE); + timeline.play(); + } + }catch (Exception ex){ + //cannot connect to Airavata + ex.printStackTrace(); + } + } + + public boolean handleSEAGridWebLogin(){ + final WebEngine webEngine = loginWebView.getEngine(); + final Label location = new Label(); + String url; + if(SEAGridConfig.DEV){ + url = "http://192.168.57.3:8008/login-desktop"; + }else{ + url = "https://seagrid.org/login-desktop"; + } + + + webEngine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> { + if (Worker.State.SUCCEEDED.equals(newValue)) { + String locationUrl = webEngine.getLocation(); + location.setText(locationUrl); + Map params = getQueryMap(locationUrl); + Stage stage = (Stage) loginButton.getScene().getWindow(); + // if(params.containsKey("status")){ + //if(params.get("status").equals("ok")){ + if(params.containsKey("status")){ + if(params.get("status").equals("ok")){ + //login successful + String token = params.get("code"); + String refreshToken = params.get("refresh_code"); + int validTime = Integer.parseInt(params.get("valid_time").trim()); + String userName = params.get("username"); + SEAGridContext.getInstance().setAuthenticated(true); + SEAGridContext.getInstance().setOAuthToken(token); + SEAGridContext.getInstance().setRefreshToken(refreshToken); + SEAGridContext.getInstance().setTokenExpiaryTime(validTime); + SEAGridContext.getInstance().setUserName(userName); + stage.close(); + }else if(params.get("status").equals("less_privileged")){ + //login failed + java.net.CookieHandler.setDefault(new com.sun.webkit.network.CookieManager()); + webEngine.load(url); + loginWebView.setVisible(false); + SEAGridDialogHelper.showInformationDialog("Login Failed", "Unauthorized login", + "You don't have permission to access this client." + + " Please contact the Gateway Admin to get your account authorized by sending an" + + " email to help@seagrid.org.", stage); + loginWebView.setVisible(true); + }else{ + //login failed + java.net.CookieHandler.setDefault(new com.sun.webkit.network.CookieManager()); + webEngine.load(url); + loginWebView.setVisible(false); + SEAGridDialogHelper.showInformationDialog("Login Failed", "Unauthorized login", + "You don't have permission to access this client." + + " Please use a correct user credentials and try again.", stage); + loginWebView.setVisible(true); + } + } + } + }); + webEngine.load(url); + return false; + } + + private Map getQueryMap(String query) + { + Map map = new HashMap<>(); + if(query.contains("?")) { + String[] params = query.split("\\?")[1].split("&"); + for (String param : params) { + String name = param.split("=")[0]; + String value = param.split("=")[1]; + map.put(name, value); + } + } + return map; + } + +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/ui/project/.DS_Store b/src/main/java/org/seagrid/desktop/ui/project/.DS_Store new file mode 100644 index 0000000..25c92ef Binary files /dev/null and b/src/main/java/org/seagrid/desktop/ui/project/.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/ui/project/._.DS_Store b/src/main/java/org/seagrid/desktop/ui/project/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/org/seagrid/desktop/ui/project/._.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/ui/project/ProjectWindow.java b/src/main/java/org/seagrid/desktop/ui/project/ProjectWindow.java new file mode 100644 index 0000000..f43c683 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/ui/project/ProjectWindow.java @@ -0,0 +1,63 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.ui.project; + +import javafx.application.Application; +import javafx.fxml.FXMLLoader; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.stage.Modality; +import javafx.stage.Stage; + +import java.io.IOException; + +public class ProjectWindow extends Application { + + private static Stage primaryStage; + + @Override + public void start(Stage primaryStage) throws Exception{ + Parent root = FXMLLoader.load(getClass().getResource("/views/project/project.fxml")); + primaryStage.setTitle("SEAGrid Desktop Client - Project"); + primaryStage.setScene(new Scene(root, 400, 150)); + primaryStage.setResizable(true); + primaryStage.show(); + } + + public static void displayCreateProject() throws IOException { + if(primaryStage == null || !primaryStage.isShowing()){ + primaryStage = new Stage(); + Parent root = FXMLLoader.load(ProjectWindow.class.getResource("/views/project/project.fxml")); + primaryStage.setTitle("SEAGrid Desktop Client - Create Project"); + primaryStage.setScene(new Scene(root, 400, 150)); + primaryStage.setResizable(true); + primaryStage.initModality(Modality.WINDOW_MODAL); + primaryStage.show(); + } + primaryStage.requestFocus(); + + } + + + public static void main(String[] args) { + launch(args); + } +} diff --git a/src/main/java/org/seagrid/desktop/ui/project/controller/ProjectController.java b/src/main/java/org/seagrid/desktop/ui/project/controller/ProjectController.java new file mode 100644 index 0000000..998d551 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/ui/project/controller/ProjectController.java @@ -0,0 +1,74 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.ui.project.controller; + +import javafx.beans.binding.BooleanBinding; +import javafx.fxml.FXML; +import javafx.scene.control.Button; +import javafx.scene.control.TextArea; +import javafx.scene.control.TextField; +import javafx.stage.Stage; +import org.apache.airavata.model.workspace.Project; +import org.seagrid.desktop.connectors.airavata.AiravataManager; +import org.seagrid.desktop.ui.commons.SEAGridDialogHelper; +import org.seagrid.desktop.util.messaging.SEAGridEvent; +import org.seagrid.desktop.util.messaging.SEAGridEventBus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ProjectController { + private final static Logger logger = LoggerFactory.getLogger(ProjectController.class); + + @FXML + public TextArea projectDescField; + + @FXML + public TextField projectNameField; + + @FXML + private Button saveButton; + + public void initialize() { + BooleanBinding projectNameBind = new BooleanBinding(){ + {super.bind(projectNameField.textProperty());} + + @Override + protected boolean computeValue() { + return (projectNameField.getText().isEmpty()); + } + }; + saveButton.disableProperty().bind(projectNameBind); + + saveButton.setOnMouseClicked(event -> { + try { + Project project = AiravataManager.getInstance().createProject( + projectNameField.getText(),projectDescField.getText()); + Stage stage = (Stage) saveButton.getScene().getWindow(); + stage.close(); + SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.PROJECT_CREATED,project)); + } catch (Exception e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", saveButton.getScene().getWindow(), + "Failed tp save project !"); + } + }); + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/ui/storage/.DS_Store b/src/main/java/org/seagrid/desktop/ui/storage/.DS_Store new file mode 100644 index 0000000..8b2cf37 Binary files /dev/null and b/src/main/java/org/seagrid/desktop/ui/storage/.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/ui/storage/._.DS_Store b/src/main/java/org/seagrid/desktop/ui/storage/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/org/seagrid/desktop/ui/storage/._.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/ui/storage/MassStorageBrowserWindow.java b/src/main/java/org/seagrid/desktop/ui/storage/MassStorageBrowserWindow.java new file mode 100644 index 0000000..ddc16e9 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/ui/storage/MassStorageBrowserWindow.java @@ -0,0 +1,76 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.ui.storage; + +import com.jcraft.jsch.JSchException; +import com.jcraft.jsch.SftpException; +import javafx.application.Application; +import javafx.fxml.FXMLLoader; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.stage.Modality; +import javafx.stage.Stage; +import org.seagrid.desktop.ui.storage.controller.MassStorageBrowserController; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; + +public class MassStorageBrowserWindow extends Application{ + private final static Logger logger = LoggerFactory.getLogger(MassStorageBrowserWindow.class); + + private static Stage primaryStage; + private static MassStorageBrowserController controller; + + @Override + public void start(Stage primaryStage) throws Exception { + Parent root = FXMLLoader.load(getClass().getResource("/views/storage/mass-storage-browser.fxml")); + primaryStage.setTitle("SEAGrid Desktop Client - Storage Browser"); + primaryStage.setScene(new Scene(root, 800, 600)); + primaryStage.show(); + } + + public static void displayFileBrowse(String path) throws IOException, SftpException, JSchException { + if(primaryStage == null || !primaryStage.isShowing()) { + primaryStage = new Stage(); + FXMLLoader loader = new FXMLLoader(MassStorageBrowserWindow.class.getResource( + "/views/storage/mass-storage-browser.fxml")); + Parent root = loader.load(); + controller = loader.getController(); + primaryStage.setTitle("SEAGrid Desktop Client - Storage Browser"); + primaryStage.setScene(new Scene(root, 800, 600)); + primaryStage.initModality(Modality.WINDOW_MODAL); + primaryStage.show(); + } + + if(path != null){ + if(!path.startsWith("/")){ + path = "/" + path; + } + controller.gotoRemoteDir(path); + } + primaryStage.requestFocus(); + } + + public static void main(String[] args) { + launch(args); + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/ui/storage/controller/MassStorageBrowserController.java b/src/main/java/org/seagrid/desktop/ui/storage/controller/MassStorageBrowserController.java new file mode 100644 index 0000000..62e53cf --- /dev/null +++ b/src/main/java/org/seagrid/desktop/ui/storage/controller/MassStorageBrowserController.java @@ -0,0 +1,590 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.ui.storage.controller; + +import com.github.sardine.DavResource; +import com.jcraft.jsch.ChannelSftp; +import com.jcraft.jsch.JSchException; +import com.jcraft.jsch.SftpException; +import javafx.beans.property.SimpleObjectProperty; +import javafx.beans.property.SimpleStringProperty; +import javafx.collections.FXCollections; +import javafx.collections.ObservableList; +import javafx.concurrent.Service; +import javafx.concurrent.Task; +import javafx.concurrent.WorkerStateEvent; +import javafx.fxml.FXML; +import javafx.geometry.Pos; +import javafx.scene.Cursor; +import javafx.scene.ImageCursor; +import javafx.scene.control.*; +import javafx.scene.image.Image; +import javafx.scene.input.ClipboardContent; +import javafx.scene.input.DataFormat; +import javafx.scene.input.Dragboard; +import javafx.scene.input.TransferMode; +import javafx.scene.layout.HBox; +import javafx.stage.Stage; +import org.seagrid.desktop.connectors.NextcloudStorage.*; +import org.seagrid.desktop.ui.commons.SEAGridDialogHelper; +import org.seagrid.desktop.ui.storage.model.FileListModel; +import org.seagrid.desktop.util.SEAGridContext; +import org.seagrid.desktop.util.messaging.SEAGridEvent; +import org.seagrid.desktop.util.messaging.SEAGridEventBus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Vector; + +public class MassStorageBrowserController { + private final static Logger logger = LoggerFactory.getLogger(MassStorageBrowserController.class); + + private static final DataFormat SERIALIZED_MIME_TYPE = new DataFormat("application/x-java-serialized-object"); + + @FXML + private TableView fbLocalFileTable; + + @FXML + private TableColumn fbLocalFileTblFileName; + + @FXML + private TableColumn fbLocalFileTblFileSize; + + @FXML + private TableColumn fbLocalFileTblLastMod; + + @FXML + private TableView fbRemoteFileTable; + + @FXML + private TableColumn fbRemoteFileTblFileName; + + @FXML + private TableColumn fbRemoteFileTblFileSize; + + @FXML + public TableColumn fbRemoteFileTblLastMod; + + @FXML + private TextField fbLocalPath; + + @FXML + private TextField fbRemotePath; + + private Path currentLocalPath; + + private String currentRemotePath; + + ObservableList currentLocalFileList, currentRemoteFileList; + + @SuppressWarnings("unused") + public void initialize(){ + try{ + initialiseColumnWidths(); + initializeLocalFileTable(); + initializeRemoteFileTable(); + + fbLocalPath.setAlignment(Pos.BASELINE_LEFT); + fbRemotePath.setAlignment(Pos.BASELINE_LEFT); + }catch (Exception e){ + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", null, + "Failed opening mass storage browser"); + if(fbLocalPath != null && fbLocalPath.getScene() != null && fbLocalPath.getScene().getWindow() != null) + ((Stage)fbLocalPath.getScene().getWindow()).close(); + } + } + + private void initialiseColumnWidths(){ + fbLocalFileTblFileName.prefWidthProperty().bind(fbLocalFileTable.widthProperty().divide(3)); + fbLocalFileTblFileSize.prefWidthProperty().bind(fbLocalFileTable.widthProperty().divide(3)); + fbLocalFileTblLastMod.prefWidthProperty().bind(fbLocalFileTable.widthProperty().divide(3)); + + fbRemoteFileTblFileName.prefWidthProperty().bind(fbRemoteFileTable.widthProperty().divide(3)); + fbRemoteFileTblFileSize.prefWidthProperty().bind(fbRemoteFileTable.widthProperty().divide(3)); + fbRemoteFileTblLastMod.prefWidthProperty().bind(fbRemoteFileTable.widthProperty().divide(3)); + } + + private void initializeLocalFileTable(){ + String userHome = System.getProperty("user.home"); + this.currentLocalPath = Paths.get(userHome); + fbLocalFileTblFileName.setCellValueFactory(cellData-> new SimpleObjectProperty(cellData.getValue())); + fbLocalFileTblFileName.setCellFactory(param -> new TableCell(){ + @Override + public void updateItem(FileListModel item, boolean empty){ + if(item != null){ + HBox hBox = new HBox(2); + Image fileImage; + if(item.getFileListModelType().equals(FileListModel.FileListModelType.FILE)){ + fileImage = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/file.png")); + }else{ + fileImage = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/folder.png")); + } + hBox.getChildren().add(new javafx.scene.image.ImageView(fileImage)); + hBox.getChildren().add(new Label(item.getFileName())); + setGraphic(hBox); + }else{ + setGraphic(null); + } + } + }); + fbLocalFileTblFileSize.setCellValueFactory(cellData -> cellData.getValue().getFileListModelType() + .equals(FileListModel.FileListModelType.FILE) ? new SimpleStringProperty(cellData.getValue().getSize()+" bytes") + : null); + fbLocalFileTblFileSize.setCellFactory(param -> new TableCell(){ + @Override + public void updateItem(String item, boolean empty){ + setText(item); + setAlignment(Pos.CENTER_RIGHT); + } + }); + fbLocalFileTblLastMod.setCellValueFactory(cellData -> cellData.getValue().getFileListModelType() + .equals(FileListModel.FileListModelType.PARENT_DIR) ? null + : new SimpleStringProperty(LocalDateTime.ofEpochSecond(cellData.getValue().getLastModifiedTime() / 1000, 0, + SEAGridContext.getInstance().getTimeZoneOffset()).toString())); + fbLocalFileTblLastMod.setCellFactory(param -> new TableCell(){ + @Override + public void updateItem(String item, boolean empty){ + setText(item); + setAlignment(Pos.CENTER_RIGHT); + } + }); + + currentLocalFileList = FXCollections.observableArrayList(); + fbLocalFileTable.setItems(currentLocalFileList); + + fbLocalFileTable.setOnMouseClicked(event -> { + FileListModel fileListModel = fbLocalFileTable.getSelectionModel().getSelectedItem(); + if(fileListModel != null && event.getClickCount()==2) { + if (fileListModel.getFileListModelType().equals(FileListModel.FileListModelType.DIR)) { + currentLocalPath = Paths.get(currentLocalPath.toString() + File.separator + fileListModel.getFileName()); + } else if (fileListModel.getFileListModelType().equals(FileListModel.FileListModelType + .PARENT_DIR)) { + currentLocalPath = currentLocalPath.getParent(); + } + populateLocalFileList(); + } + }); + + fbLocalFileTable.setRowFactory(tv -> { + TableRow row = new TableRow<>(); + row.setOnDragDetected(event -> { + if (!row.isEmpty() && !currentLocalFileList.get(row.getIndex()).getFileName().equals("..") + && (currentLocalFileList.get(row.getIndex()).getFileListModelType().equals(FileListModel + .FileListModelType.FILE) || (currentLocalFileList.get(row.getIndex()).getFileListModelType() + .equals(FileListModel.FileListModelType.DIR)))){ + FileListModel selectedFileListModel = fbLocalFileTable.getSelectionModel().getSelectedItem(); + Dragboard db = row.startDragAndDrop(TransferMode.MOVE); + db.setDragView(row.snapshot(null, null)); + ClipboardContent cc = new ClipboardContent(); + cc.put(SERIALIZED_MIME_TYPE, selectedFileListModel); + db.setContent(cc); + event.consume(); + } + }); + return row; + }); + fbLocalFileTable.setOnDragOver(event -> { + fbRemoteFileTable.getScene().setCursor(Cursor.DEFAULT); + Dragboard db = event.getDragboard(); + if (db.hasContent(SERIALIZED_MIME_TYPE)) { + if (((FileListModel) db.getContent(SERIALIZED_MIME_TYPE)).getFileLocation().equals(FileListModel.FileLocation.REMOTE)) { + Image image = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/add.png")); + fbRemoteFileTable.getScene().setCursor(new ImageCursor(image)); + event.acceptTransferModes(TransferMode.COPY_OR_MOVE); + event.consume(); + } + } + }); + fbLocalFileTable.setOnDragDropped(event -> { + fbRemoteFileTable.getScene().setCursor(Cursor.DEFAULT); + Dragboard db = event.getDragboard(); + if (db.hasContent(SERIALIZED_MIME_TYPE)) { + FileListModel draggedFileListModel = (FileListModel) db.getContent(SERIALIZED_MIME_TYPE); + if(draggedFileListModel.getFileListModelType().equals(FileListModel.FileListModelType.FILE)) { + downloadFile(draggedFileListModel.getFilePath(), + currentLocalPath.toString() + File.separator + draggedFileListModel.getFileName(), draggedFileListModel); + }else if(draggedFileListModel.getFileListModelType().equals(FileListModel.FileListModelType.DIR)){ + downloadDir(draggedFileListModel.getFilePath(), + currentLocalPath.toString() + File.separator + draggedFileListModel.getFileName(), draggedFileListModel); + } + event.setDropCompleted(true); + event.consume(); + } + }); + + populateLocalFileList(); + } + + private void populateLocalFileList(){ + currentLocalFileList.clear(); + fbLocalPath.setText(currentLocalPath.toString()); + FileListModel fileListModel; + if(currentLocalPath.getParent() != null){ + fileListModel = new FileListModel("..", FileListModel.FileListModelType.PARENT_DIR,0,0, FileListModel.FileLocation.LOCAL, + currentLocalPath.getParent().toString()); + currentLocalFileList.add(fileListModel); + } + File parent = new File(currentLocalPath.toString()); + File[] children = parent.listFiles(); + for(File child : children){ + if(child.getName().equals(".") || child.getName().equals("..")) continue; + fileListModel = new FileListModel(child.getName(),child.isFile() == true + ? FileListModel.FileListModelType.FILE : FileListModel.FileListModelType.DIR, child.length(), + child.lastModified(), FileListModel.FileLocation.LOCAL, currentLocalPath.toString() + + File.separator + child.getName()); + currentLocalFileList.add(fileListModel); + } + } + + private void initializeRemoteFileTable() throws SftpException, JSchException, IOException { + this.currentRemotePath = "/"; + + fbRemoteFileTblFileName.setCellValueFactory(cellData-> new SimpleObjectProperty(cellData.getValue())); + fbRemoteFileTblFileName.setCellFactory(param -> new TableCell(){ + @Override + public void updateItem(FileListModel item, boolean empty){ + if(item != null){ + HBox hBox = new HBox(2); + Image fileImage; + if(item.getFileListModelType().equals(FileListModel.FileListModelType.FILE)){ + fileImage = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/file.png")); + }else{ + fileImage = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/folder.png")); + } + hBox.getChildren().add(new javafx.scene.image.ImageView(fileImage)); + hBox.getChildren().add(new Label(item.getFileName())); + setGraphic(hBox); + }else{ + setGraphic(null); + } + } + }); + fbRemoteFileTblFileSize.setCellValueFactory(cellData -> cellData.getValue().getFileListModelType() + .equals(FileListModel.FileListModelType.FILE) ? new SimpleStringProperty(cellData.getValue().getSize()+" bytes") + : null); + fbRemoteFileTblFileSize.setCellFactory(param -> new TableCell(){ + @Override + public void updateItem(String item, boolean empty){ + setText(item); + setAlignment(Pos.CENTER_RIGHT); + } + }); + fbRemoteFileTblLastMod.setCellValueFactory(cellData -> cellData.getValue().getFileListModelType() + .equals(FileListModel.FileListModelType.PARENT_DIR) ? null + : new SimpleStringProperty(LocalDateTime.ofEpochSecond(cellData.getValue().getLastModifiedTime() / 1000, 0, + SEAGridContext.getInstance().getTimeZoneOffset()).toString())); + fbRemoteFileTblLastMod.setCellFactory(param -> new TableCell(){ + @Override + public void updateItem(String item, boolean empty){ + setText(item); + setAlignment(Pos.CENTER_RIGHT); + } + }); + + currentRemoteFileList = FXCollections.observableArrayList(); + fbRemoteFileTable.setItems(currentRemoteFileList); + + fbRemoteFileTable.setOnMouseClicked(event -> { + FileListModel fileListModel = fbRemoteFileTable.getSelectionModel().getSelectedItem(); + if(fileListModel != null && event.getClickCount()==2) { + if (fileListModel.getFileListModelType().equals(FileListModel.FileListModelType.DIR)) { + currentRemotePath = currentRemotePath + "/" + fileListModel.getFileName(); + } else if (fileListModel.getFileListModelType().equals(FileListModel.FileListModelType + .PARENT_DIR)) { + currentRemotePath = (new File(currentRemotePath)).getParent(); + } + try { + populateRemoteFileTable(); + } catch (Exception e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", fbRemoteFileTable.getScene().getWindow(), + "Failed to load remote directory information"); + } + } + }); + + fbRemoteFileTable.setRowFactory(tv -> { + TableRow row = new TableRow<>(); + row.setOnDragDetected(event -> { + if (!row.isEmpty() && !currentRemoteFileList.get(row.getIndex()).getFileName().equals("..") + && (currentRemoteFileList.get(row.getIndex()).getFileListModelType().equals(FileListModel + .FileListModelType.FILE) || (currentRemoteFileList.get(row.getIndex()).getFileListModelType() + .equals(FileListModel.FileListModelType.DIR)))) { + FileListModel selectedFileListModel = fbRemoteFileTable.getSelectionModel().getSelectedItem(); + Dragboard db = row.startDragAndDrop(TransferMode.MOVE); + db.setDragView(row.snapshot(null, null)); + ClipboardContent cc = new ClipboardContent(); + cc.put(SERIALIZED_MIME_TYPE, selectedFileListModel); + db.setContent(cc); + event.consume(); + } + }); + return row; + }); +// fbRemoteFileTable.setOnDragOver(event -> { +// fbRemoteFileTable.getScene().setCursor(Cursor.DEFAULT); +// Dragboard db = event.getDragboard(); +// if (db.hasContent(SERIALIZED_MIME_TYPE)) { +// if (((FileListModel) db.getContent(SERIALIZED_MIME_TYPE)).getFileLocation().equals(FileListModel.FileLocation.LOCAL)) { +// Image image = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/add.png")); +// fbRemoteFileTable.getScene().setCursor(new ImageCursor(image)); +// event.acceptTransferModes(TransferMode.COPY_OR_MOVE); +// event.consume(); +// } +// } +// }); +// fbRemoteFileTable.setOnDragDropped(event -> { +// fbRemoteFileTable.getScene().setCursor(Cursor.DEFAULT); +// Dragboard db = event.getDragboard(); +// if (db.hasContent(SERIALIZED_MIME_TYPE)) { +// FileListModel draggedFileListModel = (FileListModel) db.getContent(SERIALIZED_MIME_TYPE); +// if(draggedFileListModel.getFileListModelType().equals(FileListModel.FileListModelType.FILE)) { +// if ((new File(currentRemotePath)).getParent() != null && !(new File(currentRemotePath)).getParent().isEmpty()) { +// uploadFile(draggedFileListModel.getFilePath(), currentRemotePath.toString() + "/" + draggedFileListModel +// .getFileName(), draggedFileListModel); +// } else { +// uploadFile(draggedFileListModel.getFilePath(), "/" + draggedFileListModel +// .getFileName(), draggedFileListModel); +// } +// }else if(draggedFileListModel.getFileListModelType().equals(FileListModel.FileListModelType.DIR)){ +// uploadDir(draggedFileListModel.getFilePath(), "/" + draggedFileListModel +// .getFileName(), draggedFileListModel); +// } +// event.setDropCompleted(true); +// event.consume(); +// } +// }); + + populateRemoteFileTable(); + } + + private void populateRemoteFileTable() throws JSchException, SftpException, IOException { + currentRemoteFileList.clear(); + fbRemotePath.setText(SEAGridContext.getInstance().getUserName() + currentRemotePath.toString()); + FileListModel fileListModel; + if((new File(currentRemotePath)).getParent() != null && !(new File(currentRemotePath)).getParent().isEmpty()){ + fileListModel = new FileListModel("..", FileListModel.FileListModelType.PARENT_DIR,0,0, FileListModel.FileLocation.REMOTE, + (new File(currentRemotePath).getParent())); + currentRemoteFileList.add(fileListModel); + } + + List resources = NextcloudStorageManager.getInstance().listDirectories(currentRemotePath.toString()); + int count = 0; + if(resources!= null) { + for (DavResource res : resources) { + if(count != 0) { + if (res.getName().equals(".") || res.getName().equals("..")) continue; + fileListModel = new FileListModel(res.getName(), res.isDirectory() == false + ? FileListModel.FileListModelType.FILE : FileListModel.FileListModelType.DIR, res.getContentLength().intValue(), + res.getModified().getTime(), FileListModel.FileLocation.REMOTE, currentRemotePath.toString() + + "/" + res.getName()); + currentRemoteFileList.add(fileListModel); + } + count++; + } + } + } + + private void uploadFile(String localFile, String remotePath, FileListModel upldFileModel){ + Service service = new Service() { + @Override + protected Task createTask() { + try { + return new NextcloudSingleFileUploadTask(remotePath, localFile); + } catch (Exception e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", fbRemoteFileTable.getScene().getWindow(), + "Unable To Connect To File Server !"); + } + return null; + } + }; + SEAGridDialogHelper.showProgressDialog(service, "Progress Dialog", fbRemoteFileTable.getScene().getWindow(), + "Uploading File " + upldFileModel.getFileName()); + service.setOnFailed((WorkerStateEvent t) -> { + SEAGridDialogHelper.showExceptionDialogAndWait(service.getException(), "Exception Dialog", + fbRemoteFileTable.getScene().getWindow(), "File Upload Failed"); + }); + service.setOnSucceeded((WorkerStateEvent t)->{ + //removing the duplicate file with the same name + for(int i=0;i service = new Service() { + @Override + protected Task createTask() { + try { + return new NextcloudFolderUploadTask(remoteDir, localDir); + } catch (Exception e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", fbRemoteFileTable.getScene().getWindow(), + "Unable To Connect To File Server !"); + } + return null; + } + }; + SEAGridDialogHelper.showProgressDialog(service, "Progress Dialog", fbRemoteFileTable.getScene().getWindow(), + "Uploading Directory " + upldFileModel.getFileName()); + service.setOnFailed((WorkerStateEvent t) -> { + SEAGridDialogHelper.showExceptionDialogAndWait(service.getException(), "Exception Dialog", + fbRemoteFileTable.getScene().getWindow(), "Directory Upload Failed"); + }); + service.setOnSucceeded((WorkerStateEvent t)->{ + //removing the duplicate file with the same name + for(int i=0;i service = new Service() { + @Override + protected Task createTask() { + try { + return new NextcloudFileDownloadTask(remoteFile, localFile); + } catch (Exception e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", fbLocalFileTable.getScene().getWindow(), + "Unable To Connect To File Server !"); + } + return null; + } + }; + SEAGridDialogHelper.showProgressDialog(service, "Progress Dialog", fbLocalFileTable.getScene().getWindow(), + "Downloading File " + downFileModel.getFileName()); + service.setOnFailed((WorkerStateEvent t) -> { + SEAGridDialogHelper.showExceptionDialogAndWait(service.getException(), "Exception Dialog", + fbLocalFileTable.getScene().getWindow(), "File Download Failed"); + }); + service.setOnSucceeded((WorkerStateEvent t)->{ + //removing the duplicate file with the same name + for(int i=0;i service = new Service() { + @Override + protected Task createTask() { + try { + return new NextCloudFolderdownloadtask(remoteDir, localDir); + } catch (Exception e) { + e.printStackTrace(); + SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", fbLocalFileTable.getScene().getWindow(), + "Unable To Connect To File Server !"); + } + return null; + } + }; + SEAGridDialogHelper.showProgressDialog(service, "Progress Dialog", fbLocalFileTable.getScene().getWindow(), + "Downloading Directory " + downFileModel.getFileName()); + service.setOnFailed((WorkerStateEvent t) -> { + SEAGridDialogHelper.showExceptionDialogAndWait(service.getException(), "Exception Dialog", + fbLocalFileTable.getScene().getWindow(), "Directory Download Failed"); + }); + service.setOnSucceeded((WorkerStateEvent t)->{ + //removing the duplicate file with the same name + for(int i=0;i resources = NextcloudStorageManager.getInstance().listDirectories(currentRemotePath.toString()); + if(resources!=null) { + for (DavResource res : resources) { + if (count != 0) { + ; + if (res.getName().equals(".") || res.getName().equals("..")) continue; + fileListModel = new FileListModel(res.getName(), res.isDirectory() == false + ? FileListModel.FileListModelType.FILE : FileListModel.FileListModelType.DIR, res.getContentLength().intValue(), + res.getModified().getTime(), FileListModel.FileLocation.REMOTE, currentRemotePath.toString() + + "/" + res.getName()); + currentRemoteFileList.add(fileListModel); + } + count++; + } + } + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/ui/storage/model/FileListModel.java b/src/main/java/org/seagrid/desktop/ui/storage/model/FileListModel.java new file mode 100644 index 0000000..eb97e57 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/ui/storage/model/FileListModel.java @@ -0,0 +1,103 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.ui.storage.model; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.Serializable; + +public class FileListModel implements Serializable{ + private final static Logger logger = LoggerFactory.getLogger(FileListModel.class); + + public static enum FileListModelType{ + FILE, DIR, PARENT_DIR + } + + public static enum FileLocation{ + REMOTE, LOCAL + } + + private String fileName; + private FileListModelType fileListModelType; + private FileLocation fileLocation; + private long size; + private long lastModifiedTime; + private String filePath; + + public FileListModel(String fileName, FileListModelType fileListModelType, long size, long lastModifiedTime, FileLocation + fileLocation, String filePath) { + this.fileName = fileName; + this.fileListModelType = fileListModelType; + this.size = size; + this.lastModifiedTime = lastModifiedTime; + this.fileLocation = fileLocation; + this.filePath = filePath; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public FileListModelType getFileListModelType() { + return fileListModelType; + } + + public void setFileListModelType(FileListModelType fileListModelType) { + this.fileListModelType = fileListModelType; + } + + public long getSize() { + return size; + } + + public void setSize(long size) { + this.size = size; + } + + public long getLastModifiedTime() { + return lastModifiedTime; + } + + public void setLastModifiedTime(long lastModifiedTime) { + this.lastModifiedTime = lastModifiedTime; + } + + public FileLocation getFileLocation() { + return fileLocation; + } + + public void setFileLocation(FileLocation fileLocation) { + this.fileLocation = fileLocation; + } + + public String getFilePath() { + return filePath; + } + + public void setFilePath(String filePath) { + this.filePath = filePath; + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/util/.DS_Store b/src/main/java/org/seagrid/desktop/util/.DS_Store new file mode 100644 index 0000000..6add6f9 Binary files /dev/null and b/src/main/java/org/seagrid/desktop/util/.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/util/._.DS_Store b/src/main/java/org/seagrid/desktop/util/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/java/org/seagrid/desktop/util/._.DS_Store differ diff --git a/src/main/java/org/seagrid/desktop/util/SEAGridConfig.java b/src/main/java/org/seagrid/desktop/util/SEAGridConfig.java new file mode 100644 index 0000000..af9cf5c --- /dev/null +++ b/src/main/java/org/seagrid/desktop/util/SEAGridConfig.java @@ -0,0 +1,63 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.util; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SEAGridConfig { + private final static Logger logger = LoggerFactory.getLogger(SEAGridConfig.class); + + public static final boolean DEV = true; //true + public static final boolean IS_USE_HTTPS = false; + + public static final String USER_NAME = "user.name"; + public static final String AUTHENTICATED = "authenticated"; + public static final String OAUTH_TOKEN = "oauth.token"; + public static final String OAUTH_REFRESH_TOKEN = "oauth.refresh.token"; + public static final String OAUTH_TOKEN_EXPIRATION_TIME = "oauth.expiration.time"; + public static final String AIRAVATA_HOST = "airavata.host"; + public static final String DEV_AIRAVATA_HOST = "dev.airavata.host"; + public static final String AIRAVATA_PORT = "airavata.port"; + public static final String DEV_AIRAVATA_PORT = "dev.airavata.port"; + public static final String AIRAVATA_GATEWAY_ID = "airavata.gateway-id"; + public static final String DEV_AIRAVATA_GATEWAY_ID = "dev.airavata.gateway-id"; + public static final String SFTP_HOST = "sftp.host"; + public static final String DEV_SFTP_HOST = "dev.sftp.host"; + public static final String SFTP_PORT = "sftp.port"; + public static final String DEV_SFTP_PORT = "dev.sftp.port"; + + public static final String DEFAULT_FILE_DOWNLOAD_PATH = "default.file.download.path"; + public static final java.lang.String GATEWAY_STORAGE_ID = "gateway.storage.resource.id"; + public static final java.lang.String DEV_GATEWAY_STORAGE_ID = "dev.gateway.storage.resource.id"; + public static final java.lang.String REMOTE_DATA_DIR_ROOT = "remote.data.dir.root"; + public static final java.lang.String DEV_REMOTE_DATA_DIR_ROOT = "dev.remote.data.dir.root"; + public static final java.lang.String REMOTE_DATA_DIR_PREFIX = "remote.data.dir.prefix"; + public static final java.lang.String DEV_REMOTE_DATA_DIR_PREFIX = "dev.remote.data.dir.prefix"; + + public static final java.lang.String NEXTCLOUD_SERVERNAME = "nextcloud.server"; + public static final java.lang.String NEXTCLOUD_WEBDAV_BASEPATH = "nextcloudwebdav.base.path"; + public static final java.lang.String CLIENT_ID = "nextcloud.client.id"; + public static final java.lang.String TOKEN_ENDPOINT = "nextcloud.token.endpoint"; + public static final java.lang.String TOKEN_GRANTYPE = "nextcloud.grantype"; + public static final java.lang.String TOKEN_VALIDATION_URL = "nextcloud.tokenvalidation.api"; + public static final java.lang.String BASE_DOWNLOAD_PATH = "nextcloud.file.basedownloadpath"; +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/util/SEAGridContext.java b/src/main/java/org/seagrid/desktop/util/SEAGridContext.java new file mode 100644 index 0000000..7c97f93 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/util/SEAGridContext.java @@ -0,0 +1,289 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.util; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.TimeZone; + +public class SEAGridContext { + private final static Logger logger = LoggerFactory.getLogger(SEAGridContext.class); + + private Map dynamicConfigurations = new HashMap<>(); + + private Properties properties = new Properties(); + private static final String PROPERTY_FILE_NAME = "/seagrid.properties"; + + private static SEAGridContext instance; + + private UserPrefs userPrefs; + + private SEAGridContext(){ + InputStream inputStream = SEAGridContext.class.getResourceAsStream(PROPERTY_FILE_NAME); + try { + properties.load(inputStream); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static SEAGridContext getInstance(){ + if(SEAGridContext.instance == null){ + SEAGridContext.instance = new SEAGridContext(); + } + return SEAGridContext.instance; + } + + public ZoneOffset getTimeZoneOffset(){ + LocalDateTime dt = LocalDateTime.now(); + return dt.atZone(TimeZone.getDefault().toZoneId()).getOffset(); + } + + public String getFileDownloadLocation(){ + if(properties.getProperty(SEAGridConfig.DEFAULT_FILE_DOWNLOAD_PATH) != null && !properties.getProperty( + SEAGridConfig.DEFAULT_FILE_DOWNLOAD_PATH).isEmpty()) { + return properties.getProperty(SEAGridConfig.DEFAULT_FILE_DOWNLOAD_PATH); + }else{ + return System.getProperty("user.home") + File.separator + "SEAGrid" + File.separator + "ExperimentData"; + } + } + + public String getAiravataGatewayId(){ + if(SEAGridConfig.DEV){ + return properties.getProperty(SEAGridConfig.DEV_AIRAVATA_GATEWAY_ID); + } + return properties.getProperty(SEAGridConfig.AIRAVATA_GATEWAY_ID); + } + + public void setUserName(String userName){ dynamicConfigurations.put(SEAGridConfig.USER_NAME, userName);} + + public String getUserName(){ return dynamicConfigurations.get(SEAGridConfig.USER_NAME);} + + public int getMaxRecentExpCount(){ return 20; } + + public String getRecentExperimentsDummyId(){ return "$$$$$$"; } + + public void setAuthenticated(boolean authenticated) { + if(authenticated) + dynamicConfigurations.put(SEAGridConfig.AUTHENTICATED, "true"); + } + + public boolean getAuthenticated() { return dynamicConfigurations.containsKey(SEAGridConfig.AUTHENTICATED); } + + public void setOAuthToken(String oauthToken) { + dynamicConfigurations.put(SEAGridConfig.OAUTH_TOKEN,oauthToken); + } + + public String getOAuthToken(){ + return dynamicConfigurations.get(SEAGridConfig.OAUTH_TOKEN); + } + + public void setRefreshToken(String refreshToken){ + dynamicConfigurations.put(SEAGridConfig.OAUTH_REFRESH_TOKEN, refreshToken); + } + + public String getRefreshToken(){ + return dynamicConfigurations.get(SEAGridConfig.OAUTH_REFRESH_TOKEN); + } + + public void setTokenExpiaryTime(long tokenExpiarationTime) { + dynamicConfigurations.put(SEAGridConfig.OAUTH_TOKEN_EXPIRATION_TIME, tokenExpiarationTime + ""); + } + + public long getOAuthTokenExpirationTime(){ + return Long.parseLong(dynamicConfigurations.get(SEAGridConfig.OAUTH_TOKEN_EXPIRATION_TIME)); + } + + public String getAiravataHost() { + if(SEAGridConfig.DEV){ + return properties.getProperty(SEAGridConfig.DEV_AIRAVATA_HOST); + } + return properties.getProperty(SEAGridConfig.AIRAVATA_HOST); + } + + public int getAiravataPort() { + if(SEAGridConfig.DEV){ + return Integer.parseInt(properties.getProperty(SEAGridConfig.DEV_AIRAVATA_PORT)); + } + return Integer.parseInt(properties.getProperty(SEAGridConfig.AIRAVATA_PORT)); + } + + public String getSFTPHost() { + if(SEAGridConfig.DEV){ + return properties.getProperty(SEAGridConfig.DEV_SFTP_HOST); + } + return properties.getProperty(SEAGridConfig.SFTP_HOST); + } + + public int getSFTPPort() { + if(SEAGridConfig.DEV){ + return Integer.parseInt(properties.getProperty(SEAGridConfig.DEV_SFTP_PORT)); + } + return Integer.parseInt(properties.getProperty(SEAGridConfig.SFTP_PORT)); + } + + public String getGaussianAppName() { + return "gaussian"; + } + + public String getGamessAppName() { return "gamess"; } + + public String getNwchemAppName() { return "nwchem"; } + + public String getPsi4AppName() { return "psi4"; } + + public String getMolcasAppName() { return "molcas"; } + + public String getGatewayaStorageId(){ + if(SEAGridConfig.DEV){ + return properties.getProperty(SEAGridConfig.DEV_GATEWAY_STORAGE_ID); + } + return properties.getProperty(SEAGridConfig.GATEWAY_STORAGE_ID); + } + + public String getGatewayUserDataRoot(){ + if(SEAGridConfig.DEV){ + return properties.getProperty(SEAGridConfig.DEV_REMOTE_DATA_DIR_ROOT); + } + return properties.getProperty(SEAGridConfig.REMOTE_DATA_DIR_ROOT) + getUserName() + "/"; + } + + public String getRemoteDataDirPrefix(){ + if(SEAGridConfig.DEV){ + return properties.getProperty(SEAGridConfig.DEV_REMOTE_DATA_DIR_PREFIX); + } + return properties.getProperty(SEAGridConfig.REMOTE_DATA_DIR_PREFIX); + } + + + public UserPrefs getUserPrefs(){ + if(this.userPrefs == null){ + try + { + FileInputStream fis = new FileInputStream(getFileDownloadLocation()+"/.prefs/user_pref.ser"); + ObjectInputStream ois = new ObjectInputStream(fis); + this.userPrefs = (UserPrefs)ois.readObject(); + if(this.userPrefs == null){ + this.userPrefs = new UserPrefs(); + return this.userPrefs; + } + } + catch (Exception e){ + this.userPrefs = new UserPrefs(); + } + } + return this.userPrefs; + } + + public void saveUserPrefs() { + File file = new File((getFileDownloadLocation()+"/.prefs")); + if(!file.exists()){ + file.mkdirs(); + } + FileOutputStream fos = null; + try { + fos = new FileOutputStream(getFileDownloadLocation()+"/.prefs/user_pref.ser"); + ObjectOutputStream oos = new ObjectOutputStream(fos); + oos.writeObject(this.userPrefs); + oos.close(); + fos.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public String getNextcloudServername() { return properties.getProperty(SEAGridConfig.NEXTCLOUD_SERVERNAME); } + + public String getDavBasepath() { + return properties.getProperty(SEAGridConfig.NEXTCLOUD_WEBDAV_BASEPATH); + } + + public boolean isUseHttps() { + return SEAGridConfig.IS_USE_HTTPS; + } + + public String getClientID() { + return properties.getProperty(SEAGridConfig.CLIENT_ID); + } + + public String getTokenGenerateEndpoint() { + return properties.getProperty(SEAGridConfig.TOKEN_ENDPOINT); + } + + public String getGrantType() { + return properties.getProperty(SEAGridConfig.TOKEN_GRANTYPE); + } + + public String getValidationURL() { + return properties.getProperty(SEAGridConfig.TOKEN_VALIDATION_URL); + } + + public String getBaseDownloadPath() { + return properties.getProperty(SEAGridConfig.BASE_DOWNLOAD_PATH); + } + + //FIXME - There is an issue in loading file from resources. This is a temporary hack + public static final String logoBase64 = "iVBORw0KGgoAAAANSUhEUgAAAdkAAACTCAMAAAD1LZOOAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5" + + "ccllPAAAAGxQTFRF1PPxWMW/j9jUx+zqLbqx8fr6LrevSsC6q+LfZc3H4/X0dM/KPLy11fHvgtTPuefkZsrFnd3as+vmnODc9Pz7YM7HNsC36f" + + "n43vb0xu/sgNbRmOHcquXhOr63ctLMit3Wt+rmVsnBILKq////7wPFkQAAACR0Uk5T//////////////////////////////////////////////" + + "8AWCwNDQAADaFJREFUeNrsnWmbpCgSgBMokUIO3ane7p7emdnV//8fN28vjgDBPJr45FOVovBCEBEEeBiKvKccShMUskUK2SKFbJFCtkghW6SQLWSLF" + + "LJFCtkihWyRQrZIIVvIbpQv4/WX549Fnp/swXh98PyxSCFbpJAtZAvZQraQLWQL2UK2SCFbpJAtZKEiSYexQkdRGHdEvhrZipzenvYXQajFTMLv5uRa+aM" + + "0GGv5JmSlQv1KkCIgsuTUJU7yJ77LePnfXarLVd0bhDYacnPXUkP1sXx1shUWvUUErpa//n44yr8OV/n598e/P24yXk0u/7n+8rt7vFmkAtWAoL4PqMLi5tZ6b8" + + "2S9Ty5P9kK094h1Ngwt9K7470f99+OV5PLPwDv0NifD2hbiXqnUBbZKU79wjvmWT1qNmR+0vURiO9KlojeI6bKXUrn9RxiLFnmwuIdtbj3CrIWojbce2u+kexxlBM72Z" + + "7KHckCmqXvlbl0Sfs0ZFvXw4lH5bSQGljatKrj7x2bb0q277GdLKCbJiPb9CBpTKVfwSYgizaQRbAaGPGAwLrQNv2a7LqxJu9I9iKLe6CodemV6FOR7VyPdk9OCloDYRguNfBey" + + "p0PX5Bdq7j9yZIeLGRVetMnI+saO12qGrTxvaKvnQ9fku21lazeiayAt4tYlk76dGSPjXSSiy7D+NwQJ1e4I0Qmq8FqvMiAe002711prcgup9ORLN6HrNEkrVENqNth8rYpyJ6FXp" + + "vpPEeA7ljXgJ4CaBi3yD9oTTbGOQTl79jzOWRFdgkQeQZ/crJLhHV3e0fOGmpTSF/nSMXPZVDif5+fn98+7zJe/roFNWCGVBDZhV1M1WSI6xW5+UiqVuTZbTqt9Kr62qEv1mQXgxb1KS" + + "daANkFOuIOYMxL7+bDE/MEceNwsvNXbBZKkLcudawXXPmi+j7HT/Z2sgsNNyGL9iBL3I7NIGt7uxzQlCwlSVYEgslWvrlwrq2xwy9YG2py1m2Qw68wkG2tntnqLTnGOjFZ5rYc" + + "JybCuu4HOiWrh8eQJe6uucTX2DW56eYZWuqYCQxkhd3nloanNGnJYm8Mj1h7/GHyj48m0SrezIKCRGuYPwoprOMOeW/G1snI5qRafo7sUWx96T51lYts47exGitZnoasvjUTA64EzGrQ+i" + + "MZyFo35Vf2gWQrR5xsnNL53coLQBtGVge2y4zskIbsPVRXQU0NbJ1EjXYSstqP2t+xHWS1oUzpjIC27OS/42n5cLRhZIk/7Gcl+1cashW9z2etP6oIrQEBkSX+mLTjn8rwsPDYNhjtIWu" + + "7TMl+piHLRp3P/GHFtGSrCLLtepZut5AFo01CVqJRVGay7ajZKlvYJ7wGfEzgwcxKdogg263meGYLNAPXo9COZM0ln2JQYwjq49styDTm0Ewv71dfAN+UTqZcma0GSchOw871sUPKx" + + "mqSAclaDLn9yOYZs2xqgOse5OQ9lKxzNYJEkYVV4tXIopmZSY3Bgeciy8ArY2Cy+A3J8nmkpwG5tI8l6xi0LJJs94Zku/lEox3Bh6chS6CmEJQsLE3qxcjWC/+eQiKMDyZrS8pYJd" + + "dsydV6dbJ8OT01EOX0aLKWpEs5xJEF5qy+Flm1tPolJAPh4WRNeRlUD3Fk1fBosj8i/VnX9g+x6rQC0IsfT/a8SWIeSZJDJNlqeMMxK9e+ggJ04ycgO1muOVeB+cqB53S/BVm1VkcSEGF8" + + "BrLzgvAQTZa9JVlhsCCEPz/3rcjKdySrTYEb5VdRb0V2eEeyjck25H6zopB9drLUqI5q7+xTtPGTk9XmNPzOu2b5YmSvSol09e9iQTXmRuHerXgvRnb8p2k7evt4st8jIxU/LOVVtt2UtW9h62XJGn" + + "cf8ixk9QPHLLPtZep8Lm1usnU2std8vqhBmyTfeBeyrW1pkvssi8xkeR9MVkHJmtbtWQ6yoQcoJCRb2XVR6+l0mcnicLIITNawbp9lFS90y25Cssy+sZT17qSZvGQ5zUqW5cupIHFGd2qytb1Olef" + + "NspLlNTBjNJJsZczGICnIDs4NpHuR5S7DsHVbFh6yXJ+yjDWPIrtYnlPJyVrOPxGKEbKV7DIjoNUPINu5dvkztzvgIsvHeIDAPJCsVBQeIYol6zgAheptZNcZWrADKH/M/VnruYt/Ljzbr0B" + + "lfPMNumCyfBHmoTiArFQCeLjMNrKxZyVBFs9M8UwY3NlePNsJJBjwItxdkcbZrDayhvSk9Rl7ZrK8E6Ghv1iyJDKnfMN5UAC4ycgq95DQTlVoIwvaD2UgWzEUseMmlqyMzCkPSCw" + + "zzuNyH7LCY+1Tl/kSQnZliC3JVqyNSxeNJTvkJOtaX6oZz09W+maVxuXSBpFdatQ5Wd1EJ7I8J1n3mZJ1xzOTVb6IqXaFtcPICkdQkG7IUHpOst7DBxuSlazwNh11RBjDyC6ma+he" + + "G+GL+T0rWe/R1UjmI6v9mbbK8YtAsjiGLPZG1J+W7DAwEbxDLBHZxr98JR2jOpBsG0yWKkBg7onJHsdOG5jknIgsBcxjwu4WBZJFwWQFpPGemqzT5je5HWnIApTxTR3zh5AFZSTEkuX7k" + + "PXAZfPgYqJ9PQBlfFPHOJgswozMA0oRZJuMZEnkHumoT1tZ4S63hCZZEahg64fCqhetZIW6DrZKhJN1H7eYjizLGF0MgIsykGWwPWjYWlUbWWn+CYSsUJwFquMMaz3OHJcNn6OrWO3rREn" + + "ItrDELm7Vi4CVdx1C9jLUq0B1HEsW5VvFc7XmKtu5SU4WqIyvC32mXgwgS+Bk70GZNixBLGVORU8bRiq3q7X5E5KLz4rR5GQ76IbgztYDUpJVlXGcAzpewjwoigGZhgk+DtrY1XEKsjVU3XGb" + + "1k5HlpK1mw3NAo4ka5jxalDCUorPvrZWDysBWQ73GGuLS5uOrLZ36UzRRQJYQs5HVuYk24HdiutPu3xkkd3s8qvjKLKVCLKHU5OdaYxRLX2Pi1QsNvaAlfHN2BD5yGpj1BOQTwH7MWxfDxl2J" + + "As6kzxuzMqQDUWtOWkmGVnpsjB8kx8KJ8vrwIyc5GS7fGQVXBnf7EiVjaxzGupSk+Uq8/5ZiOeTj6wI2SlWmbtBNrKzTTd1KrLofH52a1kzrd6E7HVUCAQTalTd+ciqAHUMJrt9wfAVyMK/EO" + + "rwLfORlQG72dKQRe9ClsaQXWqsfGRn6lgUsnCyOgrs0srISBYDN/UsXMN4svRNyDZxZOvdyHLgRrxBC/82SdCpQfwJyCaIVMQp42X1M5KdjUS7Oq5af2YRkGz3FmM2Uhkvmy0n2Q4SHjIm4q/D" + + "vyCy4i3ItrFkxW5kOWT9vQaZ8MDzjdkbkK36aNF7kZ1Ro/7gq8tNgpGl8vXJsniyzW5k/elQBJqfBvyOwI6reLnItvFkZ0tdWcn606EQ1DmFftWlfnWyG5TxfDbKStabDkXASaV7fz2NTeKyck+y" + + "3RayaDeyzGPezHxy1CC7EfWE38XLQ7beQnbq0uYlW/XudCi6SGDira3EJ/zGlnF9duvuD74J7NSjx36fYQPZuTlQORYNbqZPa2lQlHLIpjkrFUPGbOh33rttZIX59XBA3wSSdadDkTURbnkdFG5CJ" + + "COr/J54m4rsNmU8jc9jv13ZbiDrznDqDH0NbSELPfoyjKxwLY97chc/WBBZuRHsxAMhXlUm+y1knelQ2FAu3kA24ZeYmK/DzKOidrL3iR9EVm0lS81kTX7+vAYqlKx2Rex1PFmBSTVU8+8JwE+Y3n" + + "5W6iLcPRsTh8n/Pu5VA5EVW8lOjAJPhr2sHaspALIzdVxbmy+QLB2betxhE3AK8eazUpenV8yGxEFNyd4aFUJ2szKezvi1a1cMb6wTNJSsSx1XTrLaSnauW7rAxEUY2dV2u/F15Or4wflMfNAzssd7G" + + "SHkP+Qu4+XPxMp42smWhZ13sp2pkq71ZC1AyBLXhCVcZLmN7HLSYAFrAWCyhsB8fQlJudzI7xcn9S//WakX+WfuztIEZLshxjXG4WSd6VDKQVbYIhViZQ1w3IUd9Q8gWwVMeYvwyGFi9FtPILnIH2nW3" + + "M2R8ya6BjCyypEOxR1kOxvZ0I+sRK4I6Bir5Va6iCLbpCA7tnEFVwFsiCArXXkwjZXsohehwNWcBGs94HZu1qWTKLI0CVkVbpA1QwxZpzq+fUJiTbazreJ1e5GNXhM+TKoRQpYlATttYxYJFkjWpY5vz16" + + "RRdZWlruRhY3atjKW3oSTbdOQnU4OkgYN8kCy7nQoZSS7GgcI8KDkZNefoAcFNA+TioSQTQR2vsnY212EHmLJetKhlIHsOmLyGLLzZUXTUje3l34+Z/URY3be2YhzUrEc6wEk27nToTRdkl1/sWAkS3cle9Rn" + + "DpVsO994EqkKIctRErArfUesXUbYvEUgWV92atXMyArmsmaanckeX68zH9xmOpP8a7HGfvj19+dVvn1+ri9/3X53ZaCuWyZvURGgNKe9p5dLZVKuFWtWy4Oi7ewmC56Ic7qa/M5o2vLxdQhz2ql1tTvZ88jVWI0" + + "NqbCWwNIPodky+YQTcoPg+1LVnsIur6TTlJa3QZ+U7G8hhWwhW8gWsoVsIVvIFrJFCtkihWwhW8gWsoXs70L2y3j95fljkecnW6SQLVLIFilkC9kihWyRQrZIIVukkC0SIv8XYADBmU9ntNClogAAAABJRU5ErkJggg=="; +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/util/UserPrefs.java b/src/main/java/org/seagrid/desktop/util/UserPrefs.java new file mode 100644 index 0000000..2fa463d --- /dev/null +++ b/src/main/java/org/seagrid/desktop/util/UserPrefs.java @@ -0,0 +1,72 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.util; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.Serializable; + +public class UserPrefs implements Serializable{ + private static final long serialVersionUID = 1L; + + private final static Logger logger = LoggerFactory.getLogger(UserPrefs.class); + + private String userName = ""; + + private String password = ""; + + private boolean rememberPassword = false; + + private String lastApplicationId = null; + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public boolean isRememberPassword() { + return rememberPassword; + } + + public void setRememberPassword(boolean rememberPassword) { + this.rememberPassword = rememberPassword; + } + + public String getLastApplicationId() { + return lastApplicationId; + } + + public void setLastApplicationId(String lastApplicationId) { + this.lastApplicationId = lastApplicationId; + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/util/date/DateUtil.java b/src/main/java/org/seagrid/desktop/util/date/DateUtil.java new file mode 100644 index 0000000..e087fd3 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/util/date/DateUtil.java @@ -0,0 +1,37 @@ +package org.seagrid.desktop.util.date; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +/** + * Helper functions for handling dates. + * + */ +public class DateUtil { + + private static final String DATE_PATTERN = "dd.MM.yyyy"; + + private static final DateTimeFormatter DATE_FORMATTER = + DateTimeFormatter.ofPattern(DATE_PATTERN); + + public static String format(LocalDate date) { + if (date == null) { + return null; + } + return DATE_FORMATTER.format(date); + } + + public static LocalDate parse(String dateString) { + try { + return DATE_FORMATTER.parse(dateString, LocalDate::from); + } catch (DateTimeParseException e) { + return null; + } + } + + public static boolean validDate(String dateString) { + // Try to parse the String. + return DateUtil.parse(dateString) != null; + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/util/date/LocalDateAdapter.java b/src/main/java/org/seagrid/desktop/util/date/LocalDateAdapter.java new file mode 100644 index 0000000..6c2e180 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/util/date/LocalDateAdapter.java @@ -0,0 +1,18 @@ +package org.seagrid.desktop.util.date; + +import java.time.LocalDate; + +import javax.xml.bind.annotation.adapters.XmlAdapter; + +public class LocalDateAdapter extends XmlAdapter { + + @Override + public LocalDate unmarshal(String v) throws Exception { + return LocalDate.parse(v); + } + + @Override + public String marshal(LocalDate v) throws Exception { + return v.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/util/messaging/SEAGridEvent.java b/src/main/java/org/seagrid/desktop/util/messaging/SEAGridEvent.java new file mode 100644 index 0000000..90c5086 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/util/messaging/SEAGridEvent.java @@ -0,0 +1,59 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.util.messaging; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SEAGridEvent { + private final static Logger logger = LoggerFactory.getLogger(SEAGridEvent.class); + + public enum SEAGridEventType{ + EXPERIMENT_CREATED, FILE_DOWNLOADED, EXPERIMENT_LAUNCHED, EXPERIMENT_DELETED, FILE_UPLOADED, LOGOUT, + EXPERIMENT_CANCELLED, EXPERIMENT_EDIT_REQUEST, EXPERIMENT_UPDATED, EXPERIMENT_CLONED, EXPORT_GAUSSIAN_EXP, + EXPORT_GAMESS_EXP, EXPORT_NWCHEM_EXP, EXPORT_PSI4_EXP, EXPORT_MOLCAS_EXP, PROJECT_CREATED + } + + private SEAGridEventType eventType; + + private Object payload; + + public SEAGridEvent(SEAGridEventType eventType, Object payload){ + this.eventType = eventType; + this.payload = payload; + } + + public SEAGridEventType getEventType() { + return eventType; + } + + public void setEventType(SEAGridEventType eventType) { + this.eventType = eventType; + } + + public Object getPayload() { + return payload; + } + + public void setPayload(Object payload) { + this.payload = payload; + } +} \ No newline at end of file diff --git a/src/main/java/org/seagrid/desktop/util/messaging/SEAGridEventBus.java b/src/main/java/org/seagrid/desktop/util/messaging/SEAGridEventBus.java new file mode 100644 index 0000000..0cbaa23 --- /dev/null +++ b/src/main/java/org/seagrid/desktop/util/messaging/SEAGridEventBus.java @@ -0,0 +1,56 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +package org.seagrid.desktop.util.messaging; + +import com.google.common.eventbus.EventBus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SEAGridEventBus { + private final static Logger logger = LoggerFactory.getLogger(SEAGridEventBus.class); + + private static SEAGridEventBus instance; + + private EventBus eventBus; + + private SEAGridEventBus(){ + this.eventBus = new EventBus(); + } + + public static SEAGridEventBus getInstance(){ + if(SEAGridEventBus.instance == null){ + SEAGridEventBus.instance = new SEAGridEventBus(); + } + return SEAGridEventBus.instance; + } + + public void register(Object subscriber){ + eventBus.register(subscriber); + } + + public void unregister(Object subscriber){ + eventBus.unregister(subscriber); + } + + public void post(SEAGridEvent event){ + eventBus.post(event); + } +} \ No newline at end of file diff --git a/src/main/resources/.DS_Store b/src/main/resources/.DS_Store new file mode 100644 index 0000000..ab33c1e Binary files /dev/null and b/src/main/resources/.DS_Store differ diff --git a/src/main/resources/SEAGrid-icon-64x64.png b/src/main/resources/SEAGrid-icon-64x64.png new file mode 100644 index 0000000..417b557 Binary files /dev/null and b/src/main/resources/SEAGrid-icon-64x64.png differ diff --git a/src/main/resources/cct/.DS_Store b/src/main/resources/cct/.DS_Store new file mode 100644 index 0000000..e47ef9d Binary files /dev/null and b/src/main/resources/cct/.DS_Store differ diff --git a/src/main/resources/cct/._.DS_Store b/src/main/resources/cct/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/resources/cct/._.DS_Store differ diff --git a/src/main/resources/cct/CCTAtomTypes.properties b/src/main/resources/cct/CCTAtomTypes.properties new file mode 100644 index 0000000..88a94a0 --- /dev/null +++ b/src/main/resources/cct/CCTAtomTypes.properties @@ -0,0 +1,132 @@ + +H*baseElement=H +H*geometry=Terminal single + +Li*baseElement=Li +Li*geometry=Terminal single + +Be*baseElement=Be +Be*geometry=Linear Single-Single + +B*baseElement=B +B*geometry=Trigonal Planar (SSS) + +C.1*baseElement=C +C.1*geometry=Linear Single-Triple + +C.2*baseElement=C +C.2*geometry=Linear Double-Double + +C.3*baseElement=C +C.3*geometry=Trigonal Planar (DSS) + +C.4*baseElement=C +C.4*geometry=Tetrahedral (SSSS) +C.4*default=true + +N.1*baseElement=N +N.1*geometry=Terminal triple + +N.2*baseElement=N +N.2*geometry=Bended Single-Double + +N.3*baseElement=N +N.3*geometry=Trigonal Planar (DSS) + +N.4*baseElement=N +N.4*geometry=Tetrahedral (SSSLp) +N.4*default=true + +N.4+*baseElement=N +N.4+*geometry=Tetrahedral (SSSS) + +O.2*baseElement=O +O.2*geometry=Terminal double + +O.4*baseElement=O +O.4*geometry=Tetrahedral (SSLpLp) +O.4*default=true + + +F*baseElement=F +F*geometry=Terminal single + +Na*baseElement=Na +Na*geometry=Terminal single + +Mg*baseElement=Mg +Mg*geometry=Linear Single-Single + +Al*baseElement=Al +Al*geometry=Trigonal Planar (SSS) + +Si.1*baseElement=Si +Si.1*geometry=Linear Single-Triple + +Si.2*baseElement=Si +Si.2*geometry=Linear Double-Double + +Si.3*baseElement=Si +Si.3*geometry=Trigonal Planar (DSS) + +Si.4*baseElement=Si +Si.4*geometry=Tetrahedral (SSSS) +Si.4*default=true + +Si.6*baseElement=Si +Si.6*geometry=Trigonal bipyramid + +P.2*baseElement=P +P.2*geometry=Bended Single-Double + +P.3*baseElement=P +P.3*geometry=Trigonal Planar (SSS) + +P.4*baseElement=P +P.4*geometry=Tetrahedral (SSSLp) + +P.5*baseElement=P +P.5*geometry=Tetrahedral (SSSD) +P.5*default=true + +S.2*baseElement=S +S.2*geometry=Terminal double + +S.3*baseElement=S +S.3*geometry=Trigonal Planar (DSS) + +S.4*baseElement=S +S.4*geometry=Tetrahedral (SSLpLp) +S.4*default=true + +S.5*baseElement=S +S.5*geometry=Trigonal bipyramid + +S.6*baseElement=S +S.6*geometry=Tetrahedral (SSDD) + +S.o*baseElement=S +S.o*geometry=Octahedral + +Cl*baseElement=Cl +Cl*geometry=Terminal single +Cl*default=true + +K*baseElement=K +K*geometry=Terminal single + +Ca*baseElement=Ca +Ca*geometry=Linear Single-Single + +Sc*baseElement=Sc +Sc*geometry=Linear Single-Single +Sc*default=true + + +Br*baseElement=Br +Br*geometry=Terminal single +Br*default=true + +I*baseElement=I +I*geometry=Terminal single +I*default=true diff --git a/src/main/resources/cct/MessagesBundle.properties b/src/main/resources/cct/MessagesBundle.properties new file mode 100644 index 0000000..be6c322 --- /dev/null +++ b/src/main/resources/cct/MessagesBundle.properties @@ -0,0 +1,36 @@ +# +# +# Main Menu +file_menu = File +edit_menu = Edit +view_menu = View +calculate_menu = Calculate +grid_menu = Grid +analyze_menu = Analyze +tools_menu = Tools +analyze_menu = Analyze +setup_menu = Setup +help_menu = Help + +# Generic + +error = Error +errors_log = Errors Log +gaussian = Gaussian +mopac = Mopac + +# Open/save file related + +append_molecule_file = Append Molecule File +fetch_from_pdb = Fetch from PDB bank +load_from_sftp = Load from sftp server +load_graphics_object = Load Graphics Object +open_as = Open As +open_molecule_file = Open Molecule File +save_as = Save As +save_image = Save Image +save_image_as = Save Image As + + +seagrid_export= SEAGrid Export +seagrid_gaussian_export= Gaussian \ No newline at end of file diff --git a/src/main/resources/cct/MessagesBundle_ru_RU.properties b/src/main/resources/cct/MessagesBundle_ru_RU.properties new file mode 100644 index 0000000..81409e0 --- /dev/null +++ b/src/main/resources/cct/MessagesBundle_ru_RU.properties @@ -0,0 +1,13 @@ +# +# +# Main Menu +file_menu=\u0412\u0432\u043e\u0434/\u0412\u044b\u0432\u043e\u0434 +edit_menu = \u0420\u0435\u0434\u0430\u043a\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435 +view_menu = \u0412\u0438\u0437\u0443\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f +calculate_menu = \u0421\u0447\u0438\u0442\u0430\u0442\u044c +grid_menu = \u0413\u0440\u0438\u0434 +analyze_menu = Analyze +tools_menu = \u0418\u043d\u0441\u0442\u0440\u0443\u043c\u0435\u043d\u0442\u044b +analyze_menu = \u0410\u043d\u0430\u043b\u0438\u0437 +setup_menu = \u0423\u0441\u0442\u0430\u043d\u043e\u0432\u043a\u0438 +help_menu = \u0421\u043f\u0440\u0430\u0432\u043a\u0430 diff --git a/src/main/resources/cct/cct-config.xml b/src/main/resources/cct/cct-config.xml new file mode 100644 index 0000000..c219b5c --- /dev/null +++ b/src/main/resources/cct/cct-config.xml @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/cct/cct.properties b/src/main/resources/cct/cct.properties new file mode 100644 index 0000000..dbd46ea --- /dev/null +++ b/src/main/resources/cct/cct.properties @@ -0,0 +1,151 @@ +cct.tools.CCTParser.debug = true +cct.dialogs.JEditorFrame@redirectStderr = false + +moleculeInterfaceClass = cct.modelling.Molecule + +urlHomePage = http://sf.anu.edu.au/~vvv900/cct/appl/jmoleditor/index.html +helpEMail = vvv900@gmail.com + +! --- File format extensions + +extension_All_Formats = * +extension_ADF_Input = in;inp;dat;run +extension_ADF_Output = out;log +extension_G03_GJF = gjf;com;inp;dat;in;g03 +extension_G03_Output = log;out +extension_G03_Cube = cub;cube +extension_G03_Fragment = frg +extension_G03_Trajectory = trj;7;log;out +extension_G03_FormCheckpoint = fchk;fch +extension_GAMESS_Input = inp +extension_GAMESS_Output = out;log +extension_MOPAC_Input = dat;inp;mop +extension_MOPAC_Output = out +extension_MOPAC_Log = log +extension_PDB = pdb;ent;Z +extension_Geom = gf +extension_VRML = wrl +extension_Mol2 = mol2 +extension_CCT = cct +extension_XMol_XYZ = xyz +extension_MDL_Molfile = mol +extension_GRO = gro +extension_Prmtop = top;prmtop +extension_Prep = in;prepin;prep +extension_AmberLib = off;lib +extension_Ambercrd = crd;rst;inpcrd +extension_AmberTraj = crd;rst;mdcrd +extension_Povray = pov +extension_VASP_POSCAR = dat;inp;poscar +extension_VASP_Vasprun = xml +extension_QChem_Input = in +extension_QChem_Output = out;log +extension_GULP_Input = in;inp;gin;grs +extension_GULP_Trajectory = trg;trj +extension_SIESTA_Input = fdf;dat;inp;in +extension_CPMD_Output = out +extension_CPMD_Trajectory = xyz + +! --- format descriptions + +fformat_all = All Chemistry Format Files +fformat_adfInput = ADF Input +fformat_adfOutput = ADF Output +fformat_gaussian03GJF = Gaussian G03 Input +fformat_gaussian03Output = Gaussian G03 Output +fformat_gaussian03Cube = Geometry from G03 cube +fformat_gaussianFragment = Gaussian G03 Fragment +fformat_gaussianTrajectory = Gaussian G03 Trajectory +fformat_gaussianFormCheckpoint = Gaussian G03 Formatted Checkpoint +fformat_gamessInput = GAMESS Input +fformat_gamessOutput = GAMESS Output +fformat_geom = Geom Format File +fformat_vrml = VRML Format File +fformat_mopacInput = Mopac Input File +fformat_mopacLog = Mopac2002 Log File +fformat_mopacOutput = Mopac Output File +fformat_pdb = PDB +fformat_triposMol2 = Tripos Mol2 +fformat_cct = CCT File +fformat_xmolXYZ = XMol XYZ File +fformat_mdlMolfile = MDL Molfile File +fformat_gromacsGRO = Gromacs coordinate file +fformat_amberPrmtop = Amber prmtop file +fformat_amberPrep = Amber PREP file +fformat_amberLib = Amber Lib file +fformat_amberCoord = Amber coordinate/restart file +fformat_amberMdcrd = Amber trajectory file +fformat_povray = Povray file +fformat_vaspPoscar = VASP Poscar file +fformat_vaspVasprun = VASP Vasprun file +fformat_qchem = QChem Input file +fformat_qchemOutput = QChem Output file +fformat_gulpInput = GULP Input file +fformat_gulpTrajectory = GULP Trajectory file +fformat_siestaInput = SIESTA Input file +fformat_CPMDOutput = CPMD Output file +fformat_CPMDTrajectory = CPMD MD Trajectory file + +! --- Database related + +cct.dialogs.JEditorFrame@enableDatabase = false +cct.dialogs.JamberooFrame@enableDatabase = true + +database.create.script = jamberoo.sql + +jdbc.drivers = mysql sqlite + +jdbc.mysql.driver = com.mysql.jdbc.Driver +jdbc.mysql.use_host = true +jdbc.mysql.default_host = localhost +jdbc.mysql.use_port = true +jdbc.mysql.default_port = 3306 +jdbc.mysql.use_user = true +jdbc.mysql.default_user = jamberoo +jdbc.mysql.use_password = true +jdbc.mysql.default_password = jamberoo +jdbc.mysql.default_database = jamberoo + +jdbc.sqlite.driver = org.sqlite.JDBC +jdbc.sqlite.use_host = false +jdbc.sqlite.default_host = +jdbc.sqlite.use_port = false +jdbc.sqlite.default_port = +jdbc.sqlite.use_user = false +jdbc.sqlite.default_user = +jdbc.sqlite.use_password = false +jdbc.sqlite.default_password = +jdbc.sqlite.default_database = jamberoo.db + +! --- Povray related + +povray.template.movie.ini = ; Persistence Of Vision raytracer version 3.7 image sequence template file.\n\ + Antialias=On\n\ + \n\ + Antialias_Threshold=0.1\n\ + Antialias_Depth=2\n\ + Input_File_Name=@@POVRAY-CONTROL-FILE@@\n\ + \n\ + Initial_Frame=1\n\ + Final_Frame=@@FRAMES@@\n\ + Initial_Clock=1\n\ + Final_Clock=@@FRAMES@@\n\ + \n\ + Cyclic_Animation=on\n\ + Pause_when_Done=off\n\ + \n\ + Output_File_Type=J\n\ + Width=1024\n\ + Height=768\n\ + +povray.template.movie.pov = #declare _DEBUG_ = true;\n\ + #declare AnimationLength = 20.0;\n\ + #declare AnimationClock = clock * AnimationLength;\n\ + #declare file = concat("@@PREFIX@@",str(frame_number,-6,0),".pov")\n\ + #ifdef (_DEBUG_)\n\ + #debug "\\n"\n\ + #debug concat("clock = ", str(clock,7,3)," Frame number: ",str(frame_number,0,0) , "\\n")\n\ + #debug concat("AnimationClock = ", str(AnimationClock,7,3), "\\n")\n\ + #debug concat("Rendering ", file, "\\n")\n\ + #end\n\ + #include file\n\ \ No newline at end of file diff --git a/src/main/resources/cct/custom.properties b/src/main/resources/cct/custom.properties new file mode 100644 index 0000000..3e47260 --- /dev/null +++ b/src/main/resources/cct/custom.properties @@ -0,0 +1,22 @@ +!cct.ssh.SSHPanel@defaultHost = titan.sapac.edu.au +!cct.ssh.SSHPanel@defaultHost = vu.nci.org.au +!cct.ssh.SSHPanel@hostEditable = true + +!cct.grid.ui.PBSPanel@enableExtensions = false +!;cct.grid.ui.PBSPanel@enableEditExtensions = false +!cct.grid.ui.PBSPanel@defaultQueue = titan +cct.grid.ui.PBSPanel@defaultQueue = corvus +!cct.grid.ui.PBSPanel@enableEditQueue = false + +cct.ssh.SSHServiceProvider@jobKillCommand = bash --login -c '/opt/shared/torque/2.5.1/bin/qdel %s' +#cct.ssh.SSHServiceProvider@jobSubmitCommand = bash --login -c '/opt/shared/torque/2.5.1/bin/qsub-wrapper %s' +cct.ssh.SSHServiceProvider@jobSubmitCommand = bash --login -c '/opt/shared/torque/2.5.1/bin/qsub %s' +cct.ssh.SSHServiceProvider@jobStatusCommand = bash --login -c '/opt/shared/torque/2.5.1/bin/qstat -f %s' +!cct.ssh.SSHServiceProvider@jobKillCommand = qdel %s + +cct.grid.ui.gaussian.SubmitGaussianDialogNew@script = cct/g09-sample.txt + +custom-script@corvus.ersa.edu.au@g09 = g09-corvus-sample.txt +custom-script@corvus.ersa.edu.au@gamess = gamess-sample.txt +custom-script@titan.ersa.edu.au@g09 = g09-titan-sample.txt + diff --git a/src/main/resources/cct/formats.xml b/src/main/resources/cct/formats.xml new file mode 100644 index 0000000..9bf0375 --- /dev/null +++ b/src/main/resources/cct/formats.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/src/main/resources/cct/g09-sample.txt b/src/main/resources/cct/g09-sample.txt new file mode 100644 index 0000000..298a69d --- /dev/null +++ b/src/main/resources/cct/g09-sample.txt @@ -0,0 +1,21 @@ +#!/bin/csh +#PBS -N @@JOBNAME@@ +#PBS -q corvus +#PBS -l walltime=@@WALLTIME@@ +#PBS -l mem=@@MEMORY@@@@MEMORY-UNITS@@, vmem=@@MUL(2,@@MEMORY@@)@@@@MEMORY-UNITS@@ +#PBS -l other=jamberoo +#PBS -l ncpus=@@NCPUS@@ +#PBS -o @@STDOUT@@ +#PBS -e @@STDERR@@ + +module load dos2unix + +dos2unix @@INPUT@@ + +module load gaussian/G09 + +echo 'Running @@EXECUTABLE@@' +@@EXECUTABLE@@ <@@INPUT@@ >@@OUTPUT@@ + +echo 'Finish Running @@EXECUTABLE@@' + diff --git a/src/main/resources/cct/grid/grid-providers.properties b/src/main/resources/cct/grid/grid-providers.properties new file mode 100644 index 0000000..3249421 --- /dev/null +++ b/src/main/resources/cct/grid/grid-providers.properties @@ -0,0 +1,15 @@ + +ssh.provider = +ssh.name=Secure Shell Provider +ssh.TaskHandler=cct.ssh.SSHServiceProvider + +provider.ssh = cct.ssh.SSHServiceProvider + +;local.provider = +;local.name=Local Provider +;local.TaskHandler=cct.grid.LocalServiceProvider + +;provider.local = cct.grid.LocalServiceProvider + +;submitter.g03 = cct.grid.ui.gaussian.SubmitGaussianDialogNew executable =g03 +submitter.g09 = cct.grid.ui.gaussian.SubmitGaussianDialogNew executable = g09 diff --git a/src/main/resources/cct/html/Java-viewer.jpg b/src/main/resources/cct/html/Java-viewer.jpg new file mode 100644 index 0000000..97a7ca4 Binary files /dev/null and b/src/main/resources/cct/html/Java-viewer.jpg differ diff --git a/src/main/resources/cct/html/Molecule-in-window.gif b/src/main/resources/cct/html/Molecule-in-window.gif new file mode 100644 index 0000000..1565e1a Binary files /dev/null and b/src/main/resources/cct/html/Molecule-in-window.gif differ diff --git a/src/main/resources/cct/html/Open-file-dialog.gif b/src/main/resources/cct/html/Open-file-dialog.gif new file mode 100644 index 0000000..d89e427 Binary files /dev/null and b/src/main/resources/cct/html/Open-file-dialog.gif differ diff --git a/src/main/resources/cct/html/Portal.gif b/src/main/resources/cct/html/Portal.gif new file mode 100644 index 0000000..8e4405a Binary files /dev/null and b/src/main/resources/cct/html/Portal.gif differ diff --git a/src/main/resources/cct/html/Save_As.gif b/src/main/resources/cct/html/Save_As.gif new file mode 100644 index 0000000..1352640 Binary files /dev/null and b/src/main/resources/cct/html/Save_As.gif differ diff --git a/src/main/resources/cct/html/View-main-window.gif b/src/main/resources/cct/html/View-main-window.gif new file mode 100644 index 0000000..d39645f Binary files /dev/null and b/src/main/resources/cct/html/View-main-window.gif differ diff --git a/src/main/resources/cct/html/index.html b/src/main/resources/cct/html/index.html new file mode 100644 index 0000000..aa0e91c --- /dev/null +++ b/src/main/resources/cct/html/index.html @@ -0,0 +1,125 @@ + + + + + + + + Chemistryl Grid Portal + + + +
+

Chemistry Grid Project

+
+

+
+
+
+

This site reflects a progress in developing a Java Molecular Viewer which will provide an interface between a user and Chemistry Grid.

+

Amber Tools

+

Interaction with Chemistry Database

+

Builder can now parse Gaussian output files.

+

Selection, Add Atoms and Delete Atoms Dialogs are added

+

+

Slide show of internal ANUSF presentation is here.

+

Before starting a viewer

+
+ +
+

It's possible to use a Molecular builder either like a standalone program or like an applet in web browser.

+
    +
  • +

    Standalone program

    + +
+
+
    +
    +
  1. Download a program as a JAR file here. +
  2. To run it issue a command "java -jar mb.jar" in command prompt or double click in Windows Exlorer (MS Windows) +
  3. +
+
    +
    +
  • +

    Applet

    + +
  • +
+

Molecular Viewer is a Java Applet and by default it is not permitted to read/write from the local hard drive. To allow an applet to access your hard drive you need under the MS Windows

+
    +
  • To find a file java.policy in your Java installation directory (usually, c:\program\files\java\j2re1.4.2_06\lib\security). This file controls the privileges given to a trusted applet; +
  • Edit this file and add the following lines at the end: +
+

grant codeBase "http://anusf.anu.edu.au/~vvv900/-" {

+

permission java.io.FilePermission "X:\\Data\\-", "read,write";

+

};

+

The above means that an applet originated from the URL http://anusf.anu.edu.au/~vvv900 is entitled to the permission to read/write to a file residing in X:\Data\ or any subdirectory of X:\Data\ (which is the meaning of the hyphen). In this example, the local file system is a MS Windows one. The path name must be written with double backslashes ("\\") to mean a single backslash (the first backslash is an escape character).

+

Now you can start a viewer.

+

If everything is fine you shall see a new window:

+
+

+
+

The Molecular Builder commands are grouped in several main functional categories listed in the menubar across the top of the screen

+

Please, keep in mind that viewer is at the development stage, so not all menu items will work. To load a new molecule use "File" -> "Open As" menu item:

+
+

+
+

Now viewer can read files only in the Tripos mol2 and Gaussian gjf formats.

+

Invoking an "Open File" dialog

+
+

+
+

you can select a file and click "Open" button. A viewer will parse a file and show a molecule

+
+

+
+

All manipulations with molecular structures are accomplished by pressing mouse button and then moving the mouse. It is strongly advisable to use a three button mouse.

+

Rotation

+

Hold down the left mouse button and then move the mouse

+

Translation

+

Hold down the right mouse button and then move the mouse

+

Scaling (Zooming)

+

Hold down the middle mouse button and then move the mouse

+
+

Edit Menu

+ +

View Menu

+ +

General Naming Conventions and Operations

+ +
+

Send all questions and comments to Vlad (vvv900@sf.anu.edu.au)

+

Best wishes,

+

Dr. Vladislav Vasilyev

+

Supercomputer Facility, ANU,

+

Canberra

+ + + \ No newline at end of file diff --git a/src/main/resources/cct/html/newball.gif b/src/main/resources/cct/html/newball.gif new file mode 100644 index 0000000..0974c94 Binary files /dev/null and b/src/main/resources/cct/html/newball.gif differ diff --git a/src/main/resources/cct/images/.DS_Store b/src/main/resources/cct/images/.DS_Store new file mode 100644 index 0000000..df3d419 Binary files /dev/null and b/src/main/resources/cct/images/.DS_Store differ diff --git a/src/main/resources/cct/images/._.DS_Store b/src/main/resources/cct/images/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/resources/cct/images/._.DS_Store differ diff --git a/src/main/resources/cct/images/MDL-16x16.png b/src/main/resources/cct/images/MDL-16x16.png new file mode 100644 index 0000000..8c52978 Binary files /dev/null and b/src/main/resources/cct/images/MDL-16x16.png differ diff --git a/src/main/resources/cct/images/Thumbs.db b/src/main/resources/cct/images/Thumbs.db new file mode 100644 index 0000000..d347a52 Binary files /dev/null and b/src/main/resources/cct/images/Thumbs.db differ diff --git a/src/main/resources/cct/images/about-32x32.gif b/src/main/resources/cct/images/about-32x32.gif new file mode 100644 index 0000000..85bf0ef Binary files /dev/null and b/src/main/resources/cct/images/about-32x32.gif differ diff --git a/src/main/resources/cct/images/about.png b/src/main/resources/cct/images/about.png new file mode 100644 index 0000000..754005c Binary files /dev/null and b/src/main/resources/cct/images/about.png differ diff --git a/src/main/resources/cct/images/add-atom-16x16.png b/src/main/resources/cct/images/add-atom-16x16.png new file mode 100644 index 0000000..7b37a17 Binary files /dev/null and b/src/main/resources/cct/images/add-atom-16x16.png differ diff --git a/src/main/resources/cct/images/add-atom.gif b/src/main/resources/cct/images/add-atom.gif new file mode 100644 index 0000000..77ec190 Binary files /dev/null and b/src/main/resources/cct/images/add-atom.gif differ diff --git a/src/main/resources/cct/images/angle-16x16.gif b/src/main/resources/cct/images/angle-16x16.gif new file mode 100644 index 0000000..b8d781a Binary files /dev/null and b/src/main/resources/cct/images/angle-16x16.gif differ diff --git a/src/main/resources/cct/images/banned-by-gaussian-16x16.png b/src/main/resources/cct/images/banned-by-gaussian-16x16.png new file mode 100644 index 0000000..94237b0 Binary files /dev/null and b/src/main/resources/cct/images/banned-by-gaussian-16x16.png differ diff --git a/src/main/resources/cct/images/bond-16x16.gif b/src/main/resources/cct/images/bond-16x16.gif new file mode 100644 index 0000000..ef3a46f Binary files /dev/null and b/src/main/resources/cct/images/bond-16x16.gif differ diff --git a/src/main/resources/cct/images/closeFile.png b/src/main/resources/cct/images/closeFile.png new file mode 100644 index 0000000..81cc1a6 Binary files /dev/null and b/src/main/resources/cct/images/closeFile.png differ diff --git a/src/main/resources/cct/images/cut-16x16.gif b/src/main/resources/cct/images/cut-16x16.gif new file mode 100644 index 0000000..08cc4db Binary files /dev/null and b/src/main/resources/cct/images/cut-16x16.gif differ diff --git a/src/main/resources/cct/images/db-16x16.gif b/src/main/resources/cct/images/db-16x16.gif new file mode 100644 index 0000000..85bce37 Binary files /dev/null and b/src/main/resources/cct/images/db-16x16.gif differ diff --git a/src/main/resources/cct/images/disk_blue.png b/src/main/resources/cct/images/disk_blue.png new file mode 100644 index 0000000..8ed26bc Binary files /dev/null and b/src/main/resources/cct/images/disk_blue.png differ diff --git a/src/main/resources/cct/images/empty-transp-16x16.png b/src/main/resources/cct/images/empty-transp-16x16.png new file mode 100644 index 0000000..3a4b6c9 Binary files /dev/null and b/src/main/resources/cct/images/empty-transp-16x16.png differ diff --git a/src/main/resources/cct/images/gaussian-16x16.png b/src/main/resources/cct/images/gaussian-16x16.png new file mode 100644 index 0000000..45a7062 Binary files /dev/null and b/src/main/resources/cct/images/gaussian-16x16.png differ diff --git a/src/main/resources/cct/images/help.png b/src/main/resources/cct/images/help.png new file mode 100644 index 0000000..d7a33f8 Binary files /dev/null and b/src/main/resources/cct/images/help.png differ diff --git a/src/main/resources/cct/images/hummer-16x16.gif b/src/main/resources/cct/images/hummer-16x16.gif new file mode 100644 index 0000000..002fde9 Binary files /dev/null and b/src/main/resources/cct/images/hummer-16x16.gif differ diff --git a/src/main/resources/cct/images/icons16x16/307-web_download.png b/src/main/resources/cct/images/icons16x16/307-web_download.png new file mode 100644 index 0000000..d9011ee Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/307-web_download.png differ diff --git a/src/main/resources/cct/images/icons16x16/Configure.png b/src/main/resources/cct/images/icons16x16/Configure.png new file mode 100644 index 0000000..4ec407d Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/Configure.png differ diff --git a/src/main/resources/cct/images/icons16x16/Copy.png b/src/main/resources/cct/images/icons16x16/Copy.png new file mode 100644 index 0000000..1dafa89 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/Copy.png differ diff --git a/src/main/resources/cct/images/icons16x16/HyperChem-16x16.png b/src/main/resources/cct/images/icons16x16/HyperChem-16x16.png new file mode 100644 index 0000000..6bc19a9 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/HyperChem-16x16.png differ diff --git a/src/main/resources/cct/images/icons16x16/MDL-16x16.png b/src/main/resources/cct/images/icons16x16/MDL-16x16.png new file mode 100644 index 0000000..8c52978 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/MDL-16x16.png differ diff --git a/src/main/resources/cct/images/icons16x16/Paste.png b/src/main/resources/cct/images/icons16x16/Paste.png new file mode 100644 index 0000000..2b78344 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/Paste.png differ diff --git a/src/main/resources/cct/images/icons16x16/Preferences.png b/src/main/resources/cct/images/icons16x16/Preferences.png new file mode 100644 index 0000000..34df0d5 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/Preferences.png differ diff --git a/src/main/resources/cct/images/icons16x16/Refresh.png b/src/main/resources/cct/images/icons16x16/Refresh.png new file mode 100644 index 0000000..63e2d76 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/Refresh.png differ diff --git a/src/main/resources/cct/images/icons16x16/Thumbs.db b/src/main/resources/cct/images/icons16x16/Thumbs.db new file mode 100644 index 0000000..6d809d9 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/Thumbs.db differ diff --git a/src/main/resources/cct/images/icons16x16/Tip.png b/src/main/resources/cct/images/icons16x16/Tip.png new file mode 100644 index 0000000..5f6ad03 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/Tip.png differ diff --git a/src/main/resources/cct/images/icons16x16/Undo.png b/src/main/resources/cct/images/icons16x16/Undo.png new file mode 100644 index 0000000..50f352f Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/Undo.png differ diff --git a/src/main/resources/cct/images/icons16x16/about.png b/src/main/resources/cct/images/icons16x16/about.png new file mode 100644 index 0000000..1a36f54 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/about.png differ diff --git a/src/main/resources/cct/images/icons16x16/acrobat-file.png b/src/main/resources/cct/images/icons16x16/acrobat-file.png new file mode 100644 index 0000000..8492c61 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/acrobat-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/add-atom-16x16.png b/src/main/resources/cct/images/icons16x16/add-atom-16x16.png new file mode 100644 index 0000000..7b37a17 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/add-atom-16x16.png differ diff --git a/src/main/resources/cct/images/icons16x16/add-atom.gif b/src/main/resources/cct/images/icons16x16/add-atom.gif new file mode 100644 index 0000000..77ec190 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/add-atom.gif differ diff --git a/src/main/resources/cct/images/icons16x16/add-fragment.png b/src/main/resources/cct/images/icons16x16/add-fragment.png new file mode 100644 index 0000000..35c95c5 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/add-fragment.png differ diff --git a/src/main/resources/cct/images/icons16x16/addEntry.png b/src/main/resources/cct/images/icons16x16/addEntry.png new file mode 100644 index 0000000..0c242d5 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/addEntry.png differ diff --git a/src/main/resources/cct/images/icons16x16/adf-16x16.png b/src/main/resources/cct/images/icons16x16/adf-16x16.png new file mode 100644 index 0000000..24e00b2 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/adf-16x16.png differ diff --git a/src/main/resources/cct/images/icons16x16/angle-16x16.gif b/src/main/resources/cct/images/icons16x16/angle-16x16.gif new file mode 100644 index 0000000..b8d781a Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/angle-16x16.gif differ diff --git a/src/main/resources/cct/images/icons16x16/arrow-reload.png b/src/main/resources/cct/images/icons16x16/arrow-reload.png new file mode 100644 index 0000000..9e6df83 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/arrow-reload.png differ diff --git a/src/main/resources/cct/images/icons16x16/arrow-up.png b/src/main/resources/cct/images/icons16x16/arrow-up.png new file mode 100644 index 0000000..105cc2f Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/arrow-up.png differ diff --git a/src/main/resources/cct/images/icons16x16/at.png b/src/main/resources/cct/images/icons16x16/at.png new file mode 100644 index 0000000..59bb050 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/at.png differ diff --git a/src/main/resources/cct/images/icons16x16/atom.png b/src/main/resources/cct/images/icons16x16/atom.png new file mode 100644 index 0000000..9de4ee8 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/atom.png differ diff --git a/src/main/resources/cct/images/icons16x16/audio-file.png b/src/main/resources/cct/images/icons16x16/audio-file.png new file mode 100644 index 0000000..3f50676 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/audio-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/avi-file.png b/src/main/resources/cct/images/icons16x16/avi-file.png new file mode 100644 index 0000000..f19a796 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/avi-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/banned-by-gaussian-16x16.png b/src/main/resources/cct/images/icons16x16/banned-by-gaussian-16x16.png new file mode 100644 index 0000000..94237b0 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/banned-by-gaussian-16x16.png differ diff --git a/src/main/resources/cct/images/icons16x16/blue-arrow-down.png b/src/main/resources/cct/images/icons16x16/blue-arrow-down.png new file mode 100644 index 0000000..adfc4e4 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/blue-arrow-down.png differ diff --git a/src/main/resources/cct/images/icons16x16/blue-arrow-up.png b/src/main/resources/cct/images/icons16x16/blue-arrow-up.png new file mode 100644 index 0000000..5a56f11 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/blue-arrow-up.png differ diff --git a/src/main/resources/cct/images/icons16x16/bond-16x16.gif b/src/main/resources/cct/images/icons16x16/bond-16x16.gif new file mode 100644 index 0000000..ef3a46f Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/bond-16x16.gif differ diff --git a/src/main/resources/cct/images/icons16x16/bookmark.png b/src/main/resources/cct/images/icons16x16/bookmark.png new file mode 100644 index 0000000..42f0caf Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/bookmark.png differ diff --git a/src/main/resources/cct/images/icons16x16/bookmark_add.png b/src/main/resources/cct/images/icons16x16/bookmark_add.png new file mode 100644 index 0000000..22e449a Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/bookmark_add.png differ diff --git a/src/main/resources/cct/images/icons16x16/bookmark_delete.png b/src/main/resources/cct/images/icons16x16/bookmark_delete.png new file mode 100644 index 0000000..73baf98 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/bookmark_delete.png differ diff --git a/src/main/resources/cct/images/icons16x16/bookmark_down.png b/src/main/resources/cct/images/icons16x16/bookmark_down.png new file mode 100644 index 0000000..e550a34 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/bookmark_down.png differ diff --git a/src/main/resources/cct/images/icons16x16/bookmark_new.png b/src/main/resources/cct/images/icons16x16/bookmark_new.png new file mode 100644 index 0000000..a7c2158 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/bookmark_new.png differ diff --git a/src/main/resources/cct/images/icons16x16/bookmark_preferences.png b/src/main/resources/cct/images/icons16x16/bookmark_preferences.png new file mode 100644 index 0000000..8df2c64 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/bookmark_preferences.png differ diff --git a/src/main/resources/cct/images/icons16x16/bookmark_up.png b/src/main/resources/cct/images/icons16x16/bookmark_up.png new file mode 100644 index 0000000..dbd655a Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/bookmark_up.png differ diff --git a/src/main/resources/cct/images/icons16x16/bookmarks.png b/src/main/resources/cct/images/icons16x16/bookmarks.png new file mode 100644 index 0000000..2c01549 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/bookmarks.png differ diff --git a/src/main/resources/cct/images/icons16x16/bookmarks_preferences.png b/src/main/resources/cct/images/icons16x16/bookmarks_preferences.png new file mode 100644 index 0000000..a304e10 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/bookmarks_preferences.png differ diff --git a/src/main/resources/cct/images/icons16x16/bug_red.png b/src/main/resources/cct/images/icons16x16/bug_red.png new file mode 100644 index 0000000..cbaaf4f Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/bug_red.png differ diff --git a/src/main/resources/cct/images/icons16x16/c-file.png b/src/main/resources/cct/images/icons16x16/c-file.png new file mode 100644 index 0000000..6fa9a53 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/c-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/camera.png b/src/main/resources/cct/images/icons16x16/camera.png new file mode 100644 index 0000000..876e8ac Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/camera.png differ diff --git a/src/main/resources/cct/images/icons16x16/centroid.png b/src/main/resources/cct/images/icons16x16/centroid.png new file mode 100644 index 0000000..fabfad4 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/centroid.png differ diff --git a/src/main/resources/cct/images/icons16x16/certificate.png b/src/main/resources/cct/images/icons16x16/certificate.png new file mode 100644 index 0000000..e9cdf99 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/certificate.png differ diff --git a/src/main/resources/cct/images/icons16x16/certificate_add.png b/src/main/resources/cct/images/icons16x16/certificate_add.png new file mode 100644 index 0000000..0a0c8bc Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/certificate_add.png differ diff --git a/src/main/resources/cct/images/icons16x16/certificate_broken.png b/src/main/resources/cct/images/icons16x16/certificate_broken.png new file mode 100644 index 0000000..2f43c8a Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/certificate_broken.png differ diff --git a/src/main/resources/cct/images/icons16x16/certificate_delete.png b/src/main/resources/cct/images/icons16x16/certificate_delete.png new file mode 100644 index 0000000..0da2d7b Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/certificate_delete.png differ diff --git a/src/main/resources/cct/images/icons16x16/certificate_error.png b/src/main/resources/cct/images/icons16x16/certificate_error.png new file mode 100644 index 0000000..49e20d6 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/certificate_error.png differ diff --git a/src/main/resources/cct/images/icons16x16/certificate_information.png b/src/main/resources/cct/images/icons16x16/certificate_information.png new file mode 100644 index 0000000..62209d5 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/certificate_information.png differ diff --git a/src/main/resources/cct/images/icons16x16/certificate_new.png b/src/main/resources/cct/images/icons16x16/certificate_new.png new file mode 100644 index 0000000..72de320 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/certificate_new.png differ diff --git a/src/main/resources/cct/images/icons16x16/certificate_ok.png b/src/main/resources/cct/images/icons16x16/certificate_ok.png new file mode 100644 index 0000000..904d401 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/certificate_ok.png differ diff --git a/src/main/resources/cct/images/icons16x16/certificate_preferences.png b/src/main/resources/cct/images/icons16x16/certificate_preferences.png new file mode 100644 index 0000000..b842314 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/certificate_preferences.png differ diff --git a/src/main/resources/cct/images/icons16x16/certificate_refresh.png b/src/main/resources/cct/images/icons16x16/certificate_refresh.png new file mode 100644 index 0000000..c664330 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/certificate_refresh.png differ diff --git a/src/main/resources/cct/images/icons16x16/certificate_view.png b/src/main/resources/cct/images/icons16x16/certificate_view.png new file mode 100644 index 0000000..37926f1 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/certificate_view.png differ diff --git a/src/main/resources/cct/images/icons16x16/certificate_warning.png b/src/main/resources/cct/images/icons16x16/certificate_warning.png new file mode 100644 index 0000000..0539058 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/certificate_warning.png differ diff --git a/src/main/resources/cct/images/icons16x16/client_network.png b/src/main/resources/cct/images/icons16x16/client_network.png new file mode 100644 index 0000000..ee3c7f5 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/client_network.png differ diff --git a/src/main/resources/cct/images/icons16x16/clients.png b/src/main/resources/cct/images/icons16x16/clients.png new file mode 100644 index 0000000..a203f85 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/clients.png differ diff --git a/src/main/resources/cct/images/icons16x16/clipboard.png b/src/main/resources/cct/images/icons16x16/clipboard.png new file mode 100644 index 0000000..e450f11 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/clipboard.png differ diff --git a/src/main/resources/cct/images/icons16x16/clipboard_empty.png b/src/main/resources/cct/images/icons16x16/clipboard_empty.png new file mode 100644 index 0000000..58e9144 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/clipboard_empty.png differ diff --git a/src/main/resources/cct/images/icons16x16/clipboard_next.png b/src/main/resources/cct/images/icons16x16/clipboard_next.png new file mode 100644 index 0000000..1ffec49 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/clipboard_next.png differ diff --git a/src/main/resources/cct/images/icons16x16/clipboard_next_down.png b/src/main/resources/cct/images/icons16x16/clipboard_next_down.png new file mode 100644 index 0000000..30a2696 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/clipboard_next_down.png differ diff --git a/src/main/resources/cct/images/icons16x16/closeFile.png b/src/main/resources/cct/images/icons16x16/closeFile.png new file mode 100644 index 0000000..81cc1a6 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/closeFile.png differ diff --git a/src/main/resources/cct/images/icons16x16/component.png b/src/main/resources/cct/images/icons16x16/component.png new file mode 100644 index 0000000..e6b7c1d Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/component.png differ diff --git a/src/main/resources/cct/images/icons16x16/component_add.png b/src/main/resources/cct/images/icons16x16/component_add.png new file mode 100644 index 0000000..8209489 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/component_add.png differ diff --git a/src/main/resources/cct/images/icons16x16/compressed-transp.png b/src/main/resources/cct/images/icons16x16/compressed-transp.png new file mode 100644 index 0000000..e0f0e60 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/compressed-transp.png differ diff --git a/src/main/resources/cct/images/icons16x16/compressed.png b/src/main/resources/cct/images/icons16x16/compressed.png new file mode 100644 index 0000000..c74f488 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/compressed.png differ diff --git a/src/main/resources/cct/images/icons16x16/cpp-file.png b/src/main/resources/cct/images/icons16x16/cpp-file.png new file mode 100644 index 0000000..7c8bcec Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/cpp-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/cube_molecule.png b/src/main/resources/cct/images/icons16x16/cube_molecule.png new file mode 100644 index 0000000..f6771cf Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/cube_molecule.png differ diff --git a/src/main/resources/cct/images/icons16x16/cut-16x16.gif b/src/main/resources/cct/images/icons16x16/cut-16x16.gif new file mode 100644 index 0000000..08cc4db Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/cut-16x16.gif differ diff --git a/src/main/resources/cct/images/icons16x16/data.png b/src/main/resources/cct/images/icons16x16/data.png new file mode 100644 index 0000000..cb8f04d Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_add.png b/src/main/resources/cct/images/icons16x16/data_add.png new file mode 100644 index 0000000..8c21457 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_add.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_certificate.png b/src/main/resources/cct/images/icons16x16/data_certificate.png new file mode 100644 index 0000000..081fbfe Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_certificate.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_connection.png b/src/main/resources/cct/images/icons16x16/data_connection.png new file mode 100644 index 0000000..f31f7eb Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_connection.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_copy.png b/src/main/resources/cct/images/icons16x16/data_copy.png new file mode 100644 index 0000000..211fe81 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_copy.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_delete.png b/src/main/resources/cct/images/icons16x16/data_delete.png new file mode 100644 index 0000000..895f601 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_delete.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_disk.png b/src/main/resources/cct/images/icons16x16/data_disk.png new file mode 100644 index 0000000..09719cf Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_disk.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_down.png b/src/main/resources/cct/images/icons16x16/data_down.png new file mode 100644 index 0000000..1fc0854 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_down.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_edit.png b/src/main/resources/cct/images/icons16x16/data_edit.png new file mode 100644 index 0000000..a48cace Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_edit.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_error.png b/src/main/resources/cct/images/icons16x16/data_error.png new file mode 100644 index 0000000..d9f638b Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_error.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_find.png b/src/main/resources/cct/images/icons16x16/data_find.png new file mode 100644 index 0000000..0a0214b Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_find.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_forbidden.png b/src/main/resources/cct/images/icons16x16/data_forbidden.png new file mode 100644 index 0000000..3fcab1e Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_forbidden.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_gear.png b/src/main/resources/cct/images/icons16x16/data_gear.png new file mode 100644 index 0000000..0f37e97 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_gear.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_information.png b/src/main/resources/cct/images/icons16x16/data_information.png new file mode 100644 index 0000000..46959b4 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_information.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_into.png b/src/main/resources/cct/images/icons16x16/data_into.png new file mode 100644 index 0000000..45ee076 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_into.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_lock.png b/src/main/resources/cct/images/icons16x16/data_lock.png new file mode 100644 index 0000000..e2deeae Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_lock.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_new.png b/src/main/resources/cct/images/icons16x16/data_new.png new file mode 100644 index 0000000..33037e8 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_new.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_next.png b/src/main/resources/cct/images/icons16x16/data_next.png new file mode 100644 index 0000000..f3020be Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_next.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_ok.png b/src/main/resources/cct/images/icons16x16/data_ok.png new file mode 100644 index 0000000..4cfd9a5 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_ok.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_out.png b/src/main/resources/cct/images/icons16x16/data_out.png new file mode 100644 index 0000000..152bbf1 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_out.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_preferences.png b/src/main/resources/cct/images/icons16x16/data_preferences.png new file mode 100644 index 0000000..344643a Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_preferences.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_previous.png b/src/main/resources/cct/images/icons16x16/data_previous.png new file mode 100644 index 0000000..dcae65a Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_previous.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_refresh.png b/src/main/resources/cct/images/icons16x16/data_refresh.png new file mode 100644 index 0000000..e9c6dd9 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_refresh.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_replace.png b/src/main/resources/cct/images/icons16x16/data_replace.png new file mode 100644 index 0000000..e83d9aa Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_replace.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_scroll.png b/src/main/resources/cct/images/icons16x16/data_scroll.png new file mode 100644 index 0000000..1a3cbd7 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_scroll.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_table.png b/src/main/resources/cct/images/icons16x16/data_table.png new file mode 100644 index 0000000..92a03c1 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_table.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_time.png b/src/main/resources/cct/images/icons16x16/data_time.png new file mode 100644 index 0000000..a68d777 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_time.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_unknown.png b/src/main/resources/cct/images/icons16x16/data_unknown.png new file mode 100644 index 0000000..bd97f43 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_unknown.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_up.png b/src/main/resources/cct/images/icons16x16/data_up.png new file mode 100644 index 0000000..f163cf8 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_up.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_view.png b/src/main/resources/cct/images/icons16x16/data_view.png new file mode 100644 index 0000000..430e0d3 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_view.png differ diff --git a/src/main/resources/cct/images/icons16x16/data_warning.png b/src/main/resources/cct/images/icons16x16/data_warning.png new file mode 100644 index 0000000..0dcaed3 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/data_warning.png differ diff --git a/src/main/resources/cct/images/icons16x16/date-time.png b/src/main/resources/cct/images/icons16x16/date-time.png new file mode 100644 index 0000000..f228f24 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/date-time.png differ diff --git a/src/main/resources/cct/images/icons16x16/date-time_preferences.png b/src/main/resources/cct/images/icons16x16/date-time_preferences.png new file mode 100644 index 0000000..912c538 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/date-time_preferences.png differ diff --git a/src/main/resources/cct/images/icons16x16/db-16x16.gif b/src/main/resources/cct/images/icons16x16/db-16x16.gif new file mode 100644 index 0000000..85bce37 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/db-16x16.gif differ diff --git a/src/main/resources/cct/images/icons16x16/delete.png b/src/main/resources/cct/images/icons16x16/delete.png new file mode 100644 index 0000000..c13d669 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/delete.png differ diff --git a/src/main/resources/cct/images/icons16x16/delete2.png b/src/main/resources/cct/images/icons16x16/delete2.png new file mode 100644 index 0000000..069609d Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/delete2.png differ diff --git a/src/main/resources/cct/images/icons16x16/die.png b/src/main/resources/cct/images/icons16x16/die.png new file mode 100644 index 0000000..dd94263 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/die.png differ diff --git a/src/main/resources/cct/images/icons16x16/die_gold.png b/src/main/resources/cct/images/icons16x16/die_gold.png new file mode 100644 index 0000000..c5ab565 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/die_gold.png differ diff --git a/src/main/resources/cct/images/icons16x16/dihedral.png b/src/main/resources/cct/images/icons16x16/dihedral.png new file mode 100644 index 0000000..b28a090 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/dihedral.png differ diff --git a/src/main/resources/cct/images/icons16x16/disk_blue.png b/src/main/resources/cct/images/icons16x16/disk_blue.png new file mode 100644 index 0000000..8ed26bc Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/disk_blue.png differ diff --git a/src/main/resources/cct/images/icons16x16/disk_blue_error.png b/src/main/resources/cct/images/icons16x16/disk_blue_error.png new file mode 100644 index 0000000..a07e4e9 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/disk_blue_error.png differ diff --git a/src/main/resources/cct/images/icons16x16/disk_blue_information.png b/src/main/resources/cct/images/icons16x16/disk_blue_information.png new file mode 100644 index 0000000..1892307 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/disk_blue_information.png differ diff --git a/src/main/resources/cct/images/icons16x16/disk_blue_ok.png b/src/main/resources/cct/images/icons16x16/disk_blue_ok.png new file mode 100644 index 0000000..c6d3b97 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/disk_blue_ok.png differ diff --git a/src/main/resources/cct/images/icons16x16/disk_blue_warning.png b/src/main/resources/cct/images/icons16x16/disk_blue_warning.png new file mode 100644 index 0000000..7a63724 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/disk_blue_warning.png differ diff --git a/src/main/resources/cct/images/icons16x16/disk_blue_window.png b/src/main/resources/cct/images/icons16x16/disk_blue_window.png new file mode 100644 index 0000000..60a6029 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/disk_blue_window.png differ diff --git a/src/main/resources/cct/images/icons16x16/disk_green.png b/src/main/resources/cct/images/icons16x16/disk_green.png new file mode 100644 index 0000000..bb28ea8 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/disk_green.png differ diff --git a/src/main/resources/cct/images/icons16x16/disk_yellow.png b/src/main/resources/cct/images/icons16x16/disk_yellow.png new file mode 100644 index 0000000..cfd32d3 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/disk_yellow.png differ diff --git a/src/main/resources/cct/images/icons16x16/diskdrive.png b/src/main/resources/cct/images/icons16x16/diskdrive.png new file mode 100644 index 0000000..a75da78 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/diskdrive.png differ diff --git a/src/main/resources/cct/images/icons16x16/disks.png b/src/main/resources/cct/images/icons16x16/disks.png new file mode 100644 index 0000000..6975998 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/disks.png differ diff --git a/src/main/resources/cct/images/icons16x16/divx-file.png b/src/main/resources/cct/images/icons16x16/divx-file.png new file mode 100644 index 0000000..163ab01 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/divx-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/djvu-file.png b/src/main/resources/cct/images/icons16x16/djvu-file.png new file mode 100644 index 0000000..218cfb3 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/djvu-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/document.png b/src/main/resources/cct/images/icons16x16/document.png new file mode 100644 index 0000000..768be13 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_add.png b/src/main/resources/cct/images/icons16x16/document_add.png new file mode 100644 index 0000000..cc47d9a Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_add.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_attachment.png b/src/main/resources/cct/images/icons16x16/document_attachment.png new file mode 100644 index 0000000..9258403 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_attachment.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_certificate.png b/src/main/resources/cct/images/icons16x16/document_certificate.png new file mode 100644 index 0000000..071b77e Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_certificate.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_chart.png b/src/main/resources/cct/images/icons16x16/document_chart.png new file mode 100644 index 0000000..fa4f179 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_chart.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_check.png b/src/main/resources/cct/images/icons16x16/document_check.png new file mode 100644 index 0000000..d999cee Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_check.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_connection.png b/src/main/resources/cct/images/icons16x16/document_connection.png new file mode 100644 index 0000000..5a3a7a8 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_connection.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_cup.png b/src/main/resources/cct/images/icons16x16/document_cup.png new file mode 100644 index 0000000..b2af09b Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_cup.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_delete.png b/src/main/resources/cct/images/icons16x16/document_delete.png new file mode 100644 index 0000000..3a16b95 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_delete.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_dirty.png b/src/main/resources/cct/images/icons16x16/document_dirty.png new file mode 100644 index 0000000..17afe8c Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_dirty.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_edit.png b/src/main/resources/cct/images/icons16x16/document_edit.png new file mode 100644 index 0000000..01890bc Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_edit.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_error.png b/src/main/resources/cct/images/icons16x16/document_error.png new file mode 100644 index 0000000..477151f Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_error.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_exchange.png b/src/main/resources/cct/images/icons16x16/document_exchange.png new file mode 100644 index 0000000..7aa0cd5 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_exchange.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_find.png b/src/main/resources/cct/images/icons16x16/document_find.png new file mode 100644 index 0000000..bfa0b92 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_find.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_gear.png b/src/main/resources/cct/images/icons16x16/document_gear.png new file mode 100644 index 0000000..0c4bf96 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_gear.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_heart.png b/src/main/resources/cct/images/icons16x16/document_heart.png new file mode 100644 index 0000000..66ee4ca Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_heart.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_info.png b/src/main/resources/cct/images/icons16x16/document_info.png new file mode 100644 index 0000000..4c4c77b Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_info.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_into.png b/src/main/resources/cct/images/icons16x16/document_into.png new file mode 100644 index 0000000..fb01938 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_into.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_lock.png b/src/main/resources/cct/images/icons16x16/document_lock.png new file mode 100644 index 0000000..104d888 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_lock.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_music.png b/src/main/resources/cct/images/icons16x16/document_music.png new file mode 100644 index 0000000..bc65f16 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_music.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_new.png b/src/main/resources/cct/images/icons16x16/document_new.png new file mode 100644 index 0000000..8bb3b3e Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_new.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_notebook.png b/src/main/resources/cct/images/icons16x16/document_notebook.png new file mode 100644 index 0000000..3be2d4f Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_notebook.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_ok.png b/src/main/resources/cct/images/icons16x16/document_ok.png new file mode 100644 index 0000000..50c983c Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_ok.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_out.png b/src/main/resources/cct/images/icons16x16/document_out.png new file mode 100644 index 0000000..efc0e0d Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_out.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_pinned.png b/src/main/resources/cct/images/icons16x16/document_pinned.png new file mode 100644 index 0000000..771abb8 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_pinned.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_plain.png b/src/main/resources/cct/images/icons16x16/document_plain.png new file mode 100644 index 0000000..8104358 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_plain.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_plain_new.png b/src/main/resources/cct/images/icons16x16/document_plain_new.png new file mode 100644 index 0000000..cce90df Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_plain_new.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_preferences.png b/src/main/resources/cct/images/icons16x16/document_preferences.png new file mode 100644 index 0000000..8a4764e Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_preferences.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_pulse.png b/src/main/resources/cct/images/icons16x16/document_pulse.png new file mode 100644 index 0000000..0cc859b Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_pulse.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_refresh.png b/src/main/resources/cct/images/icons16x16/document_refresh.png new file mode 100644 index 0000000..a12aa8b Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_refresh.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_stop.png b/src/main/resources/cct/images/icons16x16/document_stop.png new file mode 100644 index 0000000..0e9501b Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_stop.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_text.png b/src/main/resources/cct/images/icons16x16/document_text.png new file mode 100644 index 0000000..790de20 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_text.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_time.png b/src/main/resources/cct/images/icons16x16/document_time.png new file mode 100644 index 0000000..8961117 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_time.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_view.png b/src/main/resources/cct/images/icons16x16/document_view.png new file mode 100644 index 0000000..3ae2413 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_view.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_warning.png b/src/main/resources/cct/images/icons16x16/document_warning.png new file mode 100644 index 0000000..80d2113 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_warning.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_zoom_in.png b/src/main/resources/cct/images/icons16x16/document_zoom_in.png new file mode 100644 index 0000000..44809fd Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_zoom_in.png differ diff --git a/src/main/resources/cct/images/icons16x16/document_zoom_out.png b/src/main/resources/cct/images/icons16x16/document_zoom_out.png new file mode 100644 index 0000000..cc7240b Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/document_zoom_out.png differ diff --git a/src/main/resources/cct/images/icons16x16/documents.png b/src/main/resources/cct/images/icons16x16/documents.png new file mode 100644 index 0000000..330aca9 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/documents.png differ diff --git a/src/main/resources/cct/images/icons16x16/documents_gear.png b/src/main/resources/cct/images/icons16x16/documents_gear.png new file mode 100644 index 0000000..d3dc5fa Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/documents_gear.png differ diff --git a/src/main/resources/cct/images/icons16x16/documents_new.png b/src/main/resources/cct/images/icons16x16/documents_new.png new file mode 100644 index 0000000..e05bcb6 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/documents_new.png differ diff --git a/src/main/resources/cct/images/icons16x16/documents_preferences.png b/src/main/resources/cct/images/icons16x16/documents_preferences.png new file mode 100644 index 0000000..f1cf620 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/documents_preferences.png differ diff --git a/src/main/resources/cct/images/icons16x16/door2.gif b/src/main/resources/cct/images/icons16x16/door2.gif new file mode 100644 index 0000000..8c268c4 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/door2.gif differ diff --git a/src/main/resources/cct/images/icons16x16/empty-transp-16x16.png b/src/main/resources/cct/images/icons16x16/empty-transp-16x16.png new file mode 100644 index 0000000..3a4b6c9 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/empty-transp-16x16.png differ diff --git a/src/main/resources/cct/images/icons16x16/error.png b/src/main/resources/cct/images/icons16x16/error.png new file mode 100644 index 0000000..03c373c Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/error.png differ diff --git a/src/main/resources/cct/images/icons16x16/file_delete.png b/src/main/resources/cct/images/icons16x16/file_delete.png new file mode 100644 index 0000000..771be33 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/file_delete.png differ diff --git a/src/main/resources/cct/images/icons16x16/first_aid.png b/src/main/resources/cct/images/icons16x16/first_aid.png new file mode 100644 index 0000000..41d0dab Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/first_aid.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder.png b/src/main/resources/cct/images/icons16x16/folder.png new file mode 100644 index 0000000..37f00a9 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_add.png b/src/main/resources/cct/images/icons16x16/folder_add.png new file mode 100644 index 0000000..0ec3b1a Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_add.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_closed.png b/src/main/resources/cct/images/icons16x16/folder_closed.png new file mode 100644 index 0000000..078e85e Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_closed.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_cubes.png b/src/main/resources/cct/images/icons16x16/folder_cubes.png new file mode 100644 index 0000000..171700f Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_cubes.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_delete.png b/src/main/resources/cct/images/icons16x16/folder_delete.png new file mode 100644 index 0000000..8eb2e94 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_delete.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_document.png b/src/main/resources/cct/images/icons16x16/folder_document.png new file mode 100644 index 0000000..5bd2bbd Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_document.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_edit.png b/src/main/resources/cct/images/icons16x16/folder_edit.png new file mode 100644 index 0000000..c873e99 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_edit.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_forbidden.png b/src/main/resources/cct/images/icons16x16/folder_forbidden.png new file mode 100644 index 0000000..587642a Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_forbidden.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_gear.png b/src/main/resources/cct/images/icons16x16/folder_gear.png new file mode 100644 index 0000000..ba12025 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_gear.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_information.png b/src/main/resources/cct/images/icons16x16/folder_information.png new file mode 100644 index 0000000..97cde82 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_information.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_into.png b/src/main/resources/cct/images/icons16x16/folder_into.png new file mode 100644 index 0000000..2c8046b Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_into.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_lock.png b/src/main/resources/cct/images/icons16x16/folder_lock.png new file mode 100644 index 0000000..2923189 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_lock.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_movie.png b/src/main/resources/cct/images/icons16x16/folder_movie.png new file mode 100644 index 0000000..b05e5f2 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_movie.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_music.png b/src/main/resources/cct/images/icons16x16/folder_music.png new file mode 100644 index 0000000..ffb2d6a Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_music.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_network.png b/src/main/resources/cct/images/icons16x16/folder_network.png new file mode 100644 index 0000000..54e3ce8 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_network.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_new.png b/src/main/resources/cct/images/icons16x16/folder_new.png new file mode 100644 index 0000000..e162b3e Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_new.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_ok.png b/src/main/resources/cct/images/icons16x16/folder_ok.png new file mode 100644 index 0000000..88df8db Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_ok.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_out.png b/src/main/resources/cct/images/icons16x16/folder_out.png new file mode 100644 index 0000000..bc429a3 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_out.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_preferences.png b/src/main/resources/cct/images/icons16x16/folder_preferences.png new file mode 100644 index 0000000..54078f3 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_preferences.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_refresh.png b/src/main/resources/cct/images/icons16x16/folder_refresh.png new file mode 100644 index 0000000..4b28335 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_refresh.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_time.png b/src/main/resources/cct/images/icons16x16/folder_time.png new file mode 100644 index 0000000..0ed79ed Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_time.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_up.png b/src/main/resources/cct/images/icons16x16/folder_up.png new file mode 100644 index 0000000..5cec06a Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_up.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_view.png b/src/main/resources/cct/images/icons16x16/folder_view.png new file mode 100644 index 0000000..151eded Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_view.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_warning.png b/src/main/resources/cct/images/icons16x16/folder_warning.png new file mode 100644 index 0000000..d337b76 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_warning.png differ diff --git a/src/main/resources/cct/images/icons16x16/folder_window.png b/src/main/resources/cct/images/icons16x16/folder_window.png new file mode 100644 index 0000000..5380853 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folder_window.png differ diff --git a/src/main/resources/cct/images/icons16x16/folders.png b/src/main/resources/cct/images/icons16x16/folders.png new file mode 100644 index 0000000..8f59b67 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/folders.png differ diff --git a/src/main/resources/cct/images/icons16x16/garbage.png b/src/main/resources/cct/images/icons16x16/garbage.png new file mode 100644 index 0000000..fa6a61d Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/garbage.png differ diff --git a/src/main/resources/cct/images/icons16x16/gaussian-16x16.png b/src/main/resources/cct/images/icons16x16/gaussian-16x16.png new file mode 100644 index 0000000..45a7062 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/gaussian-16x16.png differ diff --git a/src/main/resources/cct/images/icons16x16/gaussian-cube-16x16.png b/src/main/resources/cct/images/icons16x16/gaussian-cube-16x16.png new file mode 100644 index 0000000..fa0a040 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/gaussian-cube-16x16.png differ diff --git a/src/main/resources/cct/images/icons16x16/gear.png b/src/main/resources/cct/images/icons16x16/gear.png new file mode 100644 index 0000000..4ed6f68 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/gear.png differ diff --git a/src/main/resources/cct/images/icons16x16/getHelpOn.png b/src/main/resources/cct/images/icons16x16/getHelpOn.png new file mode 100644 index 0000000..f0f1540 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/getHelpOn.png differ diff --git a/src/main/resources/cct/images/icons16x16/gromacs-16x16.png b/src/main/resources/cct/images/icons16x16/gromacs-16x16.png new file mode 100644 index 0000000..9066eb1 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/gromacs-16x16.png differ diff --git a/src/main/resources/cct/images/icons16x16/gulp-16x16.png b/src/main/resources/cct/images/icons16x16/gulp-16x16.png new file mode 100644 index 0000000..e73a494 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/gulp-16x16.png differ diff --git a/src/main/resources/cct/images/icons16x16/header-file.png b/src/main/resources/cct/images/icons16x16/header-file.png new file mode 100644 index 0000000..0d6f561 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/header-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/help-file.png b/src/main/resources/cct/images/icons16x16/help-file.png new file mode 100644 index 0000000..e9e9c9c Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/help-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/help.png b/src/main/resources/cct/images/icons16x16/help.png new file mode 100644 index 0000000..caa455d Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/help.png differ diff --git a/src/main/resources/cct/images/icons16x16/help2.png b/src/main/resources/cct/images/icons16x16/help2.png new file mode 100644 index 0000000..b7079d1 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/help2.png differ diff --git a/src/main/resources/cct/images/icons16x16/html-file.png b/src/main/resources/cct/images/icons16x16/html-file.png new file mode 100644 index 0000000..e13accd Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/html-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/hummer-16x16.gif b/src/main/resources/cct/images/icons16x16/hummer-16x16.gif new file mode 100644 index 0000000..002fde9 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/hummer-16x16.gif differ diff --git a/src/main/resources/cct/images/icons16x16/icc-file.png b/src/main/resources/cct/images/icons16x16/icc-file.png new file mode 100644 index 0000000..27ccaa4 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/icc-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/ico-file.png b/src/main/resources/cct/images/icons16x16/ico-file.png new file mode 100644 index 0000000..c466073 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/ico-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/image-file.png b/src/main/resources/cct/images/icons16x16/image-file.png new file mode 100644 index 0000000..2ea5fe2 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/image-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/importObject.png b/src/main/resources/cct/images/icons16x16/importObject.png new file mode 100644 index 0000000..325ec84 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/importObject.png differ diff --git a/src/main/resources/cct/images/icons16x16/java-file.png b/src/main/resources/cct/images/icons16x16/java-file.png new file mode 100644 index 0000000..abfb646 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/java-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/layout_center.png b/src/main/resources/cct/images/icons16x16/layout_center.png new file mode 100644 index 0000000..0df1232 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/layout_center.png differ diff --git a/src/main/resources/cct/images/icons16x16/layout_east.png b/src/main/resources/cct/images/icons16x16/layout_east.png new file mode 100644 index 0000000..8833a3e Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/layout_east.png differ diff --git a/src/main/resources/cct/images/icons16x16/layout_horizontal.png b/src/main/resources/cct/images/icons16x16/layout_horizontal.png new file mode 100644 index 0000000..9c0d062 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/layout_horizontal.png differ diff --git a/src/main/resources/cct/images/icons16x16/layout_north.png b/src/main/resources/cct/images/icons16x16/layout_north.png new file mode 100644 index 0000000..670cc6c Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/layout_north.png differ diff --git a/src/main/resources/cct/images/icons16x16/layout_northeast.png b/src/main/resources/cct/images/icons16x16/layout_northeast.png new file mode 100644 index 0000000..82a746b Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/layout_northeast.png differ diff --git a/src/main/resources/cct/images/icons16x16/layout_northwest.png b/src/main/resources/cct/images/icons16x16/layout_northwest.png new file mode 100644 index 0000000..d34874d Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/layout_northwest.png differ diff --git a/src/main/resources/cct/images/icons16x16/layout_south.png b/src/main/resources/cct/images/icons16x16/layout_south.png new file mode 100644 index 0000000..ceece64 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/layout_south.png differ diff --git a/src/main/resources/cct/images/icons16x16/layout_southeast.png b/src/main/resources/cct/images/icons16x16/layout_southeast.png new file mode 100644 index 0000000..21e281b Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/layout_southeast.png differ diff --git a/src/main/resources/cct/images/icons16x16/layout_southwest.png b/src/main/resources/cct/images/icons16x16/layout_southwest.png new file mode 100644 index 0000000..3b853a3 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/layout_southwest.png differ diff --git a/src/main/resources/cct/images/icons16x16/layout_vertical.png b/src/main/resources/cct/images/icons16x16/layout_vertical.png new file mode 100644 index 0000000..b2aed34 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/layout_vertical.png differ diff --git a/src/main/resources/cct/images/icons16x16/layout_west.png b/src/main/resources/cct/images/icons16x16/layout_west.png new file mode 100644 index 0000000..3a15cb1 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/layout_west.png differ diff --git a/src/main/resources/cct/images/icons16x16/lightbulb.png b/src/main/resources/cct/images/icons16x16/lightbulb.png new file mode 100644 index 0000000..dd26129 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/lightbulb.png differ diff --git a/src/main/resources/cct/images/icons16x16/lightbulb_on.png b/src/main/resources/cct/images/icons16x16/lightbulb_on.png new file mode 100644 index 0000000..b292ed4 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/lightbulb_on.png differ diff --git a/src/main/resources/cct/images/icons16x16/line-chart.png b/src/main/resources/cct/images/icons16x16/line-chart.png new file mode 100644 index 0000000..dc4e6ad Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/line-chart.png differ diff --git a/src/main/resources/cct/images/icons16x16/mail.png b/src/main/resources/cct/images/icons16x16/mail.png new file mode 100644 index 0000000..986b756 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mail.png differ diff --git a/src/main/resources/cct/images/icons16x16/mail2.png b/src/main/resources/cct/images/icons16x16/mail2.png new file mode 100644 index 0000000..b543653 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mail2.png differ diff --git a/src/main/resources/cct/images/icons16x16/mail2_view.png b/src/main/resources/cct/images/icons16x16/mail2_view.png new file mode 100644 index 0000000..610bc3c Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mail2_view.png differ diff --git a/src/main/resources/cct/images/icons16x16/mail_add.png b/src/main/resources/cct/images/icons16x16/mail_add.png new file mode 100644 index 0000000..014e7c0 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mail_add.png differ diff --git a/src/main/resources/cct/images/icons16x16/mail_attachment.png b/src/main/resources/cct/images/icons16x16/mail_attachment.png new file mode 100644 index 0000000..3bbc28f Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mail_attachment.png differ diff --git a/src/main/resources/cct/images/icons16x16/mail_delete.png b/src/main/resources/cct/images/icons16x16/mail_delete.png new file mode 100644 index 0000000..76fcf46 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mail_delete.png differ diff --git a/src/main/resources/cct/images/icons16x16/mail_earth.png b/src/main/resources/cct/images/icons16x16/mail_earth.png new file mode 100644 index 0000000..059d8c2 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mail_earth.png differ diff --git a/src/main/resources/cct/images/icons16x16/mail_exchange.png b/src/main/resources/cct/images/icons16x16/mail_exchange.png new file mode 100644 index 0000000..65ca96b Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mail_exchange.png differ diff --git a/src/main/resources/cct/images/icons16x16/mail_find.png b/src/main/resources/cct/images/icons16x16/mail_find.png new file mode 100644 index 0000000..91cde25 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mail_find.png differ diff --git a/src/main/resources/cct/images/icons16x16/mail_forward.png b/src/main/resources/cct/images/icons16x16/mail_forward.png new file mode 100644 index 0000000..16c5676 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mail_forward.png differ diff --git a/src/main/resources/cct/images/icons16x16/mail_into.png b/src/main/resources/cct/images/icons16x16/mail_into.png new file mode 100644 index 0000000..fb62dcb Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mail_into.png differ diff --git a/src/main/resources/cct/images/icons16x16/mail_lock.png b/src/main/resources/cct/images/icons16x16/mail_lock.png new file mode 100644 index 0000000..1f48167 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mail_lock.png differ diff --git a/src/main/resources/cct/images/icons16x16/mail_new.png b/src/main/resources/cct/images/icons16x16/mail_new.png new file mode 100644 index 0000000..75ab392 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mail_new.png differ diff --git a/src/main/resources/cct/images/icons16x16/mail_out.png b/src/main/resources/cct/images/icons16x16/mail_out.png new file mode 100644 index 0000000..604eaea Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mail_out.png differ diff --git a/src/main/resources/cct/images/icons16x16/mail_preferences.png b/src/main/resources/cct/images/icons16x16/mail_preferences.png new file mode 100644 index 0000000..55114ac Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mail_preferences.png differ diff --git a/src/main/resources/cct/images/icons16x16/mail_server.png b/src/main/resources/cct/images/icons16x16/mail_server.png new file mode 100644 index 0000000..ac297d2 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mail_server.png differ diff --git a/src/main/resources/cct/images/icons16x16/mail_view.png b/src/main/resources/cct/images/icons16x16/mail_view.png new file mode 100644 index 0000000..9552405 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mail_view.png differ diff --git a/src/main/resources/cct/images/icons16x16/mail_write.png b/src/main/resources/cct/images/icons16x16/mail_write.png new file mode 100644 index 0000000..78b5d6c Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mail_write.png differ diff --git a/src/main/resources/cct/images/icons16x16/media_beginning.png b/src/main/resources/cct/images/icons16x16/media_beginning.png new file mode 100644 index 0000000..60a0323 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/media_beginning.png differ diff --git a/src/main/resources/cct/images/icons16x16/media_end.png b/src/main/resources/cct/images/icons16x16/media_end.png new file mode 100644 index 0000000..2de17cf Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/media_end.png differ diff --git a/src/main/resources/cct/images/icons16x16/media_fast_forward.png b/src/main/resources/cct/images/icons16x16/media_fast_forward.png new file mode 100644 index 0000000..0d4d35e Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/media_fast_forward.png differ diff --git a/src/main/resources/cct/images/icons16x16/media_pause.png b/src/main/resources/cct/images/icons16x16/media_pause.png new file mode 100644 index 0000000..0557de6 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/media_pause.png differ diff --git a/src/main/resources/cct/images/icons16x16/media_play.png b/src/main/resources/cct/images/icons16x16/media_play.png new file mode 100644 index 0000000..abeef45 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/media_play.png differ diff --git a/src/main/resources/cct/images/icons16x16/media_play_back.png b/src/main/resources/cct/images/icons16x16/media_play_back.png new file mode 100644 index 0000000..9516856 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/media_play_back.png differ diff --git a/src/main/resources/cct/images/icons16x16/media_play_green.png b/src/main/resources/cct/images/icons16x16/media_play_green.png new file mode 100644 index 0000000..5da532e Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/media_play_green.png differ diff --git a/src/main/resources/cct/images/icons16x16/media_rewind.png b/src/main/resources/cct/images/icons16x16/media_rewind.png new file mode 100644 index 0000000..07c130a Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/media_rewind.png differ diff --git a/src/main/resources/cct/images/icons16x16/media_step_back.png b/src/main/resources/cct/images/icons16x16/media_step_back.png new file mode 100644 index 0000000..7185171 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/media_step_back.png differ diff --git a/src/main/resources/cct/images/icons16x16/media_step_forward.png b/src/main/resources/cct/images/icons16x16/media_step_forward.png new file mode 100644 index 0000000..350c45f Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/media_step_forward.png differ diff --git a/src/main/resources/cct/images/icons16x16/media_stop.png b/src/main/resources/cct/images/icons16x16/media_stop.png new file mode 100644 index 0000000..a18f4a0 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/media_stop.png differ diff --git a/src/main/resources/cct/images/icons16x16/media_stop_red.png b/src/main/resources/cct/images/icons16x16/media_stop_red.png new file mode 100644 index 0000000..91e7048 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/media_stop_red.png differ diff --git a/src/main/resources/cct/images/icons16x16/megaphone.png b/src/main/resources/cct/images/icons16x16/megaphone.png new file mode 100644 index 0000000..bde5e44 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/megaphone.png differ diff --git a/src/main/resources/cct/images/icons16x16/memory-monitor-16x16.png b/src/main/resources/cct/images/icons16x16/memory-monitor-16x16.png new file mode 100644 index 0000000..776ea35 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/memory-monitor-16x16.png differ diff --git a/src/main/resources/cct/images/icons16x16/message.png b/src/main/resources/cct/images/icons16x16/message.png new file mode 100644 index 0000000..f574f98 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/message.png differ diff --git a/src/main/resources/cct/images/icons16x16/message_add.png b/src/main/resources/cct/images/icons16x16/message_add.png new file mode 100644 index 0000000..5f0e60e Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/message_add.png differ diff --git a/src/main/resources/cct/images/icons16x16/message_delete.png b/src/main/resources/cct/images/icons16x16/message_delete.png new file mode 100644 index 0000000..54a1d61 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/message_delete.png differ diff --git a/src/main/resources/cct/images/icons16x16/message_edit.png b/src/main/resources/cct/images/icons16x16/message_edit.png new file mode 100644 index 0000000..58ec4fb Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/message_edit.png differ diff --git a/src/main/resources/cct/images/icons16x16/messages.png b/src/main/resources/cct/images/icons16x16/messages.png new file mode 100644 index 0000000..90cac97 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/messages.png differ diff --git a/src/main/resources/cct/images/icons16x16/mol-3.png b/src/main/resources/cct/images/icons16x16/mol-3.png new file mode 100644 index 0000000..09ff91f Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mol-3.png differ diff --git a/src/main/resources/cct/images/icons16x16/monitor.png b/src/main/resources/cct/images/icons16x16/monitor.png new file mode 100644 index 0000000..7180649 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/monitor.png differ diff --git a/src/main/resources/cct/images/icons16x16/monitor2.png b/src/main/resources/cct/images/icons16x16/monitor2.png new file mode 100644 index 0000000..fb3bae4 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/monitor2.png differ diff --git a/src/main/resources/cct/images/icons16x16/monitor_brush.png b/src/main/resources/cct/images/icons16x16/monitor_brush.png new file mode 100644 index 0000000..5ca9617 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/monitor_brush.png differ diff --git a/src/main/resources/cct/images/icons16x16/monitor_preferences.png b/src/main/resources/cct/images/icons16x16/monitor_preferences.png new file mode 100644 index 0000000..fdde272 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/monitor_preferences.png differ diff --git a/src/main/resources/cct/images/icons16x16/monitor_rgb.png b/src/main/resources/cct/images/icons16x16/monitor_rgb.png new file mode 100644 index 0000000..cebf257 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/monitor_rgb.png differ diff --git a/src/main/resources/cct/images/icons16x16/mopac-16x16.png b/src/main/resources/cct/images/icons16x16/mopac-16x16.png new file mode 100644 index 0000000..5b57218 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mopac-16x16.png differ diff --git a/src/main/resources/cct/images/icons16x16/mouse.png b/src/main/resources/cct/images/icons16x16/mouse.png new file mode 100644 index 0000000..7606242 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mouse.png differ diff --git a/src/main/resources/cct/images/icons16x16/mouse2.png b/src/main/resources/cct/images/icons16x16/mouse2.png new file mode 100644 index 0000000..94521e0 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/mouse2.png differ diff --git a/src/main/resources/cct/images/icons16x16/movie.png b/src/main/resources/cct/images/icons16x16/movie.png new file mode 100644 index 0000000..2be0e62 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/movie.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_down_blue.png b/src/main/resources/cct/images/icons16x16/nav_down_blue.png new file mode 100644 index 0000000..fbae915 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_down_blue.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_down_green.png b/src/main/resources/cct/images/icons16x16/nav_down_green.png new file mode 100644 index 0000000..12edc38 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_down_green.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_down_left_blue.png b/src/main/resources/cct/images/icons16x16/nav_down_left_blue.png new file mode 100644 index 0000000..2a18430 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_down_left_blue.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_down_left_green.png b/src/main/resources/cct/images/icons16x16/nav_down_left_green.png new file mode 100644 index 0000000..5a23807 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_down_left_green.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_down_left_red.png b/src/main/resources/cct/images/icons16x16/nav_down_left_red.png new file mode 100644 index 0000000..3007e39 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_down_left_red.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_down_red.png b/src/main/resources/cct/images/icons16x16/nav_down_red.png new file mode 100644 index 0000000..a69a448 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_down_red.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_down_right_blue.png b/src/main/resources/cct/images/icons16x16/nav_down_right_blue.png new file mode 100644 index 0000000..2d1dad3 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_down_right_blue.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_down_right_green.png b/src/main/resources/cct/images/icons16x16/nav_down_right_green.png new file mode 100644 index 0000000..f25f130 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_down_right_green.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_down_right_red.png b/src/main/resources/cct/images/icons16x16/nav_down_right_red.png new file mode 100644 index 0000000..8ff1345 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_down_right_red.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_left_blue.png b/src/main/resources/cct/images/icons16x16/nav_left_blue.png new file mode 100644 index 0000000..18b81bf Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_left_blue.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_left_green.png b/src/main/resources/cct/images/icons16x16/nav_left_green.png new file mode 100644 index 0000000..30e9a02 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_left_green.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_left_red.png b/src/main/resources/cct/images/icons16x16/nav_left_red.png new file mode 100644 index 0000000..087aaa2 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_left_red.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_right_blue.png b/src/main/resources/cct/images/icons16x16/nav_right_blue.png new file mode 100644 index 0000000..1b699a3 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_right_blue.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_right_green.png b/src/main/resources/cct/images/icons16x16/nav_right_green.png new file mode 100644 index 0000000..c5bdab8 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_right_green.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_right_red.png b/src/main/resources/cct/images/icons16x16/nav_right_red.png new file mode 100644 index 0000000..b1df947 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_right_red.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_up_blue.png b/src/main/resources/cct/images/icons16x16/nav_up_blue.png new file mode 100644 index 0000000..fc23620 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_up_blue.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_up_green.png b/src/main/resources/cct/images/icons16x16/nav_up_green.png new file mode 100644 index 0000000..12b0dec Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_up_green.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_up_left_blue.png b/src/main/resources/cct/images/icons16x16/nav_up_left_blue.png new file mode 100644 index 0000000..535234e Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_up_left_blue.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_up_left_green.png b/src/main/resources/cct/images/icons16x16/nav_up_left_green.png new file mode 100644 index 0000000..628af6f Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_up_left_green.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_up_left_red.png b/src/main/resources/cct/images/icons16x16/nav_up_left_red.png new file mode 100644 index 0000000..37a61e5 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_up_left_red.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_up_red.png b/src/main/resources/cct/images/icons16x16/nav_up_red.png new file mode 100644 index 0000000..945f0ea Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_up_red.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_up_right_blue.png b/src/main/resources/cct/images/icons16x16/nav_up_right_blue.png new file mode 100644 index 0000000..030d9cb Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_up_right_blue.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_up_right_green.png b/src/main/resources/cct/images/icons16x16/nav_up_right_green.png new file mode 100644 index 0000000..36cc216 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_up_right_green.png differ diff --git a/src/main/resources/cct/images/icons16x16/nav_up_right_red.png b/src/main/resources/cct/images/icons16x16/nav_up_right_red.png new file mode 100644 index 0000000..c68334c Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/nav_up_right_red.png differ diff --git a/src/main/resources/cct/images/icons16x16/navigate_down.png b/src/main/resources/cct/images/icons16x16/navigate_down.png new file mode 100644 index 0000000..e930163 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/navigate_down.png differ diff --git a/src/main/resources/cct/images/icons16x16/navigate_down2.png b/src/main/resources/cct/images/icons16x16/navigate_down2.png new file mode 100644 index 0000000..63f6f91 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/navigate_down2.png differ diff --git a/src/main/resources/cct/images/icons16x16/navigate_left.png b/src/main/resources/cct/images/icons16x16/navigate_left.png new file mode 100644 index 0000000..4c48700 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/navigate_left.png differ diff --git a/src/main/resources/cct/images/icons16x16/navigate_left2.png b/src/main/resources/cct/images/icons16x16/navigate_left2.png new file mode 100644 index 0000000..4072000 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/navigate_left2.png differ diff --git a/src/main/resources/cct/images/icons16x16/navigate_right.png b/src/main/resources/cct/images/icons16x16/navigate_right.png new file mode 100644 index 0000000..b994488 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/navigate_right.png differ diff --git a/src/main/resources/cct/images/icons16x16/navigate_right2.png b/src/main/resources/cct/images/icons16x16/navigate_right2.png new file mode 100644 index 0000000..6735f12 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/navigate_right2.png differ diff --git a/src/main/resources/cct/images/icons16x16/navigate_up.png b/src/main/resources/cct/images/icons16x16/navigate_up.png new file mode 100644 index 0000000..d4ec497 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/navigate_up.png differ diff --git a/src/main/resources/cct/images/icons16x16/navigate_up2.png b/src/main/resources/cct/images/icons16x16/navigate_up2.png new file mode 100644 index 0000000..0138cd8 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/navigate_up2.png differ diff --git a/src/main/resources/cct/images/icons16x16/newFile.png b/src/main/resources/cct/images/icons16x16/newFile.png new file mode 100644 index 0000000..67a88cf Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/newFile.png differ diff --git a/src/main/resources/cct/images/icons16x16/newObject.png b/src/main/resources/cct/images/icons16x16/newObject.png new file mode 100644 index 0000000..ea933e2 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/newObject.png differ diff --git a/src/main/resources/cct/images/icons16x16/newProject.png b/src/main/resources/cct/images/icons16x16/newProject.png new file mode 100644 index 0000000..fe3e957 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/newProject.png differ diff --git a/src/main/resources/cct/images/icons16x16/not-implemented-16x16.gif b/src/main/resources/cct/images/icons16x16/not-implemented-16x16.gif new file mode 100644 index 0000000..3889e36 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/not-implemented-16x16.gif differ diff --git a/src/main/resources/cct/images/icons16x16/openFile.png b/src/main/resources/cct/images/icons16x16/openFile.png new file mode 100644 index 0000000..d4f742a Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/openFile.png differ diff --git a/src/main/resources/cct/images/icons16x16/openProject.png b/src/main/resources/cct/images/icons16x16/openProject.png new file mode 100644 index 0000000..b1a6398 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/openProject.png differ diff --git a/src/main/resources/cct/images/icons16x16/package.png b/src/main/resources/cct/images/icons16x16/package.png new file mode 100644 index 0000000..26ad257 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/package.png differ diff --git a/src/main/resources/cct/images/icons16x16/package_add.png b/src/main/resources/cct/images/icons16x16/package_add.png new file mode 100644 index 0000000..e763acd Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/package_add.png differ diff --git a/src/main/resources/cct/images/icons16x16/package_delete.png b/src/main/resources/cct/images/icons16x16/package_delete.png new file mode 100644 index 0000000..42b08c5 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/package_delete.png differ diff --git a/src/main/resources/cct/images/icons16x16/package_error.png b/src/main/resources/cct/images/icons16x16/package_error.png new file mode 100644 index 0000000..082cb22 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/package_error.png differ diff --git a/src/main/resources/cct/images/icons16x16/package_find.png b/src/main/resources/cct/images/icons16x16/package_find.png new file mode 100644 index 0000000..ef14985 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/package_find.png differ diff --git a/src/main/resources/cct/images/icons16x16/package_new.png b/src/main/resources/cct/images/icons16x16/package_new.png new file mode 100644 index 0000000..5474f8c Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/package_new.png differ diff --git a/src/main/resources/cct/images/icons16x16/package_ok.png b/src/main/resources/cct/images/icons16x16/package_ok.png new file mode 100644 index 0000000..6ccefd3 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/package_ok.png differ diff --git a/src/main/resources/cct/images/icons16x16/package_preferences.png b/src/main/resources/cct/images/icons16x16/package_preferences.png new file mode 100644 index 0000000..dea2618 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/package_preferences.png differ diff --git a/src/main/resources/cct/images/icons16x16/package_view.png b/src/main/resources/cct/images/icons16x16/package_view.png new file mode 100644 index 0000000..89e4a53 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/package_view.png differ diff --git a/src/main/resources/cct/images/icons16x16/pcx-file.png b/src/main/resources/cct/images/icons16x16/pcx-file.png new file mode 100644 index 0000000..db82d09 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/pcx-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/pdb-transp-16x16.png b/src/main/resources/cct/images/icons16x16/pdb-transp-16x16.png new file mode 100644 index 0000000..1bc2953 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/pdb-transp-16x16.png differ diff --git a/src/main/resources/cct/images/icons16x16/percent.png b/src/main/resources/cct/images/icons16x16/percent.png new file mode 100644 index 0000000..109b985 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/percent.png differ diff --git a/src/main/resources/cct/images/icons16x16/photoshop-file.png b/src/main/resources/cct/images/icons16x16/photoshop-file.png new file mode 100644 index 0000000..084a572 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/photoshop-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/povray-file.png b/src/main/resources/cct/images/icons16x16/povray-file.png new file mode 100644 index 0000000..c39ba14 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/povray-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/powerpoint-file.png b/src/main/resources/cct/images/icons16x16/powerpoint-file.png new file mode 100644 index 0000000..d5d717a Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/powerpoint-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/preferences-2.png b/src/main/resources/cct/images/icons16x16/preferences-2.png new file mode 100644 index 0000000..87d29e4 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/preferences-2.png differ diff --git a/src/main/resources/cct/images/icons16x16/printer.png b/src/main/resources/cct/images/icons16x16/printer.png new file mode 100644 index 0000000..bda7099 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/printer.png differ diff --git a/src/main/resources/cct/images/icons16x16/printer2.png b/src/main/resources/cct/images/icons16x16/printer2.png new file mode 100644 index 0000000..ecfe08e Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/printer2.png differ diff --git a/src/main/resources/cct/images/icons16x16/printer_add.png b/src/main/resources/cct/images/icons16x16/printer_add.png new file mode 100644 index 0000000..d41a721 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/printer_add.png differ diff --git a/src/main/resources/cct/images/icons16x16/printer_delete.png b/src/main/resources/cct/images/icons16x16/printer_delete.png new file mode 100644 index 0000000..4d02d82 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/printer_delete.png differ diff --git a/src/main/resources/cct/images/icons16x16/printer_error.png b/src/main/resources/cct/images/icons16x16/printer_error.png new file mode 100644 index 0000000..842b3e9 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/printer_error.png differ diff --git a/src/main/resources/cct/images/icons16x16/printer_information.png b/src/main/resources/cct/images/icons16x16/printer_information.png new file mode 100644 index 0000000..6f9222e Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/printer_information.png differ diff --git a/src/main/resources/cct/images/icons16x16/printer_network.png b/src/main/resources/cct/images/icons16x16/printer_network.png new file mode 100644 index 0000000..3029a85 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/printer_network.png differ diff --git a/src/main/resources/cct/images/icons16x16/printer_new.png b/src/main/resources/cct/images/icons16x16/printer_new.png new file mode 100644 index 0000000..eb26f0f Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/printer_new.png differ diff --git a/src/main/resources/cct/images/icons16x16/printer_ok.png b/src/main/resources/cct/images/icons16x16/printer_ok.png new file mode 100644 index 0000000..15b3138 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/printer_ok.png differ diff --git a/src/main/resources/cct/images/icons16x16/printer_preferences.png b/src/main/resources/cct/images/icons16x16/printer_preferences.png new file mode 100644 index 0000000..e7d05a4 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/printer_preferences.png differ diff --git a/src/main/resources/cct/images/icons16x16/printer_view.png b/src/main/resources/cct/images/icons16x16/printer_view.png new file mode 100644 index 0000000..e46ce53 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/printer_view.png differ diff --git a/src/main/resources/cct/images/icons16x16/printer_warning.png b/src/main/resources/cct/images/icons16x16/printer_warning.png new file mode 100644 index 0000000..c034aaf Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/printer_warning.png differ diff --git a/src/main/resources/cct/images/icons16x16/projectProperties.png b/src/main/resources/cct/images/icons16x16/projectProperties.png new file mode 100644 index 0000000..15a513c Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/projectProperties.png differ diff --git a/src/main/resources/cct/images/icons16x16/qchem-16x16.png b/src/main/resources/cct/images/icons16x16/qchem-16x16.png new file mode 100644 index 0000000..a9c765b Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/qchem-16x16.png differ diff --git a/src/main/resources/cct/images/icons16x16/question_and_answer.png b/src/main/resources/cct/images/icons16x16/question_and_answer.png new file mode 100644 index 0000000..08070b3 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/question_and_answer.png differ diff --git a/src/main/resources/cct/images/icons16x16/quicktime-file.png b/src/main/resources/cct/images/icons16x16/quicktime-file.png new file mode 100644 index 0000000..816d232 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/quicktime-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/rar-file.png b/src/main/resources/cct/images/icons16x16/rar-file.png new file mode 100644 index 0000000..c1ced31 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/rar-file.png differ diff --git a/src/main/resources/cct/images/icons16x16/recycle.png b/src/main/resources/cct/images/icons16x16/recycle.png new file mode 100644 index 0000000..6f95523 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/recycle.png differ diff --git a/src/main/resources/cct/images/icons16x16/recycle_preferences.png b/src/main/resources/cct/images/icons16x16/recycle_preferences.png new file mode 100644 index 0000000..ba22dab Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/recycle_preferences.png differ diff --git a/src/main/resources/cct/images/icons16x16/redo.png b/src/main/resources/cct/images/icons16x16/redo.png new file mode 100644 index 0000000..9995b66 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/redo.png differ diff --git a/src/main/resources/cct/images/icons16x16/refresh-2.png b/src/main/resources/cct/images/icons16x16/refresh-2.png new file mode 100644 index 0000000..c7567da Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/refresh-2.png differ diff --git a/src/main/resources/cct/images/icons16x16/removeEntry.png b/src/main/resources/cct/images/icons16x16/removeEntry.png new file mode 100644 index 0000000..fa89cb4 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/removeEntry.png differ diff --git a/src/main/resources/cct/images/icons16x16/reopenObject.png b/src/main/resources/cct/images/icons16x16/reopenObject.png new file mode 100644 index 0000000..361604d Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/reopenObject.png differ diff --git a/src/main/resources/cct/images/icons16x16/replace2.png b/src/main/resources/cct/images/icons16x16/replace2.png new file mode 100644 index 0000000..a220558 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/replace2.png differ diff --git a/src/main/resources/cct/images/icons16x16/row.png b/src/main/resources/cct/images/icons16x16/row.png new file mode 100644 index 0000000..5ecccfc Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/row.png differ diff --git a/src/main/resources/cct/images/icons16x16/row_add.png b/src/main/resources/cct/images/icons16x16/row_add.png new file mode 100644 index 0000000..71502da Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/row_add.png differ diff --git a/src/main/resources/cct/images/icons16x16/row_add_after.png b/src/main/resources/cct/images/icons16x16/row_add_after.png new file mode 100644 index 0000000..02235a9 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/row_add_after.png differ diff --git a/src/main/resources/cct/images/icons16x16/row_add_before.png b/src/main/resources/cct/images/icons16x16/row_add_before.png new file mode 100644 index 0000000..f4fbba3 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/row_add_before.png differ diff --git a/src/main/resources/cct/images/icons16x16/row_delete.png b/src/main/resources/cct/images/icons16x16/row_delete.png new file mode 100644 index 0000000..08a8045 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/row_delete.png differ diff --git a/src/main/resources/cct/images/icons16x16/row_preferences.png b/src/main/resources/cct/images/icons16x16/row_preferences.png new file mode 100644 index 0000000..0323640 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/row_preferences.png differ diff --git a/src/main/resources/cct/images/icons16x16/save-file-16x16.gif b/src/main/resources/cct/images/icons16x16/save-file-16x16.gif new file mode 100644 index 0000000..d006dab Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/save-file-16x16.gif differ diff --git a/src/main/resources/cct/images/icons16x16/saveFile.png b/src/main/resources/cct/images/icons16x16/saveFile.png new file mode 100644 index 0000000..df61361 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/saveFile.png differ diff --git a/src/main/resources/cct/images/icons16x16/saveFiles.png b/src/main/resources/cct/images/icons16x16/saveFiles.png new file mode 100644 index 0000000..edd6fc3 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/saveFiles.png differ diff --git a/src/main/resources/cct/images/icons16x16/selection.png b/src/main/resources/cct/images/icons16x16/selection.png new file mode 100644 index 0000000..3da06dc Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/selection.png differ diff --git a/src/main/resources/cct/images/icons16x16/selection_delete.png b/src/main/resources/cct/images/icons16x16/selection_delete.png new file mode 100644 index 0000000..ab7e61f Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/selection_delete.png differ diff --git a/src/main/resources/cct/images/icons16x16/selection_recycle.png b/src/main/resources/cct/images/icons16x16/selection_recycle.png new file mode 100644 index 0000000..e0778c2 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/selection_recycle.png differ diff --git a/src/main/resources/cct/images/icons16x16/selection_replace.png b/src/main/resources/cct/images/icons16x16/selection_replace.png new file mode 100644 index 0000000..49f48d7 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/selection_replace.png differ diff --git a/src/main/resources/cct/images/icons16x16/server.png b/src/main/resources/cct/images/icons16x16/server.png new file mode 100644 index 0000000..5c2e828 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_add.png b/src/main/resources/cct/images/icons16x16/server_add.png new file mode 100644 index 0000000..8d098e5 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_add.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_certificate.png b/src/main/resources/cct/images/icons16x16/server_certificate.png new file mode 100644 index 0000000..f95587b Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_certificate.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_client.png b/src/main/resources/cct/images/icons16x16/server_client.png new file mode 100644 index 0000000..d3b4a73 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_client.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_client_exchange.png b/src/main/resources/cct/images/icons16x16/server_client_exchange.png new file mode 100644 index 0000000..eb5e2ac Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_client_exchange.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_connection.png b/src/main/resources/cct/images/icons16x16/server_connection.png new file mode 100644 index 0000000..84a4eb8 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_connection.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_delete.png b/src/main/resources/cct/images/icons16x16/server_delete.png new file mode 100644 index 0000000..c1a04b4 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_delete.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_document.png b/src/main/resources/cct/images/icons16x16/server_document.png new file mode 100644 index 0000000..cc5e804 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_document.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_earth.png b/src/main/resources/cct/images/icons16x16/server_earth.png new file mode 100644 index 0000000..ac727bf Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_earth.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_error.png b/src/main/resources/cct/images/icons16x16/server_error.png new file mode 100644 index 0000000..1353e40 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_error.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_forbidden.png b/src/main/resources/cct/images/icons16x16/server_forbidden.png new file mode 100644 index 0000000..100e49c Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_forbidden.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_from_client.png b/src/main/resources/cct/images/icons16x16/server_from_client.png new file mode 100644 index 0000000..69361e2 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_from_client.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_id_card.png b/src/main/resources/cct/images/icons16x16/server_id_card.png new file mode 100644 index 0000000..e96d806 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_id_card.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_information.png b/src/main/resources/cct/images/icons16x16/server_information.png new file mode 100644 index 0000000..a28c1b6 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_information.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_into.png b/src/main/resources/cct/images/icons16x16/server_into.png new file mode 100644 index 0000000..5306af4 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_into.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_lock.png b/src/main/resources/cct/images/icons16x16/server_lock.png new file mode 100644 index 0000000..f56759b Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_lock.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_mail.png b/src/main/resources/cct/images/icons16x16/server_mail.png new file mode 100644 index 0000000..05247e0 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_mail.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_mail_download.png b/src/main/resources/cct/images/icons16x16/server_mail_download.png new file mode 100644 index 0000000..6868820 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_mail_download.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_mail_upload.png b/src/main/resources/cct/images/icons16x16/server_mail_upload.png new file mode 100644 index 0000000..d708b33 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_mail_upload.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_network.png b/src/main/resources/cct/images/icons16x16/server_network.png new file mode 100644 index 0000000..58ab39a Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_network.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_new.png b/src/main/resources/cct/images/icons16x16/server_new.png new file mode 100644 index 0000000..2731863 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_new.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_ok.png b/src/main/resources/cct/images/icons16x16/server_ok.png new file mode 100644 index 0000000..281f95d Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_ok.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_out.png b/src/main/resources/cct/images/icons16x16/server_out.png new file mode 100644 index 0000000..33a41e7 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_out.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_preferences.png b/src/main/resources/cct/images/icons16x16/server_preferences.png new file mode 100644 index 0000000..6c842b9 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_preferences.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_time.png b/src/main/resources/cct/images/icons16x16/server_time.png new file mode 100644 index 0000000..1e6ab94 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_time.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_to_client.png b/src/main/resources/cct/images/icons16x16/server_to_client.png new file mode 100644 index 0000000..ed9be4b Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_to_client.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_unknown.png b/src/main/resources/cct/images/icons16x16/server_unknown.png new file mode 100644 index 0000000..b1d30d9 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_unknown.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_view.png b/src/main/resources/cct/images/icons16x16/server_view.png new file mode 100644 index 0000000..7947a50 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_view.png differ diff --git a/src/main/resources/cct/images/icons16x16/server_warning.png b/src/main/resources/cct/images/icons16x16/server_warning.png new file mode 100644 index 0000000..4b96bba Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/server_warning.png differ diff --git a/src/main/resources/cct/images/icons16x16/siesta-16x16.png b/src/main/resources/cct/images/icons16x16/siesta-16x16.png new file mode 100644 index 0000000..e9360bf Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/siesta-16x16.png differ diff --git a/src/main/resources/cct/images/icons16x16/sort_ascending.png b/src/main/resources/cct/images/icons16x16/sort_ascending.png new file mode 100644 index 0000000..bf6b1c0 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/sort_ascending.png differ diff --git a/src/main/resources/cct/images/icons16x16/sort_descending.png b/src/main/resources/cct/images/icons16x16/sort_descending.png new file mode 100644 index 0000000..f86be79 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/sort_descending.png differ diff --git a/src/main/resources/cct/images/icons16x16/table.png b/src/main/resources/cct/images/icons16x16/table.png new file mode 100644 index 0000000..4a041b6 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_add.png b/src/main/resources/cct/images/icons16x16/table_add.png new file mode 100644 index 0000000..9b79223 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_add.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_connection.png b/src/main/resources/cct/images/icons16x16/table_connection.png new file mode 100644 index 0000000..a6f2ff2 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_connection.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_delete.png b/src/main/resources/cct/images/icons16x16/table_delete.png new file mode 100644 index 0000000..b448716 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_delete.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_new.png b/src/main/resources/cct/images/icons16x16/table_new.png new file mode 100644 index 0000000..df1195e Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_new.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_preferences.png b/src/main/resources/cct/images/icons16x16/table_preferences.png new file mode 100644 index 0000000..0e9b1c4 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_preferences.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_refresh.png b/src/main/resources/cct/images/icons16x16/table_refresh.png new file mode 100644 index 0000000..ec78c2f Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_refresh.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_replace.png b/src/main/resources/cct/images/icons16x16/table_replace.png new file mode 100644 index 0000000..7cbbae7 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_replace.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_selection_all.png b/src/main/resources/cct/images/icons16x16/table_selection_all.png new file mode 100644 index 0000000..4f41e1e Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_selection_all.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_selection_block.png b/src/main/resources/cct/images/icons16x16/table_selection_block.png new file mode 100644 index 0000000..f2dfa15 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_selection_block.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_selection_cell.png b/src/main/resources/cct/images/icons16x16/table_selection_cell.png new file mode 100644 index 0000000..067c918 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_selection_cell.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_selection_column.png b/src/main/resources/cct/images/icons16x16/table_selection_column.png new file mode 100644 index 0000000..286960c Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_selection_column.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_selection_row.png b/src/main/resources/cct/images/icons16x16/table_selection_row.png new file mode 100644 index 0000000..d96d19a Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_selection_row.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_sql.png b/src/main/resources/cct/images/icons16x16/table_sql.png new file mode 100644 index 0000000..804ed97 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_sql.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_sql_add.png b/src/main/resources/cct/images/icons16x16/table_sql_add.png new file mode 100644 index 0000000..7fce784 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_sql_add.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_sql_check.png b/src/main/resources/cct/images/icons16x16/table_sql_check.png new file mode 100644 index 0000000..ca2c49d Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_sql_check.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_sql_create.png b/src/main/resources/cct/images/icons16x16/table_sql_create.png new file mode 100644 index 0000000..1900d79 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_sql_create.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_sql_delete.png b/src/main/resources/cct/images/icons16x16/table_sql_delete.png new file mode 100644 index 0000000..771be33 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_sql_delete.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_sql_run.png b/src/main/resources/cct/images/icons16x16/table_sql_run.png new file mode 100644 index 0000000..40e80ef Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_sql_run.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_sql_select.png b/src/main/resources/cct/images/icons16x16/table_sql_select.png new file mode 100644 index 0000000..d050d7b Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_sql_select.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_sql_view.png b/src/main/resources/cct/images/icons16x16/table_sql_view.png new file mode 100644 index 0000000..bcf9ad2 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_sql_view.png differ diff --git a/src/main/resources/cct/images/icons16x16/table_view.png b/src/main/resources/cct/images/icons16x16/table_view.png new file mode 100644 index 0000000..02ac148 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/table_view.png differ diff --git a/src/main/resources/cct/images/icons16x16/tables.png b/src/main/resources/cct/images/icons16x16/tables.png new file mode 100644 index 0000000..65c5134 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/tables.png differ diff --git a/src/main/resources/cct/images/icons16x16/tables_delete.png b/src/main/resources/cct/images/icons16x16/tables_delete.png new file mode 100644 index 0000000..0f2b0af Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/tables_delete.png differ diff --git a/src/main/resources/cct/images/icons16x16/tripos-transp-16x16.png b/src/main/resources/cct/images/icons16x16/tripos-transp-16x16.png new file mode 100644 index 0000000..4cc5c62 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/tripos-transp-16x16.png differ diff --git a/src/main/resources/cct/images/icons16x16/up.png b/src/main/resources/cct/images/icons16x16/up.png new file mode 100644 index 0000000..500baa6 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/up.png differ diff --git a/src/main/resources/cct/images/icons16x16/up_minus.png b/src/main/resources/cct/images/icons16x16/up_minus.png new file mode 100644 index 0000000..15815f9 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/up_minus.png differ diff --git a/src/main/resources/cct/images/icons16x16/up_plus.png b/src/main/resources/cct/images/icons16x16/up_plus.png new file mode 100644 index 0000000..0fdf6c9 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/up_plus.png differ diff --git a/src/main/resources/cct/images/icons16x16/vasp-16x16.png b/src/main/resources/cct/images/icons16x16/vasp-16x16.png new file mode 100644 index 0000000..b93f8a9 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/vasp-16x16.png differ diff --git a/src/main/resources/cct/images/icons16x16/vasp-transparent-16x16.png b/src/main/resources/cct/images/icons16x16/vasp-transparent-16x16.png new file mode 100644 index 0000000..f23e9fc Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/vasp-transparent-16x16.png differ diff --git a/src/main/resources/cct/images/icons16x16/warning.png b/src/main/resources/cct/images/icons16x16/warning.png new file mode 100644 index 0000000..85f544d Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/warning.png differ diff --git a/src/main/resources/cct/images/icons16x16/window_delete.png b/src/main/resources/cct/images/icons16x16/window_delete.png new file mode 100644 index 0000000..44a3684 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/window_delete.png differ diff --git a/src/main/resources/cct/images/icons16x16/wrench.png b/src/main/resources/cct/images/icons16x16/wrench.png new file mode 100644 index 0000000..91d9036 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/wrench.png differ diff --git a/src/main/resources/cct/images/icons16x16/xml-file.png b/src/main/resources/cct/images/icons16x16/xml-file.png new file mode 100644 index 0000000..b0d93a5 Binary files /dev/null and b/src/main/resources/cct/images/icons16x16/xml-file.png differ diff --git a/src/main/resources/cct/images/icons32x32/Archive_TAR.png b/src/main/resources/cct/images/icons32x32/Archive_TAR.png new file mode 100644 index 0000000..1eb93bf Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/Archive_TAR.png differ diff --git a/src/main/resources/cct/images/icons32x32/Archive_TGZ.png b/src/main/resources/cct/images/icons32x32/Archive_TGZ.png new file mode 100644 index 0000000..4315096 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/Archive_TGZ.png differ diff --git a/src/main/resources/cct/images/icons32x32/HyperChem-32x32.png b/src/main/resources/cct/images/icons32x32/HyperChem-32x32.png new file mode 100644 index 0000000..5153813 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/HyperChem-32x32.png differ diff --git a/src/main/resources/cct/images/icons32x32/MDL-32x32.png b/src/main/resources/cct/images/icons32x32/MDL-32x32.png new file mode 100644 index 0000000..58b7f60 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/MDL-32x32.png differ diff --git a/src/main/resources/cct/images/icons32x32/Thumbs.db b/src/main/resources/cct/images/icons32x32/Thumbs.db new file mode 100644 index 0000000..d02d007 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/Thumbs.db differ diff --git a/src/main/resources/cct/images/icons32x32/Tripos-icon-transp-32x32.png b/src/main/resources/cct/images/icons32x32/Tripos-icon-transp-32x32.png new file mode 100644 index 0000000..18e358e Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/Tripos-icon-transp-32x32.png differ diff --git a/src/main/resources/cct/images/icons32x32/arrowDown.gif b/src/main/resources/cct/images/icons32x32/arrowDown.gif new file mode 100644 index 0000000..e9f538e Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/arrowDown.gif differ diff --git a/src/main/resources/cct/images/icons32x32/arrowDownFaded.gif b/src/main/resources/cct/images/icons32x32/arrowDownFaded.gif new file mode 100644 index 0000000..43561a5 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/arrowDownFaded.gif differ diff --git a/src/main/resources/cct/images/icons32x32/arrowUp.gif b/src/main/resources/cct/images/icons32x32/arrowUp.gif new file mode 100644 index 0000000..6eb2fe6 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/arrowUp.gif differ diff --git a/src/main/resources/cct/images/icons32x32/arrowUpFaded.gif b/src/main/resources/cct/images/icons32x32/arrowUpFaded.gif new file mode 100644 index 0000000..71551ee Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/arrowUpFaded.gif differ diff --git a/src/main/resources/cct/images/icons32x32/bmp-file.png b/src/main/resources/cct/images/icons32x32/bmp-file.png new file mode 100644 index 0000000..f73edae Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/bmp-file.png differ diff --git a/src/main/resources/cct/images/icons32x32/button-ok.png b/src/main/resources/cct/images/icons32x32/button-ok.png new file mode 100644 index 0000000..230de53 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/button-ok.png differ diff --git a/src/main/resources/cct/images/icons32x32/document_gear.png b/src/main/resources/cct/images/icons32x32/document_gear.png new file mode 100644 index 0000000..0c4bf96 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/document_gear.png differ diff --git a/src/main/resources/cct/images/icons32x32/document_plain.png b/src/main/resources/cct/images/icons32x32/document_plain.png new file mode 100644 index 0000000..ba32cf9 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/document_plain.png differ diff --git a/src/main/resources/cct/images/icons32x32/document_text.png b/src/main/resources/cct/images/icons32x32/document_text.png new file mode 100644 index 0000000..ce24954 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/document_text.png differ diff --git a/src/main/resources/cct/images/icons32x32/emptyTransparent.png b/src/main/resources/cct/images/icons32x32/emptyTransparent.png new file mode 100644 index 0000000..bbe2304 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/emptyTransparent.png differ diff --git a/src/main/resources/cct/images/icons32x32/fileSaveAs.png b/src/main/resources/cct/images/icons32x32/fileSaveAs.png new file mode 100644 index 0000000..61a080e Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/fileSaveAs.png differ diff --git a/src/main/resources/cct/images/icons32x32/filesave.png b/src/main/resources/cct/images/icons32x32/filesave.png new file mode 100644 index 0000000..dd00abd Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/filesave.png differ diff --git a/src/main/resources/cct/images/icons32x32/folder_closed.png b/src/main/resources/cct/images/icons32x32/folder_closed.png new file mode 100644 index 0000000..026bd5a Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/folder_closed.png differ diff --git a/src/main/resources/cct/images/icons32x32/folder_window.png b/src/main/resources/cct/images/icons32x32/folder_window.png new file mode 100644 index 0000000..73389dd Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/folder_window.png differ diff --git a/src/main/resources/cct/images/icons32x32/folders.png b/src/main/resources/cct/images/icons32x32/folders.png new file mode 100644 index 0000000..196754f Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/folders.png differ diff --git a/src/main/resources/cct/images/icons32x32/gif-file.png b/src/main/resources/cct/images/icons32x32/gif-file.png new file mode 100644 index 0000000..583bc61 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/gif-file.png differ diff --git a/src/main/resources/cct/images/icons32x32/gromacs-32x32.png b/src/main/resources/cct/images/icons32x32/gromacs-32x32.png new file mode 100644 index 0000000..42a189d Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/gromacs-32x32.png differ diff --git a/src/main/resources/cct/images/icons32x32/html-file.png b/src/main/resources/cct/images/icons32x32/html-file.png new file mode 100644 index 0000000..be0c7e9 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/html-file.png differ diff --git a/src/main/resources/cct/images/icons32x32/image-file.png b/src/main/resources/cct/images/icons32x32/image-file.png new file mode 100644 index 0000000..b4cc473 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/image-file.png differ diff --git a/src/main/resources/cct/images/icons32x32/jar.png b/src/main/resources/cct/images/icons32x32/jar.png new file mode 100644 index 0000000..eefd0b6 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/jar.png differ diff --git a/src/main/resources/cct/images/icons32x32/mopac-32x32.png b/src/main/resources/cct/images/icons32x32/mopac-32x32.png new file mode 100644 index 0000000..48ac15c Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/mopac-32x32.png differ diff --git a/src/main/resources/cct/images/icons32x32/mpeg-file.png b/src/main/resources/cct/images/icons32x32/mpeg-file.png new file mode 100644 index 0000000..6deddbb Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/mpeg-file.png differ diff --git a/src/main/resources/cct/images/icons32x32/rar-file.png b/src/main/resources/cct/images/icons32x32/rar-file.png new file mode 100644 index 0000000..2808bfe Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/rar-file.png differ diff --git a/src/main/resources/cct/images/icons32x32/server_from_client.png b/src/main/resources/cct/images/icons32x32/server_from_client.png new file mode 100644 index 0000000..c7a67e0 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/server_from_client.png differ diff --git a/src/main/resources/cct/images/icons32x32/tetrahedral-3.png b/src/main/resources/cct/images/icons32x32/tetrahedral-3.png new file mode 100644 index 0000000..b07b278 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/tetrahedral-3.png differ diff --git a/src/main/resources/cct/images/icons32x32/tetrahedral-4.png b/src/main/resources/cct/images/icons32x32/tetrahedral-4.png new file mode 100644 index 0000000..705aab8 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/tetrahedral-4.png differ diff --git a/src/main/resources/cct/images/icons32x32/text_code_c.png b/src/main/resources/cct/images/icons32x32/text_code_c.png new file mode 100644 index 0000000..fe328a8 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/text_code_c.png differ diff --git a/src/main/resources/cct/images/icons32x32/text_code_cplusplus.png b/src/main/resources/cct/images/icons32x32/text_code_cplusplus.png new file mode 100644 index 0000000..bf8baac Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/text_code_cplusplus.png differ diff --git a/src/main/resources/cct/images/icons32x32/text_code_java.png b/src/main/resources/cct/images/icons32x32/text_code_java.png new file mode 100644 index 0000000..27805da Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/text_code_java.png differ diff --git a/src/main/resources/cct/images/icons32x32/trigonal-3.png b/src/main/resources/cct/images/icons32x32/trigonal-3.png new file mode 100644 index 0000000..0c046fc Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/trigonal-3.png differ diff --git a/src/main/resources/cct/images/icons32x32/wav-file.png b/src/main/resources/cct/images/icons32x32/wav-file.png new file mode 100644 index 0000000..9a8639f Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/wav-file.png differ diff --git a/src/main/resources/cct/images/icons32x32/window-exit.png b/src/main/resources/cct/images/icons32x32/window-exit.png new file mode 100644 index 0000000..330a8be Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/window-exit.png differ diff --git a/src/main/resources/cct/images/icons32x32/window-new.png b/src/main/resources/cct/images/icons32x32/window-new.png new file mode 100644 index 0000000..b7eadc0 Binary files /dev/null and b/src/main/resources/cct/images/icons32x32/window-new.png differ diff --git a/src/main/resources/cct/images/icons48x48/AppleSZ.png b/src/main/resources/cct/images/icons48x48/AppleSZ.png new file mode 100644 index 0000000..70f4cf7 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/AppleSZ.png differ diff --git a/src/main/resources/cct/images/icons48x48/Archive_GZIP.png b/src/main/resources/cct/images/icons48x48/Archive_GZIP.png new file mode 100644 index 0000000..0428063 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Archive_GZIP.png differ diff --git a/src/main/resources/cct/images/icons48x48/Archive_RAR.png b/src/main/resources/cct/images/icons48x48/Archive_RAR.png new file mode 100644 index 0000000..d311479 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Archive_RAR.png differ diff --git a/src/main/resources/cct/images/icons48x48/Archive_TAR.png b/src/main/resources/cct/images/icons48x48/Archive_TAR.png new file mode 100644 index 0000000..2864c7f Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Archive_TAR.png differ diff --git a/src/main/resources/cct/images/icons48x48/Archive_TGZ.png b/src/main/resources/cct/images/icons48x48/Archive_TGZ.png new file mode 100644 index 0000000..2d166e6 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Archive_TGZ.png differ diff --git a/src/main/resources/cct/images/icons48x48/Archive_ZIP.png b/src/main/resources/cct/images/icons48x48/Archive_ZIP.png new file mode 100644 index 0000000..9d10dc6 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Archive_ZIP.png differ diff --git a/src/main/resources/cct/images/icons48x48/AttentionSZ.png b/src/main/resources/cct/images/icons48x48/AttentionSZ.png new file mode 100644 index 0000000..bd43a8f Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/AttentionSZ.png differ diff --git a/src/main/resources/cct/images/icons48x48/Audio_AIFF.png b/src/main/resources/cct/images/icons48x48/Audio_AIFF.png new file mode 100644 index 0000000..dde44c4 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Audio_AIFF.png differ diff --git a/src/main/resources/cct/images/icons48x48/Audio_MP3.png b/src/main/resources/cct/images/icons48x48/Audio_MP3.png new file mode 100644 index 0000000..a1c43f2 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Audio_MP3.png differ diff --git a/src/main/resources/cct/images/icons48x48/Audio_OGG.png b/src/main/resources/cct/images/icons48x48/Audio_OGG.png new file mode 100644 index 0000000..6e7a794 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Audio_OGG.png differ diff --git a/src/main/resources/cct/images/icons48x48/Audio_WAV.png b/src/main/resources/cct/images/icons48x48/Audio_WAV.png new file mode 100644 index 0000000..2b2d5da Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Audio_WAV.png differ diff --git a/src/main/resources/cct/images/icons48x48/Audio_WMA.png b/src/main/resources/cct/images/icons48x48/Audio_WMA.png new file mode 100644 index 0000000..6d78df8 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Audio_WMA.png differ diff --git a/src/main/resources/cct/images/icons48x48/Audio_WMA_2.png b/src/main/resources/cct/images/icons48x48/Audio_WMA_2.png new file mode 100644 index 0000000..ba9dad3 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Audio_WMA_2.png differ diff --git a/src/main/resources/cct/images/icons48x48/Bloc Notes SZ.png b/src/main/resources/cct/images/icons48x48/Bloc Notes SZ.png new file mode 100644 index 0000000..ca0810a Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Bloc Notes SZ.png differ diff --git a/src/main/resources/cct/images/icons48x48/BrushSZ.png b/src/main/resources/cct/images/icons48x48/BrushSZ.png new file mode 100644 index 0000000..2ba3291 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/BrushSZ.png differ diff --git a/src/main/resources/cct/images/icons48x48/Image_BMP.png b/src/main/resources/cct/images/icons48x48/Image_BMP.png new file mode 100644 index 0000000..8edeca1 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Image_BMP.png differ diff --git a/src/main/resources/cct/images/icons48x48/Image_GIF.png b/src/main/resources/cct/images/icons48x48/Image_GIF.png new file mode 100644 index 0000000..ca53295 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Image_GIF.png differ diff --git a/src/main/resources/cct/images/icons48x48/Image_JPG.png b/src/main/resources/cct/images/icons48x48/Image_JPG.png new file mode 100644 index 0000000..f633b55 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Image_JPG.png differ diff --git a/src/main/resources/cct/images/icons48x48/Image_PNG.png b/src/main/resources/cct/images/icons48x48/Image_PNG.png new file mode 100644 index 0000000..d7468b8 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Image_PNG.png differ diff --git a/src/main/resources/cct/images/icons48x48/Office_DOC.png b/src/main/resources/cct/images/icons48x48/Office_DOC.png new file mode 100644 index 0000000..07fc3cb Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Office_DOC.png differ diff --git a/src/main/resources/cct/images/icons48x48/Office_HTML.png b/src/main/resources/cct/images/icons48x48/Office_HTML.png new file mode 100644 index 0000000..d7773f3 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Office_HTML.png differ diff --git a/src/main/resources/cct/images/icons48x48/Office_HTML2.png b/src/main/resources/cct/images/icons48x48/Office_HTML2.png new file mode 100644 index 0000000..088509c Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Office_HTML2.png differ diff --git a/src/main/resources/cct/images/icons48x48/Office_MAIL.png b/src/main/resources/cct/images/icons48x48/Office_MAIL.png new file mode 100644 index 0000000..98b9a67 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Office_MAIL.png differ diff --git a/src/main/resources/cct/images/icons48x48/Office_MAIL_open.png b/src/main/resources/cct/images/icons48x48/Office_MAIL_open.png new file mode 100644 index 0000000..08e026f Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Office_MAIL_open.png differ diff --git a/src/main/resources/cct/images/icons48x48/Office_PDF.png b/src/main/resources/cct/images/icons48x48/Office_PDF.png new file mode 100644 index 0000000..5805cc5 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Office_PDF.png differ diff --git a/src/main/resources/cct/images/icons48x48/Office_PPT.png b/src/main/resources/cct/images/icons48x48/Office_PPT.png new file mode 100644 index 0000000..e40384c Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Office_PPT.png differ diff --git a/src/main/resources/cct/images/icons48x48/Office_TXT.png b/src/main/resources/cct/images/icons48x48/Office_TXT.png new file mode 100644 index 0000000..8dbfbf8 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Office_TXT.png differ diff --git a/src/main/resources/cct/images/icons48x48/Office_XLS.png b/src/main/resources/cct/images/icons48x48/Office_XLS.png new file mode 100644 index 0000000..41b3135 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Office_XLS.png differ diff --git a/src/main/resources/cct/images/icons48x48/QuicktimeSZ.png b/src/main/resources/cct/images/icons48x48/QuicktimeSZ.png new file mode 100644 index 0000000..81c8b56 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/QuicktimeSZ.png differ diff --git a/src/main/resources/cct/images/icons48x48/System-Binary.png b/src/main/resources/cct/images/icons48x48/System-Binary.png new file mode 100644 index 0000000..b6f190e Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/System-Binary.png differ diff --git a/src/main/resources/cct/images/icons48x48/Text.png b/src/main/resources/cct/images/icons48x48/Text.png new file mode 100644 index 0000000..364914f Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Text.png differ diff --git a/src/main/resources/cct/images/icons48x48/Thumbs.db b/src/main/resources/cct/images/icons48x48/Thumbs.db new file mode 100644 index 0000000..2bb45cf Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Thumbs.db differ diff --git a/src/main/resources/cct/images/icons48x48/Video_AVI.png b/src/main/resources/cct/images/icons48x48/Video_AVI.png new file mode 100644 index 0000000..66eced3 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Video_AVI.png differ diff --git a/src/main/resources/cct/images/icons48x48/Video_MOVIE.png b/src/main/resources/cct/images/icons48x48/Video_MOVIE.png new file mode 100644 index 0000000..1133fde Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Video_MOVIE.png differ diff --git a/src/main/resources/cct/images/icons48x48/Video_MPEG.png b/src/main/resources/cct/images/icons48x48/Video_MPEG.png new file mode 100644 index 0000000..49f84cf Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Video_MPEG.png differ diff --git a/src/main/resources/cct/images/icons48x48/Video_WMV.png b/src/main/resources/cct/images/icons48x48/Video_WMV.png new file mode 100644 index 0000000..ab850ca Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/Video_WMV.png differ diff --git a/src/main/resources/cct/images/icons48x48/WinrarSZ.png b/src/main/resources/cct/images/icons48x48/WinrarSZ.png new file mode 100644 index 0000000..713c292 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/WinrarSZ.png differ diff --git a/src/main/resources/cct/images/icons48x48/bended_single_double_atom.png b/src/main/resources/cct/images/icons48x48/bended_single_double_atom.png new file mode 100644 index 0000000..4885bc5 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/bended_single_double_atom.png differ diff --git a/src/main/resources/cct/images/icons48x48/config.png b/src/main/resources/cct/images/icons48x48/config.png new file mode 100644 index 0000000..725e6ae Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/config.png differ diff --git a/src/main/resources/cct/images/icons48x48/emptyTransparent.png b/src/main/resources/cct/images/icons48x48/emptyTransparent.png new file mode 100644 index 0000000..2061f41 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/emptyTransparent.png differ diff --git a/src/main/resources/cct/images/icons48x48/gromacs-48x48.png b/src/main/resources/cct/images/icons48x48/gromacs-48x48.png new file mode 100644 index 0000000..b7f0797 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/gromacs-48x48.png differ diff --git a/src/main/resources/cct/images/icons48x48/linear_double_double_atom.png b/src/main/resources/cct/images/icons48x48/linear_double_double_atom.png new file mode 100644 index 0000000..fe02aa9 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/linear_double_double_atom.png differ diff --git a/src/main/resources/cct/images/icons48x48/linear_single_single_atom.png b/src/main/resources/cct/images/icons48x48/linear_single_single_atom.png new file mode 100644 index 0000000..c1c8c72 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/linear_single_single_atom.png differ diff --git a/src/main/resources/cct/images/icons48x48/linear_single_triple_atom.png b/src/main/resources/cct/images/icons48x48/linear_single_triple_atom.png new file mode 100644 index 0000000..7377011 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/linear_single_triple_atom.png differ diff --git a/src/main/resources/cct/images/icons48x48/mopac.png b/src/main/resources/cct/images/icons48x48/mopac.png new file mode 100644 index 0000000..5670b9a Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/mopac.png differ diff --git a/src/main/resources/cct/images/icons48x48/octahedral_atom.png b/src/main/resources/cct/images/icons48x48/octahedral_atom.png new file mode 100644 index 0000000..4cc92fc Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/octahedral_atom.png differ diff --git a/src/main/resources/cct/images/icons48x48/seesaw_shaped_atom.png b/src/main/resources/cct/images/icons48x48/seesaw_shaped_atom.png new file mode 100644 index 0000000..a86574c Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/seesaw_shaped_atom.png differ diff --git a/src/main/resources/cct/images/icons48x48/square_planar_atom.png b/src/main/resources/cct/images/icons48x48/square_planar_atom.png new file mode 100644 index 0000000..16ce9ba Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/square_planar_atom.png differ diff --git a/src/main/resources/cct/images/icons48x48/t_shaped_atom.png b/src/main/resources/cct/images/icons48x48/t_shaped_atom.png new file mode 100644 index 0000000..2116503 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/t_shaped_atom.png differ diff --git a/src/main/resources/cct/images/icons48x48/terminal_double_atom.png b/src/main/resources/cct/images/icons48x48/terminal_double_atom.png new file mode 100644 index 0000000..2a2d428 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/terminal_double_atom.png differ diff --git a/src/main/resources/cct/images/icons48x48/terminal_single_atom.png b/src/main/resources/cct/images/icons48x48/terminal_single_atom.png new file mode 100644 index 0000000..de8adbc Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/terminal_single_atom.png differ diff --git a/src/main/resources/cct/images/icons48x48/terminal_triple_atom.png b/src/main/resources/cct/images/icons48x48/terminal_triple_atom.png new file mode 100644 index 0000000..6c64d24 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/terminal_triple_atom.png differ diff --git a/src/main/resources/cct/images/icons48x48/tetrahedral-2.png b/src/main/resources/cct/images/icons48x48/tetrahedral-2.png new file mode 100644 index 0000000..213fd1a Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/tetrahedral-2.png differ diff --git a/src/main/resources/cct/images/icons48x48/tetrahedral-3.png b/src/main/resources/cct/images/icons48x48/tetrahedral-3.png new file mode 100644 index 0000000..62b9bf7 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/tetrahedral-3.png differ diff --git a/src/main/resources/cct/images/icons48x48/tetrahedral-4.png b/src/main/resources/cct/images/icons48x48/tetrahedral-4.png new file mode 100644 index 0000000..802732a Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/tetrahedral-4.png differ diff --git a/src/main/resources/cct/images/icons48x48/tetrahedral_ssdd_atom.png b/src/main/resources/cct/images/icons48x48/tetrahedral_ssdd_atom.png new file mode 100644 index 0000000..43a1891 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/tetrahedral_ssdd_atom.png differ diff --git a/src/main/resources/cct/images/icons48x48/tetrahedral_sssd_atom.png b/src/main/resources/cct/images/icons48x48/tetrahedral_sssd_atom.png new file mode 100644 index 0000000..0d1162c Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/tetrahedral_sssd_atom.png differ diff --git a/src/main/resources/cct/images/icons48x48/trigonal-3.png b/src/main/resources/cct/images/icons48x48/trigonal-3.png new file mode 100644 index 0000000..7a6b950 Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/trigonal-3.png differ diff --git a/src/main/resources/cct/images/icons48x48/trigonal_bipyramid_atom.png b/src/main/resources/cct/images/icons48x48/trigonal_bipyramid_atom.png new file mode 100644 index 0000000..1f03a3d Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/trigonal_bipyramid_atom.png differ diff --git a/src/main/resources/cct/images/icons48x48/trigonal_planar_dss_atom.png b/src/main/resources/cct/images/icons48x48/trigonal_planar_dss_atom.png new file mode 100644 index 0000000..7b7943c Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/trigonal_planar_dss_atom.png differ diff --git a/src/main/resources/cct/images/icons48x48/trigonal_planar_saa_atom.png b/src/main/resources/cct/images/icons48x48/trigonal_planar_saa_atom.png new file mode 100644 index 0000000..34abafa Binary files /dev/null and b/src/main/resources/cct/images/icons48x48/trigonal_planar_saa_atom.png differ diff --git a/src/main/resources/cct/images/image-file.png b/src/main/resources/cct/images/image-file.png new file mode 100644 index 0000000..2ea5fe2 Binary files /dev/null and b/src/main/resources/cct/images/image-file.png differ diff --git a/src/main/resources/cct/images/jmoleditor-128x128.png b/src/main/resources/cct/images/jmoleditor-128x128.png new file mode 100644 index 0000000..b4bb630 Binary files /dev/null and b/src/main/resources/cct/images/jmoleditor-128x128.png differ diff --git a/src/main/resources/cct/images/mopac-16x16.png b/src/main/resources/cct/images/mopac-16x16.png new file mode 100644 index 0000000..5b57218 Binary files /dev/null and b/src/main/resources/cct/images/mopac-16x16.png differ diff --git a/src/main/resources/cct/images/not-implemented-16x16.gif b/src/main/resources/cct/images/not-implemented-16x16.gif new file mode 100644 index 0000000..3889e36 Binary files /dev/null and b/src/main/resources/cct/images/not-implemented-16x16.gif differ diff --git a/src/main/resources/cct/images/openFile.png b/src/main/resources/cct/images/openFile.png new file mode 100644 index 0000000..d4f742a Binary files /dev/null and b/src/main/resources/cct/images/openFile.png differ diff --git a/src/main/resources/cct/images/pdb-transp-16x16.png b/src/main/resources/cct/images/pdb-transp-16x16.png new file mode 100644 index 0000000..1bc2953 Binary files /dev/null and b/src/main/resources/cct/images/pdb-transp-16x16.png differ diff --git a/src/main/resources/cct/images/save-file-16x16.gif b/src/main/resources/cct/images/save-file-16x16.gif new file mode 100644 index 0000000..d006dab Binary files /dev/null and b/src/main/resources/cct/images/save-file-16x16.gif differ diff --git a/src/main/resources/cct/images/seagrid.png b/src/main/resources/cct/images/seagrid.png new file mode 100644 index 0000000..6ee1bf0 Binary files /dev/null and b/src/main/resources/cct/images/seagrid.png differ diff --git a/src/main/resources/cct/images/tripos-transp-16x16.png b/src/main/resources/cct/images/tripos-transp-16x16.png new file mode 100644 index 0000000..4cc5c62 Binary files /dev/null and b/src/main/resources/cct/images/tripos-transp-16x16.png differ diff --git a/src/main/resources/cct/tools/FileTypeDescription.properties b/src/main/resources/cct/tools/FileTypeDescription.properties new file mode 100644 index 0000000..e69de29 diff --git a/src/main/resources/cct/tools/FileTypeIcons16x16.properties b/src/main/resources/cct/tools/FileTypeIcons16x16.properties new file mode 100644 index 0000000..317626f --- /dev/null +++ b/src/main/resources/cct/tools/FileTypeIcons16x16.properties @@ -0,0 +1,158 @@ + +acrobatImage_16x16 = acrobat-file.png +audioFileImage_16x16 = audio-file.png +aviImage_16x16 = avi-file.png +cFileImage_16x16 = c-file.png +cppFileImage_16x16 = cpp-file.png +compressedFileImage_16x16 = compressed-transp.png +folder_16x16 = folder.png +document_16x16 = document.png +divxImage_16x16 = divx-file.png +djvuImage_16x16 = djvu-file.png +gaussianImage_16x16 = gaussian-16x16.png +headerFileImage_16x16 = header-file.png +helpFileImage_16x16 = help-file.png +htmlFileImage_16x16 = html-file.png +iccFileImage_16x16 = icc-file.png +icoFileImage_16x16 = ico-file.png +imageFileImage_16x16 = image-file.png +javaFileImage_16x16 = java-file.png +mdlImage_16x16 = MDL-16x16.png +movieImage_16x16 = movie.png +pcxFileImage_16x16 = pcx-file.png +photoshopFileImage_16x16 = photoshop-file.png +povrayFileImage_16x16 = povray-file.png +powerpointFileImage_16x16 = powerpoint-file.png +quicktimeFileImage_16x16 = quicktime-file.png +rarFileImage_16x16 = rar-file.png +triposImage_16x16 = tripos-transp-16x16.png +xmlImage_16x16 = xml-file.png + + + +chm = helpFileImage_16x16 +cnt = helpFileImage_16x16 +hlp = helpFileImage_16x16 + +c = cFileImage_16x16 +cpp = cppFileImage_16x16 + +cur = icoFileImage_16x16 +ico = icoFileImage_16x16 + +dcx = pcxFileImage_16x16 +pcx = pcxFileImage_16x16 + +div = divxImage_16x16 +divx = divxImage_16x16 + +djv = djvuImage_16x16 +djvu = djvuImage_16x16 + +fdf = acrobatImage_16x16 +pdf = acrobatImage_16x16 +pdx = acrobatImage_16x16 + +ace = compressedFileImage_16x16 +arj = compressedFileImage_16x16 +bz2 = compressedFileImage_16x16 +gz = compressedFileImage_16x16 +gzip = compressedFileImage_16x16 +uue = compressedFileImage_16x16 +cab = compressedFileImage_16x16 +lha = compressedFileImage_16x16 +lzh = compressedFileImage_16x16 +tar = compressedFileImage_16x16 +tbz = compressedFileImage_16x16 +tbz2 = compressedFileImage_16x16 +tgz = compressedFileImage_16x16 +zip = compressedFileImage_16x16 +rar = rarFileImage_16x16 + +h = headerFileImage_16x16 + +hdt = htmlFileImage_16x16 +hdtl = htmlFileImage_16x16 +html = htmlFileImage_16x16 +htm = htmlFileImage_16x16 +shtm = htmlFileImage_16x16 +shtml = htmlFileImage_16x16 +url = htmlFileImage_16x16 + +icc = iccFileImage_16x16 +icm = iccFileImage_16x16 + +iff = audioFileImage_16x16 +m2v = audioFileImage_16x16 +m4v = audioFileImage_16x16 +m3u = audioFileImage_16x16 +mid = audioFileImage_16x16 +midi = audioFileImage_16x16 +mp3 = audioFileImage_16x16 +ra = audioFileImage_16x16 +snd = audioFileImage_16x16 +vox = audioFileImage_16x16 +wav = audioFileImage_16x16 +wave = audioFileImage_16x16 +wv = audioFileImage_16x16 + +java = javaFileImage_16x16 +class = javaFileImage_16x16 +jar = javaFileImage_16x16 + +gjf = gaussianImage_16x16 +mol2 = triposImage_16x16 +mol = mdlImage_16x16 + +moov = quicktimeFileImage_16x16 +mov = quicktimeFileImage_16x16 +movie = quicktimeFileImage_16x16 +qpx = quicktimeFileImage_16x16 +qt = quicktimeFileImage_16x16 +qti = quicktimeFileImage_16x16 +qtif = quicktimeFileImage_16x16 +qtl = quicktimeFileImage_16x16 +qtp = quicktimeFileImage_16x16 +qts = quicktimeFileImage_16x16 +qtx = quicktimeFileImage_16x16 + +avi = aviImage_16x16 +mpeg = movieImage_16x16 +mpg = movieImage_16x16 +mpv = movieImage_16x16 +mpv2 = movieImage_16x16 +rv = movieImage_16x16 +vob = movieImage_16x16 +wma = movieImage_16x16 + +pov = povrayFileImage_16x16 + +pps = powerpointFileImage_16x16 +ppt = powerpointFileImage_16x16 +ppthtml = powerpointFileImage_16x16 +pptmhtml = powerpointFileImage_16x16 + +psd = photoshopFileImage_16x16 +psp = photoshopFileImage_16x16 + +bmp = imageFileImage_16x16 +crw = imageFileImage_16x16 +jpe = imageFileImage_16x16 +jpg = imageFileImage_16x16 +jpeg = imageFileImage_16x16 +gif = imageFileImage_16x16 +nef = imageFileImage_16x16 +pct = imageFileImage_16x16 +pgm = imageFileImage_16x16 +pic = imageFileImage_16x16 +pict = imageFileImage_16x16 +pix = imageFileImage_16x16 +png = imageFileImage_16x16 +raw = imageFileImage_16x16 +tga = imageFileImage_16x16 +tif = imageFileImage_16x16 +tiff = imageFileImage_16x16 +wbmp = imageFileImage_16x16 +xif = imageFileImage_16x16 + +xml = xmlImage_16x16 diff --git a/src/main/resources/cct/tools/FileTypeIcons32x32.properties b/src/main/resources/cct/tools/FileTypeIcons32x32.properties new file mode 100644 index 0000000..be64f42 --- /dev/null +++ b/src/main/resources/cct/tools/FileTypeIcons32x32.properties @@ -0,0 +1,50 @@ + +bmpImage_32x32 = bmp-file.png +cImage_32x32 = text_code_c.png +cppImage_32x32 = text_code_cplusplus.png +gifImage_32x32 = gif-file.png +gromacsImage_32x32 = gromacs-32x32.png +htmlImage_32x32 = html-file.png +hyperchemImage_32x32 = HyperChem-32x32.png +jarImage_32x32 = jar.png +javaImage_32x32 = text_code_java.png +mdlImage_32x32 = MDL-32x32.png +mpegImage_32x32 = mpeg-file.png +pictureImage_32x32 = image-file.png +rarImage_32x32 = rar-file.png +textImage_32x32 = document_text.png +triposImage_32x32 = Tripos-icon-transp-32x32.png +wavImage_32x32 = wav-file.png + +bmp = bmpImage_32x32 + +c = cImage_32x32 +cpp = cppImage_32x32 + +gif = gifImage_32x32 + +htm = htmlImage_32x32 +html = htmlImage_32x32 + +jar = jarImage_32x32 +java = javaImage_32x32 + +gro = gromacsImage_32x32 +g96 = gromacsImage_32x32 +hin = hyperchemImage_32x32 +mol = mdlImage_32x32 +mol2 = triposImage_32x32 + +mpeg = mpegImage_32x32 +mpg = mpegImage_32x32 + +png = pictureImage_32x32 + +# +rar = rarImage_32x32 + +doc = textImage_32x32 +log = textImage_32x32 +txt = textImage_32x32 + +wav = wavImage_32x32 diff --git a/src/main/resources/cct/tools/Tripos-icon-transp-16x16.png b/src/main/resources/cct/tools/Tripos-icon-transp-16x16.png new file mode 100644 index 0000000..4cc5c62 Binary files /dev/null and b/src/main/resources/cct/tools/Tripos-icon-transp-16x16.png differ diff --git a/src/main/resources/client_truststore.jks b/src/main/resources/client_truststore.jks new file mode 100644 index 0000000..4eefccd Binary files /dev/null and b/src/main/resources/client_truststore.jks differ diff --git a/src/main/resources/images/.DS_Store b/src/main/resources/images/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/src/main/resources/images/.DS_Store differ diff --git a/src/main/resources/images/add.png b/src/main/resources/images/add.png new file mode 100644 index 0000000..619e8d2 Binary files /dev/null and b/src/main/resources/images/add.png differ diff --git a/src/main/resources/images/file.png b/src/main/resources/images/file.png new file mode 100644 index 0000000..4ea6d8a Binary files /dev/null and b/src/main/resources/images/file.png differ diff --git a/src/main/resources/images/folder.png b/src/main/resources/images/folder.png new file mode 100644 index 0000000..eee5e45 Binary files /dev/null and b/src/main/resources/images/folder.png differ diff --git a/src/main/resources/images/local-storage.png b/src/main/resources/images/local-storage.png new file mode 100644 index 0000000..eee5e45 Binary files /dev/null and b/src/main/resources/images/local-storage.png differ diff --git a/src/main/resources/images/logo.png b/src/main/resources/images/logo.png new file mode 100644 index 0000000..c52dee1 Binary files /dev/null and b/src/main/resources/images/logo.png differ diff --git a/src/main/resources/images/remote-storage.png b/src/main/resources/images/remote-storage.png new file mode 100644 index 0000000..6239820 Binary files /dev/null and b/src/main/resources/images/remote-storage.png differ diff --git a/src/main/resources/legacy.editors.zip b/src/main/resources/legacy.editors.zip new file mode 100644 index 0000000..477ef97 Binary files /dev/null and b/src/main/resources/legacy.editors.zip differ diff --git a/src/main/resources/legacy.editors/.DS_Store b/src/main/resources/legacy.editors/.DS_Store new file mode 100644 index 0000000..c553861 Binary files /dev/null and b/src/main/resources/legacy.editors/.DS_Store differ diff --git a/src/main/resources/legacy.editors/nanocad/.DS_Store b/src/main/resources/legacy.editors/nanocad/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/src/main/resources/legacy.editors/nanocad/.DS_Store differ diff --git a/src/main/resources/log4j.properties b/src/main/resources/log4j.properties new file mode 100644 index 0000000..2e8e8a2 --- /dev/null +++ b/src/main/resources/log4j.properties @@ -0,0 +1,24 @@ +# Define the root logger with appender file +log4j.rootLogger = DEBUG, FILE + +# Define the file appender +log4j.appender.FILE=org.apache.log4j.RollingFileAppender + +# Set the name of the file +log4j.appender.FILE.File=${app.data.dir}/seagrid.log + +# Set the immediate flush to true (default) +log4j.appender.FILE.ImmediateFlush=true + +# Set the threshold to debug mode +log4j.appender.FILE.Threshold=debug + +# Set the append to false, should not overwrite +log4j.appender.FILE.Append=true + +# Set the maximum file size before rollover +log4j.appender.FILE.MaxFileSize=5KB + +# Define the layout for file appender +log4j.appender.FILE.layout=org.apache.log4j.PatternLayout +log4j.appender.FILE.layout.conversionPattern=%m%n \ No newline at end of file diff --git a/src/main/resources/seagrid.properties b/src/main/resources/seagrid.properties new file mode 100644 index 0000000..b7745bc --- /dev/null +++ b/src/main/resources/seagrid.properties @@ -0,0 +1,70 @@ +#/* +# * +# * Licensed to the Apache Software Foundation (ASF) under one +# * or more contributor license agreements. See the NOTICE file +# * distributed with this work for additional information +# * regarding copyright ownership. The ASF licenses this file +# * to you under the Apache License, Version 2.0 (the +# * "License"); you may not use this file except in compliance +# * with the License. You may obtain a copy of the License at +# * +# * http://www.apache.org/licenses/LICENSE-2.0 +# * +# * Unless required by applicable law or agreed to in writing, +# * software distributed under the License is distributed on an +# * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# * KIND, either express or implied. See the License for the +# * specific language governing permissions and limitations +# * under the License. +# * +#*/ + +#Airavata host +airavata.host=scigap02.sciencegateways.iu.edu +#dev.airavata.host=apidev.scigap.org +dev.airavata.host=192.168.57.3 +#Airavata port +airavata.port=9930 +dev.airavata.port=9930 +#Airavata gateway ID +airavata.gateway-id=seagrid +dev.airavata.gateway-id=default +#Gateway storage resource id +gateway.storage.resource.id=gf4.ucs.indiana.edu_61552681-96f0-462a-a36c-a62a010bffc6 +#dev.gateway.storage.resource.id=gw54.iu.xsede.org_5cd90eaf-ec37-4cb9-86eb-27588bf86d0a +#dev.gateway.storage.resource.id=pgadev.scigap.org_7ddf28fd-d503-4ff8-bbc5-3279a7c3b99e +dev.gateway.storage.resource.id=192.168.57.3_ae6091dc-e748-4f0a-bac3-826a7d8dec33 +#dev.gateway.storage.resource.id=149.165.156.34_e839bf2a-c0ee-4d28-bed5-bc09ebca2362 +#SFTP host +sftp.host=seagrid.org +#dev.sftp.host=dev.seagrid.org +dev.sftp.host=192.168.57.3 +#SFTP port +sftp.port=9000 +dev.sftp.port=9000 +#Remote Data Dir Root +remote.data.dir.root=/var/www/portals/gateway-user-data/seagrid/ +#dev.remote.data.dir.root=/var/www/portals/gateway-user-data/dev-seagrid/ +dev.remote.data.dir.root = /Documents/ +#dev.remote.data.dir.root=/var/www/portals/gateway-user-data/test-seagrid1/ +#dev.remote.data.dir.root=/var/www/html/nextcloud/data/ +#dev.remote.data.dir.root=/test/ +#Remote Data Dir Prefix +remote.data.dir.prefix=file://pga@seagrid.org: +dev.remote.data.dir.prefix=file://pga@dev.seagrid.org: +#dev.remote.data.dir.prefix=file://ubuntu@149.165.157.194: +#dev.remote.data.dir.prefix=file://root@192.168.57.3: + +#Default file download location. If not set will be downloaded to use.dir/SEAGrid/ExperimentData +default.file.download.path= + +#Nextcloud configurations, Jetstream instance is specified at present +#nextcloud.server=149.165.157.194 +nextcloud.server=149.165.156.34 +nextcloudwebdav.base.path=remote.php/dav/files +nextcloud.client.id = jjfg-k567rtfvw-7555-319 +nextcloud.client.secret= +nextcloud.token.endpoint=http://149.165.157.194:8180/auth/realms/realm-nextcloud/protocol/openid-connect/token +nextcloud.grantype=password +nextcloud.tokenvalidation.api=http://149.165.157.194/checkuser.php +nextcloud.file.basedownloadpath= \ No newline at end of file diff --git a/src/main/resources/views/.DS_Store b/src/main/resources/views/.DS_Store new file mode 100644 index 0000000..a96c639 Binary files /dev/null and b/src/main/resources/views/.DS_Store differ diff --git a/src/main/resources/views/._.DS_Store b/src/main/resources/views/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/resources/views/._.DS_Store differ diff --git a/src/main/resources/views/experiment/.DS_Store b/src/main/resources/views/experiment/.DS_Store new file mode 100644 index 0000000..bed2afa Binary files /dev/null and b/src/main/resources/views/experiment/.DS_Store differ diff --git a/src/main/resources/views/experiment/._.DS_Store b/src/main/resources/views/experiment/._.DS_Store new file mode 100644 index 0000000..8ac37fc Binary files /dev/null and b/src/main/resources/views/experiment/._.DS_Store differ diff --git a/src/main/resources/views/experiment/create/experiment-create.fxml b/src/main/resources/views/experiment/create/experiment-create.fxml new file mode 100644 index 0000000..c7974ac --- /dev/null +++ b/src/main/resources/views/experiment/create/experiment-create.fxml @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + +